如何在Django视图中保存ModelMultipleChoiceField?(How to save ModelMultipleChoiceField in Django view?)

编程入门 行业动态 更新时间:2024-10-28 02:34:22
如何在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.save

I made the mistake of trying to squeeze in the subjects in the create_user method with all the other variables.

更多推荐

本文发布于:2023-07-20 20:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1203657.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   如何在   Django   view   ModelMultipleChoiceField

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!