我正在尝试为用户的个人资料添加其他字段,只能由管理员进行编辑。
当我尝试在管理模块中保存新的城市值时,我收到错误:
global name 'created' is not defined
此错误来自:
signals.py in create_profile, line 7
我描述了到目前为止我所做的事情:) 我开始了一个新的app profil
在models.py
中from django.db import models
from django.contrib.auth.models import User
from django.utils.encoding import smart_str
class UserProfile(models.Model):
"""Model przechowujący dodatkowe informacje o użytkowniku"""
user = models.ForeignKey(User, unique=True)
city = models.CharField(max_length=255, verbose_name=u'Miasto', blank=True, null=True)
class Meta:
verbose_name = 'Profil użytkownika'
verbose_name_plural = 'Profile użytkowników'
def __unicode__(self):
return u'%s' self.user.username
def __str__(self):
return smart_str('%s' % self.user.username)
import profil.signals
在file:signals.py
中from django.contrib.auth.models import User
from django.db.models.signals import post_save
from profil.models import UserProfile
def create_profile(sender, instance, **kwargs):
if created == True:
UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)
forms.py
from django import forms
from profil.models import UserProfile
class UserProfileForm(forms.ModelForm):
'''Formularz modelu UserProfile'''
class Meta:
model = UserProfile
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from profil.forms import UserProfileForm
from profil.models import UserProfile
class UserProfileInline(admin.StackedInline):
model = UserProfile
fk_name = 'user'
max_num = 1
form = UserProfileForm
class UserProfileAdmin(UserAdmin):
inlines = [UserProfileInline, ]
admin.site.unregister(User)
admin.site.register(User, UserProfileAdmin)
答案 0 :(得分:0)
您可以使用:
def create_profile(sender, instance, **kwargs):
if kwargs.get('created', False) ...
或
def create_profile(sender, instance, created, **kwargs):
if created == True:
答案 1 :(得分:0)
在您使用signals.py
的{{1}}中,但尚未定义。
所以,你可以使用这个created
Fianlly,你kwargs.get('created')
函数应该是这样的。
create_profile