S
S
Stanislav Shabalin2020-09-12 23:27:34
Django
Stanislav Shabalin, 2020-09-12 23:27:34

Passing argument from template to view?

I'm trying to create a generic url to call a view with and without argument passing.

For example: site.ru/contacts I can open directly without a link and I want to open it from the link in the template, while not on the main page.
Now my link looks like this: site.ru/design/contacts and I have to create two URLs to call the view.
The point is that if you follow the link site.ru/contacts without passing an argument, then the full page of contacts opens, and if with an argument, then a sidebar should be displayed on the page

#urls.py
urlpatterns = [
  path('admin/', admin.site.urls),
  re_path(r'(?P<section>/)contacts/$', views.contacts, name='contacts-url'),
  path('contacts/', views.contacts, name='contacts-url'),
  re_path(r'about/$', views.about_us, name='about-us-url'),
  re_path(r'^thanks/$', views.message_thanks, name='thanks-url'),
  path('', include('design.urls')),
]

#views.py

def contacts(request, section=''):

  context = {
    'selected_section': section,
    'classes': ['contacts'],
  }
  print('!!!'+section)
  if section != '':
    context['classes'].append('is-nav')

  return render(request, 'contacts.html', context)

#sidebar.html

...
<li><a href="{% url 'contacts-url' section='design' %}">Контакты</a></li>
...


Maybe there is a more logical way, using one url?

Thanx

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rodion, 2020-09-13
@Starck43

Probably if you use this method. Swap section/ and contacts/ and make the last one optional:

urlpatterns = [
    re_path(r'contacts/(?P<section>\w+)/', views.contacts),
]

def contacts(request, section=''):
    ...
    return render(request, 'contacts.html', context)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question