嵌套模型表单保存:此字段是必需的错误

时间:2016-04-05 10:20:52

标签: django django-models django-forms django-views

models.py:

from django.db import models
from django.contrib.auth.models import User as BaseUser

CHOICE_GENDER = ((1, 'Male'), (2, 'Female'))


class Location(models.Model):
    city = models.CharField(max_length=75)
    country = models.CharField(max_length=25)

    def __str__(self):
        return ', '.join([self.city, self.state])


class Users(BaseUser):
    user = models.OneToOneField(BaseUser, on_delete=models.CASCADE)
    gender = models.IntegerField(choices=CHOICE_GENDER)
    birth = models.DateField()
    location = models.ForeignKey(Location)

    class Meta:
        ordering = ('user',)

forms.py:

from django.contrib.auth.forms import UserCreationForm
from django import forms
from .models import Users, Location


class LocationForm(forms.ModelForm):
    class Meta:
        model = Location
        fields = '__all__'


class RegistrationForm(UserCreationForm):
    class Meta:
        model = Users
        fields = ('username', 'email', 'first_name', 'last_name', 'gender', 'birth', 'location')

views.py:

def signup(request):
    if request.method == "POST":
        reg_form = forms.RegistrationForm(request.POST)
        loc_form = forms.LocationForm(request.POST)
        if loc_form.is_valid():
            reg_form.location = loc_form.save()
            if reg_form.is_valid():
                reg_form.save()
                return redirect('./')
    reg_form = forms.RegistrationForm()
    loc_form = forms.LocationForm()
    return render(request, 'signup.html', {'loc_form': loc_form, 'reg_form': reg_form})

我无法完成这项工作,但会出现location - This field is required错误。我已经尝试了views.py中的每个组合,并且由于这个原因它从未通过reg_form.is_valid()命令。有人可以帮助我吗?提前谢谢!

求助:views.py新的,工作代码:

def signup(request):
    if request.method == "POST":
        reg_form = forms.RegistrationForm(request.POST)
        loc_form = forms.LocationForm(request.POST)
        if reg_form.is_valid():
            reg = reg_form.save(commit=False)
            if loc_form.is_valid():
                reg.location = loc_form.save()
                reg.save()
                return redirect('./')
    reg_form = forms.RegistrationForm()
    loc_form = forms.LocationForm()
    return render(request, 'signup.html', {'loc_form': loc_form, 'reg_form': reg_form})

1 个答案:

答案 0 :(得分:1)

location字段元组中删除RegistrationForm应停止此行为。

由于您使用单独的位置表单,因此您不应使用location填充RegistrationForm字段。