Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to save user uploaded data both locally and in the cloud?
When the user uploads some data to Django, I would like to create both a local copy and a cloud copy. The following succesfully creates a cloud copy, how can I modify it so it creates a local copy too? class fileUpload(models.Model): fileName = models.CharField(max_length=200, unique=True, blank=True) file = models.FileField(storage=PrivateMediaStorage()) class PrivateMediaStorage(S3Boto3Storage): location = "rawFiles" file_overwrite = False default_acl = "private" -
Function reserved for each user in Django
I have my function/python code which is used to clean data from my database according to user request, Now for every user's request python code is executed, if 1000 user ask for different - different parameters then python code/function has to be executed for 1000 times by which user have to wait for very long becz it's single function which will be running for single user at each time. Is their any way to duplicate or make a executable copy of python function which will be reserved for each user.? -
Django | Serializer for Foreign Key
I got two models Book and Author implemented like this: class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=50) author = models.ForeignKey(Author, on_delete=models.CASCADE) In addition to this I got the following Serializers: class AuthorSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=50) class BookSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=50) author = AuthorSerializer() Serializing objects works without any problems. Now I got the following situation: Author's: id name 1 Josh Robert 2 J. R. R. Tolkien 3 Mike Towers I get a POST request to an API endpoint on my server http://127.0..0.1:8000/api/book looking like this: payload = { 'name': 'Lord of the rings', 'author': 2 } How can I use my Serializers to create a new Book with the given name and link it with the author no. 2? -
Get parents by filtering two date range in childs table with Django ORM
I have two tables with this informations: Room id room name 1 room 1 2 room 2 and a child table with this information: Reservation id room id (reserved_rooms) from date to date 1 1 2022-05-20 2022-05-22 2 1 2022-05-23 2022-05-25 I want to get available rooms for a certain amount of time: Witch doesn't have any reservation rooms where no reservation has been made at a specific time such as 2022-05-24 I tried the following code, but the problem is that the booked room is returned with id=1, while it has a reservation on the desired date. Room.objects.filter(Q(reserved_rooms__isnull=True) | Q(reserved_rooms__from_date__gt=date) | Q(reserved_rooms__to_date__lt=date)) This query ignored reservation with id=2, because 2022-05-23 < 2022-05-24 < 2022-05-25, but reservation with id=1 causes that room with id=1 is returned. because 2022-05-24 not in range 2022-05-20 and 2022-05-22. so I expected that the only room with id=2 would be returned, but both 1 and 2 were returned. What is your suggestion to solve this challenge? -
Upload data to the cloud and Django instance storage
I have set my Django application to upload files to AWS and it works fine. When I upload a file, I see it in the cloud storage and the django admin has a downloadable URL. Here is the code anyways. In the settings.py MEDIAFILES_LOCATION = env("AWS_S3_ENDPOINT_URL") + "media" In the models class fileUpload(models.Model): fileName = models.CharField(max_length=200) file = models.FileField(storage=PrivateMediaStorage()) In the FileField class PrivateMediaStorage(S3Boto3Storage): location = "rawFiles" file_overwrite = False default_acl = "private" And in the views def create(self, request, *args, **kwargs): .... file = serializer.validated_data["file"] object = fileUpload.objects.create(file=file, fileName=name) .... When I check the Admin panel, I am able to download the file from the file url from model into my computer. I want to retrieve this file that I have uploaded into AWS and run some calculation on it using Django. How can I modify the fileUpload upload class to also store the data locally in the Django? (I am also open to alternative approaches). -
How to create postgres db index for a jsonfield in Django using the ORM?
I made a migration and added this exact sql: migrations.RunSQL("CREATE INDEX my_json_idx on my_table((my_json_data->'id'));") It works. All i'm trying to do is, get this exact equivalent but using the Django ORM so that I can put something in my models.py file in the class Meta: indexes=[...] That way it can all be managed at the "code" level and have django take care of the rest. I tried this: models.Index(KeyTextTransform('id', 'my_json_data'), name='my_json_idx') This creates an index fine, but it uses ->> something like CREATE INDEX my_json_idx on my_table((my_json_data->>'id'));") Which is a problem because queries from the django orm such as my_table.objects.filter(my_json_data__id=123) get translated into -> by the ORM. And the index ends up getting skipped. It does a full scan. -
Django Ratelimit custom method
I try to limit the pages of one of my site with django-ratelimits. But how can I limit with custom methods. For example if the rate is 3/m then if you fill out a form and press enter then this will count as a visit for the limiter. Something like flask-limiter cost methods. -
How to access a postgres container through its name? Could not translate host name error
I have a django and postgres containers. When it's time for django to apply migrations, it doesn't see a postgres container that I named pgdb and I get this error: django.db.utils.OperationalError: could not translate host name "pgdb" to address: Temporary failure in name resolution It appears that there is no docker container with name "pgdb". If I run "docker-compose run pgdb" it creates a postgres container with a name of "app_pgdb_run_23423423" under the "app" group. The cute thing is that I made it work previously with this settings.py setup and "pgdb" postgres container name. What could be the underlying issue? You can clone the full code from https://github.com/UberStreuner/mailing-service My settings.py setup, the environment variables definitely aren't at fault. DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE', 'django.db.backends.postgresql_psycopg2'), 'NAME': os.environ.get('POSTGRES_DB'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': os.environ.get('POSTGRES_HOST', 'pgdb'), 'PORT': os.environ.get('POSTGRES_PORT', '5432') } } docker-compose.yml version: "3.8" services: django: build: . container_name: django command: ./docker-entrypoint.sh volumes: - .:/usr/src/app/ ports: - "8000:8000" env_file: - ./.dev.env depends_on: - pgdb - redis celery: build: . command: celery -A mailing worker -l INFO volumes: - .:/usr/src/app/ env_file: - ./.dev.env depends_on: - django - redis - pgdb celery-beat: build: . command: celery -A mailing beat -l INFO volumes: - … -
Django Checkbox Multiple Select to SQLite [closed]
I will be specific I have a problem! There is a modal with a list of data that I get from a table in a database in sqlite, I have implemented a checkbox in each row, I want to achieve that when selecting each row with the checkbox, that selection when clicking on the button " adjust" I save it in another table of the database. HOW DO I ACHIEVE THIS? I need your help Imagen de Referencia -
Please enter a valid date/time django error
i suddenly got an error. Please enter a valid date/time. It used to work just fine but I don't know what's going on now LANGUAGE_CODE = 'nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = False USE_TZ = False DATE_INPUT_FORMATS = ['%d-%m-%Y %H:%M'] class JobForm(forms.ModelForm): class Meta: model = ShiftPlace fields = ['add','medewerker','job_type','firmaName','date','dateTo','adress','postcode','HouseNumber','city','comment'] widgets = { 'date': DateTimePickerInput(), 'dateTo': DateTimePickerInput(), 'comment':forms.Textarea, class DateTimePickerInput(forms.DateTimeInput): input_type = 'datetime-local' date_format=['%d-%m-%Y %H:%M'] -
Django localization - translating models cross apps
I'm translating model choices in a django APP but the local APPs do not use the localized string. I have an APP named base_app with the following model: class User(AbstractUser): LIVING_AREA_CHOICES = ( ('urban', _('Urban')), ('rural', _('Rural')), ) name = models.CharField( _('Option Name'), null=True, max_length=255, blank=True ) def __str__(self): return self.name or '' living_area = models.CharField( _('Living Area'), choices=LIVING_AREA_CHOICES, max_length=255, null=True, blank=True ) ... other stuff... This model is used in a modelform of forms.py from courses_app (added as external app through requirements.txt of base_app): model = get_user_model() fields = ('username', 'email', 'name', 'first_name', 'last_name', 'image', 'occupation', 'city', 'site', 'biography', 'phone_number','social_facebook', 'social_twitter', 'social_instagram', 'preferred_language', 'neighborhood', 'living_area', 'race', 'birth_date','city', 'gender') and rendered in profile-edit.html, template of a third app (client_app configured in .env): {% with errors=form.living_area.errors %} <div class="form-group{{ errors|yesno:" has-error,"}}"> <label class="col-xs-12 col-sm-3 col-lg-2 control-label" translate>Living area </label> <div class="col-xs-12 col-sm-9 col-lg-10"> {{ form.living_area }} {% for error in errors %}<small class="warning-mark">{{error}}</small>{% endfor %} </div> </div> {% endwith %} I've already tried to use localized_fields = ('living_area',) in forms.py with no success. The only way I've got it working is adding the strings of LIVING_AREA_CHOICES inside client_app's po/mo files. Is there a way for the client_app template to retrieve the … -
How do I create a unique number for Django model objects?
I am working on a project where a user can create a card under their company. Unfortunately, the databases indexes all the cards, regardless of the company. I would like to create a unique number for all the cards but serialised according to the company, e.g like creating an invoice number that will always be unique. The two models are here: class Company(Organization): name = models.Charfield(max_length=256, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) email = models.EmailField(null=True) date_created = models.DateField(default=timezone.now, null=True) class Card (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='card_user', null=True) thecompany = models.ForeignKey(Company, related_name = "company_card", on_delete=models.CASCADE, null=True) date_created = models.DateField(default=timezone.now) card_number = models.PositiveIntegerField(default=1, null=True, editable=False) def save(self, *args, **kwargs): if self.card_number == 1: try: last = Card.objects.filter(thecompany=self.thecompany).latest('card_number') self.card_number = last.card_number + 1 except: self.card_number = 1 super(Card, self).save(*args, **kwargs) I can sequence the objects created according to the company, using the card_number field on Card. Below is the model: The save method works well and maintains Card_Number sequence even when you delete cards, up until you delete the card object with the largest number. Then if you create a card object after you have deleted the card with the largest card_number, it repeats. I thought of creating a list with … -
How to hit a json database index in Django query?
I created an index on a models.JSONField in my postgres db. class Meta: indexes=[ models.Index(KeyTextTransform('id', 'my_json_field'), name='my_json_id_idx') ] i wrote some sql on pg_indexes to verify and it is there CREATE INDEX my_json_id_idx on my_model USING btree (((my_json_field ->> 'id'::text))) One thing to note is it uses ->> which means it casts to text im pretty sure. So then if i try to query like this my_query = MyModel.objects.filter(my_json_field__id=1234) If i analyze with my_query.explain(analyze=True) it shows a sequential Scan. It does NOT hit my index at all. When i look at the SQL of the query i think im noticing the difference is it uses Filter: (my_model.my_json_field -> 'id'::text) = '1234'::jsonb Or if i just look at the SQL of the query it basically is: select * from my_model where (my_json_field -> id) = 1234 I think the -> in the query vs --> in the index is what makes the discrepancy. What is the proper way to write the query so it hits the index, or should i rewrite the index so it uses -> ? Does anyone know how to rewrite the statement in the indexes so that it creates it with -> ? P.S I can write … -
How to use sync_to_async() in Django template?
I am trying to make the Django tutorial codes polls into async with uvicorn async view. ORM query works with async view by wrapping in sync_to_async() as such. question = await sync_to_async(Question.objects.get, thread_sensitive=True)(pk=question_id) But I have no idea how to apply sync_to_async or thread inside Django templates. This code fails saying 'You cannot call this from an async context - use a thread or sync_to_async.' Or any other way to work around this? {% for choice in question.choice_set.all %} I use Python 3.10, Django 4.0.4 and uvicorn 0.17.6 -
Django runserver not worked after login
I used this command: python manage.py runserver 0:8080 After I logined the system I can reach rest API pages, but can't reach other pages. Although I send a request, the command output does not log. Quit the server with CONTROL-C. -
Django and Celery: unable to pickle task kombu.exceptions.EncodeError
I have this async Celery task recalculate_emissions_task.delay(assessment, answers,reseller, user) where the parameters supplied are all Django objects, my task function is defined like this @app.task @transaction.atomic def recalculate_emissions_task(assessment, answers, reseller, requesting_user=None): for ans in answers: approver = None if ans.is_approved: approver = ans.approver auto_approved = ans.auto_approved auto_approval_notes = ans.auto_approval_notes ans.unapprove() ans.report_upstream_emissions = ans.scope in assessment.scopes_for_upstream ans.report_transmission_and_distribution = assessment.report_transmission_and_distribution ans.for_mbi_assessment = assessment.uses_mbi if approver: ans.approve( approver, auto_approved=auto_approved, auto_approval_notes=auto_approval_notes ) else: ans.save() and the error I am receiving is : Traceback (most recent call last): File "dir/bin/django-python.py", line 18, in <module> runpy.run_path(path, run_name='__main__') File "/usr/lib/python3.8/runpy.py", line 265, in run_path return _run_module_code(code, init_globals, run_name, File "/usr/lib/python3.8/runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "/usr/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "test.py", line 15, in <module> recalculate_emissions_task.delay(assessment, answers,reseller, user) File "dir/lib/python3.8/site-packages/celery/app/task.py", line 427, in delay return self.apply_async(args, kwargs) File "dir/lib/python3.8/site-packages/celery/app/task.py", line 566, in apply_async return app.send_task( File "dir/lib/python3.8/site-packages/celery/app/base.py", line 756, in send_task amqp.send_task_message(P, name, message, **options) File "dir/lib/python3.8/site-packages/celery/app/amqp.py", line 543, in send_task_message ret = producer.publish( File "dir/lib/python3.8/site-packages/kombu/messaging.py", line 167, in publish body, content_type, content_encoding = self._prepare( File "dir/lib/python3.8/site-packages/kombu/messaging.py", line 252, in _prepare body) = dumps(body, serializer=serializer) File "dir/lib/python3.8/site-packages/kombu/serialization.py", line 221, in dumps payload = encoder(data) File "/usr/lib/python3.8/contextlib.py", line 131, in __exit__ self.gen.throw(type, … -
HttpResponse object. It returned None instead
The view main.views.add_venue didn't return an HttpResponse object. It returned None instead. -- Value Error error error appeared after creating views.py views.py def add_venue(request): if request.method == "POST": form = VenueForm(request.POST) if form.is_valid(): form.save() return redirect('/add_venue?submitted=True') else: form = VenueForm() if 'submitted' in request.GET: submitted = True else: return HttpResponseRedirect('/add_venue?submitted=True') return render(request, 'main/add_venue.html', {'form': form, 'submitted':submitted}) models.py, HTML, admin.py and forms.py works correctly. If I delete return HttpResponseRedirect(/add_venue?submitted=True) error won't (when going to the page) appear until I fill out the form -
zappa : Failed to manage IAM roles
Im trying to deploy a django app with zappa. I have set the region and everything in the zappa init. Now when i try to do zappa deploy I have this error: "Error: Failed to manage IAM roles!" Exception reported by AWS:An error occurred (InvalidClientTokenId) when calling the CreateRole operation: The security token included in the request is invalid. I've created a user under Iam in aws console and I have attached IAMFullAccess and PowerUserAccess Iam predefined policies/strategies. I dont know what to do Thank you Best, -
ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields'
Can anyone please help me? I am getting this error from a week. I really need HELP THE Django Server is not working and i am getting this error when I enter Previously i was using python another version and now I installed python v10 so what should i do now? py manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management_init_.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "", line 241, in _call_with_frames_removed File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django_filters_init_.py", line 7, in from .filterset import FilterSet … -
I'm getting a TemplateSyntaxError in my local django server at my template html file regarding the block tag that I used
"Invalid block tag on line 2: 'endblock'. Did you forget to register or load this tag?" This is the error I'm getting and the following is my code in my index.html file in vs code which for some reason keeps getting aligned into one line after saving despite saving each block as a different line after one another: {% extends 'base.html' %} {% block body %} This is body block {% endblock body %} -
Django "NoReverseMatch: Reverse for 'ads.views.AdListView' not found" while doing Test
I implemented some tests to check the status code of some pages, but this one with the reverse function throws me the error: django.urls.exceptions.NoReverseMatch: Reverse for 'ads.views.AdListView' not found. 'ads.views.AdListView' is not a valid view function or pattern name. Reading the documentation and some answers on stackoverflow I'm supposed to use either the view function name or the pattern name inside the parenthesis of the reverse function, but none of them seems to work. Here's my code: ads/tests/test_urls.py from django.test import TestCase from django.urls import reverse class SimpleTests(TestCase): def test_detail_view_url_by_name(self): resp = self.client.get(reverse('ad_detail')) # I've also tried: resp = self.client.get(reverse('ads/ad_detail')) self.assertEqual(resp.status_code, 200) ... ads\urls.py from django.urls import path, reverse_lazy from . import views app_name='ads' urlpatterns = [ path('', views.AdListView.as_view(), name='all'), path('ad/<int:pk>', views.AdDetailView.as_view(), name='ad_detail'), ... ] mysite/urls.py from django.urls import path, include urlpatterns = [ path('', include('home.urls')), # Change to ads.urls path('ads/', include('ads.urls')), ... ] ads/views.py class AdDetailView(OwnerDetailView): model = Ad template_name = 'ads/ad_detail.html' def get(self, request, pk) : retrieved_ad = Ad.objects.get(id=pk) comments = Comment.objects.filter(ad=retrieved_ad).order_by('-updated_at') comment_form = CommentForm() context = { 'ad' : retrieved_ad, 'comments': comments, 'comment_form': comment_form } return render(request, self.template_name, context) I'm a newbie with Django, so I don't really understand what's going on. Any idea of what is … -
How to configure a server on raspian with django, apache2, mariasql, vhosts, pipenv
I am trying to set up a webserver, and have made some steps towards setting it up but I have hit a hurdle that maybe some one can help me with. I am getting the following error "This site can't be reached". Checking the connection Checking the proxy and the firewall. I have only done this setup once before and it was ages ago, but have exhausted my documentation at the time that I did it. And any scraps for information would be most helpful. Heres my setup and steps so far, some steps are for later e.g. certbot etc. What I am currently trying to do is show domain.co.uk in the browser after setting the /etc/hosts file. So nothing over the internet for now, just everything on the local machine. Equipment: Raspberry Pi 3 Model B V1.2 16 GB MICRO SD CARD Keyboard Mouse 4K HDMI Monitor Power Cable HDMI Cable WIFI Access Power Supply Software: SD Memory Card Formatter Raspberry Pi OS with desktop (bullseye) MD5 & SHA Checksum Utility Raspberry Pi Imager PassMark ImageUSB Chromium apache2 libapache2-mod-php Process: Download “SD Memory Card Formatter”. Format “16 GB MICRO SD CARD” with “SD Memory Card Formatter”. Download “Raspberry Pi … -
Setting up VS Code for use with Django, Apache, virtualenv on a remote server
we have a django project on a development server which is running within a virtual environment. I was hoping to be able to use VS Code for development from my local PC, but I am not sure if I am able to or not. It seems like something that would make sense to do! I think I have managed to set the interpreter as the virtualenv on the server using UNC paths and have activated it, but when I try to run manage.py to create a new app, I get No module named 'django' which perhaps suggested the virtualenv hasn't activate properly? Is it possible to use VS Code in this way? thanks, Phil -
ajax request in django
My ajax code $.ajax({ type: "get", url: "", statusCode: { 500: function() { alert("error"); }}, data: { "map":JSON.stringify(jsonmap), "road":JSON.stringify(sourceGoal), "line":JSON.stringify(straightLineToDestination) }, success: function(response){ alert("success") } }); my views.py code : import json from telnetlib import STATUS from urllib import request from django.shortcuts import render from django.http import HttpResponse import os from django.views.generic import View from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt,csrf_protect from .algocode import a_star import pprint @csrf_exempt def home_view(request): if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': if request.method == 'Get': straight_line=json.loads(request.Get.get('line')) SourceandGoal=json.loads(request.Get.get('road')) Graph=json.loads(request.Get.get('map')) heuristic, cost, optimal_path = a_star(SourceandGoal["start"], SourceandGoal["end"],Graph,straight_line) result=' -> '.join(city for city in optimal_path) print(result) print(heuristic) print(cost) return JsonResponse({"heuristic":heuristic,"cost":cost,"result":result}) return render(request,'index.html') My URLS.py : urlpatterns = [ path('admin/', admin.site.urls), path('',home_view), ] my problems are : When ajax type was "post" I had a "500 eternal server error" but the data is passed and I can access it and use it as I want in my views.py I changed ajax type to "get " there was no errors put now I get the data in a wrong format and I cant use it in my project "GET /?map=%22%7B%5C%22City1%5C%22%3A%7B%5C%22City2%5C%22%3A123%7D%2C%5C%22City2%5C%22%3A%7B%5C%22City1%5C%22%3A12%7D%7D%22&road=%7B%22start%22%3A%22City1%22%2C%22end%22%3A%22City2%22%7D&line=%7B%22City2%22%3A32%2C%22City1%22%3A222%7D HTTP/1.1" 200 1247 when ajax type was "post" the data I receive comes like this even with the server Erorr : { … -
Django:TypeError: serve() got an unexpected keyword argument 'Document_root'
hello I am facing some issues with my code. this is the error that I am getting TypeError: serve() got an unexpected keyword argument 'Document_root' this is my settings.py STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto- field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' here is my url.py from xml.dom.minidom import Document from django.conf import settings from django.contrib import admin from django.urls import path from django.conf.urls.static import static from customer.views import Index, About, Order urlpatterns = [ path('admin/', admin.site.urls), path('', Index.as_view(), name='index'), path('about/', About.as_view(), name='about'), path('order/', Order.as_view(), name='order'), ] + static(settings.MEDIA_URL, Document_root=settings.MEDIA_ROOT) and here is my Html file <button type="button" class="btn btn-dark" data-toggle="modal" data-target="#submitModal" > Submit Order! </button> <!-- <button class="btn btn-dark mt-5">Place Order!</button> --> <!-- Modal --> <div class="modal fade" id="submitModal" tabindex="-1" role="dialog" aria-labelledby="submitModalLabel" aria-hidden="true" > <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="submitModalLabel"> Submit Your Order! </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-footer"> <button type="button" class="btn btn-light" data-dismiss="modal" > Go Back </button> <button type="submit" class="btn btn-dark">Place Order! </button> </div> </div> </div> </div> </form> What should I do to stop getting this error. I have been struggling from 2 days. and yes the app …