Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I name Django ManyToMany object relations in Django admin?
Is there a way to give the relations their name instead of calling them "object-n" like shown below? Here is the code for the two models in question: class jobTag(models.Model): Tag = models.CharField(max_length=15) def __str__(self): return self.Tag class job(models.Model): Company_name = models.CharField(max_length=200, null=True, blank= True) Position = models.CharField(max_length=200, null=False, blank=False) Type = models.ForeignKey(jobType, default=" ",verbose_name="Type", on_delete=models.SET_DEFAULT) Industry = models.ForeignKey(jobIndustry, default=" ", verbose_name="Industry", on_delete=models.SET_DEFAULT) Location = models.ForeignKey(jobLocation, default=" ", verbose_name="Location", on_delete=models.SET_DEFAULT) Role_description = tinymce_models.HTMLField(default="") Role_requirements = tinymce_models.HTMLField(default="") Role_duties = tinymce_models.HTMLField(default="") Special_benefits = tinymce_models.HTMLField(default="") Date_posted = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField('jobTag', related_name="job-tags+", blank=True) def time_posted(self): return humanize.naturaltime(self.Date_posted) def __str__(self): return self.Position class Meta: verbose_name_plural = "Jobs" Thanks in advance. -
How to convert synchronous code to async Python?
I have been working on a code that would create owners and lots and assign lots to each owner. While I got the code to work, it takes too long to run and was thinking about improving it by making it asynchronous. I have been watching a few videos and reading resources online but I am still confused as to how to implement this. I was wondering if it would be possible for someone to guide me how to accomplish this feat and optimize my code for performance. Here is the code below: def handle_csv(csv): database = pd.read_csv(csv) lot= database[['lot_description','lot_number', 'lot_rate']] owner = database[['account_number', 'first_name', 'last_name', 'occupation']] address = database[['area','lot_number', 'account_number','street_name', 'street_number']] for index in database.index: try: owner_new = Owner.objects.get(pk=owner["account_number"][index]) except: owner_new = Owner.objects.create( account_number=owner["account_number"][index], first_name= owner["first_name"][index], last_name= owner["last_name"][index], ) owner_new.save() try: lot_new = Lot.objects.get(pk=lot["lot_number"][index]) except: lot_new = Lot.objects.create( lot_number=lot["lot_number"][index], lot_description= lot["lot_description"][index], ) lot_new.owner.add(owner_new) lot_new.save() -
Django Model function behavior changes based on how many tests being run
I have a need for a uniqueID within my Django code. I wrote a simple model like this class UniqueIDGenerator(models.Model): nextID = models.PositiveIntegerField(blank=False) @classmethod def getNextID(self): if(self.objects.filter(id=1).exists()): idValue = self.objects.get(id=1).nextID idValue += 1 self.objects.filter(id=1).update(nextID=idValue) return idValue tempObj = self(nextID=1) tempObj.save() return tempObj.nextID Then I wrote a unit test like this: class ModelWorking(TestCase): def setUp(self): return None def test_IDGenerator(self): returnValue = UniqueIDGenerator.getNextID() self.assertEqual(returnValue, 1) returnValue = UniqueIDGenerator.getNextID() self.assertEqual(returnValue, 2) return None When I run this test by itself, it runs fine. No issues. When I run this test as a suite, which includes a bunch of other unit tests as well (which include calls to getNextID() as well), this test fails. The getNextID() always returns 1. Why would that be happening? -
Django Multiple user type
I have different types of users where I have to collect different types of information from different types of users. Eg:- if the user is accountant the required information would be id proof; if the user is executive the required information would be id proof and other personal details; if the user is client the required information would be official details like Company name, company id, etc. Please help me out in this. Thank you in advance. -
ImportError: attempted relative import with no known parent package. Python packages
... File "/Users/mammadaliyevmammadali/Desktop/dev/ecom/apis/tasks.py", line 12, in create_fake_phone from .models import Phone ImportError: attempted relative import with no known parent package module layout # tasks.py from random import choice from faker import Faker from celery import shared_task from .models import Phone # error occurs here fake = Faker() @shared_task def create_fake_phone() -> None: Phone.objects.bulk_create([ Phone( ... ) for _ in range(10) ]) I get this error when I just try to run tasks.py file. What is the matter here, guys? Why I am getting this error. Please help! -
How to get the field definition by name of related objects in Django
I need to retrieve the field of related objects of a model by name. For example if Book has a ForeignKey field to Author called author, I would like to be able to something like: field = 'author__name' Book._meta.get_field(field).verbose_name It is general purpose so that string author__name is not known in advance -- I can't hardcode the fields or traversal. Furthermore, it may span more than one relation like author__address__city if there was a fk to an Address model on the Author. _meta.get_field() returns MODEL has no field named FIELD when I try such a field name with fk traversal. Django must have ways of doing this as these traversals must be done internally all the time, but I could not find how in the docs or looking into the code. Any ideas appreciated! -
Python Django, unit test for functions?
In a Python Django project, the function retrieve_timerange(request) is not a member of any class and contains an embedded function parse_timestamp(datetime_str). I want to write unit tests to cover the boundary conditions, e.g. entering and leaving Summer Daylight Saving Time in the local time zone. I am wondering: How to write the unit test for the function retrieve_timerange(request)? How to write the unit test for the embedded function parse_timestamp(datetime_str)? I generated the below unit test test_service.py by PyCharm, and it runs. However, I don't see any connection to the functions under test. I don't know how to feed input to the function call and verify the return. I am new to unit test writing, so I would highly appreciate any hints or suggestions. Partial sample source code of service.py: from django.utils import timezone from dateutil.parser import isoparse import datetime ... def retrieve_timerange(request): def parse_timestamp(datetime_str): ... return timestamp ... time_from = None time_to = None if query_params is not None: time_from = parse_timestamp(str_time_from) time_to = parse_timestamp(str_time_to) return time_from, time_to ... Sample unit test source code of test_service.py: from unittest import TestCase import unittest import dateutil import pytz class Test(TestCase): def test_parse_timestamp(self): self.fail() -
connect() to unix:/home/glenn/blog.sock failed (13: Permission denied) while connecting to upstream
I am trying to connect my django project to a gunicorn socket using Nginx (ubuntu 22.04) server, and I think my configuration file is okay. However when I try to go to my Ip address on the server I get a 502 getway error. When I check the error log, I get the following output: 2022/08/09 22:05:36 [crit] 7960#7960: *5 connect() to unix:/home/glenn/blog.sock failed (13: Permission denied) while connecting to upstream, client: 197.231.183.74, server : 67.205.168.227, request: "GET / HTTP/1.1", upstream: "http://unix:/home/glenn/blog.s ock:/", host: "67.205.168.227" I have followed the documentation to check for possible troubleshooting guides, and I have been adviced to check for my permissions. On doing so, I get the following error log drwxr-xr-x root root / drwxr-xr-x root root home drwxr-x--- glenn glenn glenn srwxrwxrwx glenn www-data blog.sock So does anyone know of a specific command I can use to edit the permissions? Or how I can edit my configuration file to change the permissions here is how my sites-available file looks like server { listen 80; server_name 67.205.168.227; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/glenn/blog; } location /media/ { root /home/glenn/blog; } location / { include proxy_params; proxy_pass http://unix:/home/glenn/blog.sock; … -
Notification from sql new object when user login - Django
My query is the next: How can I display a notification to a user who logged for the first time after the action that created the notification has been executed. In my case I want the user to get notified when he win something. -
Error: pg_config executable not found when deploying django app in aws
I understand this problem is common, and I've tried many solutions, none of which have worked. I'm following this tutorial to deploy a Django App to AWS EBS: https://realpython.com/deploying-a-django-app-to-aws-elastic-beanstalk/ More detail on error message from eb-engine.log: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] .ebextensions/01_packages.config: packages: yum: git: [] postgresql-devel: [] .ebextensions/02_packages.config: container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python matador-web/manage.py migrate --noinput" leader_only: true 02_createsu: command: "source /opt/python/run/venv/bin/activate && python matador-web/manage.py createsu" leader_only: true 03_collectstatic: command: "source /opt/python/run/venv/bin/activate && python matador-web/manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "matador_web.settings" "PYTHONPATH": "/opt/python/current/app/iotd:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: matador-web/matador_web/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" .elasticbeanstalk/config.yaml: branch-defaults: feat-deploy: environment: matador-web-dev environment-defaults: matador-web-dev: branch: feat-deploy repository: origin global: application_name: matador_web branch: null default_ec2_keyname: aws-eb default_platform: Python 3.8 running on 64bit Amazon Linux 2 default_region: us-east-1 include_git_submodules: true instance_profile: null platform_name: … -
Media Query - Django
I am trying to find a way to insert media query on Django. I want to insert them both in views.py and find a way to adapt the articles on different screens. -
how to send image file with json request?
I am working on an e-commerce project, and I want to add products from the front end. The files in my product app in Django is as follows this is my model.py: class Product(models.Model): pub_date = models.DateTimeField(default=datetime.now) price = models.DecimalField(max_digits=100000,decimal_places=5,null=False,blank=False) device_name = models.CharField(max_length = 50, null=True) photo = models.ImageField(upload_to = 'product_photos/%y/%m/%d',null=True) and this is my views.py @api_view(['POST']) @permission_classes ([AllowAny] , ) def addproduct(request,pk): data = request.data product = Product( price = data['price'], device_name = data['product_name'], photo = data['photo'], user = Users.objects.get(id=pk) ) if product: product.save() serializer = ProductSerializer(product,many=False) return Response(serializer.data) else: return Response({'error':'4'}) It works fine when it comes to fetching data (products I created in the Django admin) but how to send a JSON request that also contains the images and the other data ,NOTE: my views is function_based -
How to override "Cannot asign must be an instance" in Django?
I have two models: class Message(models.Model): username = models.CharField(max_length=255) room = models.CharField(max_length=255) content = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Notification(models.Model): notification_author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="notifauthor") notification_from = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="notiffrom") is_read = models.BooleanField(default=False) signals: @receiver(post_save, sender=Message) def create_user_notification(sender, instance, created, **kwargs): if created: Notification.objects.create( notification_author=instance.username, notification_from=instance.room) @receiver(post_save, sender=Message) def save_user_notification(sender, instance, **kwargs): instance.username.save() I am trying to create signal for creating notification after message is created. But have error: Cannot assign "20": "Notification.notification_author" must be a "Profile" instance. How to override it (if possible) without changing CharField to FK in Message model? Found smth about eval(), but it does not still work -
How to access all children for Django QuerySet
I have the following models where a Project has many Goals and a Goal has many Tasks. What is the best way to find a QuerySet containing all Tasks related to an individual Project? models.py are per below: class IndividualProject(models.Model): project = models.CharField( max_length = 64 ) def __str__(self): return f"Project {self.project}" class IndividualGoal(models.Model): goal = models.CharField( max_length = 64 ) project = models.ForeignKey( IndividualProject, on_delete=models.CASCADE, related_name="projects", blank=True, null=True, ) def __str__(self): return f"{self.goal}" class IndividualTask(models.Model): task = models.CharField( max_length = 256, blank=False, null=True, ) goal = models.ForeignKey( IndividualGoal, on_delete=models.CASCADE, related_name="goals", blank=False, null=True, ) I have tried using _set but have had no luck. I would like to use a query where I select the Project and then select a specific Task. -
Can't get Django to upload files
I have read many questions, followed the Django docs, googled for answers, and I can't get to upload a file in my Django app. There is no error, form.cleaned_data shows the file and the other foreign key field, but no upload to media folder and no record in my db. I can't figure what am I missing. Any help would be much appreciated. #models.py class ReportFile(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE) file = models.FileField(upload_to='files/reports') uploaded = models.DateTimeField(auto_now_add=True) uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE) def save(self, *args, **kwargs): user = get_current_user() if user and not user.pk: user = None if not self.pk: self.creado_por = user #forms.py class FileForm(forms.ModelForm): class Meta: model = ReportFile fields = ['file','report'] This is the view I'm using, based on what I've read #views.py def CreateFile(request): if request.method == 'POST': form = FileForm(request.POST,request.FILES) if form.is_valid(): form.save() print(form.cleaned_data) #OUTPUT: HTTP POST /file 200 [0.09, 127.0.0.1:59053] # {'file': <InMemoryUploadedFile: test-image.png (image/png)>, 'report': <Report: 49>} return render(request, 'segcom/file_upload.html', {'form': form,}) else: form = FileForm() context = { 'form':form, } return render(request, 'segcom/file_upload.html', context) The relevant settings that I know of #settings.py # Media Root MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' This is the template I'm using {% extends "layouts/base.html" %} {% load … -
Trying to create a separate comments app for a ticket project using django generic class based views
I'm trying to create a separate comments app from my tickets app. I believe that I've gotten most of the functionality down because when I use the frontend, the comments show up in my admin site but it is not connected to the respective ticket. Instead what happens is that the comment creates its own new page of tickets. How do I connect the comment with the ticket even though they are in separate apps? I believe the problem lies in my urls.py files and in the way that I implemented them but it could also be a problem with my models or views that I am not seeing. Here's what I have so far tickets urls.py urlpatterns = [ path('', TicketListView.as_view(), name='ticket-home'), path('user/<str:username>', UserTicketListView.as_view(), name='user-tickets'), path('tickets/<int:pk>/', TicketDetailView.as_view(), name='ticket-detail'), path('tickets/new/', TicketCreateView.as_view(), name='ticket-create'), path('tickets/<int:pk>/update/', TicketUpdateView.as_view(), name='ticket-update'), path('tickets/<int:pk>/delete/', TicketDeleteView.as_view(), name='ticket-delete'), path('about/', views.about, name='tickets-about'), ] comments urls.py urlpatterns = [ path('<int:pk>/', CommentListView.as_view(), name='comment-detail'), path('tickets/<int:pk>/comments/new/', CommentCreateView.as_view(), name='comment-create'), path('tickets/comments/<int:pk>/update/', CommentUpdateView.as_view(), name='comment-update'), path('tickets/comments/<int:pk>/delete/', CommentDeleteView.as_view(), name='comment-delete'), ] ticket models.py class Ticket(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) status = models.BooleanField(choices=MARKED, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) label = models.CharField(choices=TYPES, default='Misc', max_length=100) def __str__(self): return … -
How to unpack Django RawQuerySet result in a pandas dataframe
I'm using a raw SQL query to bring objects from a Postgresql table: data_result = Search.objects.raw(search_sql) The problem is that when I try to put it into a Pandas data frame, I'm left with a data frame as a single column full of objects, instead of having them unpacked for every property: 0 Search object (167157) 1 Search object (167159) 2 Search object (167160) 3 Search object (167163) 4 Search object (167164) 5 Search object (167165) 6 Search object (167166) 7 Search object (167169) 8 Search object (167170) 9 Search object (167174) The only way I managed to make it happens was accessing dict property and then removing the "_state" property, but this doesn't seem to be the properly way to do it: data_result = pd.DataFrame([{key: value for key, value in row.__dict__.items() if key != '_state'} for row in data_result]) id number date 0 167157 180981-02 2022-02-04 1 167159 180983-01 2022-01-31 2 167160 180982-01 2022-01-31 3 167163 180990-01 2022-02-06 4 167164 180992-01 2022-01-24 5 167165 180998-01 2022-01-23 6 167166 180993-01 2022-02-08 7 167169 181001-01 2022-02-09 8 167170 181002-01 2022-02-11 9 167174 181026-02 2022-02-09 I tried creating a serializer to see if it comes as a dictionary, but I had no … -
Django - initial load/seed of model attributes from a CSV?
I have a CSV with ~500 columns that represent data I need to use in my Django app in a single model. I don't want to manually go through and declare 500 attributes in my models.py file for this new model. Is there some way to bootstrap this or make it easier? -
How can I filter multiple tables that are linked together and make it work correctly?
I want to make a filter for the following tables, but in an orm way, I used the traditional filter through objects.row, but the method brings me a lot of problems I own several tables class Store(ModelUseBranch): name = models.CharField(verbose_name=_("Name"), max_length=50, unique=True) is_stoped = models.BooleanField(verbose_name=_("Is Stopped"), default=False) def __str__(self): return self.name class Meta: verbose_name = _("Store") class Item(ModelUseBranch): name = models.CharField(verbose_name=_("name"), max_length=50, unique=True) def __str__(self): return self.name class Meta: verbose_name = _("Item") class ItemMainData(CustomModel): item = models.ForeignKey(Item, on_delete=models.CASCADE) is_stopped = models.BooleanField(verbose_name=_("Is Stopped"), default=False) use_expir_date = models.BooleanField( verbose_name=_("Use Expiration Date"), default=False ) def __str__(self): return str(self.item) class Meta: verbose_name = _("ItemMainData") class StoreQuantity(CustomModel): item = models.ForeignKey(Item, on_delete=models.PROTECT, blank=True,verbose_name=_("Item")) qty = models.PositiveIntegerField(verbose_name=_("qty"),) store = models.ForeignKey(Store, on_delete=models.PROTECT, blank=True,verbose_name=_("store")) expire_date = models.DateField(verbose_name=_("expire date"), null=True, blank=True) class Meta: verbose_name = _("Store Quantity") def __str__(self): return str(self.expire_date)+" "+str(self.qty)+" "+str(self.store) Now I want to make a query via orm with this sql = "SELECT DISTINCT warehouse_item.id ,warehouse_item.name_ar , warehouse_store.name,qty,expire_date FROM warehouse_storequantity,public.warehouse_item ,public.warehouse_itemmaindata,public.warehouse_store WHERE date (warehouse_storequantity.expire_date) - date (now()) <= (SELECT 0 FROM warehouse_storequantity,public.warehouse_item ,public.warehouse_itemmaindata,public.warehouse_store where warehouse_item.id = warehouse_itemmaindata.item_id and warehouse_item.id = warehouse_storequantity.item_id and warehouse_store.id = warehouse_storequantity.store_id and warehouse_itemmaindata.use_expir_date='1')" I tried, but I did not reach the desired goal StoreQuantity.objects.values( "pk", "item__name_ar", "store__name", "qty", "expire_date" ) .filter(item_id__in=col2) -
Django Dropbox BadInputException: OAuth2 access token must be set
I've built a Python application which utilizes the dropbox API to access the amount of files and folders within a given directory. I've been trying to host this on a web portal that my partner and I have created in Django. Due to dropbox no longer using permanent keys, the plan was to have an admin user login to the web portal and manually pass in a new app key retrieved from the dropbox console's website and pass it into the app. The issue that arises though is when I try to pass in a new access token code through the UI, Django fires the following error: BadInputException at /landBoxReport/ OAuth2 access token or refresh token or app key/secret must be set Request Method: POST Request URL: http://localhost:7000/landBoxReport/ Django Version: 4.0.5 Exception Type: BadInputException Exception Value: OAuth2 access token or refresh token or app key/secret must be set Exception Location: C:\Users\username\AppData\Local\Programs\Python\Python310\lib\site-packages\dropbox\dropbox_client.py, line 189, in __init__ Python Executable: C:\Users\username\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.5 Here's the rest of my code: For the logic in my views.py which is firing the error form = LandBoxTokenForm(request.POST) if request.method == 'POST': token = request.GET.get('landToken') if token != 'None': manager = LandBoxManager(token) manager.dropbox_show_folders() return render(request, 'landBox_report.html', {'form': … -
Django prefetch related returns null
The requirement is to have subtopics prefetched at the Campaigns queryset as the attribute prefetched_subtopics but it currently returns null Models class SubTopic(Base): name = models.CharField(max_length=100, unique=True) class CampaignSubTopicAssn(HistoryMixin, Base): campaign = models.ForeignKey(Campaign, related_name='subtopic_assn', on_delete=models.CASCADE) subtopic = models.ForeignKey(SubTopic, related_name='campaign_assn', on_delete=models.PROTECT) View def get_queryset(self): return super(CampaignViewSet, self).get_queryset().prefetch_related(Prefetch('subtopic_assn__subtopic', queryset=SubTopic.objects.all(), to_attr='prefetched_subtopics')) -
NOT NULL constraint failed: shipping_ship.user_id Django
So I'm working on a shipping website with the django rest framework. The website brings two to four people together so they can easily ship their goods together at the same time. But I'm facing a major stumbling block on the views where user book a shipping the code is below. models.py from django.db import models from django.contrib import get_user_model User = get_user_model() class Container(models.Model): container_type = models.Charfield(max_length = 30, blank=False, null = False) max_users = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places =2, default=0, blank=True, null=True) users = models.ManyToManyField(User) class Ship(models.Model): container = models.ForeignKey(Container, related_name='cont', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='shipper', on_delete=models.CASCADE) location = ( ('France', 'France'), ) from_location = models.CharField(max_length=30, choices=location, blank=False, null=False) to_location = ( ('Lagos', 'Lagos'), ('Abuja', 'Abuja'), ('Abeokuta', 'Abeokuta'), ('Osun', 'Osun'), ) to_location = models.CharField(max_length=30, choices=to_location, blank=False, null=False) date_leaving = models.DateField(auto_now=False) price = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True, null=True) def __str__(self): return self.user then my serializer.py file from rest_framework import serializers from .models import Container, Ship class ContainerSerializer(serializers.ModelSerializer): class Meta: model = Container fields = '__all__' class MiniContainerSerializer(serializers.ModelSerializer): class Meta: model = Container fields =['container_type', 'price'] class ShipSerializer(serializers.ModelSerializer): class Meta: model = Ship fields = '__all__' read_only_fields = ('user', 'price') class MiniShipSerializer(serializers.ModelSerializer): class Meta: model = Ship fields = … -
What is the difference between queryset last() and latest() in django?
I want to get data which inserted in the last so I used a django code user = CustomUser.objects.filter(email=email).last() so it gives me the last user detail but then experimentally I used user = CustomUser.objects.filter(email=email).latest() then It didn't give me a user object. Now, what is the difference between earliest(), latest, first and last()? -
Can't extract Data with For Loop (JavaScript / Fetch)
Why can't I extract the fields that I want from the for loop? Console Log JSON Data document.addEventListener('DOMContentLoaded', function() { let user = 'example'; fetch(`/jsonresponse/${user}`) .then(response => response.json()) .then(data => { // The line below works and prints the username console.log(data['UsersInfo'][0].username) // Doesn't work in a for Loop for (let i = 0; i < data.length; i++) { console.log(data['UsersInfo'][i].username); } }); Any hints would be appreciated -
Drag And Drop Feature Not Working in Django
I am making a website using django as backend framework. I have made the frontend of image upload for content writers so that they can upload image either by clicking on "browse files" or by just dragging and dropping the image. The simple button click(browse files) feature works perfectly. However, when using drag and drop, the file is not uploaded to the django files request nor in the post request. I need help on how to make it appear in the file or post request in my backend. When I upload the File using the button instead of drag and drop then i can see the file appear in the files request like this:- What I want is to make the file appear here in the yellow marked area when I use drag and drop:- Here is the code .html {% extends 'main/navbar.html' %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'css/main/index.css' %}"> <link rel="stylesheet" href="{% static 'css/contentWriting/Create Event.css' %}"> {% endblock %} {% block content %} <div class="min-h-screen flex items-center justify-center"> <form method="POST" enctype="multipart/form-data" class="w-3/4 mx-auto"> {% csrf_token %} <input type="file" name="event-banner-image" id="id-event-banner-image"> {# Main Container For Image and Details Of Event#} <div class="flex …