I'm following Django documentation here in order to achieve a simple objective: Create a user profile as soon as a new user is created.
I have an 'accounts' app and my accounts.models looks like this:
# -*- coding: utf-8 -*- from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from main.models import Store class UserProfile(models.Model): GENRE_CHOICES = ( ('m', 'Masculino'), ('f', 'Feminino'), ) MARITAL_STATUS_CHOICES = ( ('s', 'Solteiro'), ('c', 'Casado'), ('d', 'Divorciado'), ('v', 'Viúvo'), ) user = models.ForeignKey(User, unique=True) birth_date = models.DateField() genre = models.CharField(max_length=1, choices=GENRE_CHOICES) address = models.CharField(max_length=150) postal_code_4 = models.PositiveIntegerField() postal_code_3 = models.PositiveIntegerField() locatity = models.CharField(max_length=30) marital_status = models.CharField(max_length=1, choices=MARITAL_STATUS_CHOICES) child_amount = models.PositiveSmallIntegerField() is_merchant = models.BooleanField(default=False) store = models.ForeignKey(Store, null=True) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User)
Everything looks fine to me but when trying to add a new user (using django admin), instead of having a newly created user and user profile, I get the following error: InternalError at /admin/auth/user/add/ current transaction is aborted, commands ignored until end of transaction block
Here is the traceback error part:
/djangoProjects/lwboanova/lwboanova/apps/accounts/models.py in create_user_profile 34: UserProfile.objects.create(user=instance)
It seems like an integrity error but I'm not getting the reason for it.
Would be great if any of ya could give me some help on this.
Add "accounts" at the bottom of "INSTALLED_APPS". And add the "AUTH_PROFILE_MODULE" config at the bottom of the entire file. We will add "accounts" app in settings.py and use the "AUTH_USER_MODEL" config to tell Django to use our another model. And our another model will UserProfile.
Django doesn't have multiple users - it only has one user and then based on permissions users can do different things. So, to start off with - there is only one user type in django. If you use the default authentication framework, the model for this user is called User , from django.
You shouldn't use:
user = models.ForeignKey(User, unique=True)
Instead use this:
from django.conf import settings .. user = models.OneToOneField(settings.AUTH_USER_MODEL)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With