Formset,外键和OneToOne

时间:2014-07-10 19:50:45

标签: python django foreign-keys inline-formset

我想在不使用任何外部应用程序的情况下创建注册表单,但我无法保存foregin和OneToOne与formset的关系。 这是我的models.py:

class UserProfile(models.Model):
user = models.OneToOneField(User)
avatar = models.ImageField(null=True, blank=True, upload_to='avatar/')
website = models.URLField(null=True, blank=True)
birthday = models.DateField()
country = CountryField()

GENDER_CHOICES = (
    ('M', 'Male'),
    ('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

def __str__(self):
    return "UserProfile(models)"


class UserLanguage(models.Model):
    user = models.ForeignKey(User)
    language = models.CharField(max_length=7, choices=LANGUAGES)
    level = models.CharField(max_length=1)
    # http://stackoverflow.com/questions/3201018/django-language-codes

    def __str__(self):
        return "UserLanguage(models)"

这是我的forms.py:

class RegisterForm(forms.ModelForm):
class Meta:
    model = User
    fields = ('username', 'password',)
    exclude = ('last_login',)
    widgets = {'password': forms.PasswordInput(), }


UserProfileFormSet = inlineformset_factory(User, UserProfile, can_delete=False)
UserLanguageFormSet = inlineformset_factory(User, UserLanguage, can_delete=False, extra=1)

和我的views.py:

def registration(request):
if request.method == "POST":
    user = RegisterForm(request.POST)
    user_profile = UserProfileFormSet(request.POST)
    user_language = UserLanguageFormSet(request.POST)

    if user.is_valid() and user_profile.is_valid() and user_language.is_valid():
        u = user.save()

        user_profile.user = u
        user_profile.save()

        user_language.user = u
        user_language.save()

else:
    user = RegisterForm()
    user_profile = UserProfileFormSet()
    user_language = UserLanguageFormSet()

return render(request, 'user/registration.html', locals())

我收到了这个错误:

  

列' user_id'不能为空

我可以做些什么来解决我的问题?你有别的评论吗? 谢谢。

1 个答案:

答案 0 :(得分:1)

您的格式集user_profileuser_language令人困惑。但它们不是配置文件或语言对象,它们是表单集,因此设置其用户属性将不起作用。

这有效:

for profile_form in user_profile.forms:
    up = profile_form.save(commit=False)
    up.user = u
    up.save()

for language_form in user_language.forms:
    ul = language_form.save(commit=False)
    ul.user = u
    ul.save()

但实际上你应该把它们命名为它们。