Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: static() got an unexpected keyword argument 'document_root' in Django
After review questions before mine and apply changes Im keep receiving this error, as below. I tried to change all recomendations but it doesn't work anyway. I have not issue to recover static images, the problem comes when I attempt catch dinamic image from database. TypeError: static() got an unexpected keyword argument 'document_root' setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static #from django.utils.text import slugify from django.contrib.auth.models import User from django.shortcuts import render from backoffice.views.section import * from backoffice.views.user import * import backoffice.views.home import frontoffice.views urlpatterns = [ path('admin/', admin.site.urls), path('backoffice/', backoffice.views.home.management, name="backoffice"), # all list area path('backoffice/all_sections', SectionListView.as_view(), name="all_section"), path('backoffice/all_users', UserListView.as_view(), name="all_users"), # all frontoffice area path('', frontoffice.views.home, name="home"), path('about/', frontoffice.views.about, name="about"), path('contact/', frontoffice.views.contact, name="contact"), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model class Profile(models.Model): """ Model Profile extending funcionalities from our user model""" user = models.OneToOneField(User, on_delete=models.CASCADE) section = models.ForeignKey(Section, on_delete=models.CASCADE) ceo = models.BooleanField() employee = models.BooleanField() seller = models.BooleanField() guess = models.BooleanField(default=True) photouser = models.ImageField( upload_to='backoffice/static/avatars', default='backoffice/static/avatars/', blank=True, null=True ) cargo = models.CharField(max_length=100) notas = models.TextField(blank=True) def __str__(self): """Returning username.""" return self.user.username html … -
ChainedManyToManyField not working properly in django
I am trying to make dependent drop down in django admin page for models : class ItemCode(models.Model): **Name=models.CharField(max_length=50,blank=True,null=True)** def __str__(self): return self.Name class Vendor(models.Model): first_name = models.CharField(_('first name'), max_length=150, blank=False) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField(_('email address'), blank=False) PhoneNo=models.CharField(_('Phone No'),max_length=150, blank=False) # new **Item=models.ForeignKey(ItemCode,on_delete=models.CASCADE,verbose_name="Item** Code",blank=True,null=True) class Offer(models.Model): Auction_id=models.CharField(max_length=20,blank=False,null=False,verbose_name = "Auction ID") Item=models.ForeignKey(ItemCode, on_delete=models.CASCADE,blank=True,null=True,unique=False,related_name='itemcode') Vendor = ChainedManyToManyField( Ven, chained_field="Item", chained_model_field="Name") But Vendor is showing all the vendor instead of filtering Vendor list as per Item.Please help! -
How to add(set) the ES6 59 atom editor? W104 - 'let' is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz)
enter image description here How to add(set) the ES6 59 atom editor? -
Django parsing json (from Webhooks)
I am trying to parse some json received from Mailchimp to a Webhook in my Django application. The format will look like this: { "type": "subscribe", "fired_at": "2009-03-26 21:35:57", "data": { "id": "8a25ff1d98", "list_id": "a6b5da1054", "email": "api@mailchimp.com", "email_type": "html", "ip_opt": "10.20.10.30", "ip_signup": "10.20.10.30", "merges": { "EMAIL": "api@mailchimp.com", "FNAME": "Mailchimp", "LNAME": "API", "INTERESTS": "Group1,Group2" } } } I have tried the following: def marketing_email_handler(request): if request.method == 'POST': reqtype = request.body['type'] reqdata = request.body['data'] reqemail = request.body['data']['email'] I received the error 'byte indices must be integers'. I've tried changing this to the below, however this results in an error 'TypeError: 'int' object is not subscriptable'. And doing request.json() also results in an error reqtype = request.body[0]['type'] reqdata = request.body[0]['data'] reqemail = request.body[0]['data']['email'] -
NoReverseMatch at / Reverse for 'singlepropa' with arguments '('mens-shirt-1',)' not found. 1 pattern(s) tried
I am trying to pass 2 parameters from html tag to the urls in django. But I am getting error: NoReverseMatch. If I pass only one parameter then it is working fine but it is generating error whenever i am passing 2 parameters. I have read the documentation for this but I am not clear about that,,and I have also searched for this issues. But nothing is working. Can You please help me to figure it out how I can I fix this? My href in html tag is: <a href='{% url "update_cart" product.slug qty=10 %}' class="float-right">Add to Cart</a> My urls.py is: urlpatterns = [ path('', home.Index.as_view(), name='homepage'), path('signup', signup.SignUp.as_view(), name="signup"), path('login', login.Login.as_view(), name="login"), path('logout', login.logout , name="logout"), path('basket', basket.Basket.as_view() , name="basket"), path('singlepropa/<str:slug>/<int:qty>', singlepropa.SinglePropa.as_view() , name="singlepropa"), path('s/', search.Search.as_view() , name="search"), path('update_cart/<str:slug>', basket.update_cart , name="update_cart"), ] The method for the mapped url is: from django.shortcuts import render, redirect, HttpResponseRedirect from django.views import View from MStore.models.cartModel import Cart, CartItem from MStore.models.productModel import ProductModel from django.urls import reverse # login class class Basket(View): def get(self, request): try: the_id = request.session["cart_id"] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {'cart': cart} else: empty_msg = "Your Cart is empty. Please keep shopping!" … -
Using models / queryset to generate questionnaire or django-survey
I am assuming I won't be the first one to ask this or a similair question, however I do think an answer on this question could help multiple people. the idea: create an online portal (django backend, js frontend, incl rest-framework API). As I would like this app to be accesible by other companies and also to communicate via API with other endpoints, I started to create several models, mapped them, etc. the question: what would be the best way (memory/deployment/security) to include a questionnaire in the front end (keeping in mind the requirements)? To be more specific, should i create a userform and map these directly to the API, or can i use something as https://github.com/Pierre-Sassoulas/django-survey? Does anyone has experience with such sort of apps hosted on github? It seems that packages like this make use of the admin panel and therefore I would probably need to map these which would be an extra step from my view. Feel free to bring up any other points of attention or your own questions. -
How to get the value of Queryset in Django
How to get this value covid_id and convert it to list? in QuerySet? <QuerySet [{'covid_id': 1653718671360'},{'covid_id': '1624728932475'}]> Expected output ['1653718671360','1624728932475'] sample sample= Person.objects.filter(pk__in=product_ids).values('covid_id') #output<QuerySet [{'covid_id': 1653718671360'},{'covid_id': '1624728932475'}]> print(sample) -
Can anybody please explain why I am facing this error [closed]
C:\Users\Najeebullah Tahir\PycharmProjects\PyShop>PyShop $django-admin startproject pyshop. 'PyShop' is not recognized as an internal or external command, operable program or batch file. -
unable want to check length of list, i want to check list length greater than 0 than loop over it and render each element
Trying to loop over a list , and then show each element of that list in span element, but its not working first I want to check if length of that list is greater than 0 than loop over the list , I am not familiar with syntax , need help . code: {%if len(prediction)>0%} {%for predict in prediction%} <span>{{predict}}</span> {% endfor %} -
Django Order QuerySet by Min Value from Child Table
I am trying to create a specific complex query in Django that I am struggling with. I am using pagination to display a list of cakes on the index page. I want to sort them by different attributes. Below is a screenshot of my index page. Name (A-Z) & Name (Z-A) are implemented by simply ordering the Cake queryset by 'name' or '-name' which I am getting as POST from the form at the top of the page. cakes_list = Cake.objects.all().order_by('name') However I am struggling to order the queryset by minimum price. Each cake is available in different dimensions which have different prices (dimensions and prices between cakes are different). These are stored in Dimension with a foreign key pointing to the Cake they belong to. I want to find out the cheapest option for each cake and order my list of cakes that is used in the pagination based on that (both min price asc and desc). I have also created a method from_price which returns the price of that cake. Which I use in my template to display each cake name together with the minimum price. But I cannot seem to be able to implement that into my … -
MultipleChoiceField only with choices, not with ManyToManyField
I have a problem with a MultipleChoiceField, I can not save it. Model: class Companyd(models.Model): months_recurrence_options = ( ("1", "Enero"), ("2", "Febrero"), ("3", "Marzo"), ("4", "Abril"), ("5", "Mayo"), ("6", "Junio"), ("7", "Julio"), ("8", "Julio"), ("9", "Septiembre"), ("10", "Octubre"), ("11", "Noviembre"), ("12", "Diciembre") ) months_recurrence=models.CharField(max_length=100,choices=months_recurrence_options, blank=True,null=True) Forms: class CompanyFormAdmin(forms.ModelForm): months_recurrence = forms.MultipleChoiceField(required=False,widget=forms.CheckboxSelectMultiple, choices=Company.months_recurrence_options) class Meta: model = Company fields = [... months_recurrence ... ] Views form = CompanyFormAdmin(request.POST or None, request.FILES or None, instance=obj) if request.method == 'POST': if form.is_valid(): form.save() When I save the form, I have this problem: {'months_recurrence': [ValidationError(["Escoja una opción válida. ['5', '7', '10'] no es una de las opciones disponibles."])]} -
while using dependency dropdown list in django the correct list is displayed only when save button is hit
I am new to Django. Tried with the example mentioned in the below link for getting dependency dropdown. But I am not sure where i am wrong the correct dropdown is getting loaded after hitting the save button. https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html Could you please help me in resolving this. Regards, Sindhu Sumukha -
Create automatic links to an iterated list within Django
I have a Python Django project which is similar to a wickipedia. The entries are md files with a markup language which will be rendered to HMTL if a user click on one of that entries. The folder with the entries can be found in the following picture which are actually CSS.md, Django.md and so on. entries In a separate HTML file it should be viewed an unordered list with the entries. This is working well with the following two steps. I created a function within view.py as you can see within the following picture with the code. def index The dictionary "entries": util.lits_entries() within that function comes from another function which is calling list-entries and be saved in a folder util.py. In a html file calling index.html I am iterating trough the folder entries to get an unordered list with the entries name as following in the picture below. index.html This works well as you can see on the screen below: unordered list with entries name My question now is how can I iterate trough my entries, get the entries name in my unordered list in my index.html page, but with an automatically created link for the iterated names. … -
How run static file when debug is false?
With debug turned off Django won't handle static files for you any more - your production web server. Implement this code inside your project: settings.py STATIC_DIR=os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' if DEBUG: STATICFILES_DIRS = [ STATIC_DIR, ] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ... ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATICFILES_DIRS) -
[Heroku][Django]Logging in from an external server with the requests module takes 30 seconds and times out
I'm currently trying to login to a Django app on Heroku using the requirements module from an external server. If I login to Heroku (main app) from my local PC via an external server (another Heroku server) using the requirements module, I can login in a few seconds. However, if you try to login to your own Heroku (main app) from the main Heroku app via an external server (another Heroku server), it takes almost 30 seconds. It also takes almost 30 seconds when I try to log in to my main Heroku app directly from my main Heroku app. When I check the logs, there is no difference in the request header or body in either case, so I would like to know what is causing the time difference. Login path ○ (a few seconds): Local PC → External server Flask app (another Heroku) → Heroku (Django main app) ×(30 seconds): Heroku (Django main app) → external server Flask app (another Heroku) → Heroku (Django main app) ■ Log local PC → external server Flask app (another Heroku) → Heroku(Django main app) [enter image description here][1] ■ Log Heroku (Django main app) → External server Flask app (another Heroku) … -
Django: Pass a variable/parameter to form from view?
I'm trying to do passing a variable to form from view on Django. Simply, what I want to do is something like this below. # views.py def tmp(request): if request.method == 'POST': f = tmpForm(request.POST) if f.is_valid(): // something more here. else: // this will pass nothing to the form f = tmpForm() // want to pass variable/parameter to the form initial = '''{ "hoge": "hogehoge" }''' f = tmpForm(initial) // should be something like this maybe? return render(request, 'tmpapp/tmp.html', {'form': f}) # forms.py class tmpForm(forms.Form): // retrieve the variable/parameter and set `initial` or something like that json = forms.CharField(widget=forms.Textarea, label='', help_text='JSON formatted data here.', initial= textwrap.dedent( # '''{ # "hoge": "hogehoge" # }''' initial // so you can use the variable like this. ) ) So, How can I implement this? -
How to enter prompts in bash script for python manage.py
Hi I want to use python manage.py changepassword command with bash script. When I do it askes double time for new password. How can I answer those in bash ? python manage.py changepassword testuser Changing password for user 'testuser' Password: Password (again): Password changed successfully for user 'testuser' I know I can do it like below but how can i do that without using below and Expect. Since environment I am using does not have Expect. echo "from accounts.models import User;u= User.objects.get(username='testuser'); u.set_password('$1'); u.save();" | python3 manage.py shell; -
Django: how to check a guest or a page owner entered the page
I am doing a social network, I have one profile template for all users, how to check a guest or a page owner entered the page, {% if profile.user.username == None%} tried to write like this in html but it works strangely.For users, I use the Profile model class Profile(models.Model): first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=150, blank=True) country = models.CharField(max_length=100, blank=True) avatar = models.ImageField(default = 'avatar.svg', upload_to = 'avatars/%Y/%m/%d', blank=True) friends = models.ManyToManyField(User, blank=True, related_name='friends') update = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user}-{self.created}" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() -
ValueError: source code string cannot contain null bytes -django
This is the traceback I'm getting whenever I try to run the server. C:\Users\sarathmahe024\Downloads\website (1)\website\website>python manage.py runserver Traceback (most recent call last): File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 16, in setup from django.urls import set_script_prefix File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\__init__.py", line 1, in <module> from .base import ( File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\base.py", line 9, in <module> from .exceptions import NoReverseMatch, Resolver404 File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\exceptions.py", line 1, in <module> from django.http import Http404 File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\http\__init__.py", line 5, in <module> from django.http.response import ( File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\http\response.py", line 15, in <module> from django.core.serializers.json import DjangoJSONEncoder File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\serializers\__init__.py", line 23, in <module> from django.core.serializers.base import SerializerDoesNotExist File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\serializers\base.py", line 7, in <module> from django.db import models File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\__init__.py", line 3, in <module> from django.db.models.aggregates import * # NOQA File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\aggregates.py", line 5, in <module> from django.db.models.expressions import Case, Func, Star, When File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\expressions.py", line 8, in <module> from django.db.models import fields File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 11, in <module> from django import forms File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\__init__.py", line 6, in <module> from django.forms.boundfield import * # NOQA ValueError: source code string cannot contain null bytes During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\sarathmahe024\Downloads\website (1)\website\website\manage.py", … -
Django Heroku Collectstatic error only on deploy
I've looked through a bunch of other StackOverflow and forum pages with very similar issues, but none of their solutions worked. The error is caused during the python manage.py collectstatic --noinput test command when you deploy to heroku. Running python manage.py collectstatic --noinput on my local project works without errors. Here is my requirements.txt: dj-database-url==0.5.0 Django==2.0 django-heroku==0.3.1 gunicorn==20.0.4 psycopg2==2.8.6 python-dotenv==0.15.0 pytz==2021.1 whitenoise==5.2.0 my settings.py: import os import django_heroku from dotenv import load_dotenv load_dotenv() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv("SECRET_KEY") ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' django_heroku.settings(locals()) Here is my file tree: . ├── Procfile ├── README.md ├── db.sqlite3 ├── manage.py ├── .env ├── project_polus │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── settings.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ └── wsgi.cpython-39.pyc │ ├── settings.py │ ├── static │ ├── urls.py │ └── wsgi.py ├── requirements.txt └── runtime.txt This is the full error that heroku outputs: -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 197, in fetch_command app_name = commands[subcommand] KeyError: 'collectstatic' During handling of the above … -
Django : No operator matches the given name and argument types. You might need to add explicit type casts
I'm having a trouble on getting this error when filtering data on my postgresql, it says that the error comes from this line .filter(bene_id='31452'). I've been using two tables in Django I tried putting double qoute, single qoute and even without elements like this .filter(bene_id="31452") ,.filter(bene_id=31452) ,.filter(bene_id='31452') . But it seems the error has not been solve.it would be great if anybody could figure out where I am doing something wrong. thank you so much in advance Error LINE 1: ...2_benes_status" WHERE "b2_benes_status"."bene_id" = 31452 L... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. views.py Testing = B2BenesStatus.objects.using('matchy_data').filter(bene_id='31452') Models.py class B2BenesStatus(models.Model): datetime = models.DateTimeField(blank=True, null=True) value = models.BooleanField(blank=True, null=True) remarks = models.TextField(blank=True, null=True) bene_id = models.IntegerField(blank=True, null=True) stat_cat_id = models.IntegerField(blank=True, null=True) updated_by_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'b2_benes_status' Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'payroll', 'USER':'root', 'PASSWORD':'', 'HOST':'localhost', 'PORT':'3306', }, 'matchy_data': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'matchy_data', 'USER':'postgres', 'PASSWORD':'samplee', 'HOST':'localhost', 'PORT':'5432', },} -
Why is the parameter from the URL coming back as undefined in Django?
I am working on a project where I'm asking the user to enter a Company name in a form and before submitting the form I have button that redirects the user to the following URL and passes in the Company name that the user entered in the form: http://.../sync/CompanyName I'm trying to now call the sync() function and pass in the above Company name as a parameter. This is the urls.py: path('sync/<str:company>', views.sync, name='sync') I am able to redirect it to the sync() view since I have some test lines in there that are being printed. This is the views.py: def sync(request,company): print(company) . . . The issue is that the company name being printed above comes back as undefined. Am I missing something here? How can I to do this without doing a POST request? I have also tried to get the company name using something like this: print(request.GET.get(company)) when my URL was http://.../sync/company=CompanyName but that didn't work either - still came back as undefined. -
Django, python How to save multiple images resized as one image?
models.py class Photo(models.Model): profile = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="Photo" ) user_photo = models.ImageField(null=True, upload_to="photo") so, when one image is saved in "user_photo", I also want to save the two resized images in separate tables. What should I do? -
Django template for loop condition
How to create a for loop inside a for loop with a condition where the inside of for loop is equal to something in outer for loop. something like this: {% for x in major %} <optgroup label="{{x.major_name}}"></optgroup > {% for y in minor %} # Add a condition like :minor.major_id == major_id {% if default_minor == y.minor_name %} <option value="{{y.minor_name}}" selected>{{y.minor_name}}</option> {% else %} <option value="{{y.minor_name}}">{{y.minor_name}}</option> {% endif %} {% endfor %} {% endfor %} -
what is the correct way to add multiple language in Django and add choose language button
what is the correct way to add multiple language in Django and add choose language button i have tried many things but all of them fails i don't know what is the error or what is the correct steps to active two language i tried these : urls.py : from django.utils.translation import gettext_lazy as _ from django.urls import LocalePrefixPattern, URLResolver, get_resolver, path from django.views.i18n import set_language from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('set_language', views.set_language, name='set_language'), path('il8n/', include('django.conf.urls.i18n')), path('admin/', admin.site.urls),] urlpatterns += i18n_patterns( path('', views.home_page, name='home_page'), path('test', views.test, name='test'), )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py : from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LLOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGES = ( ('ar', _('Arabic')), ('en', _('English')), ) views.py : def set_language(request): if requset.method == 'POST': cur_language = translation.get_language() lasturl= requset.META.get('HTTP_REFERER') lang = request.POST['language'] translation.activate(lang) request.session[translation.LANGUAGE_SESSION_KEY]=lang return HttpResponseRedirect("/"+lang) html page form : <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE …