Putting username of logged in user as label in django form field

1.9k views Asked by At

I created simple django blog app where user can login and logout. In this app user can create new posts only when he is logged in. For that i created a form for creating post for authenticated user where he has to put Title , author name and context. But i want to put username of that logged in user as a label in Author_name field which user cant edit. so i made that field disabled for editing but i couldn't put username of logged in user inside that field as a label. Need help guys.

My code goes here ....

views.py

from django.shortcuts import render , redirect , get_object_or_404
from .models import Article , members
from django.views.generic import ListView , DetailView , TemplateView
from .forms import create_form
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User

class article_view(ListView):
    model = Article
    template_name = "article.html"
    context_object_name = "articles"


@login_required
def post_creator(request):
    form = create_form()
    if request.method == "POST":
        form = create_form(request.POST)
        if form.is_valid():
            form.save()
            return redirect("/blog/home/")

    else:
        form = create_form()
    return render(request , "post_create.html" , {"form":form})

def registration(request):
    if request.method == "POST":
        form = members(request.POST)
        if form.is_valid():
            form.save()

            return redirect("/blog/home/")

    else:
        form = members()
    return render(request , "register.html" , {"form":form})    



class post_detail_view(LoginRequiredMixin , DetailView):
    model = Article
    template_name = "detail.html"

#class profile(TemplateView):
#   model = members
#   template_name = "profile.html"

def counts(request):
    counts = Article.objects.filter(author=request.user).count()
    context = {

        "counts":counts
    }
    return render(request , "profile.html" , context)

forms.py

from django import forms
from datetime import date
from .models import Article
import datetime
from django.contrib.auth.models import User

class create_form(forms.ModelForm):
    author = forms.CharField(required=False , widget=forms.TextInput(attrs={'readonly':'True'}))

    class Meta:
        model = Article
        fields = ["title" , "author" , "content"]

models.py

from django.db import models
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User



class Article(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)
    date_pub = models.DateTimeField(auto_now=True)
    content = models.TextField()

    def __str__(self):
        return self.title


class members(UserCreationForm):
    email = models.EmailField()

    class Meta:
        model = User
        fields = ["username" , "email"]

create_post.html

{% load crispy_forms_tags %}
<!DOCTYPE html>
<html>

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">



    <title>Create Post</title>
</head>


</head>
<body style="background-color: darkgrey;">
    <div>
        <fieldset style="width: 50%;background-color: white;padding: 25px ;margin-left: 350px;margin-top: 15px;border-color: black;">
            <form method="POST">
            <legend>Create New Post</legend>
                {% csrf_token %}
                {{ form|crispy }}
                <button class="btn btn-outline-info" type="submit">Create</button>
            </form>
        </fieldset>
    </div>

</body>
</html>

Hope this helps understand my problem.

1

There are 1 answers

0
robotHamster On BEST ANSWER

The easiest solution that directly applies to your code, you can do

form = create_form(initial={'author':request.user.username}) #or request.user may work because it returns the username as a string

As a more general solution, that also updates the username in case it changes for any reason, would be to use a ForeignKey

In you models.py

    class Article(models.Model):
        title = models.CharField(max_length=100)
        author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
        date_pub = models.DateTimeField(auto_now=True)
        content = models.TextField()

        def __str__(self):
            return self.title

In your forms.py do not list it in the fields list it as one of the fields (keep it as-is).

Then in your views.py, assign it is as follows:

if form.is_valid():
    instance=form.save(commit=False)
    instance.author=request.user
    instance.save()

You change the author in your example to author_name, for consistency. The idea here is that you can filter by the user (or any other property of the user, such as age or gender or whatever your model actually contains)