我有一个modelformset,如下所示:
views.py
def manage_authors(request):
AuthorFormSet = modelformset_factory(Author, fields=('name', 'title', 'birth_date'))
if request.method == 'POST':
if "del_btn" in request.POST:
query = Author.objects.get(...).delete()
formset = AuthorFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
formset = AuthorFormSet(queryset=Author.objects.all())
print "yes"
else:
formset = AuthorFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
formset = AuthorFormSet(queryset=Author.objects.all())
else:
formset = AuthorFormSet(queryset=Author.objects.all())
return render(request, "manage_authors.html", {"formset": AuthorFormSet, })
manage_authors.html
<form method="post" action="/manage_authors.html">{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{ form.id }}
<ul>
{{ form.name }} {{ form.title }} {{ form.birth_date }}
<input type="submit" name="del_btn" value="Delete"/>
</ul>
{% endfor %}
<input type='submit' name="edit_btn" value='Edit / Add'/>
我可以定义什么查询,以便删除按钮可以工作?
现在,我知道必须删除哪一行有问题。
提前致谢
答案 0 :(得分:3)
首先,我建议您在admin.py中注册您的用户模型:
admin.site.register(Author)
Django会处理剩下的事情。
但如果您想使用此代码执行此操作,请执行以下操作:
<form method="post" action="/manage_authors.html">{% csrf_token %}
{{ formset.management_form }}
for form in formset %}
{{ form.id }}
<ul>
{{ form.name }} {{ form.title }} {{ form.birth_date }}
<input type="submit" name="del_btn{{ form.instance.id }}" value="Delete"/>
</ul>
{% endfor %}
<input type='submit' name="edit_btn" value='Edit / Add'/>
因此对象的主键将与删除按钮名称相关。
现在,在views.py中:
import re, urllib
def manage_authors(request):
AuthorFormSet = modelformset_factory(Author, fields=('name', 'title', 'birth_date'))
if request.method == 'POST':
enurl=urllib.urlencode(request.POST) # To convert POST into a string
matchobj=re.search(r'del_btn\d', enurl) # To match for e.g. del_btn1
btnname=matchobj.group() # Contains matched button name
pri_key=btname[-1] # slice the number of btn to identify primarykey
if matchobj:
query = Author.objects.get(pk=pri_key).delete()
formset = AuthorFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
formset = AuthorFormSet(queryset=Author.objects.all())
print "yes"
else:
formset = AuthorFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
formset = AuthorFormSet(queryset=Author.objects.all())
else:
formset = AuthorFormSet(queryset=Author.objects.all())
return render(request, "manage_authors.html", {"formset": AuthorFormSet, })