要完成注册,我希望用户填写辅助表格。但是,次级表格未提交。我认为用户未在注册中获得身份验证,因此辅助表单未提交。 login()似乎不起作用。
# the form in this view that's not submitting
def agreements(request):
if request.method == "POST":
form = AgreementsForm(request.POST)
if form.is_valid():
user = request.user
agree = form.save(commit=False)
agree.save()
else:
raise ValidationError("Form is not valid. Try Again.")
else:
form = AgreementsForm()
return render(request, 'agree.html', {'form': form})
以下是协议的forms.py:
class AgreementsForm(forms.ModelForm):
non_ent=forms.BooleanField(label='kdmkl kdldsk')
agreement1=forms.BooleanField(label='dmklsd. lkdfmld')
class Meta:
model = Agreements
fields = ('non_ent', 'agreement1')
def save(self, commit=True):
agree = super(AgreementsForm, self).save(commit=False)
agree.non_ent = self.cleaned_data['non_ent']
agree.agreement1 = self.cleaned_data['agreement1']
if commit:
agree.save()
return agree
这是初始注册视图:
# register view which submits, but I think it's not authenticating the user
def registration(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = True
user.save()
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
return redirect('agreements_page')
else:
raise ValidationError("Form is not valid. Try Again.")
else:
form = CustomUserCreationForm()
return render(request, 'register.html', {'form': form})
协议模型:
class Agreements(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,blank=True, null=True)
non_ent = models.BooleanField(default=False, blank=True, null=True)
agreement1 = models.BooleanField(default=False, blank=True, null=True)
date = models.DateTimeField(default=datetime.now, blank=True, null=True)
def __str__(self):
return f'{self.user} ({self.date})'
答案 0 :(得分:1)
您需要先验证用户身份才能登录: def注册(请求):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = True
user.save()
# authenticate user first
user = authenticate(request,username=form.cleaned_data['username'],password=form.cleaned_data['password'])
if user:
login(request, user)
return redirect('agreements_page')
然后以辅助形式保存request.user
,如下所示。
希望您在OneToOne
模型中与用户建立Agreement
关系。
form = AgreementsForm(request.POST)
if form.is_valid():
agree = form.save(commit=False)
agree.user = request.user
agree.save()