TypeError:__ init __()得到一个意外的关键字参数'instance'

时间:2016-04-04 11:20:34

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

models.py:

Application.Current.MainWindow.Close()

forms.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',)

views.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', 'location')

    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']
        user.location = self.cleaned_data['location']
        if commit:
            user.save()
        return user

我从from django.shortcuts import render, redirect from django.forms import formset_factory from . import forms def signup(request): if request.method == "POST": loc_form = forms.LocationForm(request.POST) if loc_form.is_valid(): loc = loc_form.save() RegistrationFormSet = formset_factory(forms.RegistrationForm) formset = RegistrationFormSet(request.POST, instance=loc) if formset.is_valid(): formset.save() return redirect('./') # else: # how to make to render the POST data to the template page and fill all fields? return render(request, 'signup.html') 处的标题中收到错误。我正在尝试创建一个有效的视图,它将在保存到主窗体之前调用另一个窗体的调用,这就是我使用FormSet的原因,但我无法使其工作。有人可以帮助我吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

RegistrationFormSet是通过调用formset_factory创建的,因此它对实例一无所知。我认为你的意思是使用支持它们的inlineformset_factory