Django Admin创建表格内联OneToOne

时间:2019-06-05 17:04:59

标签: python django django-models django-admin

我有以下模型:

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)

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

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/上):

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

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

1 个答案:

答案 0 :(得分:0)

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

# 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()