简体   繁体   中英

Foreign key to User table in django

I'm using django's built-in contrib.auth module and have setup a foreign key relationship to a User for when a 'post' is added:

class Post(models.Model):
    owner = models.ForeignKey('User')
    # ... etc.

Now when it comes to actually adding the Post, I'm not sure what to supply in the owner field before calling save(). I expected something like an id in user's session but I noticed User does not have a user_id or id attribute. What data is it that I should be pulling from the user's authenticated session to populate the owner field with? I've tried to see what's going on in the database table but not too clued up on the sqlite setup yet.

Thanks for any help...

You want to provide a "User" object. Ie the same kind of thing you'd get from User.objects.get(pk=13).

If you're using the authentication components of Django, the user is also attached to the request object, and you can use it directly from within your view code:

request.user

If the user isn't authenticated, then Django will return an instance of django.contrib.auth.models.AnonymousUser. (per http://docs.djangoproject.com/en/dev/ref/request-response/#attributes )

Requirements --> Django 3, python 3

1) For add username to owner = models.ForeignKey('User') for save that, in the first step you must add from django.conf import settings above models.py and edit owner = models.ForeignKey('User') to this sample:

class Post(models.Model):
    slug = models.SlugField(max_length=100, unique=True, null=True, allow_unicode=True)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)

2) And for show detail Post , special owner name or family or username under the post, you must add the following code in the second step in views.py :

from django.shortcuts import get_object_or_404
.
.
. 

def detailPost(request,slug=None):
    instance = get_object_or_404(Post, slug=slug)
    context = {
        'instance': instance,
    }
return render(request, template_name='detail_post.html', context=context)

3) And in the third step , you must add the following code for show user information like user full name that creates a post:

<p class="font-small grey-text">Auther: {{ instance.owner.get_full_name  }} </p>

now if you want to use user name , you can use {{ instance.owner.get_username }} or if you want to access short name, you can use {{ instance.owner.get_short_name }} . See this link for more information.

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