我想在更新/编辑表单中创建一个Cancel
按钮,但我一直收到AttributeError
例外:
'PatientUpdate' object has no attribute 'object'
视图:
class PatientUpdate(LoginRequiredMixin, UpdateView):
model = User
form_class = MyPatientEditForm
template_name = "patient/patient_edit.html"
success_url = reverse_lazy('patient_list')
def post(self, request, *args, **kwargs):
if "cancel" in request.POST:
url = self.get_success_url()
return HttpResponseRedirect(url)
else:
return super(PatientUpdate, self).post(request, *args, **kwargs)
HTML:
<button class="btn" type="submit" name="cancel" value="Cancel" />Cancel</button>
回溯:
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/braces/views.py" in dispatch
107. request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "/Users/Maziar/Dropbox/Sandbox/tutorial/web/views.py" in post
60. url = self.get_success_url()
File "/Library/Python/2.7/site-packages/django/views/generic/edit.py" in get_success_url
133. url = self.success_url % self.object.__dict__
Exception Type: AttributeError at /patient/edit/3
Exception Value: 'PatientUpdate' object has no attribute 'object'
我到底做错了什么?此外,我考虑过是否可以在模板中获取success_url
变量,只需在按钮中使用它而不执行整个POST
过程?
更新
当表格正常提交时,success_url
完全正常。
答案 0 :(得分:8)
如果用户按“取消”按钮,他会重定向到患者列表?那么为什么不在没有任何额外逻辑的情况下创建简单的链接:
<a href="{% url 'patient_list' %}">Cancel</a>
答案 1 :(得分:2)
get_success_url
取决于实际拥有该对象。试试这个:
def post(...):
if "cancel" in request.POST:
self.object = self.get_object()
# ...
这样,get_success_url
将有权访问您正在编辑的实例,并且重定向应该有效。
获取模板的成功网址也应该有效:
def get_context_data(self, **kwargs):
kwargs['success_url'] = self.get_success_url()
return super(..., self).get_context_data(**kwargs)
答案 2 :(得分:0)
我已经更改了submit_line.html模板,并且使用了request.META.HTTP_REFERER可以返回上一个更改列表(包含过滤信息!)来自哪里:
<div class="submit-row">
{% if show_save %}
<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" />{% endif %}
{% if show_delete_link %}
{% url opts|admin_urlname:'delete' original.pk|admin_urlquote as delete_url %}
<p class="deletelink-box"><a href="{% add_preserved_filters delete_url %}" class="deletelink">{% trans "Delete" %}</a></p>
{% endif %}
{% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" />{% endif %}
<a href="{{ request.META.HTTP_REFERER }}"><input type="button" name="Cancel" value="Cancel"></a>
{% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" name="_continue" />{% endif %}
</div>