Home > Back-end >  Django - How to redirect users without hard-coding URLS
Django - How to redirect users without hard-coding URLS

Time:11-08

I am creating Django Application. We want user to be redirected to new screen on button click, but we don't want to have to hardcode URL.

We have a top level screen, and we want to redirect user to screens after they click a button on the Level screen, However, we have multiple level screens so it would't make sense to hardcode each URL for each section of the Level screen.

Here is the view for the Level1 Screen as an example:

def level1(request):
    return render(request, 'Levels/level/Welcome1.html')

As you can see, we render out Welcome1.html, however, we also have other Welcome screens assosiated with level 1, like Welcome2.html and Welcome3.html.

This is the URL for level 1:

path('levels/level1/', views.level1, name = "level1")

Again, it would't make sense for us to have a URL for each level (level 1, level2) and then all the subscreens for them such as Welcome1, Welcome2.

How can I make it so I can associate different screens with a URL and not have to render them out individually?

I am not sure how to go about doing this problem. We are working on big project and can give part of budget to someone who helps solve.

CodePudding user response:

Django has a "parser" which allows you to define dynamic links within the urls.py

A dynamic url can for example be a way to access different pictures in the /media folder. For example: host/media/{?}. This isn't how you write it in django, but this is just to explain the logic behind dynamic urls. The {?} in this scenario would be to access any file within the media folder. sort of like if you grabbed the arguments from a terminal application.

Particularly in your case, it would look something like this:

path('levels/level<int:num>/', views.levelHandler)

This would get any integer written after level and pass it along as an argument to a levels function where you can route it to the different levels you have in the script.

The function can look something like this:

def levelHandler(request, num=0):
    if(num == 0): return level0(request)
    if(num == 1): return level1(request)
    ...

This should solve the problem. I'll edit the answer incase i missed something. Give it a shot and tell me how it goes

  • Related