Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check multiple field of Django Object is exist after assignment?
I am creating an article object like this for an old model that we currently use and I do not want to change the legacy model. Article.objects.create( category=NEWSFEED, date=self.parse_date(item), display_type=ARTICLE, name=self.article_name(item), image=self.generate_image(item), ) These fields are depended on an Item and some items might not have this fields or there can be an issue while parsing Item so I want to make sure all the fields are created and assigned correctly. Also I want to be informed if any field is empty. I added error as an Array Field to check every these fields in another method like this so later on I can check the error list and see what is wrong with this article. def check_article_fields(self, article): if not article.date: article.error.append('Date of this article is missing') if not article.name: article.error.append('Name of this article is missing') if not article.subtitle: article.error.append('Subtitle of this article is missing') if not article.html_template: article.error.append('Html of this article is missing') if not article.images: article.error.append('Images of this article is missing') if not article.content: article.error.append('Content of this article is missing') However this looks like really really ugly and it could be better, yet right now I can not think of any another solution. -
How to have a field disabled for a form when just displaying data, but enabled when using the new form to input data
I have a single form that is used for either displaying data in read only format, and you get to this by clicking on a record in the table and are taken to a read only detail view. I also want to reuse the same form as a way to input data into the table - by default I have all the fields disabled for my read only view and so would like to find a way to override this when generating the form for my insert view? I thought if I wrapped the form in a POST method in my template, it would somehow enable the fields but doesn't seem to work forms.py from django import forms class BusinessDataForm(forms.Form): tableName = forms.CharField(strip=True, empty_value='NULL', disabled=True) class NewMeta: readonly = ('tableName',) views.py # Django imports from django.shortcuts import render from django.http import HttpResponse # Local imports from .forms import BusinessDataForm from .tables import ResultsTable as rt import common.dbConnectionManager as dbc # System imports import sys import pyodbc sys.path.insert(0,'..') pyodbc.pooling = False def home(request): return render(request, 'home.html') def db_display(request): dbo = dbc.dbConnectionManager() query_result_as_dict = dbo.run_query('SELECT TOP 10 DataBaseName, TableName, Version, TableKind, CreatorName FROM DBC.TABLESV;') dbo.disconnect() table = rt(query_result_as_dict) #tables.RequestConfig(request).configure(table) return render(request, "db_display.html", … -
Django filters dopdown menu valid choice error
i have a dataset with population by year and i need to it filter by year. it works with input value but it doesn't work with dropdown menu. it gives the error "Select a valid choice. That choice is not one of the available choices." models.py class Pyramid(models.Model): year = models.IntegerField(default=0) city = models.CharField(max_length=15) men_population = models.IntegerField(default=0) women_population = models.IntegerField(default=0) filters.py import django_filters from .models import Pyramid class YearFilter(django_filters.FilterSet): year_f = django_filters.ModelChoiceFilter(queryset=Pyramid.objects.values_list('year',flat=True).distinct()) class Meta: model = Pyramid fields = ['year_f '] views.py def Pyramid(request): dataset = models.Pyramid.objects.all() year_filter = YearFilter(request.GET, queryset=dataset) context = { 'dataset': dataset, 'filter': year_filter, } return render(request, 'pyramid.html', context) it shows me the year what i enter but gives error "Select a valid choice. That choice is not one of the available choices." -
I am getting and error in Python django code where when i RUN python3 manage.py runserver it raise exception
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'Mysite.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import." Project name is Mysite and the app name is mark My Url.py file: urlpatterns = [ #path('admin/', admin.site.urls), path('', views.index_one, name='index_one'), path('confirm_order', views.confirm_order, name="confirm_order"), path('confirm', views.confirm, name='confirm'), path('payment_success', views.payment_success, name='payment_success'), path('home', views.home, name='home'), path('index',views.index,name='index'), path('advertisement',views.advertisement,name='advertisement'), path('save_product',views.save_product, name="save_product"), path('advertisement_new',views.advertisement_new,name='advertisement_new'), path('advertisement_one',views.advertisement_one,name='advertisement_one') ] Settings.py file ROOT_URLCONF = 'Mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Mysite.wsgi.application' -
NoCredentialsError when accessing documents on S3 from Python
I'm writing a Jupyter script that crunches some data from my database and dumps it as json. One of the models has a Django FileField in it (the files are stored in a S3 bucket) and I try accessing it like this in my script: records = Record.objects.all() for record in records: file_url = record.zip_file.url # zip_file is the FileField When the script reaches the last line in the example above, it throws a NoCredentialsError: NoCredentialsError: Unable to locate credentials. I'm guessing it can't access the file url just like that. Is there something I can do inside the script or anywhere else to be able to access these urls? -
Adding @login_required to ClassViewList [duplicate]
This question already has an answer here: How to use permission_required decorators on django class-based views 11 answers So i tried adding the tag @login_requried to my class based view for a database queries and i kept getting various errors ("ClassView" object has no attribute 'user) I have a login form ready to go, it also redirects to the database view as i wanted but , i can simply type the database view url and it'll appear. I'd like to add permission. Meaning if you type the database url it should redirect to sign-in first before viewing from django.views.generic import ListView from django.contrib.auth import login from django.utils.decorators import method_decorator from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required, permission_required def login_view(request): if request.method =='POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): #log in user return redirect('/Database/DBQuery') else: form = AuthenticationForm() return render(request,'posts/login.html',{'form':form}) class TroubleshootListView(ListView): model = Troubleshoot template_name = 'posts/StaffView.html' @login_required def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['filter']= TroubleshootFilter(self.request.GET, queryset=self.get_queryset()) return context -
Displaying an image stored in MongoDB using Django and Ajax
I'm trying to display an image stored as base64 in MongoDB on an overlay window. The issue is whether window doesn't open up or an I get an empty window without an image. Also, when I open up the console on the website page, I see the following: GET ServerURL:8000/path/to/page/'htmlFile' 404 (Not Found) I'm using Ajax to locate the specific document and then fetch the image field value as follows. I'm using POST method as I'm not asking the user for any info and just presenting the image when they click on the button (Please correct me if I'm wrong about that): Ajax Code: $(document).ready(function(){ $('.imageInfo').on('click', function(){ const rowID = $(this).parents('tr').length ? $(this).parents('tr').attr('id') : $(this).attr('id'); document.getElementById('DocIP').innerHTML = rowID; $.ajax({ type: "POST", url: 'DisplayImage/', data: { 'IP': rowID, }, success: function(data){ document.getElementById('htmlFile').innerHTML = data.imageData; if (data.authenticated){ $('#ImageModal').modal('show') } else { $('#notLoggedInModal').modal('show') } }, error: function(err){ alert(err) } }); }); }); Python Code: def DisplayImage(request): ** some code to make sure the user is authenticated ** if request.method == "POST": ipAddr = request.POST.get('IP',False) else: ipAddr = '' try: matchedPC = PC.getSpecificIp(ipAddr) except: print("Failed to get PC info from DB") foundPC = matchedPC[0] image = foundPC['imageData'] img_tag = '<img src="data:image/jpg;base64,{0}"/>'.format(image) data = { … -
porque no funciona el searchfilter en django?
I has being trying to use SearchFilter in django, but it's not working I tryed changing ",", setting up RestFramework default filter backend on settings.py, using filter_fields, using search_fields. class ProductList(generics.ListCreateAPIView): queryset = Producto.objects.all() serializer_class = ProductoSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] filter_backends = [filters.SearchFilter,filters.OrderingFilter] search_filter = ['id',] filter_fields = ['id',] def perform_create(self, serializer): serializer.save(owner=self.request.user) -
How to save a model record as a template for reuse later
I have a basic blog app that has a Post model: class Post(models.Model): author = models.ForeignKey( get_user_model(), null=True, on_delete=models.SET_NULL) title = models.CharField(max_length=30) content = models.CharField(max_length=30) template_specific_entry = models.CharField(max_length=30) I need users to be able to create a Post template with template_specific_entry field values, and then other users to use these templates to create new post records, updating title and content but not template_specific_entry. See the example use case below: I would like to retain the original Post templates in their original form, so multiple versions of that template can be used. My question is: what's the most efficient way to go about creating this structure? Should I create two models, PostTemplate and Post and somehow link the template_specific_values between them? Since this is 'row level' functionality, is it better to do this via model methods, so templates and posts are stored in the same model? E.g. def createTemplate(self): and def createPost(self): referencing the same model? In each case how would I actually implement this? -
Enable PSQL hstore extension in Django test db during CI
Context Some steps of my Continuos Integration procedure are: start Postgres docker container run Django tests When manage.py test --noinput command is runned it: creates a new test_xxx database (drop if exists) runs the founded migrations against it runs the founded set of tests Into the tests that need to fetch data from the database are configured a set of fixtures that will be loaded automatically in the test_xxx db. Problem Some migrations need the Postgres hstore extension, in fact i'm getting this error: django.db.utils.ProgrammingError: type "hstore" does not exist Question How can i enable the hstore extension? In development and other envs it was set up with CREATE EXTENSION IF NOT EXISTS hstore; but here can't be manually set. Is possible to define a "migration zero" with the hstore creation? Anyway i don't like this approach. I've found that it should be theorically possible to listen to the pre_migrate signal, and it will be the sweet spot, but before make things more complex i'd like to search for an easier, more direct solution. -
Celery task.delay() doesn't respect broker configuration
My Configuration Celery - 4.3.0 Python - 3.7.1 Django - 2 Broker - Redis OS - Windows 10 I'm using celery for now about 6-7 months, and its amazing. Today I come across one strange problem. I have setup Redis as my message broker. So when I haven't put in restriction on bind and authentication i.e default as localhost with no authentication, everything works perfect. But when I put some restriction on bind and authentication configurations i.e. localhost changed to my network ip and authentication enabled by password, and initialized by celery as app = Celery('app_name', backend='redis', broker='redis://' + lib.get_conf('redis_db_user') + ':' + lib.get_conf('redis_db_password') + '@' + lib.get_conf('redis_db_host') + ':' + str(lib.get_conf('redis_db_port'))) I load this configuration from yaml file : #REDIS Database redis_db_host: "192.168.1.236" redis_db_user: "" redis_db_password: "pass123" redis_db_name: "1" redis_db_port: 6379 With above configuration my celery is perfectly up and running with all workers. Some of my workers are distributed in network, hence I can't use localhost configuration. TL;DR Now most of my task are scheduled by celery-beat, some of my task get called from this scheduled task by calling delay() method. Now here error occurred !!! my_task.delay(param1,..) when called it doesn't respect current celery configuration and instead it … -
What is causing ldap3 having an error "socket ssl wrapping error: [Errno 104] Connection reset by peer" when running in Docker?
Django is running without a problem on my machine. When it is running inside a docker container, I am having an error: LDAPSocketOpenError at /api-auth/login/ ('unable to open socket', [(LDAPSocketOpenError('socket ssl wrapping error: [Errno 104] Connection reset by peer'), ('10.234.230.11', 636))]) My machine and docker openssl version have same version 1.1.1c Dockerfle # base image FROM python:3.7 # environment for python logging # send output to terminal without buffer ENV PYTHONBUFFERED 1 # make workdir in container # and copy current directory contents to workdir RUN mkdir /app WORKDIR /app ADD . /app # install needed packages RUN apt-get update \ && apt-get install -y default-libmysqlclient-dev build-essential \ && pip install --trusted-host pypi.python.org -r requirements.txt \ && apt-get remove -y default-libmysqlclient-dev build-essential docker-compose.yml version: '3.3' services: db: image: mysql restart: always command: ['--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci', '--default_authentication_plugin=cache_sha256_password', '--default-authentication-plugin=mysql_native_password'] container_name: noctool_mysql environment: - MYSQL_DATABASE=$DOCKER_MYSQL_DATABASE - MYSQL_ROOT_PASSWORD=$DOCKER_MYSQL_ROOT_PASSWORD volumes: - noctool_db:/var/lib/mysql api: build: . command: bash -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" container_name: noctool_api restart: always volumes: - .:/app ports: - "8000:8000" depends_on: - db volumes: noctool_db: -
Insert row in DataTable with dynamic columns
I am trying to insert rows in my DataTable from an array. Since the columns of this table are dynamic I'm sending an array of row values from the backend to directly insert into the table by simply looping through the number of arrays. I don't have the definite values to add hence the Datatable.row.add([value 1, value 2, ...]) doesnt work since the number of columns is dynamic. I need to add the array directly as a row in the table. Tried adding it as a whole, the entire array, but it inserts the entire array in every cell, instead of individually in the row. for iid in iid_list: log_list = [] for meter in meter_list: try: logger_object = ElectricityLogger.objects.get(meter = meter, iid = iid, is_delete = False) log_list.append(logger_object.reading) except: log_list.append(0) date = ElectricityLogger.objects.filter(iid = iid, is_delete = False).first().created_on log_list.append(date) electricity_logger_data.append(log_list) $.ajax({ type:"GET", url:"", headers: headers, dataType: "text", success: function(data) { data = JSON.parse(data) data1 = data.electricity_logger_list.data.electricity_logger_list data2 = data.meter_list.data.meter_list columns = [] for(i=0; i<data2.length;i++){ columns.push({data: null, title: data2[i].meter_name}) } columns.push({data: null, title: 'Time'}) var myTable = $('#myTable').DataTable({ "processing": true, "paging": true, "searching": { "regex": true }, "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ], … -
Create a form that fills in fields within standard Python + Django code
I need to create a form on a page made in Django (Python), that it will create a file based on a "skeleton" Python code and change only the specific fields that I put in bold and save the same. -
Use Django Rest API From Any Origin
I have a REST API implemented using Django DRF. My API is working just fine when used from my-domain.com, however I would like the API to be accessible from any origin. I have implemented CORS/CSRF using the following configuration: CSRF_COOKIE_NAME="XSRF-TOKEN" CSRF_HEADER_NAME="HTTP_X_XSRF_TOKEN" CSRF_TRUSTED_ORIGINS = ( 'my-domain.com' # I have tried adding my ip address here, but no luck ) CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-xsrf-token', 'x-requested-with', 'Api-Key' ) CORS_EXPOSE_HEADERS = ( 'Set-Cookie', ) When I make a request to my-domain.com/api/ from my-domain.cm I get the expected header: Set-Cookie: XSRF-TOKEN=csmi.........................DK7; expires=Wed, 26 Aug 2020 11:43:51 GMT; Max-Age=31449600; Path=/; SameSite=Lax When I make a request to my-domain.com/api/ from my personal computer or from a 3rd REST API testing site, I do not get the expected header. I would like my API to be accessible from any ip address. How do I configure my settings? To further elaborate, I am attempting to login to my-domain.com/api/auth/ using a post request with my credentials. I am getting a 405 error, and I believe it is because I am no sending the xsrf-token in my headers. I am making an initial get request to get the xsrf token but … -
Where to put request to an external API on the server side in a django rest and react based project
I have a Django REST and React based project. For some of the functionalities I get data from the client, pass it over to the django backend using APIViews, make a request to external API on the server side and once I get a successful response from the external server, I need to create an instance of a model in the database. I wonder, about where to place the mentioned external API request logic, should it be model's serializer? Also is it the right place to create a model's instance? If the above approach is wrong, please advise the right path. Thanks -
Using linkify when not using any DB models to navigate to a detail view
Disclaimer: I've only just started using Django, so am not sure on some of my approaches I've used so far, so feel free to point out anything im doing blatantly wrong! I am putting together a simple display/insert/update django web app that interacts with a legacy database we have that runs on Teradata. With no support for teradata in django for models, I am simply using pyodbc to connect and query it directly and work with the data that way. I now have the data being displayed in a table using the django_tables2 framework and would not like to link the primary column to a detail view. The documentation says that the LinkColumn function is now deprecated and we should then use Linkify instead. I've tried playing around with it but cannot get it to work. Here is my code I have so far: tables.py class ResultsTable(tables.Table): DataBaseName = tables.Column() TableName = tables.Column(linkify={"business_data_display", (tables.A("TableName.pk"))}) Version = tables.Column() TableKind = tables.Column() CreatorName = tables.Column() # Styling the table with some CSS class Meta: attrs = {'class': 'table table-hover table-striped'} urls.py urlpatterns = [ path('', views.home, name='home'), path('admin/', admin.site.urls), path('db_display/', views.db_display, name='db_display'), path('db_display/<str:table_name>/business_data_form', views.business_data_display, name='business_data_display'), ] views.py def db_display(request): dbo = dbc.dbConnectionManager() … -
Got a `TypeError` when calling `` in django rest framework
When I am trying to POST using an API I get the error: Got a TypeError when calling Quiz.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Quiz.objects.create(). Here's the code: Views.py class createrfq(APIView): permission_classes = (permissions.AllowAny,) def post (self, request, format=None): data = request.data.copy() data['owner'] = request.user.id data['truck_type'] = 1 print("request.data is", data) serializer = createrfqSerializer(data=data) if serializer.is_valid(): serializer.save() print("s data", serializers.data) quiz_instance = get_object_or_404(Quiz,pk = serializer.data["id"]) question = Question.objects.create(text='Vehicle Ownership', quiz=quiz_instance) Bid.objects.create(text='Own Vehicle', bid_amount=0, bid_date=now, question=question) Bid.objects.create(text='Market Vehicle', bid_amount=0, bid_date=now, question=question) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class createrfqSerializer(serializers.ModelSerializer): class Meta: model = Quiz fields = "all" What is it that I am doing wrong? -
Get location of browser using ipAPI and Django
I am using ipdata.io API to get the location of users visiting my website. I am able to implement the python code from the docs, however this returns the location of where my server is hosted. I am assuming this is because the views.py is being run on that server, which is in fact making the request, not the users browser. Without using javascript on the browser side, is it possible to get the location of the user using python requests on the server side? views.py class infoRequestPage(CreateView): model = InfoRequest form_class = moreInfoForm template_name = 'info_request.html' success_url = reverse_lazy('home') def get(self, *args, **kwargs): payload = {"api-key": "myapikey"} response = requests.get('https://api.ipdata.co', params=payload).json() info_City = response['city'] info_Region = response['region'] info_Country = response['country_name'] pageVisit = InfoRequest( infoCity = info_City, infoRegion = info_Region, infoCountry = info_Country, pageVisited = "infoRequest",) pageVisit.save() return super().get(*args, **kwargs) -
Handling Django Apps in Database or Configuration File
Currently, I'm developing a web application which should host different coding competitions. We decided to make each competition a custom app. However, some components like team management or submissions should be available in all competitions. I want to have all competitions (including their name and app name) in a specific database table. My question is if there is a built-in way to perform app management in Django: For instance, I would like to automatically include all apps which are listed in the corresponding database table. Additionally, I want every url app-name/ to get redirected to the urls.py file of the app-name app. My current approach would be to define a model Competition and read the objects from the database in the urls.py and settings.py. However, this does not feel like the right way to do it. Is it more reasonable to have the basic competition configurations in a config file outside of the database? -
How to create repeatable templates from models
I have a basic blog app that has a Post model: class Post(models.Model): author = models.ForeignKey( get_user_model(), null=True, on_delete=models.SET_NULL) title = models.CharField(max_length=30) content = models.CharField(max_length=30) template_specific_entry = models.CharField(max_length=30) Now I want users to be able to create a Post template with template_specific_entry field values, and then other users to use these templates to create new post records, updating title and content but not template_specific_entry. The trick here is that I want to retain the original Post template in its original form, so multiple versions of that template can be used. My question is: what's the most efficient way to go about creating this structure? Should I create two models, PostTemplate and Post and somehow link the template_specific_values between them? Since this is 'row level' functionality, is it better to do this via model methods, so templates and posts are stored in the same model? E.g. def createTemplate(self): and def createPost(self): referencing the same model? In each case how would I actually implement this? -
How do i modify view of groups in django-admin
I want to modify the view template in django-admin -> AUTHENTICATION AND AUTHORIZATION -> Groups -> ADD GROUP. at presents it gives two options 1. Name and 2. Permissions. the Permissions gives a select list to the user so that permissions can be set to the user. What i want is The permissions comes with Checkboxes so that by clicking on the checkbox permission can be set -
How to handle current logged user as author properly when base django user model is overwriten?
Here is the deal: users/models.py (here I overwrite based django model): from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class ProfileUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.URLField() @receiver(post_save, sender=User) # Still don't know how, but next rows create ProfileUser when User is created def create_user_profile(sender, instance, created, **kwargs): if created: ProfileUser.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profileuser.save() def __str__(self): return f"{self.user}" And using (for example when I add objects (posts)) objects/views.py: from django.shortcuts import render, redirect from django.views import generic from objects.models import Object, ProfileUser from .forms import ObjectForm, CommentForm from django.contrib import messages class UserObjectsView(generic.ListView): template_name = 'user_objects.html' def get_queryset(self): user_id = self.kwargs['pk'] return Object.objects.filter(author_id = user_id) def add_object(request): if not request.user.is_authenticated: messages.info(request, 'За да добавите нов Обект, трябва да сте регистриран потребител!') return redirect('account_login') form = ObjectForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) obj.author = ProfileUser.objects.get(user=request.user) obj.save() messages.success(request, 'Успешно добавихте нов Обект, може да видите вашите обекти във вашия профил!') return redirect('home') context = { 'form': form } return render(request, "add_object.html", context) def show_object(request, pk): obj = Object.objects.get(id=pk) context = { 'object': obj } return render(request, "show_object.html", context) def add_comment_to_object(request, pk): obj … -
What is meaning of (qs | qs1) in the code below
I am a newbie in django. What is the overall logic in the code below. And still what does (qs | qs1) really mean in python/django? class TweetDetailAPIView(generics.ListAPIView): queryset = Tweet.objects.all() serializer_class = TweetModelSerializer pagination_class = StandardResultsPagination permission_classes = [permissions.AllowAny] def get_queryset(self, *args, **kwargs): tweet_id = self.kwargs.get("pk") qs = Tweet.objects.filter(pk=tweet_id) if qs.exists() and qs.count() == 1: parent_obj = qs.first() qs1 = parent_obj.get_children() qs = (qs | qs1).distinct().extra(select={"parent_id_null": 'parent_id IS NULL'}) return qs.order_by("parent_id_null", '-timestamp') the_parent = self if self.parent: the_parent = self.parent return the_parent def get_children(self): parent = self.get_parent() qs = Tweet.object.filter(parent=parent) qs_parent = Tweet.objects.filter(pk.parent.pk) return (qs | qs_parent) -
OperationalError at /i18n/setlang/ when switching language
I'm new to python and django, I'm trying to set my website with 2 languages. When I switch the language with the form in base.html I receive this OperationalError at /i18n/setlang/ no such table: django_session Settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] LANGUAGES = [ ('it', ('Italian')), ('en', ('English')), ] TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.i18n', ) urls.py urlpatterns =[ path('i18n/', include('django.conf.urls.i18n')), path('admin/', admin.site.urls), path('', include('index.urls')), path('about-us/', include('about.urls')), ] base.html <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 %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go" /> </form> thanks in advice