在我的网站中,我正在尝试创建一个模板,该模板会自动显示模型中的表单字段。我在视图中使用渲染传递了表单的实例,但模板没有识别表单,也没有显示任何输入字段
views.py:
def create_booking(request):
if request.method == 'POST':
form = BookingsForm(request.POST)
form2 = BookingsFormRecurring(request.POST)
if form.is_valid() and form2.is_valid():
booking = form.save()
bookingRecurring = form2.save()
return redirect("confirm")
else:
form = BookingsForm()
form2 = BookingsFormRecurring()
return render(request, 'makebooking.html', { 'form': form, 'form2': form2})
forms.py
class BookingsForm(forms.ModelForm):
studentUsername = 'test'
startingDate = forms.DateInput()
teacherID = forms.CharField(label = 'Select teacher', widget=forms.Select(choices=TeacherCHOICES))
startingTime = forms.CharField(label = 'Available starting times', widget=forms.Select(choices=TimeCHOICES))
lessonDuration = forms.CharField(label = 'For how long?', widget=forms.Select(choices=DURATION_CHOICES))
instrumentFocus = forms.CharField(label = 'Which instrument?', widget=forms.Select(choices=INSTRUMENTS_CHOICES))
class Meta:
model = bookingsModel
fields = ('teacherID', 'startingDate', 'startingTime', 'lessonDuration', 'instrumentFocus')
widgets = {
'startingDate': DateInput()
}
class BookingsFormRecurring(forms.ModelForm):
lessonRepeat = forms.CharField(label = "How often?", widget=forms.Select(choices=REPEATS_CHOICES), required=False)
secondaryLessonDay = forms.CharField(label = "Secondary lesson day", widget=forms.Select(choices=LESSON_DAY_CHOICES), required=False)
secondaryLessonTime = forms.CharField(label = "Secondary lesson time", widget=forms.Select(choices=TimeCHOICES), required=False)
tertiaryLessonDay = forms.CharField(label = "Third lesson day", widget=forms.Select(choices=LESSON_DAY_CHOICES), required=False)
tertiaryLessonTime = forms.CharField(label = "Third lesson time", widget=forms.Select(choices=TimeCHOICES), required=False)
class Meta:
model = bookingsModelRecurring
fields = ('lessonRepeat', 'secondaryLessonDay', 'secondaryLessonTime', 'tertiaryLessonDay', 'tertiaryLessonTime')
makebooking.html(模板)
....
<div class="container">
<div class="card-panel blue-grey darken-1 white-text">
<h3>Make a lesson booking here!</h3>
{% if user.is_authenticated %}
<div class="row">
<form class="booking" id="booking" action="" method="post">
{% csrf_token %}
<div class="col s4">
<br><br>
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
<br>
{% endfor %}
<br>
....
我不认为模板因某种原因识别{{ form }}
,因为当我使用{{ form }}
时,没有显示任何内容
编辑:
form2
稍后也会在模板页面中使用与表单