我有一个 Django 应用程序,想在用户的个人资料中显示多项选择复选框。然后他们将能够选择多个项目。
但我无法保存创建的表单。任何人都可以帮忙吗?
我的 models.py 看起来像这样:
class multiChoice(models.Model):
user=models.ForeignKey(User)
Options = (
("AUT", "Australia"),
("DEU", "Germany"),
("NLD", "Neitherlands")
)
Countries = models.ManyToManyField(Choices,choices=Options)
User.multiChoice=property(lambda u:multiChoice.objects.get_or_create(user=u)[0])
表格.py:
class multiChoiceForm(forms.Form):
Countries = forms.ModelMultipleChoiceField(queryset=Choices.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
class Meta:
model=multiChoice
fields=("Countries")
视图.py:
def multiChoice_v1(request):
args = {}
args.update(csrf(request))
if request.method == 'POST':
form = multiChoiceForm(request.POST)
if form.is_valid():
countries = form.cleaned_data.get('countries')
countries.save()
form.save_m2m()
return HttpResponseRedirect('/accounts/loggedin/')
else:
form=multiChoiceForm()
args={}
args.update(csrf(request))
args['form']=form
return render_to_response('editprofile_v2.html', args)
urls.py - 单选视图的片段:
url(r'^accounts/profile_v2/$', 'guitarclubapp.views.multiChoice_v1'),
编辑profile_v2.html:
<html>
<form method='post'>{% csrf_token %}
<label> Countries </label>
<select name="Countries" id="Countries" class="multiselect" multiple="multiple">
<option value="AUT" selected="selected">Austria</option>
<option value="DEU" selected="selected">Germany</option>
<option value="NLD" selected="selected">Netherlands</option>
</select>
<input type='submit' value='submit'>
</form>
</html>
我有什么遗漏(或)做错了什么吗?
我应该改变定义模型的方式吗?
任何帮助或参考将不胜感激。
提前致谢。