我试图在django上创建一个模型表单,但它不想渲染,即使我正确地映射了它并创建了路径。
models.py
from django.db import models
# Create your models here.
Media_Choices = (
("TV", "TV"),
("Radio", "Radio"),
("Youtube", "Youtube"),
("Podcast", "Podcast"),
)
class Appear(models.Model):
Show = models.CharField(max_length=100)
Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices)
Episode = models.IntegerField()
Date = models.DateField(max_length=100)
Time = models.TimeField(auto_now=False, auto_now_add=False)
Producer = models.CharField(max_length=100)
Producer_Email = models.EmailField(max_length=254)
def __unicode__(self):
return self.Show + ' ' + self.Producer_Email
forms.py
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Appear
class AppsForm(ModelForm):
class Meta:
model = Appear
fields = '__all__'
def clean_Producer_Email(self):
Producer_Email = self.cleaned_data.get('Producer_Email')
if (Producer_Email == ""):
raise forms.ValidationError('field cannot be left empty')
for instance in Appear.objects.all():
if instance.Producer_Email == Producer_Email:
raise forms.ValidationError('Please fill in correct email')
return Producer_Emailenter
views.py
from django.shortcuts import render
from .forms import AppsForm
# Create your views here.
def AppS(request):
form = AppsForm()
context = {'forms': form}
return render(request, 'AppsForm.html', context)
它拒绝呈现,但它显示文件中的HTML标记,而不是表单中的字段。这是HTML模板
AppsForm.html
{% extends 'base.html' %}
{% block content %}
{% load crispy_forms_tags %}
<form action="" method="POST">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="submit">
</form>
{% endblock %}
你的视图是错误的
def AppS(request):
if request.method == 'POST':
form = AppsForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = AppsForm()
return render(request, 'AppsForm.html', {'form': form})
和html
<form method="POST" class="" action="">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" class="" value="Submit">
</form>
现在你可以开始了告诉我如果你仍然得到错误
基于你的AppS()函数,你将表单作为'forms'传递给你的AppsForm.html,你可以用crispy_forms来呈现它,如:
AppsForm.html:
{% extends 'your_app/base.html' %}
{% block content %}
{% load crispy_forms_tags %}
<form method="POST" class="" action="">
{% csrf_token %}
{{ forms|crispy }}
<input type="submit" class="" value="Submit">
</form>
{% endblock %}
https://django-crispy-forms.readthedocs.io/en/latest/