我正在尝试创建一个注册表单,以将数据同时添加到2个表中。但我不确定POST方法后要写什么

时间:2019-08-12 15:32:36

标签: python django django-models django-forms

  

我想创建一个用户到auth_user中。并使用其id(主键)来   在User_Profile中填写一个条目,将其作为外键。

Models.py:

class User_Profile(models.Model):
    user =  models.OneToOneField(User, on_delete=models.CASCADE)
    contact_number = models.IntegerField()
    birth_date = models.DateField(null=False)
    address = models.CharField(max_length=200)
    role = models.ForeignKey(Role, on_delete=models.CASCADE)

Forms.py:

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    class Meta:
        model = User
        fields = ['username', 'email', 'password']


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = User_Profile
        fields = [ 'contact_number', 'birth_date', 'address', 'role']

Views.py:

def registration_view(request):

    form = UserForm(request.POST)
    form2 = UserProfileForm(request.POST)



else:
    context = {
        'form': form,
        'form2': form2
    }
    return render(request, 'Schoool/registration_form.html', context)

0 个答案:

没有答案