Home > Back-end >  Reverse resolution of URLs in Django with multiple url parameters
Reverse resolution of URLs in Django with multiple url parameters

Time:08-22

In my blog app I need to show articles based on the url:

app_name = 'blog_app'

urlpatterns = [
    path('<int:user_id>/<int:year>/<int:month>', views.IndexView.as_view(), name='index'),
    path('<int:user_id>/<int:year>/<int:month>/<int:article_id>', views.DetailView.as_view(), name='detail'),
]

The structure of the project is: myblog points to portal (for login); after login portal points to blog_app (which contains the articles list). So the steps to show articles are:

mysite_index --> portal_login --> blog_app_index

In portal app, after login, using a button I want to go to the index view of blog_app. So I need to specify all url parameters, and I'm trying to do it in this way:

{% if user.is_authenticated %}
<a href="
  {% url 'blog_app:index' 
       user_id = user.id 
       year = {% now "Y" %} 
       month = {% now "m" %} 
  %}
">
  <button  type="button">Go</button>
</a>
{% endif %}

I don't know why the URL becomes: http://127.0.0.1:8000/portal/{% url 'blog_app:index' user_id = user.id year = 2022 month = 08 %}

What I'm doing wrong? How I should do this type of reversing?

CodePudding user response:

You cannot put {% ... %} inside another {% ... %}. Another thing is you are placing a lot of "enters" and whitespaces into href and curly brackets. Do it in one line and leave no whitespace unless it's necessary (even around =), which is encoded with .

You can get current year and current month with adding timezone.now() as context, in example:

from django.utils import timezone
...
context = {..., "today": timezone.now()}

Then in template:

<a href="{% url 'blog_app:index' user_id=user.id year=today.year month=today.month %}">
  • Related