Django 1.6 redirect()导致'HttpResponseRedirect'对象没有属性'_meta'

时间:2014-03-12 17:29:15

标签: django

我有2个视图...一个用UpdateView修改数据库对象。如果对象不存在,则另一个视图使用CreateView。如果查询发现该对象不存在,我正在使用重定向到CreateView。但是,我得到'HttpResponseRedirect' object has no attribute '_meta'并且无法找出原因。

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


class AccountModify(LoginRequiredMixin,
        AccountCreateOrModify,
        UpdateView):
    def get_object(self, queryset=None):
        try:
            pk = self.request.user.pk
            query_set = self.model.objects.get(user_assigned=pk)
            return query_set
        except Employee.DoesNotExist:
            return redirect('account_add/')

class AccountCreateRecord(LoginRequiredMixin,
        AccountCreateOrModify,
        CreateView):
    print "hi"

编辑:我修改过AccountModify:

class AccountModify(LoginRequiredMixin, 
        AccountCreateOrModify,
        UpdateView):

def dispatch(self, request):
    try:
        pk = self.request.user.pk
        query_set = Employee.objects.get(user_assigned=pk)
        return query_set
    except Employee.DoesNotExist:
        return redirect('account_add')

当没有记录时,哪个有效。但是当我有记录时

Internal Server Error: /account_modify/
Traceback (most recent call last):
  File "/home/one/.virtualenvs/bot/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 201, in get_response
    response = middleware_method(request, response)
  File "/home/one/.virtualenvs/bot/local/lib/python2.7/site-packages/django/middleware/clickjacking.py", line 30, in process_response
    if response.get('X-Frame-Options', None) is not None:
AttributeError: 'Employee' object has no attribute 'get'

2 个答案:

答案 0 :(得分:3)

查看source code以了解UpdateView的工作原理。 get_object方法应该返回一个模型实例,因此你得到错误的原因是HttpResponseRedirect不是一个模型实例。

请尝试使用dispatch方法进行检查。

答案 1 :(得分:2)

问题是get_object()只是应该返回一个实例。您无法像基于函数的视图那样返回HttpResponse

一种方法是引发自定义异常以发出信号重定向,然后编写中间件来处理该异常并将其转换为重定向。如果您可能在很多不同的地方进行重定向,这可能很有用。

另一种方法是覆盖dispatch() 返回HttpResponse)并从那里重定向。

相关问题