简体   繁体   English

如何重定向到 django 中的动态 url

[英]How to redirect to a dynamic url in django

I am working on a django project.我正在做一个 Django 项目。 in the project I have a dynamic url as follows在项目中我有一个动态网址如下

app_name = 'test'

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

There exists two pages in the application.应用程序中有两个页面。 In the root page there exists a form which when submitted should redirect to the output_page .root页面中存在一个表单,提交时应重定向到output_page But because the output_page is a dynamic url, I am not able to redirect.但是因为output_page是一个动态 url,所以我无法重定向。

Here is my views file这是我的意见文件

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})

Here is the Model这是模型

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)

When the redirect happens I want the url to be as follows当重定向发生时,我希望 url 如下

http://127.0.0.1:8000/output/test-001

where test-001 is the instance_id in the model.其中test-001是模型中的 instance_id。

The output_page should filter all the data in the model with instance_id test-001 output_page 应该使用 instance_id test-001过滤模型中的所有数据

你可以这样做

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

Solution解决方案

The direct solution to your question would be the following:您的问题的直接解决方案如下:

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))

However, it would be worth investigating class based views.但是,值得研究基于类的视图。 I recommend using django's built in RedirectView for this purpose.为此,我建议使用 django 内置的RedirectView

References参考

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

Django RedirectView: https://docs.djangoproject.com/en/3.1/ref/class-based-views/base/#redirectview Django 重定向视图: https : //docs.djangoproject.com/en/3.1/ref/class-based-views/base/#redirectview

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM