[Django]-Foreign key to User table in django

4👍

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)

👤heckj

1👍

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.

Leave a comment