Django – 建立使用者配置檔案
,以實現一個簡單的目標:建立一個新的使用者建立一個使用者配置檔案.
我有一個’帳戶’應用程式和我的帳戶.模型看起來像這樣:
# -*- 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)
一切都看起來不錯,但是當嘗試新增新使用者(使用django管理員),而不是擁有新建立的使用者和使用者配置檔案時,我會收到以下錯誤:
/ admin / auth / user / add /
當前事務被中止,命令被忽略,直到事務塊結束
這是追溯錯誤部分:
/djangoProjects/lwboanova/lwboanova/apps/accounts/models.py in create_user_profile 34: UserProfile.objects.create(user=instance)
這似乎是一個完整性錯誤,但我沒有得到它的理由.
如果有任何一個可以給我一些幫助,這將是偉大的.
只是想出來
我忘了在其餘的UserProfile模型欄位中新增’null = True’欄位選項=)
所以accounts.models UserProfile欄位現在看起來像:
user = models.ForeignKey(User, unique=True) birth_date = models.DateField(null=True) genre = models.CharField(max_length=1, choices=GENRE_CHOICES, null=True) address = models.CharField(max_length=150, null=True) postal_code_4 = models.PositiveIntegerField(null=True) postal_code_3 = models.PositiveIntegerField(null=True) locatity = models.CharField(max_length=30, null=True) marital_status = models.CharField(max_length=1, choices=MARITAL_STATUS_CHOICES, null=True) child_amount = models.PositiveSmallIntegerField(null=True) is_merchant = models.BooleanField(default=False) store = models.ForeignKey(Store, null=True)
…一切都按照預期工作!
歡呼試圖幫助Ashray ^^
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/11488974/django-create-user-profile-on-user-creation