如何在Django视图中保存ModelMultipleChoiceField?(How to save ModelMultipleChoiceField in Django view?)
我有一个Subject模型和一个CustomUser模型。 注册期间,用户可以选择多个主题。 以下是我的表格代码。
forms.py
class SignUpForm(forms.Form): ... subjects = forms.ModelMultipleChoiceField(label="Subjects", widget=forms.CheckboxSelectMultiple, queryset=Subject.objects.all())我可以在views.py做些什么来保存这些数据? 清除数据然后使用保存方法的常用方法不幸运。 可疑的是,类似的问题在SO中几乎没有答案。
I have a Subject model and a CustomUser model. During registration users can select multiple subjects. The following is my code in forms.
forms.py
class SignUpForm(forms.Form): ... subjects = forms.ModelMultipleChoiceField(label="Subjects", widget=forms.CheckboxSelectMultiple, queryset=Subject.objects.all())What can I do in views.py to save this data? The usual method of cleaning the data and then using the save method doesn't work unfortunately. Scarily, similar questions have very little to no answers in SO.
最满意答案
没关系。 我找到了。
if password == password2: u = CustomUser.objects.create_user(username, email, password, first_name=fname, last_name=lname, dob=year+'-'+month+'-'+day) u.subjects = subjects u.save我犯了一个错误,试图在create_user方法中用所有其他变量挤压主题。
Nevermind. I found it.
if password == password2: u = CustomUser.objects.create_user(username, email, password, first_name=fname, last_name=lname, dob=year+'-'+month+'-'+day) u.subjects = subjects u.saveI made the mistake of trying to squeeze in the subjects in the create_user method with all the other variables.
更多推荐
发布评论