问题
I have the following model:
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)
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
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?
回答1:
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()
来源:https://stackoverflow.com/questions/56465018/django-admin-create-form-inline-onetoone