Django 1.6 UpdateView - 让def dispatch()返回queryset

时间:2014-03-12 20:26:11

标签: python django

在这个基于类的视图中......假设queryset = self.objects.get(user_assigned=pk)有一个值...我希望它将其返回AccountModify,以便def get_object(self, queryset=None):可以接受并返回它。现在def get_object()没有收到它并返回空白queryset

class AccountCreateOrModify(object):
    model = Employee
    form_class = AccountForm
    template_name = 'bot_data/account_modify.html'
    success_url = reverse_lazy('home')


class AccountModify(LoginRequiredMixin, 
        AccountCreateOrModify,
        UpdateView):

    def dispatch(self, request,
            *args, **kwargs):
        try:
            pk = self.request.user.pk
            queryset = self.model.objects.get(user_assigned=pk)
        except Employee.DoesNotExist:
            return redirect('account_add')

        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, queryset)

    def get_object(self, queryset=None):
        return queryset

1 个答案:

答案 0 :(得分:2)

在我看来,您应该将查询(...objects.get(user_assigned=pk))放在get_object方法中。

要重定向到account_add,您可以像这样包装调度方法:

def dispatch(self, request, *args, **kwargs):
  try:
    return super(AccountModify, self).dispatch(request, *args, **kwargs)
  except Employee.DoesNotExist:
    return redirect('account_add')