Md. Imrul Hasan
Md. Imrul Hasan

Reputation: 29

How to pass a variable from template to views in django?

index.html

{% if request.session.visitor_language == 'en'  %}
                                
   {% with current_page=request.resolver_match.url_name %} 
       {{current_page}}    
   {% endwith %}

   My name is  Khan <a style="color: blue;" href="{% url 'change_language' %}?current_page={{current_page}}">BN</a>
{% endif %}

Here I am trying to send the value of current_page to views through urls

urls.py

path('home/change_lang/$', views.change_visitor_language, name='change_language'), 

views.py

def change_visitor_language(request,current_page):
    print(current_page)

The Error I am getting from Screen

TypeError at /home/change_lang/$

The Error I am getting in command line

TypeError: change_visitor_language() missing 1 required positional argument: 'current_page'

Upvotes: 0

Views: 350

Answers (1)

Prakhar Shrivastava
Prakhar Shrivastava

Reputation: 101

Since you're sending current_page as a query param it will not be added as a method argument to the view.

You can access it in your view like this:

def change_visitor_language(request):
    current_page = request.GET.get('current_page')

Also, change your HTML like this

{% if request.session.visitor_language == 'en'  %}
                                
   {% with current_page=request.resolver_match.url_name %} 
       {{current_page}}    
       My name is  Khan <a style="color: blue;" href="{% url 'change_language' %}?current_page={{current_page}}">BN</a>
   {% endwith %}

{% endif %}

Upvotes: 1

Related Questions