Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Key error django - passing additional stuffs with django form
I have my models like this: class Photo(models.Model): title = models.CharField(max_length=255, blank=True) file = models.FileField(default='default.jpg') page = models.ForeignKey(Page, on_delete=models.CASCADE) class Page(Group): name = models.IntegerField() in my forms.py, to create a form for posting multiple images, I created this: I also override get_form_kwargs for passing the 'page' thing with the form as you can see that the Photo model has a page foreignkey. class PhotoForm(forms.ModelForm): def get_form_kwargs(self): kwargs = super(PhotoForm, self).get_form_kwargs() kwargs['page'] = Page.objects.get(pk=self.GET['pk']) return kwargs class Meta: model = Photo fields = ('file', ) In my main urls.py, I say like: path('page/<int:pk>/photos/', include('photos.urls')) and in photos apps urls.py, I say: path('progress-bar-upload/', views.ProgressBarUploadView.as_view(), name='progress_bar_upload') and in my photos apps views.py I say: class ProgressBarUploadView(View): model = Photo def get(self, request, **kwargs): photos_list = Photo.objects.all() page = get_object_or_404(Page, page=self.kwargs['page']) return render(self.request, 'photos/progress_bar_upload/index.html', {'photos': photos_list, 'page':page}) def post(self, request): time.sleep(1) form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) Then when in my html I call the page, {{page}} Then when I go to 'localhost:/page/1/photos/progress-bar-upload/' I get this error: KeyError at /page/7/photos/progress-bar-upload/ 'page' So what can I do? Can someone help me? Any help will be much much … -
Django static files not loading after serving files in cpanel using whitenoise
I tried serving my static files using whitenoise, but still not getting any of my css/js loading in my pages. I ran collectstatic after enabling whitenoise and static folder was generated. I tried using both STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' and django's ManifestStaticFilesStorage backend. Here are my settings INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.humanize', 'crispy_forms', 'classroom', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'django_school.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], '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 = 'django_school.wsgi.application' ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'public/static'), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' This is how my project is structured home -->etc -->thegradientboostmvp ---->classroom ---->django-app ---->public ---->static ------>admin ------>css ------>img ------>second >css >js >img ------>third >css >js >img ------>fourth >img >js >css ---->templates -
pip cannot install SciPy, error: Microsoft Visual C++ 14.0 is required
I tried to install SciPy, but it fails and tells me I need Microsoft Visual C++ 14.0. With Python 2.7 I was able to install it just fine, but now with Python 3.8 it does not work. Also I have Microsoft Visual C++ 2015-2019 installed, which is version 14.24, so I guess this should be fine? Any ideas? Greets, Tim -
Dynamic formset creation
I have a database similar to this: Group ConditionGroup Has a ForeignKey(Group) only if it is the 'main condition group' Has an ForeignKey(ConditionGroup) if it's depending of another group (like a tree and at the top it's always a main) Condition ForeignKey(ConditionGroup) Note: if an ConditionGroup has conditions it cannot have any sub conditionGroups example : [(A > B) AND (A > C)] OR [(A < B) AND [(A < C) and (B > C)] could be Group (having a main GroupCondition) [(A > B) AND (A > C)] is a GroupCondition depending directly on GroupCondition (A > B) is a Condition Thing is creating a group without creating at the same time the conditiongroups and the conditions are pointless so I am trying to do it dynamically with inline_formset_factory but I struggle to know the parent of a GroupCondition and of a Condition (at the moment they are all linked from the same management_form. Is there a way to put inside a form some formset factory (even from the form itself) ? Else I am going for an hidden input that will store the ID of the parent and figure it out from the view but i find this … -
How to apply css to a three level recursive mptt tree in Django template?
I have following template for an Django-mptt tree: {% load static i18n %} <div id="work_tree"> {% load mptt_tags %} <ol> {% recursetree piece_tree %} <li> <a href="../{{ node.id }}">{{ node.name_w_version }}</a> {% if not node.is_leaf_node %} <ul class="children"> <em>{{ children }}</em> </ul> {% endif %} </li> {% endrecursetree %} </ol> </div> The tree has three levels: Level 1 |---> Level 2 |---> Level 3 I would like to style each level differently. What do I have to change in my template to accomplish this? -
Docker: Running Celery in detatched -d mode
I'm not sure if I am missing something, or not quite understanding the nuances of containerization, but I have provisioned celery and celery-beat services that are working in attached mode, e.g., using: docker-compose -f docker-compose.production.yml up --build But the are not beating when used in detatched mode: docker-compose -f docker-compose.production.yml up --build -d I'm not sure what I am missing here? -
Match table relationship between team and player
I have 2 tables Entry and Match if tournament team based is_team=true if player based is_team=false, so my question is how can I make a more effective match table, what would you suggest? Thus i think that is not efficient for now. Note: The reason I do this may not be the team of every player, so I just can't make the winner_team and team_a and team_b. class Entry(models.Model): #Entries tournament = player = team = is_team = class Match(models.Model): entry_id = models.ForeignKey() team_a = # if player based=null team_b = player_a = # if team based = null player_b = score_a = score_b = winner_team = # if player based=null winner_player = # if team based = null -
Django Update Database record is not working
Iam trying to get a records which works, but it just does not want to update the record... ----urls.py---- from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('EditAcronis/<int:id>', views.edit_acronis, name='edit_acronis'), ] ----Views.py---- @login_required() def edit_acronis(request, id=None): item = get_object_or_404(Acronis, id=id) acroniform_form = acroniform(request.POST or None, instance=item) if acroniform_form.is_valid(): item = acroniform_form.save(commit=False) item.save(force_update=True) return redirect('/Verwaltung/Acronis') else: form = acroniform(instance=item) return render(request, 'blog/editacronis.html', {'acroniform_form': acroniform_form}) ----editacronis.html---- {% extends 'blog/base.html' %} {% load bootstrap4 %} <html lang="en"> <meta charset="UTF-8"> <title>{% block supertitle %} Home {% endblock %}</title> {% block Content %} <P></P> <form class="form-inline, form-row" action="{% url 'blog:acr' %}" method="post"> {% csrf_token %} {% bootstrap_form acroniform_form %} <button type="submit" class="btn btn-success">Update</button> </form> <p>Acronis</p> <P></P> {% endblock %} What's wrong with my code? item.save() is not saving or updating the databaserecord... -
Filter Traffic using Digital Ocean firewall and Nginx
I have two droplets on digital ocean for my project, droplet A is the application Frontend and droplet B is the Backend. Everything is working perfectly but I want to filter traffic going to droplet B to only allow access from droplet A using Digital Ocean Firewall. I created rules to allow all Tcp, HTTP, UDP, ICMP and HTTPS from droplet A, but once I implement the rule on droplet B, it blocks all access even from droplet A. I checked my firewall rules, and I have confirmed it's correct. On droplet B, I'm using Nginx server listening on port 80 and proxy_passing my gunicorn.sock; can this affect the headers since requests goes through Nginx? I have also tried binding my gunicorn to port 8000 and proxy_passing port 8000 instead. Please what is the proper way to filter traffic coming into droplet B using digital ocean firewall? Does it have anything to do with my Nginx server? -
can't delete item from database in django view
i created a view to delete an object through a template but it seems im missing something i cant quite put together def product_delete_view(request, id): obj = get_object_or_404(Product, id=id) if request.method == "POST": obj.delete() return redirect('../../') context = { "obj": obj } return render(request, "products/product_delete.html", context) from django.contrib import admin from django.urls import path from pages.views import home_view, contact_view, about_view, social_view, services_view #from products.views import product_detail_view, product_create_view, render_intial_data from products.views import render_intial_data, dynamic_lookup_view, product_delete_view urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('contact/', contact_view, name='contact'), path('about/', about_view, name='about'), path('services/', services_view, name='services'), path('social/', social_view, name='social'), #path('product/detail', product_detail_view, name='pdtDetail'), #path('product/create', product_create_view, name='pdtCreate') path('product/create', render_intial_data, name='pdtCreate'), path('product/<int:id>', dynamic_lookup_view, name="pdt"), path('product/<int:id>/delete', product_delete_view, name='pdtDelete') ] {% extends 'base.html' %} {% block content %} <form action="." method="POST"> {% csrf_token %} <h1>Do you want to delete the product "{{ obj.title }}"</h1> <p><input type="submit" value="Yes" /> <a href="../">Cancel</a></p> </form> {% endblock %} when i try to delete object is not removed from the database table -
is it possible to get exact client local IP address using django under mikrotik hotspot network?
when I connected my server to regular router request.META['REMOTE_ADDR'] works fine. it gets the correct IP, but when I setup the connection within mikrotik hotspot it gets the DNS IP which is 10.17.1.1. my settings: -> hotspot address 10.17.1.1/24 -> server address 10.17.1.2 -> server was already added in walled garden and IP Binding to bypass hotspot authentication I got an access to the server website even not logged in to hotspot but i got the client incorrect ip address which always returned as 10.17.1.1 please help... any best ideas or solutions will be much appreciated! thanks! -
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '()'
Django template throwing the following error processing a pandas data frame . "django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '()' from 's_results.iterrows()'" views.py return render(request,'search.html',{'s_results':s_results}) search.html {% for index, row in s_results.iterrows() %} {{ row['ColName'] }} {% endfor %} Can I get some help ? -
Django Uploaded web site is failing to launch
this my first time to deploy a website developed in Django into PlanetHoster. After finishing the deployment procedures and launch the web site, I am getting the error in the attached file. When I activate the display_errors in the PHP Selector section in the cPanel, I am getting the error log bellow: App 2287 output: /opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses App 2287 output: import sys, os, io, re, imp, threading, signal, traceback, socket, select, struct, logging, errno App 2287 output: Traceback (most recent call last): App 2287 output: File "/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/wsgi-loader.py", line 369, in <module> App 2287 output: app_module = load_app() App 2287 output: File "/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/wsgi-loader.py", line 76, in load_app App 2287 output: return imp.load_source('passenger_wsgi', startup_file) App 2287 output: File "/home/massvnrc/virtualenv/myproject/3.7/lib64/python3.7/imp.py", line 171, in load_source App 2287 output: module = _load(spec) App 2287 output: File "<frozen importlib._bootstrap>", line 696, in _load App 2287 output: File "<frozen importlib._bootstrap>", line 677, in _load_unlocked App 2287 output: File "<frozen importlib._bootstrap_external>", line 728, in exec_module App 2287 output: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed App 2287 output: File "/home/massvnrc/myproject/passenger_wsgi.py", line 1, in <module> App 2287 output: from myproject.wsgi import application App … -
Celery - Logging does not work when Always Eager = True
I am developing an application and use celery. Logging works fine when the tasks are run async but not when CELERY_TASK_ALWAYS_EAGER is enabled. How can I enable it? # Settings.py # http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-always-eager CELERY_TASK_ALWAYS_EAGER = True # http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-eager-propagates CELERY_TASK_EAGER_PROPAGATES = True # tasks.py from celery import shared_task, task from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @task() def test_task(): logger.info("Logging test") -
Django signals post_save update
When the student enrollment record (discount type) is updated the student discount (discount type) is also updated, but what should i do if i want to update the student enrollment record (discount type) using student discount (discount type) This is my models.py class studentDiscount(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(pre_save, sender=StudentsEnrollmentRecord) def get_older_instance(sender, instance, *args, **kwargs): try: instance._old_instance = StudentsEnrollmentRecord.objects.get(pk=instance.pk) except StudentsEnrollmentRecord.DoesNotExist: instance._old_instance = None @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): if not created: older_instance = instance._old_instance if older_instance.Discount_Type != instance.Discount_Type: studentDiscount.objects.filter( Students_Enrollment_Records=instance ).delete() else: return None discount = studentDiscount.objects.filter(Discount_Type=instance.Discount_Type) if created: print("nagsulod") studentDiscount.objects.create( Students_Enrollment_Records=instance, Discount_Type=instance.Discount_Type) else: studentDiscount.objects.create( Students_Enrollment_Records=instance, Discount_Type=instance.Discount_Type) def __str__(self): suser = '{0.Students_Enrollment_Records}' return suser.format(self) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) strands = models.ForeignKey(strand, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) ESC = models.ForeignKey(esc, on_delete=models.CASCADE,null=True,blank=True) Remarks = models.TextField(max_length=500,null=True,blank=True) class Discount(models.Model): Code=models.CharField(max_length=500,blank=True) Discount_Type=models.CharField(max_length=500,blank=True) Remarks=models.TextField(max_length=500,blank=True) TuitionFee_Discount_Amount=models.FloatField(null=True,blank=True) TuitionFee_Discount_Rate = models.FloatField(null=True,blank=True) Miscellaneous_Discount_Amount=models.FloatField(null=True,blank=True) Miscellaneous_Discount_Rate = models.FloatField(null=True,blank=True) if i update the student enrollment record (Discount_Type) the student discount (discount type) update … -
can't convert text data to json
i have the following data: data = "{'id': 26, 'photo': '/media/f082b5af-ad0.png', 'first_name': 'Islam', 'last_name': 'Mansour', 'email': 'islammansour06+8@gmail.com', 'city': 'Giza', 'cv': '/media/fbb61609-442.pdf', 'reference': 'Facebook', 'campaign': OrderedDict([('id', 2), ('name', 'javascript')]), 'status': 'Invitation Sent', 'user': None, 'at': '2020-01-20', 'time': '23:02:58.359179', 'technologies': [OrderedDict([('id', 46), ('name', 'Django'), ('category', OrderedDict([('id', 24), ('name', 'Framework'), ('_type', 'skill')]))])]}" i am trying to convert it to json by using json.loads(data.replace("\'", "\"")) but i am having the following error json.decoder.JSONDecoderError: Expecting value: line 1 column 219 (char 218) -
how to save utc time without offset in postgresql using django
Hi im using django and in my one of the model i have created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and settings.py file TIME_ZONE = 'UTC' USE_TZ = True using this date and time automatically saving PostgreSQL db in format of 2020-01-24 20:13:47.846445+05:30 with offset(+05:30) but i want to save it as 2020-01-24 14:43:47.846445+00:00 without offset means as 00 but if inspect one instance created_at row data using python manage.py shell i am getting required format so how to save date and time with offset 00:00 ? -
How to pull related data for context in a template?
I have following models: class Work_Music(MPTTModel, Work): key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) tempo = models.CharField(max_length=500, null=True, blank=True) @property def is_opera(self): return hasattr(self, 'opera') class Opera(models.Model): work = models.OneToOneField(Work_Music, verbose_name=_('work_music'), related_name='opera', on_delete=models.PROTECT) librettist = models.ForeignKey(Person, verbose_name=_('librettist'), null=True, blank=True, related_name='person', on_delete=models.PROTECT) class OperaCast(models.Model): opera = models.ForeignKey(Opera, verbose_name=_('opera'), related_name='opera_cast', null=True, blank=True, on_delete=models.PROTECT) name = models.CharField(max_length=100, null=True, blank=True) My view.py is: class Work_MusicView(TemplateView): template_name = 'composers/work_music/work.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) piece = Work_Music.objects.get(pk=self.kwargs['pk']) piece_tree = Work_Music.objects.get(pk=self.kwargs['pk']).get_family() opera = Opera.objects.get(work=self.kwargs['pk']) context.update({ 'piece': piece, 'piece_tree': piece_tree, 'opera': opera, 'opera_cast': OperaCast.objects.filter(opera__work=self.kwargs['pk']).order_by('order'), }) return context If a piece of work is an opera, I'd like to pass the Opera and OperaCast object in a the context and display these metadata in the template. Right now the metadata is not structured. -
DRF serializer remove imagefield absolute url
In DRF, now if i save the image the serializer is giving me the image with absolute path. But in my scenario, i don't want absolute path. I just need a image path which is there in DB. In my scenario, i'm hard-coding the image path in json. So i can't use the absolute path. Can anyone suggest some ideas to implement it. -
Cannot save Point in model with GeoDjango
I'm building a website with Django and, in some page, the user can use a geolocation system to save its current location. At the beginning, the page display a google map centered on a random location. Then the user clicks on a button, it locates him and its current location is displayed on the map. The field latitude and longitude of a form are automatically filled. After that, the user can submit the form and a view is responsible for saving a Point object in the database with the latitude and the longitude. The problem is that the Point is not created : when I go to the admin interface, we see that the location attribute is not initialized and when I try to get the latitude and longitude from the Point in another view, I get the error 'NoneType' object has no attribute 'y' that proves that the Point is never created. I don't understand why because the view correctly get the latitude and longitude values (I display them in a message to be sure they are correct). Here is the relevant parts of my code : models.py from django.contrib.gis.db import models as models2 class UserAdvanced(models2.Model): localisation = models2.PointField(blank … -
Adding anoter model field, jquery field uploader
I am trying to implement JQuery file uploader in Django but through me an error when I add another field in the model. I think there is a way to change the js and add another field to by process, but I'm not well documented using JS. My view @method_decorator(login_required, name='dispatch') class PictureCreateView(CreateView): model = Picture fields = "__all__" def form_valid(self, form): self.object = form.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') Model class Picture(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) file = models.FileField(upload_to="user_directory_path") slug = models.SlugField(max_length=50, blank=True) def __str__(self): return self.file.name def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.file.delete(False) super(Picture, self).delete(*args, **kwargs) -
Django forms: how to use a switch case ChoiceField / choises using request.session value?
I have 2 linked models for thesaurus with labels in English and French I have a 2 class methods (options_list_eng and options_list_fra) that return list of labels based on code pass in parameters: one that return french labels and the other return english labels I also have a request.session['language'] that catch the browser language of user I want to use theses methods to set choices attributes in my form depending of the language (value in request.session.get('language') I try ti use something like that but it do not works if self.language == 'en': TYPES = Thesaurus.options_list_eng(1) else: TYPES = Thesaurus.options_list_fra(1) below my current code that run well but do not allowed french/english translation of choices forms.py class RandomisationForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): self.request = request self.language = request.session.get('language') super(RandomisationForm, self).__init__(*args, **kwargs) TYPES = Thesaurus.options_list_eng(1) ran_pro = forms.ChoiceField(label = _("Type"), widget=forms.Select, choices=TYPES) -
why `pagedown` doesn't work in my Django application?
I followed pagedown documentation instruction as below: installing pagedown using pipenv install django-pagedown Added that in INSTALLED APPS as: 'pagedown.apps.PagedownConfig', Collected the static files: python manage.py collectstatic and in forms.py: from pagedown.widgets import PagedownWidget class ProductForm(forms.ModelForm): description = forms.CharField(widget=PagedownWidget()) class Meta: model = Product fields = ['name', 'price', 'description'] finally, according to documentation: I also added {{ form.media }}. After implementing these I don't get any error and still pagedown is not working. What is the problem? Please help me with this! thank you! -
Can't get a foreign key to filter in Django
I am just getting used to Django and I'm having trouble trying to filter data so that when I pass in a primary key, it uses that primary key to filter the data in a model so that only data courses associated with that primary key are listed. Unfortunately I keep getting 500 errors etc. The models are: class TrainingGroup(models.Model): title = models.CharField(max_length=15) img = models.CharField(max_length=50) class TrainingCourse(models.Model): title = models.CharField(max_length=30) img = models.CharField(max_length=50) group = models.ForeignKey(TrainingGroup, on_delete=models.CASCADE) I am then trying to filter the TrainingCourse table/model down using the following view: class TrainingView(View): def get(self, request, **kwargs): intPK = self.kwargs['pk'] group = TrainingGroup.objects.get(pk=intPK) courses = TrainingCourse.objects.filter(pk__eq=intPK) context = { 'group': group, 'courses': courses, } return render(request, 'training.html', context=context) I must admit that I made the pk__eq up, but I'm not really sure what I am supposed to be using to filter this and I cannot get it to work. p.s. The migration has created a table with the columns id, title and img. Thanks Mark -
In Django template, image is not displayed correctly
I have model class with fields current_value and previous_value. And then, in template used by listview, inside loop i have code like this: {% if data.current_value < data.previous_value %} <img src="{% static 'app1/negative.png' %}" width="40" height="40"> <h1>Price down</h1> {% elif data.current_value > data.previous_value %} <img src="{% static 'app1/positive.png' %}" width="40" height="40"> <h1>Price up</h1> {% else %} <img src="{% static 'app1/neutral.png' %}" width="40" height="40"> <h1>Price the same</h1> {% endif %} H1 text is displayed correctly, image is not. More specific - image for 'else' condition i believe is always ok, but for 'if' and 'elif' is displaying the same picture (one of them). Confusing and infuriating. What am i doing wrong?