Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File from django model not uploading
These are my models class Post(models.Model): title = models.TextField(default="no title") body = models.TextField(default="no body") creation_date = models.DateTimeField(default=timezone.now) creator = models.ForeignKey(User, on_delete=models.CASCADE) document = models.FileField(upload_to="uploads/", null=True, blank=True) the one that isn't working is document, i have set up a form and when i "post" the form the other stuff like title ,body, creation date and creator are being saved but the document isn't, cant even find it in any folder this is my view class Post_List(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): posts = Post.objects.order_by("-creation_date") form = PostForm() context = { "post_list" : posts, "form" : form, } return render(request, 'social/post_list.html', context) def post(self, request, *args, **kwargs): posts = Post.objects.order_by('-creation_date') form = PostForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.creator = request.user new_post.save() context = { 'post_list': posts, 'form': form, } return redirect('/feed') I tried migrating again but nothing changed -
Add 1 month above today's date with django python
I want to add 1 month to today's date and keep this date in database enter image description here i tried this but it gave error -
Media folder not working properly & Images not being saved - Django
I am trying to add images to a post. (Using Django v3.2.5) root_directory/settings.py: BASE_DIR = Path(__file__).resolve().parent.parent ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') root_directory/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')), path('app2/', include('app2.urls')), path('app3/', include('app3.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app3/models.py: from django.db import models from ckeditor.fields import RichTextField class Post_Picture(models.Model): title = models.CharField('Title', max_length=120) image = models.ImageField(blank=True, null=True, upload_to="images/") caption = RichTextField(blank=True, null=True) def __str__(self): return self.title app3/forms.py: from django import forms from django.forms import ModelForm from .models import Post_Picture class PostPicForm(ModelForm): class Meta: model = Post_Picture fields = ('title', 'image', 'caption') labels = { 'Title': '', 'Caption': '', } widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Title your post'}), 'caption': forms.Textarea(attrs={'class':'form-control', 'placeholder': 'Anything extra you want to add?'}), } app3/views.py: from django.shortcuts import render, redirect from .models import Post_Picture from .forms import PostPicForm from django.http import HttpResponseRedirect from django.contrib import messages def your_home(request): friend_posts = Post_Picture.objects.all() return render(request, "app3/your_home.html", { 'friend_posts': friend_posts, }) def post_pic(request): submitted = False if request.method == "POST": form = PostPicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('post_pic?submitted=True') else: form = PostPicForm() if 'submitted' in request.GET: submitted = True return … -
Django does not add attribute to the custom ModelForm widget
I'm trying to add another attribute in HTML (placeholder) using Django Widgets, when I do it, they don't appear in the HTML. models.py class InvitadosIngreso(forms.ModelForm): class Meta: model = InvitadosIngreso fields = ['oficina_pro' ,'documento' widgets = { 'oficina_pro' : forms.Select(attrs={'class':'form-control'},choices=ch_pro) ,'documento ': forms.TextInput(attrs={'class':'form-control', 'placeholder':'prueba',}) } forms.py class InvitadosIngreso(models.Model): oficina_pro = models.CharField(max_length=100, default='') documento = models.CharField(max_length=100, default='') nombre = models.CharField(max_length=100, default='') class Meta: db_table = 'InvitadosIngreso' -
Django -> post/get work but loading a fixture gets a "no such column error'
I've created a new model, and can post and get, and I receive all the fields. this indicates the underlying table is correct. I also manually checked my migrations and all the fields are there. And manually check the serializer (which is observably working via post/get). However, when I try the dumpdata or loaddata command, I get the error: "no such column: creator". Why would these two command think the field doesn't exist when the other aspects of the app can use it? -
How to update only a part of a json which is stored in a database with a "json path" list?
Let´s say we have a database and there is a json stored as a string which contains configurations. In the application we want to update only a specific value and write then back the json as a string to the database. The HTTP request provides a "jsonPath" which reflects a path in the json file to navigate to the object we want to update. This parameter is supplied as a list. An example for the path could be something like ['input', 'keyboard', 'language'] and the value we want to set is 'en' Here we load the configuration from the database which works so far: if request.data['jsonPath']: config = json.loads(models.Config.objects.get(name__startswith='general').value Then config is just a normal object now, which I can access with the dot notation like config.input.keyboard.language and it contains then the according part in json syntax. I am able to read out the value of the field with the following syntax: config[request.data['jsonPath'][0]][request.data['jsonPath'][1]][request.data['jsonPath'[3]] But the number of parameters can vary and I want also to write it back into the config object, convert it back to a string and write it into the database. I know it is not a nice thing but I would be interessted how it can … -
Is it possible to join two unrelated models based on a string column using Django-ORM
Currently, in a project that I'm working on, we are using the library called drf-api-tracking for logging each request that related data like an audit. The library is providing a mixin called LoggingMixin and by using that we are logging the API-related URL, status codes, requests, responses and etc. To save these data, the mixing is using a model called, APIRequestLog which is provided by the library. Let's assume the APIRequestLog model is like the below, class APIRequesLog(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) url = models.CharField(null=True, blank=True) ... In our system there we have a model called Dashboard and this model has an attribute called URL. Let's assume the Dashboard model is like below, class Dashboard(models.Model): shortname = models.CharField(null=True, blank=True) url = models.CharField(null=True, blank=True) ... My requirement is when I query the dashboard model, I need to get all the APIRequestLog records that are similar to the dashboard URL. I know that we can achieve this by iterating the dashboard records and filtering the APIRequestLog which has a similar URL to an iterating dashboard URL. But that would be time-consuming. Is there any method that we can join these two models based on the URL column and fetch the data at once? … -
How to add Tags to a model with django-taggits? (django)
I basically have a template which shows all the Tags you can click one. Then I get the Value of the checkbox (it is the Id of the Taggit Items, because I load the Tags from the Database in my Template) and send it to the database. But how can I give a model in my case a Post the Tag? In Pseudocode that would be: Create object Post Get tags from frontend >>> 1, 2 create taggit_taggeditem give item: object id: 22 tag ids: 1, 2 Thank you for answers. I don't have any ideas how to do that : ) . -
Compare values with each other and color the difference red
I have a django application. And I try to mark the difference of both the values red. So I have this to functions: pdf data: from django.utils.safestring import mark_safe from tabulate import tabulate class FilterText: def show_extracted_data_from_file(self): def show_extracted_data_from_file(self): verdi_cost = [3588.20, 5018.75,3488.16] regexes = [verdi_cost] matches = [(regex) for regex in regexes] columns = ["kosten fruit"] return mark_safe( tabulate( zip_longest(*matches), # type: ignore headers=columns, tablefmt="html", stralign="center", ) ) excel data: from django.utils.safestring import mark_safe from tabulate import tabulate class ExtractingTextFromExcel: def init(self): pass def extract_data_excel_combined(self): dict_fruit = {"Watermeloen": 3588.20, "Appel": 5018.75, "Sinaasappel": 3488.16} columns = ["naam fruit", "totaal kosten fruit"] return mark_safe( tabulate( dict_fruit.items(), headers=columns, tablefmt="html", stralign="center" ) ) So I want to compare the values from the excel data and the values from the pdf data. and the views.py: def test(request): filter_excel = ExtractingTextFromExcel() filter_text = FilterText() content_excel = "" content_pdf = "" content_pdf = filter_text.show_extracted_data_from_file() # type:ignore content_excel = filter_excel.extract_data_excel_combined() context = {"content_pdf": content_pdf, "content_excel": content_excel} for ((fruit, a), b) in zip(content_excel, content_pdf): if (a, b): return fruit return render(request, "main/test.html", context) and the template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% … -
View admin page if the log in user is admin in Django
I am doing a Django project. If the user is admin, then the admin will view the admin-profile page after logging in. But if the user is researcher, then the researcher can view the researcher-profile page after logging in. django_project/settings.py LOGIN_REDIRECT_URL = 'researcher-profile' blog/views.py from django.shortcuts import render from .models import Post, Category from django.views.generic import ListView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import PostForm # get all posts of the logged in user class UserPostListView(LoginRequiredMixin, ListView): model = Post # query the post model to create the list of articles template_name = 'blog/researcher-profile.html' context_object_name = 'posts' ordering = ['-created'] def get_queryset(self): return Post.objects.filter(author = self.request.user) researcher-profile.html {% extends 'users/base.html' %} {% block content %} {% for post in posts %} {% if post.approved %} <div class="card mb-3"> <img class="card-img-top" src="{{ post.image.url }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ post.title|truncatechars:70 }}</h5> <p class="card-text">{{ post.content|truncatechars:200|safe }}</p> <a href="{% url 'post-detail' post.aid %}" class="btn btn-primary"> See Details </a> </div> <div class="card-footer text-secondary"> <a class="mr-2" href="{% url 'researcher-profile' %}">{{ post.author }}</a>|| {{ post.created|date:"F d, Y" }} </div> </div> {% endif %} {% endfor %} {% endblock content %} admin-profile.html {% extends 'users/base.html' %} {% block content %} <h1> Admin Post Apporval Portal</h1> … -
I want to add flag field to users in User model(inbuilt) to manage account as active and deactivate in django
J want to change users flag field to disable,how to manage user profiles by flag field. Adding flag field by Boolean and manage accounts as active state and de activated state. -
Django, Nginx, and Docker. DEPLOYMENT
I want to deploy my app which is made by django and flutter and i have used docker to dockerize the django and the nginx. Here what i has so far and what should i add or change: docker-compose.yaml: version: '3.8' services: api: build: context: ./api command: gunicorn myproject.wsgi:application --bind 0.0.0.0:8000 volumes: - ./api:/app/ - static:/app/static/ expose: - 8000 depends_on: - db db: image: postgres:latest volumes: - data:/var/lib/postgresql/data/ server: build: context: ./server volumes: - static:/app/static/ - media:/app/media/ - certs:/etc/nginx/certs ports: - 443:443 - 80:80 certbot: image: certbot/certbot depends_on: - api volumes: data: static: media: certs: dockerfile (django): FROM python:latest ENV SECRET_KEY 123 ENV DATABASE_PASSWORD postgres ENV DEBUG 0 RUN mkdir /app WORKDIR /app COPY . . RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN python manage.py collectstatic --no-input dockerfile (nginx): FROM nginx:latest RUN mkdir /server RUN rm /etc/nginx/conf.d/default.conf COPY ./nginx.conf /etc/nginx/conf.d/ WORKDIR /server nginx.conf: server { listen 80; server_name mydomain.com return 301 https://$server_name$request_uri; location / { proxy_pass http://server; } location /static/ { alias /server/static/; } } server { listen 443 ssl; server_name mydomain.com; } Thanks for your time I have tried searching online but i couldn't find much answers -
How to change the size of UserCreationForm?
I wanna modify the weight of the fields in UserCreationForm. How ist that possibly? class SignUpForm(UserCreationForm): username = forms.CharField( widget=forms.TextInput(attrs={ "class": "input", "type": "text", "placeholder": "Username", }) ) email = forms.CharField(widget=forms.TextInput(attrs={ "class": "input", "type": "email", "placeholder": "Email" })) password1 = forms.CharField(widget=forms.TextInput(attrs={ "class": "input", "type": "password", "placeholder": "Password" })) password2 = forms.CharField(widget=forms.TextInput(attrs={ "class": "input", "type": "password", "placeholder": "Password" })) class Meta: model= User fields = [ "username", "email", "password1", "password2" ] I wanna modfy the size of the fields: Username, Email, Password1 and Password2 More precisely, I want the fields longer -
How to Optimize a loop "For" in Django
I want to optimize this functions, because they take too long, each of them bring specific atributes, if you can help me. I think there's maybe a way to call the atributes in the function. The functions are made with python and Django. This is what i've done so far. Definition of the functions. cand_seleccionados = ListaFinal.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) seleccionados_ids = cand_seleccionados.values_list('interesado_id', flat=True) cand_postulados = Postulados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=seleccionados_ids) postulados_ids = cand_postulados.values_list('interesado_id', flat=True) cand_entrevistados = Entrevistados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=postulados_ids) This is the loop for cand_Postulados, the others are the same so i thought it wouldnt be necesary to put more for p in cand_postulados: postulado = dict() telefono = Perfil.objects \ .values_list('telefono', flat=True) \ .get(user_id=p.interesado.candidato.id) postulado['id'] = p.interesado.candidato.id postulado['nombre'] = p.interesado.candidato.first_name postulado['email'] = p.interesado.candidato.email postulado['teléfono'] = telefono if p.interesado.id_oferta.pais is None: postulado['pais'] = "Sin pais registrado" else: postulado['pais'] = p.interesado.id_oferta.pais.nombre postulado['nombre_reclutador'] = p.interesado.id_reclutador.first_name postulado['id_reclutador'] = p.interesado.id_reclutador.id postulados.append(postulado) -
Deploying Django Postgres to Digital Ocean Droplets
I have to deploy a Django API to Digital Ocean, a service that should scale a bit over the next year. I also need a database to save all the data from the users, and I will use Postgres. Recently I saw a lot of video tutorials, official guides from the digital ocean and so on that tell us to use the Postgres that you install on the Droplets "locally" as the database, so install locally postgres and put there all the data. It actually can make sense since the droplet I will pay for is about 25 GB that I will never really reach. So, my question was if this approach makes sense at all, or is way better to set up right now a different possibility, like a database on the digital ocean itself? If I keep these settings, will I be able to easily migrate in the future? Or will it be painful if not impossible? Is there a very good cost-efficient way to do this, or this solution is good enough even for a platform that needs to scale (let's say 100,000 users and a really high amount of requests for each one of them at … -
How to add email to be able to log in via Google oauth Django
I'm building a Django project and I have 3 applications. Students log in to complete the given items. Teachers log in to manage the list of student actions. Administrators manage permissions and logins. Administrators will add student and teacher email addresses. to check that only the added email will be able to log in and my project is using only google oauth login, can anyone guide me what i need to do? If you want an admin to add an email address And only the added email will be able to login. what i tried views.py def admin_user_setting(req): if req.method == "POST": email_user = req.POST.get('email_user') obj = Add_User_Email_User(email_user=email_user) obj.save() return redirect('/admin_user_setting') else: obj = Add_User_Email_User() obj = Add_User_Email_User.objects.all() AllUser = Add_User_Email_User.objects.all() page_num = req.GET.get('page', 1) p = Paginator(AllUser, 10) try: page = p.page(page_num) except: page = p.page(1) context = { "AllUser": Add_User_Email_User.objects.all(), "page" : page, } return render(req, 'pages/admin_user_setting.html', context) urls.py urlpatterns = [ path('admin_user_setting',views.admin_user_setting, name="admin_user_setting"), ] forms.py class UserForm(ModelForm): class Meta: model = Add_User_Email_User fields = ['email_user'] admin.py admin.site.register(Add_User_Email_User) models.py class Add_User_Email_User(models.Model): email_user = models.CharField(max_length=500, null=True) def __str__(self): return self.email_user -
I want to make a subscription system with django
How can I make an auto incrementing timer, for example, it will count forward 1 year from now and these transactions will be saved in the database. -
How to check django login status in JavaScript?
What is the best way to check django user is authenticated in JavaScript file? -
How to implement recursive in Django Serializers
My serializers class class ConditionSerializers(serializers.ModelSerializer): class Meta: model = TblCondition fields = ['id','operator','condition','relation'] class ConditionSerializers(serializers.ModelSerializer): relation_with=ConditionSerializers(many=False) class Meta: model = TblCondition fields = ['id','operator','relation_with','condition','relation'] class RuleSerializers(serializers.ModelSerializer): conditiontbl=ConditionSerializers(many=True) class Meta: model = TblRule fields = ['rule_table_no','rule_no','rule_name','columns','data_file','true','conditiontbl' ] My model class class TblRule(models.Model): rule_table_no=models.AutoField(primary_key=True) rule_no=models.IntegerField(blank=False) rule_name=models.CharField(max_length=100,blank=False) columns=models.CharField(max_length=100) data_file=models.CharField(max_length=100) true=models.CharField(max_length=100) class TblCondition(models.Model): rule=models.ForeignKey(TblRule, on_delete=models.CASCADE,related_name='conditiontbl') operator=models.CharField(max_length=100) condition=models.CharField(max_length=100) relation=models.CharField(max_length=50,blank=True) relation_with=models.OneToOneField(to='self',null=True,blank=True,on_delete=models.CASCADE) Getting these results in postman API by calling ruletbl models [ { "rule_table_no": 2, "rule_no": 1, "rule_name": "Age Discritization", "columns": "Age", "data_file": "Data1", "true": "Teen", "conditiontbl": [ { "id": 4, "operator": ">", "relation_with": null, "condition": "15", "relation": "" }, { "id": 5, "operator": "<=", "relation_with": { "id": 4, "operator": ">", "condition": "15", "relation": "" }, "condition": "25", "relation": "and" } ] }, { "rule_table_no": 3, "rule_no": 1, "rule_name": "Age Discritization", "columns": "Age", "data_file": "Data1", "true": "Young", "conditiontbl": [] } ] You can see conditiontbl list fileds in ruletbl model (e.g. in JASON results), inside conditiontbl filed we have objects of tblcondition models with fileds ("relation_with"), and this relation_with filed is again refering to its own tblcondition model you can see its second object. I want this refering in relation_with fileds to its own conditiontbl model to be recursive. Any solution ? -
Prevent form from resubmitting after button click
I have a Django project where I have a few forms. What is happening is when I click button submit 30 times, my data is inserted 30 times in the database. I did my research and I saw lots of jquery or javascript solutions in general but I am not familiar much with them so I am trying to find a more pythonic/django solution. Here is my code: views: @method_decorator(login_required(login_url='index', redirect_field_name=None), name='dispatch') class CreatePostView(views.FormView): model = Post form_class = CreatePostForm template_name = 'posts/create_post.html' def form_valid(self, form): post = form.save(commit=False) post.user = self.request.user post.save() return redirect('index') template: <form action="{% url 'create post' %}" method="POST" enctype="multipart/form-data"> {{ form.as_p }} {% csrf_token %} <p> <button type="submit" class="btn btn-secondary">Submit</button> </p> </form> model: class Post(models.Model): MAX_TITLE_LENGTH = 20 MIN_TITLE_LENGTH = 3 MAX_DESTINATION_LENGTH = 30 MIN_DESTINATION_LENGTH = 3 MAX_DESCRIPTION_LENGTH = 550 MIN_DESCRIPTION_LENGTH = 5 title = models.CharField( max_length=MAX_TITLE_LENGTH, validators=(MinLengthValidator(MIN_TITLE_LENGTH), name_and_title_validator), error_messages={ 'max_length': f'Post title must be a maximum of {MAX_TITLE_LENGTH} characters.', 'min_length': f'Post title must be at least {MIN_TITLE_LENGTH} characters long.', }, null=False, blank=False, ) photo = CloudinaryField( folder='mediafiles/post_photos', public_id=get_photo_name_by_post_name, null=False, blank=False, ) destination = models.CharField( max_length=MAX_DESTINATION_LENGTH, validators=(MinLengthValidator(MIN_DESTINATION_LENGTH), ), error_messages={ 'max_length': f'Destination must be a maximum of {MAX_DESTINATION_LENGTH} characters.', 'min_length': f'Destination must be at least {MIN_DESTINATION_LENGTH} … -
using tabula with excel data with Django
I have a django application. And I try to format data from excel, But I get this error: Exception Type: ValueError Exception Value: not enough values to unpack (expected 2, got 1) So I have this function: class ExtractingTextFromExcel: def init(self): pass def extract_data_excel_combined(self): dict_fruit = {"Watermeloen": 3588.20, "Appel": 5018.75, "Sinaasappel": 3488.16} # calculate_total_fruit = self.calulate_total_fruit_NorthMidSouth() columns = ["naam fruit", "totaal kosten fruit"] print("\n".join(f"{a} {b:.2f}" for a, b in dict_fruit.items())) return "\n".join( f"{a} {b:.2f}" for a, b in mark_safe( tabulate( dict_fruit.items(), headers=columns, tablefmt="html", stralign="center", ) ) ) then views.py: def test(request): filter_excel = ExtractingTextFromExcel() content_excel = "" content_excel = filter_excel.extract_data_excel_combined() context = {"content_excel": content_excel} return render(request, "main/test.html", context) and template: <div class="form-outline"> <div class="form-group"> <div class="wishlist"> {{ content_excel }} </div> </div> </div> question: how to format data from excel correct with tabula? -
How to simulate a Field storing only hours and minutes in Django
I would like to store for a model "House", in django, a field stocking an hour and a minute, and to be able to edit it easily by only editing hour and minute. I am aware that TimeField exists in django, but its editing in Django admin is not so great : You have to set your value like this : 10:59:00 (for 10:59am) I would like to be able to get a line with : Hour [...] Minute [...] to be able to input two numbers (with validators so that the hour has to be between 0-23 and minutes between 0-59). My best idea at this point was to make a OnetoOneField in the "House" model to an "Hour" Model which get two IntegerField (And using validators). It works great, but the downside is that while editing an instance of House in admin, i can see the Hour instances linked to other instances of House. For exemple if i have two "House" instances, House1 and House2, when i edit House2, i can see the Hour instance linked to House1 in the scrolling menu. (Problem that i would not get if i had directly two IntegerField in "House" for exemple). … -
Getting query length with Ajax / Django
According to the selection in the form, I want to get the number of records that match the id of the selected data as an integer. Here is my view : def loadRelationalForm(request): main_task_id = request.GET.get('main_task_id') relational_tasks = TaskTypeRelations.objects.filter(main_task_type_id = main_task_id) data_len = len(relational_tasks) return JsonResponse({'data': data_len}) Here is my ajax : <script> $("#id_user_task-0-task_types_id").change(function () { const url = $("#usertask-form").attr("data-relationalform-url"); const mainTaskId = $(this).val(); $.ajax({ url: url, data: { 'main_task_id': mainTaskId, }, success: function (resp) { console.log(resp.data); } }); }); I want to write the number of relational tasks associated with the main_task_id of the selected data in the form. But I couldn't do it. Thanks for your help. Kind regards -
ModuleNotFoundError: No module named 'myapp.urls'
I tried to change setting to below but doesn't work: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp'] my directory: manage.py django_project __init__.py asgi.py settings.py urls.py wsgi.py myapp migration __init__.py admin.py apps.py models.py tests.py urls.py views.py it keeps showing ModuleNotFoundError: No module named 'myapp.urls' views.py from myapp: from django.shortcuts import render, Httpresponse def index(request): HttpResponse('Welcome!') urls.py from myapp: from django.urls import path urlpatterns = [ path('', views.index ), path('create/', views.index) path('read/1/', views.index) ] urls.py from django_project: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')) ] Thank you! -
Django dynamic localization not working as expected on mobile devices
I have question about show current language on mobile devices if I populate my language list in template dynamically (got from languages array from settings)... So, this code working properly: <a href="#" id="language-en" class="pure-drawer-link{% if LANGUAGE_CODE == 'en' %} active{% endif %}"> EN </a> BUT, when I'm trying this code, I can't achive that active class added to current language: {% for lng in settings.LANGUAGES %} {% if not lng.0 == "ru" %} <a href="#" id="language-{{ lng.0 }}" class="pure-drawer-link{% if LANGUAGE_CODE == '{{ lng.0 }}' %} active{% endif %}"> {{ lng.0|upper }} </a> {% if LANGUAGE_CODE == '{{ lng.0 }}' %} active {% else %} nonactive{% endif %} => this always return nonactive {% endif %} {% endfor %} Can anyone help to understood why this is happening?