Django Admin创建内联OneToOne表单 [英] Django Admin Create Form Inline OneToOne

查看:179
本文介绍了Django Admin创建内联OneToOne表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型:

from django.db import models


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    last_password_reset = models.DateTimeField(auto_now_add=True)
    needs_password_reset = models.BooleanField(default=True)
    image_url = models.URLField(max_length=500, default=None, null=True, blank=True)

我正在尝试将其内联到管理员中。我有以下内容:

I am trying to inline this into the admin. I have the following:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm

class UserProfileInline(admin.StackedInline):
    """User profile inline."""

    model = Profile
    can_delete = False
    verbose_name_plural = "Profile"


class CustomUserCreationForm(UserCreationForm):
    """Create user form."""

    class Meta:
        model = User
        fields = ("username", "first_name", "last_name", "email")


class CustomUserAdmin(UserAdmin):
    """Custom user admin."""

    add_form = CustomUserCreationForm
    inlines = (UserProfileInline,)


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

这是工作罚款到一定程度;当我创建用户时,可以看到内联的个人资料信息。但是,当我尝试提交表单时,出现以下错误(在 / admin / auth / user / add / 上):

This is working fine up to a point; when I go to create user, I can see the inlined profile information. However, when I try to submit the form I get the following error (on /admin/auth/user/add/):

psycopg2.errors.NotNullViolation: null value in column "user_id" violates not-null constraint

为什么 user_id 字段没有以内联形式填充?如何将此属性设置为由表单创建的用户的 id

Why is the user_id field not getting populated in the inline form? How can I set this attribute to the id of the user created by the form?

推荐答案

结果是,我需要删除为自动配置文件创建而编写的一些信号:

Turns out I needed to remove some signals I had written for automatic profile creation:

# Create a profile for new users
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_profile(sender, instance=None, created=False, **kwargs):
    if created:
        Profile.objects.get_or_create(user=instance)


# Update profile on user change
@receiver(post_save, sender=User)
def save_user_profile(sender, instance=None, created=False, **kwargs):
    instance.profile.save()

这篇关于Django Admin创建内联OneToOne表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆