4

Django: error with & ldquo; Username & rdquo; In my custom user template...

 2 years ago
source link: https://www.codesd.com/item/django-error-with-username-in-my-custom-user-template-the-userprofile-object-has-no-user-name-attribute.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Django: error with & ldquo; Username & rdquo; In my custom user template - the 'UserProfile' object has no 'user name' attribute

advertisements

I'm new with Django and I'm having some problems creating a custom user model. I followed every steps from the django documentation. Here is my model :

    class UserProfile(models.Model):
user = models.OneToOneField(User)
comment = models.BooleanField()
score = models.IntegerField(null=True)
profilpic = models.ImageField(upload_to="/profilepics")
bio = models.CharField(max_length=140)

Then I created several users with django-registration. But when I go to the admin and I try to delete a user I created or when I just try to click on the username, I get this error:

AttributeError at /admin/auth/user/3/
'UserProfile' object has no attribute 'username'
Exception Value:
'UserProfile' object has no attribute 'username'
Exception Location: /Users/marc-antoinelacroix/Desktop/Site/sportdub/projet/models.py in   __unicode__, line 14

So I think I have to create a "username" in my UserProfile model, and associate it to the username of the django's User, but I have no idea how to do it...

Any help would be welcome.

Thanks!


It seems like you're trying to access

def __unicode__(self):
    return self.username

but it has to be

def __unicode__(self):
    return self.user


Here's a demo

project/account/models.py

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    homepage = models.URLField(verify_exists=False)
    #...

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

project/account/admin.py

from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from account.models import UserProfile

admin.site.unregister(User)

class UserProfileInline(admin.StackedInline):
    model = UserProfile

class UserProfileAdmin(UserAdmin):
    inlines = [UserProfileInline]

admin.site.register(User, UserProfileAdmin)

project/settings.py

AUTH_PROFILE_MODULE = "account.userprofile"


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK