我无法将一些其他上下文传递到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
我没有任何错误。只是页面加载时,不会出现任何应显示的值(基于上下文)。
谢谢!
答案 0 :(得分:2)
我认为您需要在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
此外,由于您的用户个人资料与用户模型具有关联(FK或OneToOne),因此您可以像这样简单地访问它们的模板(无需在上下文中传递它):
// If OneToOne
{{ user.userprofile }}
// If FK
{{ user.userprofile_set.first }} // using reverse relationship to fetch userprofiles
有关更多详细信息,请查阅OneToOne,FK,Reverse Relationship上的文档。