我是HTML和django的新手 我在django中创建了一个表单
existing_rsets = Set.objects.all()
choices_int = tuple((p.name, p.name) for p in existing_rsets)
region_set = forms.ChoiceField(label='Set, widget=forms.Select(attrs={'class':'form-control'}),choices=choices_int,required=False)
如何在模板中呈现表单,然后在代码中获取该表单。请提供示例代码。
答案 0 :(得分:0)
简单的例子。
1)app / forms.py
from django import forms
class PersonForm(forms.Form):
GENDER_CHOICES = (
('', '----------'),
('MALE', 'Male'),
('FEMALE', 'Female'),
)
MARITAL_STATUS_CHOICES = (
('', '----------'),
('SINGLE', 'Single'),
('MARRIED', 'Married'),
)
first_name = forms.CharField(label='First name', max_length=255)
middle_name = forms.CharField(label='Middle name', max_length=255)
last_name = forms.CharField(label='Last name', max_length=255)
gender = forms.ChoiceField(label='Gender', choices=GENDER_CHOICES)
martial_status = forms.ChoiceField(label='Martial status', choices=MARITAL_STATUS_CHOICES)
2)app / views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import PersonForm
def person(request):
if request.method == 'POST':
form = PersonForm(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/some-url/xyz')
else:
form = PersonForm()
context = {
'form': form,
}
return render(request, 'app/templates/person.html', context)
3)app / templates / person.html
{% for field in form.visible_fields %}
{{ field.label_tag }}
{{ field }}
<span style='color:red'>{{ field.errors.as_text }}</span>
{% endfor %}
详细了解Django表格here。