2017-03-18 327 views
1

所以我一直在尝试添加一个取消按钮到我一直在使用的UpdateView。这里是我的代码吧:“UpdateView”对象没有属性“对象”

views.py:

class CountryEditView(generic.edit.UpdateView): 
    model = Country 
    fields = ['name'] 
    template_name_suffix = '_edit' 

    def post(self, request, *args, **kwargs): 
     if "cancel" in request.POST: 
      url = self.object.get_absolute_url() 
      return HttpResponseRedirect(url) 
     else: 
      return super(CountryEditView, self).post(request, *args, **kwargs) 
# etc.... 

models.py:

class Country(AutoUpdateModel): #A subclass of models.Model 
    def get_absolute_url(self): 
     return reverse('appName:country_info', args=(self.id,)) 
    #etc... 

country_edit.html:

<form action="" method="post"> 
    {% csrf_token %} 
    {{ form.as_p }} 
    <input type="submit" value="Update" /> 
    <input type="submit" name="cancel" value="Cancel" /> 
</form> 

但是我已经得到这个错误:

Traceback (most recent call last): 
    File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py", line 42, in inner 
    response = get_response(request) 
    File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response 
    response = self.process_exception_by_middleware(e, request) 
    File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response 
    response = wrapped_callback(request, *callback_args, **callback_kwargs) 
    File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py", line 68, in view 
    return self.dispatch(request, *args, **kwargs) 
    File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py", line 88, in dispatch 
    return handler(request, *args, **kwargs) 
    File "C:\Users\username\Envs\projName\appName\views.py", line 38, in post 

    url = self.object.get_success_url() 
AttributeError: 'CountryEditView' object has no attribute 'object' 

这对我没有意义,因为documentation pageWhen using UpdateView you have access to self.object, which is the object being updated.有什么我做错了吗?

回答

3

你这样做,但是你忽略了post(),这是object被分配的地方。所以,你需要调用的方法直接获得自己吧:

class CountryEditView(generic.edit.UpdateView): 
    model = Country 
    fields = ['name'] 
    template_name_suffix = '_edit' 

    def post(self, request, *args, **kwargs): 
     if "cancel" in request.POST: 
      object = self.get_object() 
      url = object.get_absolute_url() 
      return HttpResponseRedirect(url) 
     else: 
      return super(CountryEditView, self).post(request, *args, **kwargs) 

你应该看看CCBV - 你可以看到每个方法是很容易做的事情。

旁注:

1)你可以只传递一个对象redirect它是否get_absolute_url定义:

def post(self, request, *args, **kwargs): 
    if "cancel" in request.POST: 
     object = self.get_object() 
     return redirect(object) 
+0

为什么定义两次'POST'? – user2361174

+0

呵呵 - 不知道这是怎么发生的 - 编辑它 –