嘿,我正在尝试使用modelchoicefield在html中获取下拉列表。但是提交表单会产生无效的表单。我的代码如下。 views.py
class SubjectSelectFormView(View):
form_class = SubjectSelectForm
template_name = 'study/select_subject.html'
def get(self, request):
form = self.form_class(user=request.user)
return render(request, self.template_name, {'form':form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
subject = models.Subject.objects.get(name=form['name'])
return HttpResponseRedirect('study:quiz', subject.subject_id)
else:
return HttpResponse('<h1>Failed</h1>')
forms.py
class SubjectSelectForm(forms.Form):
name = forms.ModelChoiceField(queryset=Subject.objects.all().order_by('name'), widget=forms.Select())
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(SubjectSelectForm,self).__init__(*args, **kwargs)
self.fields['name'].queryset = Subject.objects.filter(user_id=user)
html
{% extends 'basic_home_app/base.html' %}
{% block content %}
<br>
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Start">
</form>
{% endblock %}
答案 0 :(得分:0)
首先,当发现张贴的表单无效时,应始终使用绑定的表单呈现相同的模板,这样您可以向用户显示错误:
def post(self, request):
form = ...
if form.is_valid():
...
else:
return render(request, self.template_name, {'form':form})
在模板内部,您可以使用以下任一显示错误:
{{ form.errors }} # all form errors
{{ form.non_field_errors }} # form errors that aren't for one specific field, use this if you're displaying the field errors separately
或
{{ form.name.errors }} # just the errors for one specific field
第二,我假设您要以与通过get()
请求向用户首次显示(空)时相同的方式初始化表单。
def post(self, request):
form = self.form_class(request.POST, user=request.user) # note the user
否则,您的form.__init__()
方法将仅将Subject
为user_id
的{{1}}个对象设置为查询集。