Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I refer to single value of foreign key in Django's template?
I have model: `class product(models.Model): product = models.CharField(primary_key=True, unique=True, max_length=7, editable=False) desc = models.CharField(max_length=50) class pricelist(models.Model): product = models.ForeignKey(product, on_delete=models.CASCADE) price_group = models.ForeignKey(pricegroup, on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2, null=True)` Basically I have 4 different price groups(one product may have up to 4 different prices- one for each price_group) and I'd like to display product's price of specified(filtered) price group on my product's template(DetailView). Let's say I have following price groups: "PG1", "PG2","PG3","PG4" I'm able to loop through the list of them: {% for pricelist in product.pricelist.all %} {{ pricelist.price }} {% endfor %} but I can't display prices for only two specified price groups. I need to display prices on my webpage in the following way: PG1 = 124 PG3 = 367 Sometimes only prices for two or three groups are available -
got this error while runing the django web service
django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name ' six' from 'django.utils' -
Modular python admin pages
I'm building a personal website that I need to apply modularity to it for purpose of learning. What it means is that there is a model that contains x number of classes with variations, as an example a button is a module that you can modify as much depending on provided attributes. I also have a pages model that need to select any of created modules and render it. I can't find any documentation of how to access multiple classes from one field to reference to. Model structure is as below: Modules, contains module A and module B Pages should be able to select any of module A and order its structure. Please let me know if not clear, this is the simplest form I could describe. Am I confusing this with meta classes? How one to achieve what I'm trying to achieve? -
AppRegistryNotReady: Apps aren't loaded yet
I am trying to query data from database using Python shell. settings.py includes: import django django.setup() ... INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products.apps.ProductsConfig', 'users.apps.UsersConfig', 'crispy_forms', ] When i open Python shell i do: > from django.conf import settings > settings.configure() Then I try to import models: > from products.models import Product However, Python returns: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I tried adding django.setup() call in settings and also moving this statement after INSTALLED_APPS. -
why the super(ContactView, self) ? . isnt super use to call a function of parent class and why is that argument necessary
also this line in the below code why is the return necessary: return super(ContactView, self).form_valid(form). class ContactView(FormView): form_class = ContactForm template_name = 'contact-us.html' success_url = reverse_lazy('<app-name>:contact-us') def form_valid(self, form): self.send_mail(form.cleaned_data) return super(ContactView, self).form_valid(form) def send_mail(self, valid_data): # Send mail logic print(valid_data) pass -
Django Ajax post data is not clean on insert
I am posting the data via Ajax using $("#add").click(function () { var data = { 'content': $("#content-input").val(), 'csrfmiddlewaretoken': '{{ csrf_token }}' }; var request = $.ajax({ url: "/ajax/list", method: "POST", data: data, dataType: "json" }); }); I'm trying to save the data in my view using if request.is_ajax() and request.method == 'POST': form = listModel() tmpForm = form.save(commit=False) tmpForm.content = request.POST['content'], tmpForm.user_id = request.user tmpForm.save() return HttpResponse(json.dumps({"message":"saved"}),content_type="application/json") else: return Http404 The data is being saved as ('Test input',), What am I doing wrong? I want the text to be saved normally without the parentheses. Thanks -
how do I pass context variables which use request in Class-based views in django?
In my other views, I am passing in the following context variable. tab: 'documents' authenticated: request.user.is_authenticated Exec: ('Exec' in groups) ElectionOfficer: ('ElectionOfficer' in groups) Staff: request.user.is_staff Username: request.user.username URL_ROOT: settings.URL_ROOT How can I pass in those exact same variables when accessing the page that renders with the /multiple url? in my urls.py url(r'^multiple$', views.SubmissionUploadPage.as_view(), name='multiple_example') in my forms.py class MultipleFileExampleForm(BaseForm): input_file = MultipleUploadedFileField() def save(self): example = UserSubmission.objects.create( title=self.cleaned_data['title'] ) for f in self.cleaned_data['input_file']: UploadedFile.objects.create( example=example, input_file=f ) self.delete_temporary_files() in my views.py class BaseFormView(generic.FormView): template_name = 'file_uploads/example_form.html' def get_success_url(self): return reverse('success') def form_valid(self, form): form.save() return super(BaseFormView, self).form_valid(form) class SubmissionUploadPage(BaseFormView): form_class = forms.MultipleFileExampleForm -
I want to display pptx from my local to webpage using Django
<iframe class="default_position" src="{% static 'images/aa.pps' %}" ></iframe> When i am using this, and after refreshing it, its showing ad download. i want to display on web page, not download. -
Field validation with JavaScript (Django for backend)
I'm working with my checkout form and I'm trying to style the validation form with red when the field is not valid. This is what I have so far, and it works almost perfectly: (function() { const elementsList = document.querySelectorAll("#id_street_adress, #id_zip_code, #id_country, #id_email"); const elementsArray = [...elementsList]; var form = document.getElementById('form'); var elem = document.createElement('div'); elem.id = 'notify'; elem.style.display = 'none'; form.appendChild(elem); elementsArray.forEach(element => { element.addEventListener('invalid', function(event){ event.preventDefault(); if ( ! event.target.validity.valid ) { elem.textContent = 'Please complete the fields below.'; elem.className = 'error'; element.className = 'input textinput textInput form-control invalid'; elem.style.display = 'block'; } else{ element.className = 'input textinput textInput form-control'; } }); element.addEventListener('input', function(event){ if ( 'block' === elem.style.display ) { elem.className = ''; elem.style.display = 'none'; } }); }); })(); The issue with this is that it'll add the css class invalid if the field is -obviously- invalid but it won't remove it if the user changes it to somethinh that in fact is valid. That's what I'm trying to achieve with that else statement, but it won't do the trick. I appreciate any kind of help! Let me know if you need any other code, since I tried to make it as simple as possible. -
Preventing Django view from running context_data on load
My Django site returns data when loading the view, regardless if required parameters have values. I'm using Django-Filters to provide the filter form. My end goal is for the user to have to input the filters prior to the get_context_data method from running. Views.py class BillingListView(LoginRequiredMixin, UserPassesTestMixin, ListView): login_url = '/login/' redirect_field_name = 'redirect_to' raise_exception = True model = Trip queryset = Trip.objects.select_related('pu_Location', 'do_Location', 'driver', 'vehicle') template_name = "main/billing.html" ordering = ("serviceDate", "pu_Time", "tripID") def test_func(self): return self.request.user.is_staff def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = BillingFilter(self.request.GET, queryset=self.get_queryset()) return context Filters.py class BillingFilter(django_filters.FilterSet): trip_choices = ( ('ERRORS', 'ERRORS'), ('PROCESSED', 'PROCESSED'), ) errors_only = django_filters.ChoiceFilter(choices=trip_choices, label='Billing Status', method='get_errors') serviceDate = django_filters.DateFromToRangeFilter(field_name='serviceDate', required=True, label='Date Range', widget=RangeWidget(attrs={'placeholder': 'MM/DD/YYYY'})) def get_errors(self, queryset, field_name, value): if value == 'ERRORS': return queryset.filter(Q(miles__lte=0) | Q(pu_Actual__isnull=True) | Q(pu_Clear__isnull=True) | Q(driver__isnull=True) | Q(vehicle__isnull=True)) if value == 'PROCESSED': return queryset.filter(miles__gte=0, pu_Actual__isnull=False, pu_Clear__isnull=False, driver__isnull=False, vehicle__isnull=False) class Meta: model = Trip fields = ['errors_only', 'serviceDate', ] I've tried to edit the request using a RequestFactory but it didn't seem like the best option. What are best practices to filter the data if required parameters are missing? -
Problems with request object in template
I have a project with videos and i want to make if loop that will add icon to the video if you are on this video right now. How to implement that? template <h1>{{ video.title }}</h1> <video width="960" height="620" id="plyr-video" poster="/path/to/video-poster.png" controls> <source src="{{ video.video.url }}" type="video/mp4"> <source src="/path/to/video.webm" type="video/webm"> <!-- Captions are optional --> <track kind="captions" label="English captions" src="/path/to/video-caption.vtt" srclang="en" default> </video> <h1>{{ course.title }}</h1> <div class="ui styled accordion"> {% for section in sections %} <div class="title {% if section == video.section %}active{% endif %}"> <i class="dropdown icon"></i> {{ section.title }} </div> <div class="content {% if video.section == section %}active{% endif %}"> <div class="ui divided list"> {% for video in videos %} {% if video.section == section %} <div class="item"> <i class="map video icon"></i> <div class="content"> <a class="header" href="{% url 'courses:video_detail' course.slug video.pk %}">{{ video.title }}{% if %}<i class="small play red icon"></i>{% endif %}</a> <div class="description">An excellent polish restaurant, quick delivery and hearty, filling meals.</div> </div> </div> {% endif %} {% endfor %} </div> </div> {% endfor %} -
Django cannot load static images, but can load image through web url
In my Django app, i cannot load images from DB or from local files. But i can load images through image web link. HPGRM\ hpgrm\ setting.py and other files mahasabha\ app.py and other files static\ images\ image1.JPG templates\ base.html manage.py db.sqlite3 {% load static %} <img src="{% static /orange.jpg' %}" /> or <img src="{% static images/orange.jpg' %}" /> #This is working perfectly :- <img src="http://www.clipartbest.com/cliparts/Kcj/p5B/Kcjp5Bb6i.png" class="img_size" alt="NewALT" /> I tried every possible method available on the internet moved static directory to every other directory available in project Changed path in settings.py Used different images Loaded images from Db and more but still cannot find any answers. I can, on other hand copy image link from google and use it as src='image.link.from.google' and can successfully load image [enter image description here][1] #here is error file PS E:\Abhi\HPGRM\hpgrm> py manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 27, 2020 - 21:39:23 Django version 3.0.5, using settings 'hpgrm.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [27/Apr/2020 21:39:28] "GET /home/ HTTP/1.1" 200 3189 Not Found: /home/{% static 'mahasabha/images/img.png' } Not Found: /home/{% static 'mahasabha/images/orange.jpg' } [27/Apr/2020 21:39:28] "GET /home/%7B%%20static%20'mahasabha/images/img.png'%20%7D HTTP/1.1" … -
django.db.utils.ProgrammingError: cannot cast type uuid to integer
I tried to upload my web to Heroku server and stuck at this ploblem my error when I try to migrate my database The above exception was the direct cause of the following exception: return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: cannot cast type uuid to integer LINE 1: ...ict_word" ALTER COLUMN "id" TYPE integer USING "id"::integer ^ models.py class Word(models.Model): id = models.UUIDField(primary_key=True, unique=True) esearch = models.TextField() eentry = models.TextField() tentry = models.TextField() ecat = models.TextField() ethai = models.TextField(null=True) esyn = models.TextField(null=True) eant = models.TextField(null=True) def __str__(self): return self.eentry def get_absolute_url(self): return reverse('word-detail', args=[str(self.id)]) does anybody know how to fix it -
Django: substitute password field with another field for obtaining JWT with Simple JWT
I am using Simple JWT for issuing tokens. I am generating random code upon user registration and assigning it to user. Is it possible to substitute password field which is required to obtain token with this field? -
want to create my own admin dashboard for my project using rest api
I want to create dashboard panel for my eCommerce using Django restful API, I want the users, permissions and group to be added deleted and managed from my own dashboard and other things that are created by Django default in API representation, how can I customized such that I can clone Django admin panel attributes in my API to use it. I tried using Django app and Implemented successfully but how can I make in restful API. -
Why Django Admin site renders PostGIS coordinates incorrectly?
Django Admin site renders coordinates as: { "type": "Point", "coordinates": [ 2599546.894950558431447, 7276499.344635636545718 ] } When it should be: { "type": "Point", "coordinates": [ 25.99546894950558431447, 72.76499344635636545718 ] } Why is that so? -
How to upload my Postgres database to Django Heroku app?
I want to upload my local postgres database in an existing heroku Django app. I run this: $ PGUSER=postgres PGPASSWORD=mypass heroku pg:push postgres://localhost/newschool DATABASE_URL But it shows this: The local psql command could not be located. For help installing psql, see ! https://devcenter.heroku.com/articles/heroku-postgresql#local-setup How to get psql? I have pgadmin and postgres installed on my pc already. What should I do? In the docs mentioned above, they just ask to install postgres for windows. I have done that already! ps.newschool is the database name -
How do I pass a response from an asynchronous celery task that's running in the background in django to a socket that's running in the front end?
I am running an asynchronous task using celery and RabbitMQ in django. After the successful execution of the task I should send a response to a socket that listening in front-end. I found tutorials and examples for running async task in django but I could find no blog or tutorial for my need. Thanks in advance! -
Django Multiple Databases CreateSuperUser - django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly config
I am Building a Django application using python 3.7.6 and Django 3.0.5. This solution has multiple applications each application will have its own standalone database configured. I was able to successfully complete migrations. However I am Unable to CreateSuperUser. It is failing with following error - django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. My Settings file has following DB configurations - DATABASE_ROUTERS = ['ISMABlogs.Db_Router.Db_Router'] DATABASE_APPS_MAPPING = {'Blogs': 'blog', 'ISMATutorials':'tutorial'} DATABASES = { 'default': { }, 'blog': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'isma_blogs', 'USER' : 'abc', 'PASSWORD': 'something', 'HOST': 'localhost', 'PORT':3306 }, 'tutorial': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'isma_tutorials', 'USER' : 'xyz', 'PASSWORD': 'something', 'HOST': 'localhost', 'PORT':3306 } } DEFAULT_DB_ALIAS='blog' And My Router file has following configuration - class Db_Router(object): """ A router to control all database operations on models in the user application. """ def db_for_read(self, model, **hints): """ Attempts to read ISMATutorials models go to ISMATutorials. """ if model._meta.app_label == 'Blogs': return 'blog' elif model._meta.app_label == 'ISMATutorials': return 'tutorial' return 'blog' def db_for_write(self, model, **hints): """ Attempts to write user models go to users_db. """ if model._meta.app_label == 'Blogs': return 'blog' elif model._meta.app_label == 'ISMATutorials': return 'tutorial' return 'blog' def allow_relation(self, obj1, obj2, **hints): """ Allow relations if … -
Not Authenticated Error in Django using Stripe
I am creating for the very first time a payment for an e-commerce website using stripe, I am following a guide and have reviewed every step carefully but always getting Not Authenticated Error and I'm unclear what is going wrong. I am new to Django so I'm trying to learn as much as possible from my errors. Here is my views.py class PaymentView(View): def get(self, *args, **kwargs): # order order = Order.objects.get(user=self.request.user, ordered=False) context = { 'order': order } return render(self.request, "payment.html", context) # `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, # cents currency="usd", source=token, ) # create payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order.ordered = True order.payment = payment order.save() messages.success(self.request, "Your Order was Successful ! ") return redirect("/") except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") # Since it's a decline, stripe.error.CardError will be caught return redirect("/") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.error(self.request, "Rate Limit Error") return redirect("/") … -
Efficent way to update a random value for django models
I'm using Django with PostgreSQL and I want to know if there is a way to update a certain number of models, that have uniques fields, with random values. My problem is I need to update 5k of users changing his emails and usernames with random values. These fields are uniques, which means two instances can't have the same values. My logic is: for each user, (1) generate random email string, then if there isn't any user with that email, use that string, else back to 1 # Python2.7 Django 1.11, but everything helps from django.contrib.auth.models import User from django.utils.crypto import get_random_string for user in User.objects.order_by('-pk')[:5000].iterator(): # Generate random email while True: random_email = get_random_string(10) if not User.objects.filter(email=random_email).exists(): user.email = random_email break # Generate random username while True: random_username = get_random_string(10) if not User.objects.filter(username=random_username).exists(): user.username = random_username break user.save() -
Play video uploaded by user with formset in Django
I'm not able to play videos from list made with formset in django. I want to make a video playlist with videos uploaded by user (a sort of udemy . com). Users can add fields to upload more videos or let only one field by default (there is script in javascript for that). I havent problem to upload videos, everything is ok about that (videos are uploaded correctly). The problem is to play videos. Here my models.py from django.db import models from django.utils import timezone from django.template.defaultfilters import slugify class Cours(models.Model): titre = models.CharField(max_length=100) slug = models.SlugField(max_length=100) auteur = models.CharField(max_length=42) comment = models.TextField(null=True) link = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE) def save(self, *args, **kwargs): self.slug = slugify(self.titre) super(Cours, self).save(*args, **kwargs) class Meta: verbose_name = "cours" db_table = "cours" ordering = ['date'] def __str__(self): return self.titre class Categorie(models.Model): nom = models.CharField(max_length=30) def __str__(self): return self.nom class Plan_simple(models.Model): partie = models.CharField(blank=True, max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") vid = models.FileField() cours = models.ForeignKey(Cours, related_name = "plan_simple", on_delete=models.CASCADE) def __str__(self): return self.partie class Meta: db_table = "plan_simple" my form.py from django import forms from django.forms import ModelForm from django.template.defaultfilters import slugify from django.forms import formset_factory from … -
Error Install Django-Admin (Running setup.py install for screen ... error)
I was having no problem running django but when I was about to run 'django-admin startproject', it says there is no 'django-admin' directory in my Python folder. So I ended up trying to install using pip install django-admin. Here is the error: C:\Users\syahm>pip install django-admin Collecting django-admin Using cached django_admin-2.0.1-py2.py3-none-any.whl (7.6 kB) Collecting django-excel-response2>=3.0.0 Using cached django_excel_response2-3.0.2-py2.py3-none-any.whl (4.4 kB) Collecting django-excel-base>=1.0.4 Using cached django_excel_base-1.0.4-py2.py3-none-any.whl (4.0 kB) Requirement already satisfied: django-six>=1.0.4 in c:\users\syahm\appdata\local\programs\python\python37-32\lib\site-packages (from django-excel-response2>=3.0.0->django-admin) (1.0.4) Requirement already satisfied: xlwt in c:\users\syahm\appdata\local\programs\python\python37-32\lib\site-packages (from django-excel-base>=1.0.4->django-excel-response2>=3.0.0->django-admin) (1.3.0) Collecting screen Using cached screen-1.0.1.tar.gz (8.6 kB) Requirement already satisfied: pytz in c:\users\syahm\appdata\roaming\python\python37\site-packages (from django-excel-base>=1.0.4->django-excel-response2>=3.0.0->django-admin) (2019.2) Installing collected packages: screen, django-excel-base, django-excel-response2, django-admin Running setup.py install for screen ... error ERROR: Command errored out with exit status 1: command: 'c:\users\syahm\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\syahm\\AppData\\Local\\Temp\\pip-install-o89ws43u\\screen\\setup.py'"'"'; __file__='"'"'C:\\Users\\syahm\\AppData\\Local\\Temp\\pip-install-o89ws43u\\screen\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\syahm\AppData\Local\Temp\pip-record-t_rdgtfv\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\syahm\appdata\local\programs\python\python37-32\Include\screen' cwd: C:\Users\syahm\AppData\Local\Temp\pip-install-o89ws43u\screen\ Complete output (18 lines): running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\screen copying screen\compat.py -> build\lib.win32-3.7\screen copying screen\old_str_util.py -> build\lib.win32-3.7\screen copying screen\__init__.py -> build\lib.win32-3.7\screen running build_ext building 'screen.str_util' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\source C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.25.28610\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\users\syahm\appdata\local\programs\python\python37-32\include … -
Getting rid of port in URL for django installation in production
I'm trying for the first time to deploy my Django application on a server but so far I wasn't able to get rid of port in my URL. Right now I'm using Gunicorn with Nginx with the following configuration. Nginx /etc/nginx/sites-enabled/site.conf server { listen 8000; server_name example.com; location = /favicon.ico {access_log off;log_not_found off;} location /static/ { root /home/webapp/um; } location /media/ { root /home/webapp/um; } location / { include proxy_params; proxy_pass http://unix:/home/webapp/um/um.sock; } } /etc/nginx/proxy_params proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; Gunicorn /etc/systemd/system/gunicorn.service Description=gunicorn service After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/webapp/um/ ExecStart=/root/um/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/webapp/um/um.sock um.wsgi:application [Install] WantedBy=multi-user.target Gunicorn binding gunicorn --bind 0.0.0.0:8000 um.wsgi:application Changing port 8000 with port 80 in /etc/nginx/sites-enabled/site.conf gives me a 404 on nginx. Using port 8000 I'm able to see the site using http://example.com:8000/myapp but I'm aiming at using http://example.com/myapp as my address. As a side note, the VPS I'm installing the app on came with Plesk already installed with which I'm also not familiar with. I don't know if Plesk might be interferring in catching traffic from port 80. Thanks in advance -
Override parent css settings using child gives unknown property name
I'm trying to override the parent settings of a dropdown menu using a child class in CSS. Unfortunately, when I try to do this it gives me an "unknown property name" error on the child class, even though I use the exact same property on the parent class. The CSS code looks like: .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; overflow: hidden; min-width: 160; min-heigth: 100; background-color: #f9f9f9; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); padding: 12px 16px; z-index: 1; left:20%; } .test { min-width: 1080; min-heigth: 480; } .dropdown:hover .dropdown-content { display: inline-block; } And the HTML code (django template format) looks like: {% for info in infos %} <div class="dropdown"> <a href="#">dropdown item</a> <div class="dropdown-content"> {% if info.2 == "img" %} <!-- display image --> {% elif info.2 == "gif" %} <div class="test">Gifs and Videos are disabled for preview.</div> {% endif %} </div> </div> {% endfor %} In which info.2 will always contain either the string "gif" or "img". I have not yet implemented the image yet. However, if I use inspect element I get the following error: Which does not make any sense to me, as the css within the dropdown-content class …