开发者

Foreign key to User table in django

开发者 https://www.devze.com 2023-01-05 15:56 出处:网络
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:

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. I.e. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消