Bringing Information from django.contrib.auth.models.User into View

46 views Asked by At

I have the following model in my Django project:

from django.contrib.auth.models import User

class Project(models.Model):
    project_title = models.CharField(max_length=200)
    project_description = models.CharField(max_length=200, default="")
    created_date = models.DateTimeField('date created')
    owner = models.ForeignKey(User)

    def __str__(self):
        return self.project_title

This view uses the Project model as follows:

class ProjectView(generic.edit.UpdateView):
    model = Project
    fields = ['project_title','project_description']
    template_name = 'steps/project.html'
    success_url = reverse_lazy('steps:index')

My question is how can I bring the User's fields into my ProjectView so I can then use them in templates? In particular, I would like to display the logged-in user's name and email.

2

There are 2 answers

2
Zagorodniy Olexiy On BEST ANSWER

user information placed on request, not on views. So you can write in template {{user.username}}, or {{user.email}}. and you'll get it. Of course if user.is_authenticated

0
Messaoud Zahi On

in your template write:

{% if request.user.is_authenticated %} 
  {{ request.user.username }} 
  {{ request.user.email }}
{% endif %}