Search code examples
django-modelsdjango-templatesdjango-users

How can I render username in the templates?


I created an app where a user can register and login and post a video, How can I render username in the post. I want to pass a username in each and every post user did. like social networking

this is my model

from django.db.models.fields import CharField
from django.contrib.auth.models import User
from django.db import models

Create your models here.

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    file = models.FileField(null=False, blank=False)
    title = CharField(max_length=25, blank=False)
    date_added = models.DateTimeField(auto_now_add=True) 

    def __str__(self):
        return self.title

this is my template home templates:

    <div class="container">
    {% for post in posting %}
    <div class="row justify-content-center">
        <div class="col">
            <div class="card">
                    <video
                    id="my-video"
                    class="video-js" 
                    controls
                    width="640"
                    height="264"
                    poster="MY_VIDEO_POSTER.jpg"
                    data-setup="{}"
                    type="video/mp4"
                    >
                    <source src="{{post.file.url}}">
                </video>
            <div class="card-body">
                <small>{{post.date_added}}</small>
                <br>
               <small>{{post.title}}</small>
            </div>
            </div>
        </div>
    </div>
    {% endfor %}
</div>

this is my views:

from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
from django.contrib import messages
from .models import Post

def dashboard(request):
    posting = Post.objects.all()
    return render(request, 'dashboard.html', {'posting': posting})

this is my login views:

def login(request):
if request.method == 'POST':
    username = request.POST['username']
    password = request.POST['password']

    user = auth.authenticate(username=username, password=password)

    if user is not None:
        auth.login(request, user)
        return redirect('home')
    else:
        messages.info(request, 'Invalid Credential') 
        return redirect('login')
else:        
    return render(request, 'login.html') 

this is my register views:

def register(request):

    if request.method == 'POST':
        username = request.POST['username']
        email = request.POST['email']
        password = request.POST['password']
        password2 = request.POST['password2']

        if password == password2:
            if User.objects.filter(email=email).exists():
                messages.info(request, 'Email Already taking')
                return redirect('register')
            elif User.objects.filter(username=username).exists():
            messages.info(request, 'username is taken')
                return redirect('register')
           else:
                user = User.objects.create_user(username=username, email=email, password=password)
                user.save();
                return redirect('login')
        else:
            messages.info(request, 'Password Not Match')
            return redirect('register')   
        return redirect ('/')     
    else:
        return render(request, 'signup.html')

I want pass a username in the post


Solution

  • You can access the username of the user with post.user.username, so for example:

    <div class="card-body">
        <small>{{post.date_added}} by {{ post.user.username }}</small>
        <br>
       <small>{{post.title}}</small>
    </div>

    in the view you can boost performance by selecting the relevant users with the Post in a single query:

    def dashboard(request):
        posting = Post.objects.select_related('user')
        return render(request, 'dashboard.html', {'posting': posting})

    Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.