我有一个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])
forms.py:
class multiChoiceForm(forms.Form):
Countries = forms.ModelMultipleChoiceField(queryset=Choices.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
class Meta:
model=multiChoice
fields=("Countries")
views.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'),
editprofile_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>
我错过了什么(或)做错了什么?
我应该改变我定义模型的方式吗?
非常感谢任何帮助或参考。
提前致谢。