Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I have a django loading animation while a view is being processed?
I have a view which has a form for a zipcode input, it then takes some time to run a function Scrape_by_zip. It returns a download link to an excel file once complete. While this function is processing I don't want the user to think nothing is happening. Is there a way I can get a loading bar or animation while this is going on? Another possibility is the user gets redirected to another page and shows a "Please wait for download" message, but I am not sure how to go about this approach either. Below is my view. def scrapeComplete(request): if request.method == 'POST': try: zip_code = request.POST['zip_code'] print(zip_code) df = Scrape_by_zip(int(zip_code)) with BytesIO() as b: # Use the StringIO object as the filehandle. writer = pd.ExcelWriter(b, engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() # Set up the Http response. filename=str(zip) +" Properties" +".xlsx" response = HttpResponse( b.getvalue(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response except: return HttpResponse('Error') return HttpResponse('Error') -
How to serve static files from Django using docker-compose and Nginx?
I am trying to serve static files from Django using docker-compose and Nginx. I have a compose file where I set up the three services as well as volumes for the database, static files and uploaded files: version: '3' services: lims: container_name: lims build: ./lims env_file: - ./lims/.env.django.prod ports: - '8000:8000' depends_on: - db volumes: - static_volume:/lims/staticfiles - upload_volume:/lims/upload db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./lims/.env.db.prod nginx: container_name: nginx restart: always build: ./nginx ports: - "80:80" volumes: - static_volume:/lims/staticfiles - upload_volume:/lims/upload depends_on: - lims volumes: postgres_data: static_volume: upload_volume: Now if I run this with Django's DEBUG=1 everything works fine. However as soon as I turn the Debug mode off, all static files are gone. In the Django settings I specified the static and uploaded files location like this: MEDIA_URL = '/lims/upload/' MEDIA_ROOT = BASE_DIR / 'upload' STATIC_URL = "/lims/staticfiles/" STATIC_ROOT = BASE_DIR / "staticfiles" I also tried to add the path /lims/staticfiles/ to Nginx like this: location /lims/staticfiles/ { alias /var/lib/docker/volumes/; } as I believe the volumes should be located there. However this actually lead to the static files not even appearing in Debug mode. How do I correctly serve my static files and user uploaded content here? -
Django if created new object
I will running something function if created new object. But i will not run if the object already exists Example: class Model(models.Model): test = models.Charfield(max_length=255) if created new object(!): requests.POST(blablabla) -
Django forms select option value hand to same URL
I am having trouble figuring out how get the selected option of a form handed back to the same url as a get context value: forms.py class ModeForm(forms.Form): MODES = ( ('','Select a generation mode'), ('docker','Docker'), ('docker-compose','Docker Compose'), ('kubernetes', 'Kubernetes'), ) selectedMode = forms.CharField(label="", widget=forms.Select(choices=MODES, attrs={ 'class': 'form-control', 'placeholder': 'Generation mode', 'onchange': 'form.submit();', }), ) views.py # Home page def viewHome(request): if request.method == 'POST': currentMode = request.POST.get('selectedMode') form = ModeForm(initial={'name':currentMode}) print(f"Post Mode is: {currentMode}") context = { 'data': None, 'form': form, } return render(request, 'main/home.html', context) I can obtain the selected value on the POST to the view. However, I am not sure how to have that selection remain once the selection has been made and the form is displayed again. As things are now: The select field has an initial value when the home page is initially loaded. Once a value is selected, the form is posted to the home page. In the request.POST I can get the selected value. However, the select control resets and the value is lost outside of the POST. What I am attempting to do is, get a selection on form submission. Have that value persist once a value is set. Is there … -
how to custom form errors in view
I am using this code to check how many images are being uploaded and the size of the image. Currently i am using a ValidationError but it looks like this in development and in production is just throws a 500 server error. How can I have it throw a form error that looks something like this I was using the messages framework as a work around but would much rather do it the proper way. Must be achieved in the view. code: if len(request.FILES.getlist('images')) > 3: #messages.error(request, 'More than 3 images') raise ValidationError(f'More than 3 images') for image in request.FILES.getlist('images'): if image.size > settings.MAX_UPLOAD_SIZE: raise ValidationError(f'Image {image} is too large 3mb max') -
database synchronization between sql server windows form c#.net app and Django sqllite on web server
I have a windows form application which wrote with net framework and it has local database sql local db its install in many client side and now i develop web based application with Django python . so i need suggestion with one function and its database synchronization between the local database and server database i want that all user store the data on local system so once they got internet they sync it with server database also and i dont want to delete the local data after its sync i need its be on both side so should i use REST API for this or there is another method also which is better that i use them . -
Django reusing class based views and adding arguments
Still getting used to Django and how they approach their view classes so bear with me. My current project setup is using several apps all using the same view classes just with a different database. Ideally, I would like to have one class that I can call for other apps views.py using From helperclasses import Browse view = Browse.as_view() return view(request) My question is how can I pass an argument to the imported class such as the database to use. For example, something like below From helperclasses import Browse view = Browse(database_to_use).as_view() return view -
How to use model form instance in Django template
I'm trying to access the instance of the forms in a formset, but it is not working. I CAN access them using the variable notation, as in {{ form }}, but not in code, as in {% url 'section' form.instance.pk %}. I need to iterate through the forms in the formset along with the corresponding model instance. My view: # views.py def sec(request, companyurl): company = get_if_exists(Company, author=request.user) SectionFormSet = modelformset_factory(Section, form=SectionForm, can_delete=True) sections = Section.objects.filter(company=company).order_by('order') formset = SectionFormSet(request.POST or None, initial=[{'company': company}], queryset=sections context = { 'sections': sections, 'formset': formset, } return render(request, 'questions/sections.html', context) My model: # models.py class Section(models.Model): section = models.CharField(max_length=100) company = models.ForeignKey(Company, on_delete=models.CASCADE) order = models.PositiveIntegerField(default=1000000) show = models.BooleanField(default=True) def __str__(self): return self.section My Form (I'm using django-crispy forms): # forms.py class SectionForm(forms.ModelForm): class Meta: model = Section fields = ['company', 'section', 'show', 'order'] labels = { 'section': '', 'show': 'Show' } def __init__(self, *args, **kwargs): super(SectionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( Div(HTML("##"), css_class = 'my-handle col-auto'), Div('section', css_class='col-3'), Div('show', css_class = 'col-auto'), Div('DELETE', css_class = 'col-auto'), Field('company', type='hidden'), Field('order', type='hidden'), css_class='row', ), ) My template (this is where the problem is seen): <form action="#" method="post"> {% … -
Using HTTP_408_REQUEST_TIMEOUT for POST request
I am implementing a post request for an image tagging game and need to set a timeout after 5 minutes after the game round has been created: views.py def post(self, request, *args, **kwargs): gameround = Gameround.objects.all().get(id=request.data) tag_serializer = TagSerializer(data=request.data) tagging_serializer = TaggingSerializer(data=request.data) if gameround.created + timezone.timedelta(minutes=5): if tagging_serializer.is_valid(raise_exception=True): tagging_serializer.save(tagging=request.data) return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_201_CREATED) else: return Response({"status": "error", "data": tag_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_408_REQUEST_TIMEOUT) Testing the post request in Postman yields the following TypeError: Field 'id' expected a number but got {'gameround_id': 2015658021, 'resource_id': 102209, 'tag': {'name': 'PERSON', 'language': 'en'}}. How can I get rid of this and make the timeout work? -
Normalise models the correct way
I have 4 models Profile, Product, Holding and Transaction. A user (profile) can assign products to their account. I then want the user to be able to add a transaction to the product, i.e they can add 10 of the product and the price they paid, which will then be presented in a table showing the total amount they hold as well as the average price. But im not sure if what i am doing is correct in terms of the FKs and MtM fields. class Product(models.Model): name = models.CharField(max_length=255, blank=False, unique=True) slug = models.CharField(max_length=50, blank=True,null=True) symbol = models.CharField(max_length=50, blank=True,null=True) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) capture_date = models.DateField(blank=True,null=True) logo_address = models.URLField(max_length=255, blank=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) website = models.URLField(max_length=50, blank=True) twitter = models.CharField(max_length=50, blank=True) meta = models.CharField(max_length=50, blank=True) github = models.CharField(max_length=50, blank=True) def __str__(self): return str(self.user) class Holding(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return str(self.product_name) class Transaction(models.Model): product = models.ForeignKey(Holding, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) price = models.FloatField(max_length=50, blank=True, null=True) transaction_date = models.DateField(null=True, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) I was thinking that I could … -
How to configure Geopandas with Django
Im using this https://gist.github.com/linwoodc3/0306734dfe17076dfd34e09660c198c0 from github to convert a kmz file to shp file. It works fine when I run it using hardcoded file path. I want to integrate this into my web app which uploads kmz file using this function: #Models.py class FileDocument(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True)``` The file uploads fine into documents folder and has the same size and name as the file on my local computer, however when reading the kmz file using the aforementioned function I get the following error: *No geometry data set yet (expected in column 'geometry'.)* By printing the dataframes I can see that the geometry column is missing when I upload it through django, however rest of the attributes are there. I think this error has more to do with how Geopandas, Gdal, Geos and other spatial libraries are configured in Django vs my virtual environment. Any help or insight would be appreciated. Thank you! -
Check size of multiple uploaded files
I have a feature that allows users to upload multiple files. I want to check the size of these files and dissallow files that are too large images = request.FILES['images'].size if images > settings.MAX_UPLOAD_SIZE: raise Exception(f'Image {images} is too large 3mb max') I have been playing with this code but I cannot figure out a way to loop over all of the files. What confuses me about this is i am not iterating over all the files but it still properly throws the exception no matter what order the file that is too large appears in. Is this code working properly? -
Generating x number of React components from integer variable
So I have a webpage that's meant to model a sort of questionnaire. Each question would take up the whole page, and the user would switch back and forth between questions using the arrow keys. That part's fine, swapping components on button pressing doesn't seem to be an issue, and I got a proof-of-concept of that working before. The trouble is, these questionnaires won't have the same number of questions every time. That'll depend on the choice of the person making the questionnaire. So I stored the number of questions in a variable held in the Django Model, and I fetch that variable and try to generate x number of components based on that integer. At the moment I'm just trying to get it to generate the right number of components and let me navigate between them properly, I'll worry about filling them with the proper content later, because I'm already having enough trouble with just this. So here's my code: import React, { useState, useEffect, cloneElement } from 'react'; import { useParams } from 'react-router-dom' import QuestionTest from './questiontest'; function showNextStage(displayedTable, questionCount) { let newStage = displayedTable + 1; if (newStage > questionCount) { newStage = questionCount; } return … -
Django web deployed by pythonanywhere doesn't refresh automatically [closed]
I deployed my Django project with pythonanywhere and have already pushed it from localhost to the webserver. My Django project is linked with dynamic data from my google sheet API. However, when I edit on my google sheet and reload the page, the data doesn't change accordingly. I have to manually click the "reload" button on pythonanywhere to refresh my data. Does anyone know what should I do? -
How to post data to ModelForm while testing assertRedirects
I try to test correct redirect after post data with ModelForm. In my view if form.is_valid() equals True, form is saved and view redirects to homepage. My test_forms.py looks like this: class TestForms(TestCase): def setUp(self): # imitacja witryny self.client = Client() self.tag = Tag.objects.create( name='Bull flag' ) self.data = { 'ticker': 'FB', 'exchange': 'NASDAQ', 'buy_point': 121, 'stop_loss': 120, 'description': 'ciamciaramcia', 'tags': [self.tag] } self.form = StockTradeForm(self.data) def test_stock_trade_form_valid_data(self): self.assertTrue(self.form.is_valid()) # OK self.form.save() self.assertEqual(StockTrade.objects.count(), 1) # OK after self.form.save() self.assertTrue(StockTrade.objects.filter(ticker='FB').exists()) # OK after self.form.save() def test_stock_trade_form_valid_redirect(self): response = self.client.post(reverse('create-trade'), self.data) print(response) # print result: .<HttpResponse status_code=200, "text/html; charset=utf-8"> self.assertTemplateUsed(response, 'journal/create_trade.html') # OK self.assertEquals(response.status_code, 200) # OK self.assertRedirects( response, reverse('index'), status_code=200 ) # Failure: # in assertRedirects # url = response.url # AttributeError: 'HttpResponse' object has no attribute 'url' Shouldn't response = self.client.post(reverse('create-trade'), self.data) imitate valid and saved form? My view name is: create_trade Url looks like this: urlpatterns = [ path('', views.index, name='index'), path('display-trade/<str:pk>', views.display_trade, name='display-trade'), path('create-trade', views.create_trade, name='create-trade'), path('update-trade/<str:pk>', views.update_trade, name='update-trade') ] I'm concerned about this two tests self.assertTemplateUsed(response, 'journal/create_trade.html') # OK self.assertEquals(response.status_code, 200) # OK Is it correct that after self.client.post assertTemplateUsed response is equal 'journal/create_trade.html' and status_code is 200? I tried many things with self.client.post but nothing work … -
Django howto progessively write data into a huge zipfile FileField
I have a django model like this: class Todo(models.Model): big_file = models.FileField(blank=True) status = models.PositiveSmallIntegerField(default=0) progress = models.IntegerField(default=0) I'd like to do two operations: first make an empty zipfile out of big_file (less important) and then progressively add files into my zipfile (and save it iteratively) The overall process would look like that: from django.core.files.base import File import io, zipfile def generate_data(todo): io_bytes = io.BytesIO(b'') # 1. save an empty Zip archive: with zipfile.ZipFile(io_bytes, 'w') as zip_fd: todo.generated_data.save('heavy_file.zip', File(zip_fd)) # 2. Progressively fill the Zip archive: with zipfile.ZipFile(io_bytes, 'w') zip_fd: for filename, data_bytes in long_iteration(todo): with zip_fd.open(filename, 'w') as in_zip: in_zip.write(data_bytes) if condition(something): todo.generated_data.save() # that does not work todo.status = 1 todo.progress = 123 todo.save() todo.status = 2 todo.save() But I can't figure out the right filedescriptor / file-like object / Filepath / django-File object combination ... And it seems that in django I always have to save(filename, content). But my content could be Gigabytes, so it does not sound reasonable to store it all into a "content" variable? -
Django 'this field is required' form error on non-editable field
I'm trying to build a form that lets me categorise/edit my bank transactions. Ideally all uncategorised transactions will be displayed on one page (in a formset) and I'll be able to edit some/all of them. When I hit 'submit' on the formset, I want to save any changes and navigate to a confirmation page. Here's my model for a Transaction: class Transaction(models.Model): description = models.CharField(max_length=200) post_date = models.DateTimeField('date') account = models.ForeignKey(Account, null=True, on_delete=models.SET_NULL) category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) amount = models.DecimalField(max_digits=9, decimal_places=2) uuid = models.CharField( max_length=200, primary_key = True, unique = True, editable=False) def __str__(self): return self.description Date, description, and amount are important to show on the form because they help me figure out how to categorise the transaction. I don't want to accidentally edit the date or amount, so I've made them readonly on the form. Transactions also have uuid and account fields, but those are irrelevant to categorisation and I don't want to edit them, so they shouldn't be shown at all. My form and formset look like this: class TransactionForm(ModelForm): class Meta: model = Transaction exclude = ('uuid', 'account') def __init__(self, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) cat = self.fields['category'] cat.required = False cat.blank = True self.fields['description'] self.fields['amount'].readonly … -
save() prohibited [...] due to unsaved related object, but related object already saved
I'm working with Django 4.0.1. I'm having having "save() prohibited to prevent data loss due to unsaved related object 'page'" even if the 'page' object is saved one line before. Here is the code: # Upload entity data u = Upload( message=request.POST["upload_msg"] ) # saving u here to be able to use u.datetime later u.save() # new page for the upload entity page = Page( title="notes for Upload " + str(u.datetime), content="This page is empty..." ) page.save() u.page = page u.save() The last line (u.save()) is the one causing the error. Am I having some kind of race condition here? Isn't it assured that the previous db operations are complete before trying to run the next? Any other ideas? Thank you. -
Virtual Trading Platform with Django Rest Framework (Good Idea)?
Trading application relies on many requests is it advisable to build the API backend with Django rest framework with scalability in mind? Any suggestions would be great. -
ListView with an extra argument
I want to add a parameter somevar to my listview: {% url 'products' somevar %}?" in the urls: path("products/<int:somevar>", ProductListView.as_view(), name = 'products'), in the views: class ProductListView(ListView): def get_template_names(self): print(self.kwargs) # {"somevar": xxxxx} return f"{TEMPLATE_ROOT}/products.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.get_products().order_by("number") print(kwargs) # kwargs is {} here return context def get_queryset(self): return super().get_queryset().order_by("number") How can I pass the variable to the get_context_data method? I tried defining a get method and call self.get_context_data(**kwargs) within, but this leads to an object has no attribute 'object_list' error. -
Ajax not getting data from Django view
I have a page that the user is supposed to type in the URL to a YouTube video. That URL is sent with Ajax to a Django view that checks the URL to see if its valid or not. Then it alerts with either an error message is if its not valid, or alerts with the video title if it valid. The alerts are done with the standard javascript alerts. This is just a test version of the page. I plan to display the info gathered from video on the page itself. This is the template for the page. <body> <form method="post"> {% csrf_token %} <input type="text" name="url" id="url"> <label for="url">Please Enter Video URL Below</label> <button id='button'></button> <p id = 'test'></p> </form> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <script> document.getElementById('button').addEventListener('click', find_video, false) function find_video(){ var url = document.getElementById('url').value; $.ajax({ url: "ajax/find_video/", type: "POST", data: { csrfmiddlewaretoken: window.CSRF_TOKEN, url : url}, dataType: 'json', complete: function(data){ if (data.error_message){ alert('Please enter valid url') } else { alert(data.video_title) } }, }); } </script> </body> </html> This is the Django view def find_video(request): url = request.POST.get('url') #unquotes url formating so youtube_dl can use it. urllib.parse.unquote(url) if is_valid(url): error_message = False else: … -
Django Save User Responses for Next Visit - Caching or Sessions?
I have a user review system where managers can review their employees access to specific systems. The table they are presented with looks something like this <table class="employeeTable" id="employeeTable"> <thead> <tr> <th>Status</th> <th>Employee Name</th> <th>PID</th> <th>Title</th> <th>Email</th> <th>Enabled in System</th> <th>System Permission Group</th> <th>System Name</th> <th>Approve</th> <th>Deny</th> <th>Reasoning</th> </tr> </thead> <tbody> <tr> <td class="statusCircle" accessCorrect="False"><svg class="statusCircle" style="margin-left:5px;" xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="grey" stroke="#be9b9b" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle></svg></td> <td>Last, First</td> <td>Emp ID</td> <td>Emp title</td> <td>first.last@email.com</td> <td>true</td> <td>Permissions</td> <td>System Emp ID</td> <td class="approvePerm"><svg class="approvePerm" style="float:right;" class="tableButtons" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#43a600" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg></td> <td class="denyPerm"><svg class="denyPerm" style="float:right;" class="tableButtons" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#d90e0e" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></td> <td><select class="reason" style="display: none;"> <option>No longer employed with Company</option> <option>Job role no longer requires this access</option> <option>Employee has transferred</option> </select></td> </tr> <tr> <td class="statusCircle" accessCorrect="False"><svg class="statusCircle" style="margin-left:5px;" xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="grey" stroke="#be9b9b" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle></svg></td> <td>Last, First</td> <td>Emp ID</td> <td>Emp title</td> <td>first.last@email.com</td> <td>true</td> <td>Permissions</td> <td>System Emp ID</td> <td class="approvePerm"><svg class="approvePerm" style="float:right;" class="tableButtons" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#43a600" … -
First time deploying a django app on Heroku and I'm facing 2 issues, solution?
I've worked on my social app and been able to deploy it and I'm having 2 problems: Link: https://network50web.herokuapp.com/ 1/It directs me autmatically to https://network50web.herokuapp.com/accounts/login/?next=/ and I'm only able to see the site if I write the routes manually in the address bar like(login, register) 2/When I try to login it with my existent username it throws error "Programming Error at /login relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user..." and it highlights this line " user = User.objects.create_user(username, email, password)" even when I try to register a new account I used SQL for the database Views: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect, request from django.http.response import JsonResponse from django.shortcuts import render, redirect, resolve_url, get_object_or_404 from django.urls import reverse, reverse_lazy from django.core import serializers from django.core.paginator import Paginator from django.contrib import messages from django.contrib.auth.models import User from django.db.models import Q from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from itertools import chain from .models import Relationship, Post, Profile, Like from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView from .forms import ProfileModelForm, PostModelForm, CommentModelForm def search_view(request): if request.method == "POST": searched = request.POST['searched'] profiles = Profile.objects.filter(slug__contains=searched) return render(request, … -
Django displaying uploaded images
I am working on an application that allows users to upload PDFs. I want to display the PDFs in various templates. I am using multi-tenant so that may be an issue. So far, I haven't been able to get the PDFs to display. In the place of the image I see: Page not found (404) Request Method: GET Request URL: http://co1.localhost:8000/projects/project/1/document/2/projects/documents/012022/Joint1021S.pdf The view: class ProjectDocumentsDetailView(DetailView): model = ProjectDocuments id = ProjectDocuments.objects.only('id') template_name = 'company_accounts/project_document_detail.html' The template: {% extends 'base.html' %} {% block content %} <div class="section-container container"> <div class="project-entry"> <h2>{{ projectdocuments.title }}</h2> <p>{{ projectdocuments.description | safe }}</p> <embed src="{{ projectdocuments.file }}" <img src="{{ projectdocuments.file }}"> <p>{{ projectdocuments.file }}</p> </div> <div> </div> {% endblock content %} In the main site config/urls I have the line: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The files (in this specific instance) are stored in a file in media>company1>documents>012022>file.pdf From the error, at least one issue appears to be the way the path to the pdf is being constructed. Any ideas about how to fix this? -
Show request duration in drf-spectacular (Swagger)
I have a Django/DRF project with drf-spectacular (Swagger) integration and wondering how can I add a request duration as shown on the image below. Is there any way to achive elapsed time section? Thanks in advance.