简体   繁体   中英

Django adding a custom field to registration

I'm trying to add additional field for user's profile which can be edited only by administrator.

When I try to save a new value of city in an administration module I'm getting an error:

global name 'created' is not defined

This error comes from:

signals.py in create_profile, line 7

I described what I have done till now :) I started a new app profil

In 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

In 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)

You can use:

def create_profile(sender, instance, **kwargs):
    if kwargs.get('created', False) ...

or

def create_profile(sender, instance, created, **kwargs):
    if created == True:

In your signals.py you are using created but is not defined yet.

So, you can get it from kwargs using this kwargs.get('created')

Fianlly, you create_profile function should looks like this.

def create_profile(sender, instance, **kwargs):
    if kwargs.get('created',None):
        UserProfile.objects.get_or_create(user=instance)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM