'UpdateView'对象没有属性'object'

时间:2017-03-18 03:08:33

标签: python django django-views

所以我一直在尝试为我一直在使用的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'

这对我来说没有意义,因为http://i.imgur.com/rebvLRB.jpgWhen using UpdateView you have access to self.object, which is the object being updated.我有什么问题吗?

1 个答案:

答案 0 :(得分:4)

你这样做,但是你覆盖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) 。所以你需要调用方法直接自己获取它:

get_absolute_url

你应该看看CCBV - 你可以很容易地看到每种方法的作用。

附注:

1)如果对象已定义def post(self, request, *args, **kwargs): if "cancel" in request.POST: object = self.get_object() return redirect(object) ,您只需将对象传递给redirect

Transform clone = Instantiate(spawnPrefab, spawnPoint.position, spawnPoint.rotation);
Destroy(clone.gameObject, 3f);