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









up vote
0
down vote

favorite












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
<button class="btn btn-outline-info" type="submit">Create</button>
</form>
</fieldset>
</div>

</body>
</html>


Hope this helps understand my problem.










share|improve this question

























    up vote
    0
    down vote

    favorite












    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
    <button class="btn btn-outline-info" type="submit">Create</button>
    </form>
    </fieldset>
    </div>

    </body>
    </html>


    Hope this helps understand my problem.










    share|improve this question























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      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
      <button class="btn btn-outline-info" type="submit">Create</button>
      </form>
      </fieldset>
      </div>

      </body>
      </html>


      Hope this helps understand my problem.










      share|improve this question













      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
      <button class="btn btn-outline-info" type="submit">Create</button>
      </form>
      </fieldset>
      </div>

      </body>
      </html>


      Hope this helps understand my problem.







      django forms label username django-2.1






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 9:02









      Nitin Khandagale

      66




      66






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          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)






          share|improve this answer




















          • and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
            – Nitin Khandagale
            Nov 10 at 11:00










          • No worries! Welsome to the StackOverflow community :)
            – robotHamster
            Nov 10 at 17:04










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237454%2fputting-username-of-logged-in-user-as-label-in-django-form-field%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          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)






          share|improve this answer




















          • and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
            – Nitin Khandagale
            Nov 10 at 11:00










          • No worries! Welsome to the StackOverflow community :)
            – robotHamster
            Nov 10 at 17:04














          up vote
          0
          down vote



          accepted










          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)






          share|improve this answer




















          • and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
            – Nitin Khandagale
            Nov 10 at 11:00










          • No worries! Welsome to the StackOverflow community :)
            – robotHamster
            Nov 10 at 17:04












          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          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)






          share|improve this 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)







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 10 at 9:28









          robotHamster

          343115




          343115











          • and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
            – Nitin Khandagale
            Nov 10 at 11:00










          • No worries! Welsome to the StackOverflow community :)
            – robotHamster
            Nov 10 at 17:04
















          • and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
            – Nitin Khandagale
            Nov 10 at 11:00










          • No worries! Welsome to the StackOverflow community :)
            – robotHamster
            Nov 10 at 17:04















          and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
          – Nitin Khandagale
          Nov 10 at 11:00




          and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
          – Nitin Khandagale
          Nov 10 at 11:00












          No worries! Welsome to the StackOverflow community :)
          – robotHamster
          Nov 10 at 17:04




          No worries! Welsome to the StackOverflow community :)
          – robotHamster
          Nov 10 at 17:04

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237454%2fputting-username-of-logged-in-user-as-label-in-django-form-field%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Use pre created SQLite database for Android project in kotlin

          Darth Vader #20

          Ondo