python - Django 重定向到模板传递模型

标签 python django

我想做的事情是重定向到用户删除项目时所在的同一页面。使用“django.views.generic.edit”(DeleteView)删除后,我可以将所有需要的信息收集到模型中并获取我需要的特定类别。问题是我怎样才能创建这个请求url呢?

这样我就可以到达 http://127.0.0.1:8000/productlist/floor/

<a class="dropdown-item" href="{% url 'productlist' 'floor' %}" >

View .py

class LampDelete(DeleteView):
model = Lamp
#success_url = reverse_lazy('index')

def get_success_url(self):
    categ = self.object.category
    lamps = Lamp.objects.filter(category=categ)
    return redirect('productlist', {'lamps': lamps})

url.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'),]

那么我应该使用什么方法以及如何使用选定的类别模型重定向到我的模板。如果有人能提供一个例子将非常感激。

最佳答案

实际上您在 .get_success_url() 中仍然有对象,

来自source code :

class DeletionMixin(object):
    def delete(self, request, *args, **kwargs):
        """
        Calls the delete() method on the fetched object and then
        redirects to the success URL.
        """
        self.object = self.get_object()
        success_url = self.get_success_url()
        self.object.delete()
        return HttpResponseRedirect(success_url)

如您所见,它首先计算 success_url,然后删除该对象。

你做错了什么:

  1. 您没有将 url 作为 str 对象提供,而是调用 redirect 来触发重定向并跳过整个删除过程。
  2. 使用提供queryset的url参数进行redirect查看,而不是str,因为它一直在等待([a-z0- 9]+)

我相信在 productlist View 中,您期望某种类别名称,您的产品将通过该名称进行过滤

那么你可以做什么:

  1. .get_success_url() 中返回有效的 str 对象

例如

class LampDelete(DeleteView):
    model = Lamp

    def get_success_url(self):
        category = self.object.category
        return reverse('productlist', args=[category])

关于python - Django 重定向到模板传递模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43824788/

相关文章:

django - 内网Django项目共享 `auth_user`和 `django_session`表是否安全?

Python:鼠标交互获取数据点对应信息

django - 复制 django 模型实例的所有字段

python - Django 从 1.3.1 迁移到 1.7.4 并不断收到服务器错误 500

python - Django View 检查第二个模型的值

python - 列 <column> 不存在(Django 1.8)

python - 具有元组列名称的 Pandas .loc

python - Restful API Automation 使用 ROBOT Framework 好不好

python - Pandas read_hdf 按日期和时间范围查询

python - 在 NixOS 中,如何解决冲突?