删除对象并传递一些成功消息后,如何重定向到同一视图?
HTML:
<form action="{% url 'lamp-delete' lamp.id %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="product_id" value="{{ lamp.id }}" />
<button type="submit" class="btn btn-outline-danger btn-sm">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</form>
views.py
def index(request):
lamps = Lamp.objects.all()
return render(request, 'index.html', {'lamps': lamps})
def productlist(request, categ):
MEDIA_URL = settings.MEDIA_URL
lamps = Lamp.objects.filter(category=categ)
return render(request, 'productlist.html', {'lamps': lamps, 'MEDIA_URL': MEDIA_URL})
class LampDelete(DeleteView):
model = Lamp
success_url = reverse_lazy('index')
urls.py
urlpatterns =[
url(r'^$', views.index, name='index'),
url(r'^productlist/([a-z0-9]+)/$', views.productlist, name='productlist'),
url(r'^accounts/', include('allauth.urls')),
url(r'productlist/(?P<pk>[0-9]+)/delete/$', views.LampDelete.as_view(), name='lamp-delete'),
]
我正在使用django.views.generic.edit,现在使用reverse_lazy成功删除项目后,我可以重定向到静态页面,但我正在尝试重载现有模型并将带有字符串的变量传递给此视图'productlist ”。如果有人可以提供一个例子,我会非常感激。
答案 0 :(得分:0)
Classy Class Based Views是基于类的视图的良好资源。查看https://ccbv.co.uk/projects/Django/1.10/django.views.generic.edit/DeleteView/,您可以看到有.get_success_url()
方法,在那里您还可以访问self.request
以传递某种变量。
然而,对于简单的成功消息,我会看一下Django的messages framework
from django.contrib import messages
class LampDelete(DeleteView):
model = Lamp
success_url = reverse_lazy('index')
def delete(self, request, *args, **kwargs):
obj = self.get_object()
messages.success(request, '{} was deleted'.format(obj.name))
return super(LampDelete, self).delete(request, *args, **kwargs)
然后在你的模板中:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
(这只是Django文档中逐字逐句的例子。)