gpt4 book ai didi

具有多对多关系的Django表单不保存

转载 作者:行者123 更新时间:2023-12-04 01:36:23 25 4
gpt4 key购买 nike

我有一个自定义注册表供我的用户在我的应用程序上添加配置文件。但是,最近出现了一个错误,即表单没有保存放入所有字段的信息。

我的用户模型,MyUser与另一个模型具有多对多关系,Interest ,这就是问题出现的地方。我不确定它是否是 RegistrationFormregister导致它的 View ,所以我在下面包括了两个,以及模型代码。
我还有一个 View 供用户更新他们的个人资料,也包括在内,一旦创建,这绝对是完美的。这是personal查看。
正如我所说,它只是 Interest未返回的字段,即使它已在注册页面上填写。

非常感谢任何帮助或建议,谢谢。

模型.py

class Interest(models.Model):
title = models.TextField()

def __unicode__(self):
return self.title

class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
date_of_birth = models.DateField()
course = models.ForeignKey(Course, null=True)
location = models.ForeignKey(Location, null=True)
interests = models.ManyToManyField(Interest, null=True)
bio = models.TextField(blank=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)

objects = MyUserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']

View .py
def register(request):
if request.method == 'POST':
form = RegistrationForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('/friends/home/')
else:
form = RegistrationForm()

template = "adduser.html"
data = { 'form': form, }
return render_to_response(template, data, context_instance=RequestContext(request))

@login_required(login_url='/friends/login/')
def personal(request):
"""
Personal data of the user profile
"""
profile = request.user

if request.method == "POST":
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
form.save()
messages.add_message(request, messages.INFO, _("Your profile information has been updated successfully."))
return redirect('/friends/success/')
else:
form = ProfileForm(instance=profile)

template = "update_profile.html"
data = { 'section': 'personal', 'form': form, }
return render_to_response(template, data, context_instance=RequestContext(request))

forms.py
class RegistrationForm(forms.ModelForm):
"""
Form for registering a new account.
"""
email = forms.EmailField(widget=forms.TextInput, label="Email")
password1 = forms.CharField(widget=forms.PasswordInput,
label="Password")
password2 = forms.CharField(widget=forms.PasswordInput,
label="Password (again)")
course = forms.ModelChoiceField(queryset=Course.objects.order_by('title'))
location = forms.ModelChoiceField(queryset=Location.objects.order_by('location'))

class Meta:
model = MyUser
fields = [
'first_name',
'last_name',
'date_of_birth',
'email',
'password1',
'password2',
'course',
'location',
'interests',
'bio',
]

def __init__(self, *args, **kwargs):#Sort interests alphabetically
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['interests'].queryset = Interest.objects.order_by('title')

def clean(self):
cleaned_data = super(RegistrationForm, self).clean()
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("Passwords don't match. Please enter again.")
return self.cleaned_data

def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user

最佳答案

由于您使用 commit=falsesuper(RegistrationForm, self).save调用,它不保存多对多字段。因此您需要添加 self.save_m2m()之后 user.save()在您的 save() RegistrationForm的方法.

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

编辑:save_m2m()是在表格上,而不是模型上

关于具有多对多关系的Django表单不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28057512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com