Dominic M.
Dominic M.

Reputation: 913

Get_context_data breaking breaking django listview

I have a listview that displays membership pricing, but when the user is not logged in the membership objects don't show up, so there is no pricing. It does work when I am logged in.

However, when i completely remove the def get_context_data function from my views.py, it works and the membership list object appears for non authenticated users.

So somehow the get_context_data is breaking my model=membership query for non authenticated users.

Any idea?

membership_list.html

{% for object in membership_list %}
          <td><span>${{ object.price }}</span><span class="text-muted">/mo</span></td>
{% endfor %}

views.py

class MembershipSelectView(ListView):
    model = Membership
    context_object_name = 'membership_list'
    ordering = ['price']
    #Check if user is logged in first

    def get_context_data(self, *args, **kwargs):
        if self.request.user.is_authenticated:
            context = super().get_context_data(**kwargs)
            current_membership = get_user_membership(self.request)
            context['current_membership'] = str(current_membership.membership)
            return context

Upvotes: 1

Views: 233

Answers (1)

Robert Townley
Robert Townley

Reputation: 3564

I think it's because you're not returning a context for non-authenticated users. If a user isn't authenticated, the context passed into the template is going to be None which could mess with methods of the ListView parent class. I'd have to see the specific error message to be sure, but unless there's more to the code than posted, that seems like a likely culprit.

Put the call to the super method outside of the if self.request.user.is_authenticated and also take the return context out of there.

class MembershipSelectView(ListView):
    model = Membership
    context_object_name = 'membership_list'
    ordering = ['price']
    #Check if user is logged in first

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        if self.request.user.is_authenticated:  
            current_membership = get_user_membership(self.request)
            context['current_membership'] = str(current_membership.membership)
        return context

Upvotes: 2

Related Questions