查询后两次显示个人资料信息

时间:2019-04-25 14:17:29

标签: django

我的问题是,当我尝试显示某个用户的个人资料信息时,我根据该特定用户创建的帖子数量多次显示该信息。我不知道如何在单击用户名时更改查询以获取用户的个人资料信息。

我创建了一个get_context_data方法,但是我不知道如何更改查询以获取用户信息。

views.py

class ProfilPostView(ListView):
   model=Post
   template_name='profile.html'

   #display posts created by user
   def get_queryset(self):

       return Post.objects.filter(author__username=self.kwargs['slug']).order_by('created_on')
       #return Post.objects.filter(author=self.request.user).order_by('created_on')

   #display profile information of user
   def get_context_data(self,**kwargs):
       context=super(ProfilPostView,self).get_context_data(**kwargs)
       context['profiles']=Post.objects.filter(author__username=self.kwargs['slug'])
       return context




profile.html


                   <h3 style="padding-left:40%" class="lead">Name: {{ profiles.first_name}} {{profiles.last_name}}</h3>
               <p class="text-muted" style="padding-left:40%">Created: {{profiles.created_time.day}}.{{profiles.created_time.month}}.{{profiles.created_time.year}}</p>
               <p class="text-muted" style="padding-left:40% ">Email: {{profiles.email}}</p>


**UPDATE**
the code that displays the profile informations multiple times is the below one. the upper code is the one i changed for get_context_data method


           {% for post in object_list%}
               <h3 style="padding-left:40%" class="lead">Name: {{ post.author.first_name}} {{post.author.last_name}}</h3>
               <p class="text-muted" style="padding-left:40%">Created: {{post.author.created_time.day}}.{{post.author.created_time.month}}.{{post.author.created_time.year}}</p>
               <p class="text-muted" style="padding-left:40% ">Email: {{post.author.email}}</p>
           {% endfor %}

1 个答案:

答案 0 :(得分:1)

由于您只关心一个个人资料,所以我不确定为什么要使用返回帖子列表的视图。您应该使用基于Profile的DetailView。

您的视图应该只是(不必覆盖任何方法):

class ProfilPostView(DetailView):
   model = Profil     # or whatever your profile model is called
   template_name = 'profile.html'
   slug_field = 'username'

您的模板变为:

   <h3 style="padding-left:40%" class="lead">Name: {{ object.first_name }} {{ object.last_name }}</h3>
   <p class="text-muted" style="padding-left:40%">Created: {{object.created_time.day}}.{{object.created_time.month}}.{{object.created_time.year}}</p>
   <p class="text-muted" style="padding-left:40% ">Email: {{object.email}}</p>