1

我有這將在下面所示的modelformset:Django的刪除按鈕操作的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'/> 

enter image description here

什麼查詢我可以定義,以便刪除按鈕可以工作?

現在,我知道哪一行必須被刪除。

在此先感謝

回答

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, }) 
+2

而不是使用{{form.id}}我用{{form.instance.id}}和它的工作的。重要的是將{{form.id}}添加到模板中,以避免引發MultiValueDictKeyError。謝謝@Yugandhar –