如何在Django中重定向到动态URL

3

我正在开发一个Django项目。在这个项目中,我有一个动态 URL,如下所示:

app_name = 'test'

urlpatterns = [
    path('root', views.root, name='root'),
    path('output/<str:instance>', views.output_page, name='output_page'),
]

在该应用程序中存在两个页面。在 root 页面中存在一个表单,当提交时应重定向到 output_page。但是因为 output_page 是一个动态 URL,所以我无法进行重定向。
以下是我的视图文件。
def root(request):
    if request.method == 'POST':

        name = request.POST.get('name')
        job = request.POST.get('job')

        return redirect("test:output_page")

    return render(request, 'test/root.html')

def output_page(request, instance):

    record = Object.objects.all(Instance_id=instance)

    return render(request, 'test/output_page.html', {'record': record})

这里是模型

class Object(models.Model):
    Name = models.CharField(max_length=200, null=True, blank=True)
    Job = models.CharField(max_length=200, default="")
    Instance_id = models.CharField(max_length=200)

当重定向发生时,我希望URL如下所示。
http://127.0.0.1:8000/output/test-001

其中test-001是模型中的instance_id。

output_page应该通过过滤instance_id为test-001的模型中所有数据来实现。


3个回答

3
您可以像这样操作:

return redirect(reverse("test:ouput_page",kwargs={'instance':str(instance_id)}))

返回重定向到输出页面的实例ID。

嗨。我现在遇到了这个错误:Reverse for 'output_page' with no arguments not found. 1 pattern(s) tried: ['output/(?P<instance>[^/]+)$'] - Sashaank
instance is given as a string in the URL so you need to send str(instance_id) in kwargs - Adithya
嗨。我解决了这个错误。我在模板中引用了页面。一旦我删除了它,错误就被解决了。非常感谢。 - Sashaank

3

解决方案

针对您的问题,直接的解决方案如下:

from django.urls import reverse
from django.shortcuts import get_object_or_404
...
instance = get_object_or_404(Object, name=name, job=job)
redirect(reverse('test:output_page', args=instance))

然而,值得探究基于类的视图。我建议为此使用 django 内置的 RedirectView

参考文献

Django Reverse: https://docs.djangoproject.com/en/3.1/ref/urlresolvers/

Django RedirectView: https://docs.djangoproject.com/en/3.1/ref/class-based-views/base/#redirectview


谢谢回复。我现在遇到了这个错误:output_page()缺少一个必需的位置参数:“instance” - Sashaank
你可以将args和kwargs传递给reverse函数。我已经更新了我的答案以反映这一点,但也在参考文档中注明了。 - pygeek
嗨。我现在遇到了这个错误:Reverse for 'output_page' with no arguments not found. 1 pattern(s) tried: ['output/(?P<instance>[^/]+)$'] - Sashaank
在重定向之前,您需要确保实例存在并已传递。 - pygeek
嗨。我已经解决了错误。我在模板中引用了页面,一旦我移除它,错误就被解决了。非常感谢。 - Sashaank

-1
instance_model = "xyz"
return redirect('output_page', instance=str(instance_model))
(or)
return redirect('test:output_page', instance=str(instance_model))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接