我有班级人员
class People (models.Model):
first_name = models.CharField(max_length = 50)
last_name = models.CharField(max_length = 50)
email = models.EmailField(blank = True)
grade = models.CharField(max_length = 2)
def __unicode__(self):
return '%s %s' % (self.first_name, self.last_name)
我有删除视图
def delete(request):
query = People.objects.get(pk=id)
query.delete()
return HttpResponse("Deleted!")
我有html模板代码
{% for person in people_list %}
<TR ALIGN="CENTER">
<td>{{ person.first_name }}</td>
<td>{{ person.last_name }}</td>
<td>{{ person.email }}</td>
<td>{{ person.grade }}</td>
<td><form action="/modify.html">
<input type="submit" value="Modify">
</form></td>
<td><form action="/delete.html">
<input type="submit" value="Delete">
</form></td>
</TR>
{% endfor %}
如何从模板中获取person.id并将其放在删除视图中并删除与我想要的person.id相对应的对象。
答案 0 :(得分:4)
您需要拥有delete
函数(顺便说一句,将其命名为其他内容,如delete_person
)参与参数,pk。
def delete_person(request, pk):
...
...
然后在你的urlconf中,做一些像这样的事情
url(r'^delete_person/(?P<pk>\d+)/$', 'delete_person', name='delete_person')
然后在模板中生成URL,如此
{% url 'delete-person' person.id %}
PS - 无需将您的网址以.html
PPS - 在视图中进行一些验证是个好主意,以确保用户有权删除此人。
答案 1 :(得分:4)
我认为您可以使用链接而不是表单:
替换此行
<td>
<form action="/delete.html">
<input type="submit" value="Delete">
</form>
</td>
用这个
<td><a href="/delete/{{ person.id }}">Delete</a></td>
在urls.py中,您应添加以下行,以便将您的视图与网址相关联:
url(r'^delete/(?P<person_pk>.*)$', 'person.views.delete' name='delete-person'),
然后改变你的观点:
def delete(request, person_pk):
query = People.objects.get(pk=person_pk)
query.delete()
return HttpResponse("Deleted!")
答案 2 :(得分:1)
要在@scriptmonster上进行扩展,我尝试将查询包装起来,只是正确返回了404
# urls.py
path("foo/<int:pk>/", views.ModelView.as_view(), name="foo-detail"),$
和
# views.py
from django.http import HttpResponse, HttpResponseNotFound
class ModelView(View):
model = Foo
def delete(self, request, *args, **kwargs):
foo_id = kwargs["pk"]
try:
query = Foo.objects.get(pk=foo_id)
query.delete()
return HttpResponse("Deleted!")
except:
return HttpResponseNotFound()
答案 3 :(得分:0)
from test_app.(your Application Name) import views
path('delete/(?p<id>\d+)/',views.delete_View(),
答案 4 :(得分:0)
通过基于类的视图删除对象:
views.py
from django.views import generic
from django.urls import reverse_lazy
class PeopleDeleteView(generic.edit.DeleteView):
model = People
success_url = reverse_lazy('people_list')
urls.py
...
path('delete/<int:pk>/', views.PeopleDeleteView.as_view(), name='delete'),
您需要一个删除确认模板:
myapp/people_confirmation_delete.html
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm">
</form>