django DeleteView - 如何传递用于 success_url 的参数?

标签 django django-views

我正在使用DeleteView,我希望 success_url 成为调用DeleteView 的 View 。此 success_url 需要向其传递两个参数。

型号

class Part(models.Model):
    name = models.CharField(max_length=20)
    worker = models.ForeignKey(Worker, on_delete=CASCADE)
    company = models.ForeignKey(Company, on_delete=CASCADE)

urls.py

path('listparts/<uuid:company_pk>/<uuid:worker_pk>/', views.listparts, name='listparts'),
path('deletepart/<uuid:part_pk>/', views.PartDeleteView.as_view(), name='deletepart'),

查看

def listparts(request, company_pk, worker_pk):
    ...
    ...

class PartDeleteView(DeleteView):
    model = Part
    success_url = reverse_lazy('listparts' company_pk worker_pk)

列表部分模板

<a href="{% url 'deletepart' part_pk %}">Delete this part</a>

confirm_delete模板

<div class="row">
    <div class="col-md-3">
      <form class="form-group">
        {% csrf_token %}{{ form|crispy }}
          <div class="form-group">
            <p>Are you sure you want to delete "{{ object }}"?</p>
          <input type="submit" class="btn btn-primary mt-2 mb-2" value="Update">
        </div>
      </form>
    </div>

但我不知道如何在DeleteView中处理这个问题。我确信这与处理 kwargs 有关,但我仍在学习 kwargs 如何在 def get_success_url(self)

中工作

编辑我已经包含了Part的模型和confirm_delete的模板。根据 Willem Van Onsem 的评论,我已将 PartDeleteView 修改为:

class PartDeleteView(DeleteView):
    model = Part

    def get_success_url(self, *args, **kwargs):
        return reverse_lazy('listparts', args={'company_pk':self.company.pk, 'worker_pk':self.worker.pk})

使用此代码,在单击链接删除部件后,我将进入 confirm_delete 模板。单击更新按钮不会执行任何操作。页面被带到success_url,该部分没有被删除。

最佳答案

我认为在这里覆盖 get_success_url 更有意义,因此将其实现为:

from django.urls import <strong>reverse</strong>

class PartDeleteView(DeleteView):
    model = Part

    def <strong>get_success_url</strong>(self):
        return reverse(
            'listparts',
            kwargs={
                'company_pk': self.object.company_id
                'worker_pk': self.object.worker_id
            }
        )

这里 self.object 是已被删除的对象,因此我们可以将该对象的 company_idworker_id 访问为 kwargs=... 为我们生成的 URL。

关于django DeleteView - 如何传递用于 success_url 的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68882385/

相关文章:

django - Django 中的灵活分页

python - solr-thumbnail - 一些 jpeg 没有被处理

Django 和软删除 : Implementation architecture

python - Django 说 "didn' t 返回一个 HttpResponse 对象。相反,它返回 None 。”

python - 如何在 Django 中更新 ImageField?

django - 在 Django 中更新具有外键的表中的数据

python - 获取django中多个复选框的值

django - 自定义用户模型错误

python - 获取相关模型值的字典

python - 动态添加字段到表单 python django