I am working on creating a website with user profiles but I have run into a problem. I am very confused about how User
works in Django. Here is my current code: In Models.py
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User)
username = models.CharField(max_length=20)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
biography = models.TextField(max_length=1000)
votes = models.IntegerField(blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True,
auto_now=False, null=True
)
def __unicode__(self):
return unicode(self.user.username)
class Post(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=100, blank=False)
body = models.TextField(blank=False)
description = models.CharField(max_length=100, blank=True)
date = models.DateTimeField(auto_now_add=True, auto_now=False)
keywords = models.CharField(max_length=100, blank=True)
votes = models.IntegerField(blank=True, null=True)
def __unicode__(self):
return unicode(self.title)
In my settings.py
I have AUTH_USER_MODEL = 'models.Profile'
set.
Now When I go into the Admin
site and create a new Profile
, it has a User
field where I have to choose a user. The User
that I have to choose from is my Django Admin superuser that I created with python manage.py createsuperuser
. To create a new User
entirely and not be linked to the Django Admin superuser, should I be making a custom User
using AbstractBaseUser
instead? I followed some tutorials and they seem to all use the auth.User
method. Am I doing something wrong here?
you better use ForeignKey in Post Model, since one person can have many posts, right?
class Profile(models.Model):
user = models.OneToOneField(User, related_name="user_profile")
...
class Post(models.Model):
user = models.ForeignKey(Profile, related_name="user_posts")
and you dont set AUTH_USER_MODEL
, you set it if you want to customize the authentication backend, I think you want to use django's built-in User Model to authentication. so no need for AUTH_USER_MODEL
in settings
with the models above, you can access profile in views like this:
user_profile = request.user.user_profile
user_profile.keywords
...
and in admin, you just need to create another new django user object, to be able to assign it to a new user profile object.
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.