pythondjangohttp-redirectdjango-modelsdynamic-url

How to redirect to a dynamic url in django


I am working on a django project. 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. But because the output_page is a dynamic url, I am not able to redirect.

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

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

where test-001 is the instance_id in the model.

The output_page should filter all the data in the model with instance_id test-001


Solution

  • 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.

    References

    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