从数据库Django中删除已检查的项目

时间:2017-07-03 02:59:01

标签: python django checkbox django-models django-forms

我正在尝试删除"删除"在选中要删除的行的复选框后,选择了按钮。我不知道我的代码的哪一部分是错误的,并且当选中复选框并且"删除"时,导致特定的行没有从数据库中删除。按钮已被选中。现在,当"删除"按钮已被选中,我仍然可以看到我表中的特定行。 (这意味着它没有从数据库中删除,因为我的表只显示存储在数据库中的数据。)任何人都可以在我提供的代码中发现任何错误吗?

add_remove_scholarship.html

<input type="submit" name="delete" value="Delete Selected Scholarship"   >
<form method="POST" action="">
{% csrf_token %}
    <table  id="example" class="display" cellspacing="0" width="100%" border="1.5px">
    <tr align="center">
        <th style="border-top: none;border-right: none;border-left: none"></th>
        <th> Scholarship </th>
        <th> Faculty </th>
        <th> Open Date </th>
        <th> Close Date </th>
    </tr>
    {% for item in query_results %}
    <tr align="center">
        <td style="border: none;"><input type="checkbox" name="item" value="{{item.doc}}">
        <td>{{item.doc}}</td>
        <td>{{item.faculty}}</td>
        <td>{{item.openDate}}</td>
        <td>{{item.closeDate}}</td>
    </tr>
    {% endfor %}
    </table>
</form>

views.py

def scholarship(request, id=None):
query_results = []
if request.POST.get('delete'):
   Scholarship.objects.filter(id__in=request.POST.getlist('scholarship')).delete()
   return redirect('/hrfinance/lscholarship/')
elif request.POST.get('add'):
    form = ScholarshipForm(request.POST)
    if form.is_valid():
        scholarship = form.save(commit=False)
        scholarship.save()
        return redirect('/hrfinance/lscholarship/')
else:
    form = ScholarshipForm()
    id = request.GET.get('scholarship')
query_results = Scholarship.objects.all()
data = {
        'query_results':query_results,
        'form':form
       }
return render(request, 'hrfinance/add_remove_scholarship.html', data)

class ScholarshipForm(forms.ModelForm):
    class Meta:
        model = Scholarship
        fields = '__all__'

models.py

class Scholarship(models.Model):
    doc = models.TextField("Doc", max_length=1000)
    faculty = models.TextField("Faculty", max_length=1000)
    openDate = models.DateField("Opening Date", max_length=8)
    closeDate = models.TextField("Closing Date", max_length=20, default="Jan 1, 2017")

    def __str__(self):
        return self.doc

0 个答案:

没有答案