Home > Back-end >  Django passing a variable through the path, causing path repetitions. how to get out of that loop?
Django passing a variable through the path, causing path repetitions. how to get out of that loop?

Time:09-30

I know this is an armature question but here goes.

I have a url path as follows: path('projects/<s>', PL.projects),

and i pass a string from the html template by putting it into an herf tag like so projects/some_string. this works once but then the base url changes to <ip>/projects/some_string. so when i try to excite the path to pass a string in that domain then I get an error as the url is now <ip>/projects/projects/some_string.

how do i set it up so that i can pass as many strings as possible as many times as possible without having to clean my url in the browser everytime.

Thanks for the help.

CodePudding user response:

Learn how to use the reverse() function and the url template tag and your problems will be gone.

Those functions are built-in with Django and can handle all of that nasty URL stuff.

Reverse: https://docs.djangoproject.com/en/3.2/ref/urlresolvers/

Url Template tag: https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#url

CodePudding user response:

Django has inbuilt url lookup features

path("some_random_url_link_1/", views.Link1View.as_view(), name="url_link_1"),
path("some_random_url_link_2/<int:some_id>/<slug:some_slug>/", views.Link2View.as_view(), name="url_link_2"),

in your template you can use it like this, and pass variables/parameters like this. FYI you don't need to use {{variable}} tag here

<a href="{% url 'url_link_1' %}" >Link 1</a>
<a href="{% url 'url_link_2' some_id=id1 some_slug=random_slug %}" >Link 2</a>
  • Related