Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – Testing a view name retrieved from a url parameter ie. ref=home

Simply put, I am trying to test a view name, captured from a URL parameter, within one of my view functions to see if it is valid. If not, to redirect to another page.

For example, take this url…

www.site.com/users/?ref=view_name

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Then in my view

    ref = request.GET.get('ref', None)
    return redirect(ref) if ref else redirect('users')

The problem is, of course, that if a user alters the ref parameter, it will kick back a 404. I was hoping to be able to test if ref=home is a valid view and return it, if not then redirect to another view.

I have been messing with Django’s resolve and reverse but I am not getting the results I was looking for.

I also tried to use a try/finally in all sorts of ways mixed in with resolve and reverse. Yeah, dumb…I know.

try:
     if ref:
          return redirect(resolve(ref))
finally:        
     return redirect('user')

I have searched for almost two hours to try to fund a succinct way to do this.

Any help would be appreciated!

>Solution :

The problem is that you are passing a view name to resolve() which requires a URL path. To protect against 404, you need to first reverse() the view name to get a path. Then you can use that path with resolve() to check if the path exists.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading