我使用了{{form}},如here
所示template.html
<h4>Change your details</h4><br>
<form id="edit_form" method='post'>
{% csrf_token %}
{{ form }}
<div class='section group'>
<input id="update_details_button" type='submit' class='btn btn-primary wide' value='Change'/>
</div>
</form>
views.py
def user_view(request, is_admin):
user = request.user
form = myForm()
if request.method == 'POST' and is_admin:
form = myForm(request.POST)
if form.is_valid():
data = form.cleaned_data
user.name = data['name']
user.country = data['country']
user.save()
messages.success(request, 'You have successfully updated your details.')
return render(request, 'mysite/user.html', {
'user': user,
'is_admin': is_admin,
'form': form,
})
我的表格如下
class myForm(forms.Form):
name = forms.CharField(
label="Name",
widget=forms.TextInput(attrs={'placeholder': 'Name'}))
country = CountryField(blank_label='(select country)')
def __init__(self, *args, **kwargs):
super(myForm, self).__init__(*args, **kwargs)
页面上的名称字段显示正常,但没有CountryField的迹象,是否有人指出错误?编译好的代码在服务器运行时没有出错。
答案 0 :(得分:2)
CountryField
是模型字段,而不是表单字段。您应该将其添加到您的用户模型中,在这种情况下,基于该模型的模型将自动生成国家/地区字段。由于您实际上已经向User模型添加了一个名为country
的字段,因此您应该使用CountryField。
但是,作为参考,在非模型表单上手动执行操作稍微复杂一些:
from django_countries import widgets, countries
class myForm(forms.Form):
country = forms.ChoiceField(widget=CountrySelectWidget, choices=countries)
答案 1 :(得分:1)
实际上,它更简单:https://pypi.org/project/django-countries/#custom-forms
from django_countries.fields import CountryField
class MyForm(forms.Form):
country = CountryField(blank=True).formfield()