2014-03-12 58 views
2

我有2個視圖...一個用來修改數據庫對象UpdateView。如果對象不存在,另一個視圖使用CreateView。如果查詢發現該對象不存在,我正在使用重定向到CreateView。但是,我得到'HttpResponseRedirect' object has no attribute '_meta',並找不到原因。Django 1.6 redirect()導致'HttpResponseRedirect'對象沒有屬性'_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' 
+1

您的'AccountCreateOrModify'類是一箇舊式類(不是從'object'下降的)。這可能不是一個好主意。 – lanzz

+0

謝謝,但沒有幫助我的問題 – dman

回答

3

看那source code瞭解如何UpdateView作品。 get_object方法應該返回一個模型實例,因此您爲什麼會收到錯誤,因爲HttpResponseRedirect不是模型實例。

請嘗試在dispatch方法中進行檢查。

+0

我怎麼能def_object()傳遞派遣派遣()? – dman

+1

你的意思是'get_object()'..? – Drewness

+0

對不起,請參閱編輯 – dman

1

問題是get_object()只是應該返回一個實例。您不能像使用基於函數的視圖那樣返回HttpResponse

其中一種方法是引發自定義異常信號重定向,然後編寫中間件來處理該異常並將其轉換爲重定向。如果你有可能在很多不同的地方做重定向,這可能很有用。

另一種方法是重寫dispatch()(其中確實返回HttpResponse),並從那裏做你的重定向。

相關問題