Reputation: 1586
I'm having trouble passing some additional context into a CBV. When I pass 'userprofile' as context, it prevents any other context from successfully being passed into the view.
My view started as this:
class OrderDetail(LoginRequiredMixin, DetailView):
model = Order
def dispatch(self, request, *args, **kwargs):
try:
user_checkout = UserCheckout.objects.get(user=self.request.user)
except:
user_checkout = None
if user_checkout:
obj = self.get_object()
if obj.user == user_checkout and user_checkout is not None: #checks to see if the user on the order instance ties to the user of the current request
return super(OrderDetail, self).dispatch(request, *args, **kwargs)
else:
raise Http404
else:
raise Http404
I then tried adding this
def get_context_data(self, *args, **kwargs):
context = super(OrderDetail, self).get_context_data(*args, **kwargs)
userprofile = UserProfile.objects.get(user=self.request.user)
context["userprofile"] = userprofile
I don't get any errors. It's just that when the page loads, none of the values that should appear (based on context) show up.
Thanks!
Upvotes: 1
Views: 213
Reputation: 51938
I think you need to add return context
in your get_context_data
method:
def get_context_data(self, *args, **kwargs):
context = super(OrderDetail, self).get_context_data(*args, **kwargs)
userprofile = UserProfile.objects.get(user=self.request.user)
context["userprofile"] = userprofile
return context
Also, as your userprofile has a relation(FK or OneToOne) with User model, you can simply access them template(without passing it in context) like this:
// If OneToOne
{{ user.userprofile }}
// If FK
{{ user.userprofile_set.first }} // using reverse relationship to fetch userprofiles
For more details, please check documentations on OneToOne, FK, Reverse Relationship.
Upvotes: 2