调用另一个表单的创建时出错

时间:2016-04-04 08:53:30

标签: django

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 __unicode__(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, CHOICE_GENDER


class LocationForm(forms.ModelForm):
    city = forms.CharField(max_length=75)
    country = forms.CharField(max_length=25)

    class Meta:
        model = Location
        fields = ('city', 'country',)


class RegistrationForm(UserCreationForm):
    email = forms.CharField(max_length=75)
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    gender = forms.ChoiceField(choices=CHOICE_GENDER)
    birth = forms.DateField()
    location = LocationForm()

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

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.gender = self.cleaned_data['gender']
        user.birth = self.cleaned_data['birth']
        if commit:
            user.save()
        return user

forms.py中的此代码不起作用。由于这些错误,它无法保存LocationForm:

country - This field is required.
city - This field is required.

我在这里确实做错了什么,但我不确切知道是什么。我承认我在forms.py中混淆了代码,特别是在RegistrationForm的save方法中,因为我不知道如何正确调用另一个表单的创建以及如何在两个表单之间建立连接。我搜索了互联网,但我无法找到有关这方面的确切信息,所以我试图即兴发挥但不幸的是我失败了。 有人可以帮我吗?提前谢谢!

更新:views.py(当前):

def signup(request):
    if request.method == "POST":
        reg_form = RegistrationForm(request.POST)
        loc_form = LocationForm(request.POST)
        if reg_form.is_valid() and loc_form.is_valid():
            location = loc_form.save()
            reg_form.cleaned_data['location_id'] = location.id
            registration = reg_form.save()
        else:
            pass
    else:
        reg_form = RegistrationForm()
        loc_form = LocationForm()    
    return render(request, 'signup.html', {'loc_form': loc_form, 'reg_form':reg_form})

我还修改了forms.py,但我仍然从上面得到了错误。

1 个答案:

答案 0 :(得分:1)

您可以在int中单独处理LocationForm,而不是在RegistrationForm内使用views.py,这样可以生成更清晰的代码并且易于处理。

if request.method == "POST":
    reg_form = RegistrationForm(request.POST)
    loc_form = LocationForm(request.POST)
    if reg_form.is_valid() and loc_form.is_valid():
        # since in your case they are dependent on each other
        # save location form and get location object
        location = loc_form.save()
        # now you can use it in your reg_form
        reg_form.cleaned_data['location_id'] = location.id
        registration = reg_form.save()
    else:
        # no need to handle this case only for explanation
        # use the forms, with valid post data initialized 
        # at the start of current if block
        pass
else:
    # create new forms for location and registration
    reg_form = RegistrationForm()
    loc_form = LocationForm()    
return render(request, 'signup.html', {'loc_form': loc_form, 'reg_form':reg_form})

您可以在此处阅读有关如何在django docs中处理多个嵌套表单的更多信息。