简体   繁体   中英

Django's get_context_data function not working?

I'm practicing with Django's Class Based View.

It seems like my overridden get_context_data function is not working properly, but I have no idea what is wrong :(

My code:

urls.py

url(r'^user/(?P<pk>\d+)/posts/$', UserPosts.as_view(), name='user_post'),

views.py

class UserPosts(ListView):
    template_name = 'app_blog/user_posts_page.html'
    context_object_name = 'post_list'

    def get_queryset(self):
        self.user = get_object_or_404(User, id=self.kwargs['pk'])
        return self.user.post_set.order_by('-id')
    def get_context_data(self, **kwargs):   
        context = super(UserPosts, self).get_context_data(**kwargs)
        context['user'] = self.user
        return context

user_post_page.html

{% block content %}
    <div class="main_content">
        <h2>Welcome to {{user.username}}'s User Post Page!</he>
        <ul>
        {% for post in post_list %}
            <li><a href="/blog/post/{{post.id}}/">{{post.post_title}}</a></li>
        {% endfor %}
        </ul>
    </div>
{% endblock %}

The html page correctly displays the user's post_list, BUT the h2 tag displays:

Welcome to 's User Post Page!

I'm pretty sure I passed the 'user' variable in the get_context_data function, but the html page does not displa the user.username... Any idea why this is happening :(??

Thanks

Use another name that is not user . It seems like RequestContext overwrite user variable.

Please see the default TEMPLATE_CONTEXT_PROCESSORS , which set the django.contrib.auth.context_processors.auth .

If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every RequestContext will contain these variables:

  • user – An auth.User instance representing the currently logged-in user (or an AnonymousUser instance, if the client isn't logged in).
  • perms – An instance of django.contrib.auth.context_processors.PermWrapper , representing the permissions that the currently logged-in user has.

So you'd better give your user variable another name.

As the other answers said, don't use the variable name user . But even more importantly, in this particular case the ListView is not the best generic class to use; instead, you're better off using the DetailView , which makes your view much simpler:

class UserPosts(DetailView):
    model = User
    template_name = 'app_blog/user_posts_page.html'
    context_object_name = 'listed_user'

The only change in your template is to use listed_user instead of the user variable. Since DetailView already looks into the pk URL argument, it will select and return the right User automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM