我在将一些额外的上下文传递给CBV时遇到了麻烦。当我将'userprofile'作为上下文传递时,它会阻止任何其他上下文成功传递到视图中。
我的观点始于:
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
然后我尝试添加这个
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
方法中添加get_context_data
:
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
此外,由于您的userprofile与User模型具有关系(FK或OneToOne),您只需访问它们模板(不在上下文中传递),如下所示:
// If OneToOne
{{ user.userprofile }}
// If FK
{{ user.userprofile_set.first }} // using reverse relationship to fetch userprofiles
有关详细信息,请查看有关qazxsw poi,qazxsw poi,qazxsw poi的文档。