我正在使用Django 1.10.6而我正在使用基于类的视图DeleteView。
示例myapp / views.py:
from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy
from myapp.models import Author
class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('author-list')
示例myapp / author_confirm_delete.html:
<form action="" method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm" />
</form>
因为删除是一项严肃的操作,我想添加更强大的确认,以便用户在删除作者之前需要输入作者姓名(并且必须匹配。类似于删除存储库的github确认)。我想这可能会被实现为某种形式验证。
添加此类确认的django方法是什么?
答案 0 :(得分:1)
我会创建一个Django ModelForm,然后它可以将单独的HTML输入字段与模型实例字段进行比较。在视图中,如果表单验证失败...则不会发生删除。
# myapp/forms.py
from django import forms
class ConfirmDeleteForm(forms.ModelForm):
confirm = forms.CharField(label='Confirm your name', max_length=100)
class Meta:
model = Author
fields = []
def clean(self):
confirm = super().clean().get('confirm')
if self.instance.name.lower() != confirm.lower():
raise forms.ValidationError('Confirmation incorrect')
# myapp/views.py
from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy
from myapp.models import Author
from myapp.forms import ConfirmDeleteForm
class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('author-list')
def get_context_data(self, **kwargs):
"""
Overridden to add a confirmation form to the context.
"""
context = super().get_context_data(**kwargs)
if 'form' not in kwargs:
context['form'] = ConfirmDeleteForm()
return context
def post(self, request, *args, **kwargs):
"""
Overridden to process the confirmation form before deleting
the object.
"""
self.object = self.get_object()
form = ConfirmDeleteForm(request.POST, instance=self.object)
if form.is_valid():
return self.delete(request, *args, **kwargs)
else:
return self.render_to_response(
self.get_context_data(form=form),
)
<!-- myapp/author_confirm_delete.html -->
<form method="post">
{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
{{ form }}
<input type="submit" value="Confirm" />
</form>