Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Different datetimes displayed in view and template in Django
When I display a datetime object in my template, the displayed result is a date very different from what I have in my database. Printing the datetime in the view for debbuging gives the same result as the dabatase. I'm guessing it gets parsed somewhere between the view and the rendered template which gives a different date but I cannot pinpoint exactly what's going on. I'm using DateTimeField in the database. Any help appreciated -
Converting picklefield from python2 to python3
Migrating from django==1.11.16 / python2 to django==4.0.5 / python3.8 and using django-picklefield in the database I'd like to convert the database to the new system. I'm looking for a solution how I could achieve this feat. A working way is: #on python2 venv: s = str(l.get_log()) #where get_log results the Pickled Object f = open('/tmp/somefile', 'wb') f.write(s) f.close() #on python3 venv: f = open('/tmp/somefile', 'rb') cn = f.read() l.log_list = eval(cn) Well, this is a working way, but because of eval can be very dangerous, and it uses both, the old and the new virtual env. I'm looking for a solution, which uses only one of the virtual environments for converting the picklefield rows in the database. -
Stream Django Output to HTML
I am trying to run python code and want to output that line by line to HTML page in Django Below is code I want to out to HTML page, I have integrated this in views.py(here named as as test_stream_script). I integrated this as when I was calling this code on separate cdoe.py file, I would not get at out on terminal until code was finished and then antire code would output to HTML. However integrating it in views.py I can see code being run on terminal. views.py: def ic_check_stream_test(request): global ssh_client print('connecting to the server ...') ssh_client = connect('10.9.60.70', 22, 'root', 'wh3nPO!42') print('\n') remote_connection = get_shell(ssh_client) print('connected to the server ...') ifconfig = send_command(remote_connection, 'ifconfig') print(ifconfig.decode()) process = send_command(remote_connection, 'ls -ltr /home/nms_logs/') print(process.decode()) send_command(remote_connection, '\n') print('\n') ping_test = send_command(remote_connection, 'ping 192.168.1.2 -c 20') print(ping_test.decode()) send_command(remote_connection, '\n') print('\n') close_session_bc() return render(request, 'base_app/test_script_2.html') urls.py: from django.urls import path, include, re_path from base_app import base_app_views, test_stream_script app_name = 'base_app' urlpatterns = [ re_path(r'^home/', base_app_views.home, name='home'), re_path(r'^ic_check_stream_home/', test_stream_script.test_home3, name='test_home3'), re_path(r'^ic_check_stream_test/', test_stream_script.ic_check_stream_test, name='ic_check_stream_test'), ] HTML page: <div class= "container"> <div class="jumbotron"> <h1>IC Stream Test Scripts</h1> </div> </div> <form action="/ic_check_stream_test/" method="post"> {% csrf_token %} Enter BC IP Address: <input type="text" name="param" required><br><br> <input type="submit" value="Exceute … -
How do I get rid of this object / Dictionary while retaining the data i've scrapped?
i'm web scrapping a site for data using beautifulsoup4 that i can use in a school django project, and i'm not sure how to be specific to the data i want without calling an unwanted object. I've failed to get rid of it. import requests from bs4 import BeautifulSoup headers = {'User-agent': 'Mozilla/5.0 (Windows 10; Win64; x64; rv:101.0.1) Gecko/20100101 Firefox/101.0.1'} url = "https://elitejobstoday.com/job-category/education-jobs-in-uganda/" r = requests.get(url, headers = headers) c = r.content soup = BeautifulSoup(c, "html.parser") table = soup.find("div", attrs={"article": "loadmore-item"}) def jobScan(link): the_job = {} job = requests.get(url, headers = headers) jobC = job.content jobSoup = BeautifulSoup(jobC, "html.parser") name = jobSoup.find("h3", attrs={"class": "loop-item-title"}) title = name.a.text the_job['title'] = title print('The job is: {}'.format(title)) print(the_job) return the_job jobScan(table) this is the result it fetches PS C:\Users\MUHUMUZA IVAN\Desktop\JobPortal> py absa.py The job is: 25 Credit Officers (Group lending) at ENCOT Microfinance Ltd {'urlLink': 'https://elitejobstoday.com/job-category/education-jobs-in-uganda/', 'title': '25 Credit Officers (Group lending) at ENCOT Microfinance Ltd'} I want to be able to retain "The job is: 25 Credit Officers (Group lending) at ENCOT Microfinance Ltd" and drop "{'urlLink': 'https://elitejobstoday.com/job-category/education-jobs-in-uganda/', 'title': '25 Credit Officers (Group lending) at ENCOT Microfinance Ltd'}" -
How to identify that requests are coming from my own django website?
I'm trying to use the django rest framework to identify when an API Request is coming from my own website (in order to send an error to these requests). views.py from django.shortcuts import render from django.http import JsonResponse from rest_framework.request import Request as RESTRequest def is_rest_request(request): return isinstance(request, RESTRequest) def payment(request, *args, **kwargs): if is_rest_request(request): return JsonResponse({"result": 502}) else: return JsonResponse({"result": 209}) However, when I make the following request from an online python compiler: import requests x = requests.get('https://url.com/api/payment') print(x.text) I get this output: {"result": 209}, when I should be getting {"result": 502} Any reasons why? -
Capturing An Image From The Computer's Camera And Saving It
I am trying to capture an image of someone with the computer's camera, save it as a PNG image, and then send it to a view function in the Django framework. I have found some source code for this at the following link: https://www.studytonight.com/post/capture-photo-using-webcam-in-javascript The following source code is what I have so far: <!doctype html> <head> <style> #video { border: 1px solid black; width: 320px; height: 240px; } #photo { border: 1px solid black; width: 320px; height: 240px; } #canvas { display: none; } .camera { width: 340px; display: inline-block; } .output { width: 340px; display: inline-block; } #startbutton { display: block; position: relative; margin-left: auto; margin-right: auto; bottom: 36px; padding: 5px; background-color: #6a67ce; border: 1px solid rgba(255, 255, 255, 0.7); font-size: 14px; color: rgba(255, 255, 255, 1.0); cursor: pointer; } .contentarea { font-size: 16px; font-family: Arial; text-align: center; } </style> <!--The title of the HTML document.--> <title>Facial Image Recognition</title> </head> <body> <div class="contentarea"> <h1>Facial Image Recognition</h1> <div class="camera"> <video id="video">Video stream not available.</video> </div> <!--An id on a <button> tag assigns an identifier to the button. The id allows JavaScript to easily access the <button> element and manipulate it. When a user clicks on the "Capture Image" button, … -
Get local variables of called function before return in python
I am using Django 2.2, and I have the following view (reduced version): @method_decorator(log_request(settings.LOGGER_PAYMENT_TRANSACTION), "post") class UltimateOrderPaymentView(SettingsIncludeMixin, APIView, PayTRMixin): def post(self, request, *args, **kwargs): serializer = UltimatePayOrderSerializer(data=request.data) serializer.is_valid(raise_exception=True) orders = Order.objects.filter( id__in=serializer.validated_data["order_ids"], is_paid=False, status_id=Status.objects.order_statuses(level="base").first().id, user=request.user, ).select_for_update() with transaction.atomic(): ids = list(orders.values_list("id", flat=True)) if not ids: return Response("Orders not found", status=status.HTTP_404_NOT_FOUND) return self.__create_transaction_and_generate_url(serializer.validated_data["payment_method"]) And my log logic: def _log_request_response(view_method, logger): @functools.wraps(view_method) def wrapper(request, *args, **kwargs): log = logging.getLogger(logger) response = view_method(request, *args, **kwargs) if isinstance(response, Response): data = response.data elif isinstance(response, JsonResponse): data = response.content.decode() else: data = f"Unprocessable type: {type(response)}" log.info(f"URL: {request.path}. Data: {request.data}. Response: {data}") return response return wrapper def log_request(name="django.request"): return functools.partial(_log_request_response, logger=name) Everything works fine, it is already been months since this code works in production, and I can see both request data and response data. However, now, I would like to get a list of local variables (and their values), of logged function (view_method). More like Sentry, when it shows a list of local variables when an exception happens (but in this case, there is no exception). TRY 1: I tried inspect.stack(), but as the function is called and finished, it ceases to exist in the call stack. Thus, inspect.stack() returns only previous functions, till wrapper. … -
With Apache's ProxyPassMatch, how do I pass on only part of my URL?
I'm running Apache 2.4 with a Python 3 / Django 3 app, both in Docker containers. If my Apache container gets a request with "/api", I would like to redirect that request to the Python container. So if my Apache request is http://localhost:9090/api/states/US I would like to redirect to the Python container using the URL http://web:8000/states/US In my virtual host file I have <VirtualHost *:80> ServerName directory.example.com ProxyPassMatch ^/api http://web:8000/(.*) ProxyPassReverse ^/api http://web:8000/(.*) But when I make the request for "http://localhost:9090/api/states/US", I get this in my Docker logs maps-web-1 | Not Found: /(.*)/api/states/US maps-apache-1 | 172.23.0.1 - - [30/Jun/2022:20:23:49 +0000] "GET /api/states/US HTTP/1.1" 404 6128 So evidently my ProxyPassMatch is not correct. How do I set that up properly? -
In a Django Forms drop-down list, how do I show text accessed via a foreign key?
I have code to edit a table "instruments", which has a foreign key to another table 'instrumenttype'. I'd like to show a drop-down list showing the text values from the instreumenttype table. My problem is that the drop-down list shows "InstrumentType object(n)" instead of the instrument type description from the other table. The update works fine; when I get the selected value and update the instruments table, the correct key id is put in. Here is the form: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from instruments.models import Instrument from instrumenttypes.models import InstrumentType # Form used to edit the data pertaining to a specific instrument class EditInstrumentForm(forms.ModelForm): instrumenttype = forms.ModelChoiceField(queryset=InstrumentType.objects.all()) class Meta: model = Instrument fields = ('instrument', 'dateAdded', 'dateRemoved', 'nickname', 'serialNo', 'status', 'instrumenttype') Here is the view snippet: def update_instrument_view(request, id=id): instrument = get_object_or_404(Instrument, id=id) if request.method == 'POST': form = EditInstrumentForm(request.POST, request.FILES, instance=instrument) if form.is_valid(): instrument.instrument = form.cleaned_data.get('instrument') instrument.dateAdded = form.cleaned_data.get('dateAdded') instrument.dateRemoved = form.cleaned_data.get('dateRemoved') instrument.nickname = form.cleaned_data.get('nickname') instrument.serialNo = form.cleaned_data.get('serialNo') instrument.status = form.cleaned_data.get('status') instrument.instrumenttype = form.cleaned_data.get('instrumenttype') instrument.save() messages.success(request, 'Your instrument has been updated.') return redirect('instrument_details', instrument.id) else: form = EditInstrumentForm(instance=instrument) messages.error(request, 'Issue updating data.') return render(request, 'instrument_update.html', {'form': form, 'instrument':instrument}) else: form = … -
Is it possible to change the title of a Django group?
In the django admin when one adds groups to a user, if one hover over the group ("Freelander" in the image below), it has a toole tip (html title) that just says "Freelancer". Is it possible to add some custom text explaining what the group is for (i.e. change the title of the option element)? Here the HTML of an the option: <option value="1" title="Freelancer">Freelancer</option> The best I can come up with is to extends the django admin template and add some JavaScript to change it by looking for the string and replacing them, but this is very "hacky" -
Django static CSS file not linking to html document
I am trying to link a css file to my html inside a django project but it does not seem to be linking. base.html <head> <title>Document</title> {% load static %} <link rel="stylesheet" href="{% static 'myApp/styles.css' %}"> </head> my folder structure [1]: https://i.stack.imgur.com/3nuwE.png -
Execute gcloud commands from python API
How can I send gcloud commands through python, I have been researching about the connection that can be made through python but I have not been able to find clear information about the process. For example what to send the command: gcloud info What it would do is to receive the information and display it in an interface but I have not been able to make the connection with the project created in google. At the moment the way to make the connection to the google shell is through subprocesses in python, here is an example: import subprocess def hello_world(request): if request.method=='GET': data = subprocess.call('gcloud info',shell=True) print(data) return true *In the case of the command presented, it is only to show that I am looking for a response from different commands, since the list of commands that will be executed are for the configuration of vlan attachments. The main idea is to be able to send the execution of commands to the google shell through an API created with python (Django) and access it from a user interface but I have not been able to connect to the specific project to be able to execute those commands. How can I … -
Unable to upload a file using Reactjs, apollo, django
Hello Im' trying to upload a file using django for the back and reactjs for the front and graphql with apollo for reactjs, graphene for django. Here is part of my code : Let's begin with the front files : index.js : import React from 'react'; import ReactDOM from 'react-dom'; import { ApolloClient, InMemoryCache } from '@apollo/client'; import { ApolloProvider } from '@apollo/client/react'; import { createUploadLink } from 'apollo-upload-client'; import App from './App'; const cache = new InMemoryCache(); const uri = 'http://localhost:8000/graphql/'; const link = createUploadLink({ uri }); const client = new ApolloClient({ cache, link }); ReactDOM.render( <React.StrictMode> <ApolloProvider client={client}> <App /> </ApolloProvider> </React.StrictMode>, document.getElementById('root') ); App.js import React from 'react'; import { gql, useMutation } from '@apollo/client'; const MUTATION = gql` mutation ($file: Upload!) { imageUpload(file: $file) { success } } `; function App() { const [mutate] = useMutation(MUTATION); function onChange({ target: { validity, value } }){ if (validity.valid) { const file = new Blob([value], { type: "text/plain" }); file.name = "text.txt"; mutate({ variables: { file: file } }); } } return <input type="file" onChange={onChange} />; } export default App; And now for the back : import graphene from .models import Todo from graphene_django import DjangoObjectType, DjangoListField from graphql_jwt.decorators … -
Avrage rating calculation not working after migration django
My code was doing what it should before the migration of calculating the avrage rating. After a migration it just dident calculate the avrage rating. It seems like the migration dident notice the code i had in choices= RATINGS) . Anyone got any idea how i can fix it and get the code to notice the choices again? Since it worked fine when testing it just before migrations. **code from model.py** class Review(models.Model): product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE) rating = models.IntegerField(default=3) content = models.TextField() created_by = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) RATINGS = (('1 ',1),('2 ',2), ('3 ',3),('4 ',4),('5 ',5)) rating = models.CharField(max_length=7,choices= RATINGS) def __str__(self): return '%s - %s' % (self.product.name, self.created_by) code in the migration file: class Migration(migrations.Migration): dependencies = [ ('products', '0004_review'), ] operations = [ migrations.AlterField( model_name='review', name='rating', field=models.CharField(choices=[('1 ', 1), ('2 ', 2), ('3 ', 3), ('4 ', 4), ('5 ', 5)], max_length=7), ), ] And this a snippet of the migration after i notice the avrage rating was gone even tho the code was same after migration in models.py: -
how to pass a list of dictionary in chartjs labels and data?
I'm trying to show my data into chart js graph, my data format is this: > {length: 3, objects: Array(3)} length: 3 objects: Array(3) 0: {counter: 1, date: '2022-06-01 00:00:00', income: '233.000', …} 1: {counter: 2, date: '2022-05-01 00:00:00', income: '1000.000', …} 2: {counter: 3, date: '2022-04-01 00:00:00', income: '89.000', …} length: 3 [[Prototype]]: Array(0) [[Prototype]]: Object here is what i tried in my js: function listChartMonOutcome(){ $.ajax({ type:'GET', url:'/listcharts/data/', success:function(data){ var totalMonthCanvas = $('#listChart').get(0).getContext('2d') var totalMonthData = { labels: [ data ], data:{ datasets:[{ data:[{ data }] }] } } var totalMonthOptions = { responsive : true, maintainAspectRatio : false, datasetFill : false, parsing: { xAxisKey: 'income', yAxisKey: 'date' } } var totalMonthChart = new Chart(totalMonthCanvas, { type: 'bar', data: totalMonthData, options: totalMonthOptions }) } }) } listChartMonOutcome() } <div class="card-body"> <div class="chart"> <canvas id="listChart" style="height:250px; min-height:250px"></canvas> </div> </div> but it shows nothing, in the console as well. and also tried this in the data : labels = [data.map(({datE}) => date) ] datasets: [ { data: [ data.map(({income}) => income) ], } ] but raise this error: Uncaught TypeError: data.map is not a function is there any solution for this problem please? Thank you for helping -
Directing to nested URL with react router from server
I am building an app with django3.2 and React 17 using react-router-dom. My react app is served at https://www.example.com/ And if I navigate within the app to https://www.example.com/auth/signup I get the form, however, if I input the url directly into the browser I am taken to a blank page. In my django.urls, I have a catch all that should send the path down to my react app, and in local development it works great. urlpatterns = [ ..., re_path(r'^(?:.*)/?$', homepage), ] PROBLEM: In production I am taken to a blank page. I suspect it has to do with relative paths in production. I've followed these questions: Django static file serving in conflict with React Router React router not loading dynamic url in production And so far have tried: Adding "homepage": "https://www.example.com/" to my package.json. Adding <base href="/" /> to index.html Adding "homepage": "." to package.json But so far nothing has worked, and I need this feature, particularly for email verification. Happy to clarify anything or share front end code. -
What to do if queryset is none
I have a News model, where each instance has a unique date. Which means that every day has exactly one News-instance related to it. I am redirecting to the detail-view of the News-instance from the navbar. To achieve this am I using a context_processor. The context_processor.py file looks like this: from news.models import TodayNews import datetime def todays_news(request): todays_news = TodayNews.objects.get(date=datetime.date.today()) return {'news': todays_news} This works completely fine as long as the News model has an instance on that particular date. Otherwise it returns the following error (which is very logical): TodayNews matching query does not exist. My question is, how can I do something different if the query is empty, for example if one particular date does not have a news-instance? What should I return instead of 'news': todays_news? -
Django python GET http://localhost:8000/topics 404 (Not Found)
I am learning Django using "Python Crash Course" by Eric Matthes ch.18- 20. I am trying to run the get request of my topics.html and I'm getting the error below... GET http://localhost:8000/topics 404 (Not Found) File urls.py /learning_log # from django.conf.urls import include, url OUT_OF_DATE from django.urls import include, re_path as url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('learning_logs.urls', namespace='learning_logs')), ] File urls.py /learning_logs """Defines URL patterns for Learning_logs.""" # from django.conf.urls import url from django.urls import re_path as url from learning_logs import views app_name = 'learning_log' urlpatterns = [ # Home Page url(r'^$', views.index, name='index'), # Show all topics. url(r'^$', views.topics, name='topics'), ] File views.py from django.shortcuts import render from learning_logs.models import Topic def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topic': topics} return render(request, 'learning_logs/topics.html', context) -
Nested Serializer for Foreign Keys
I have two models - Users and UserAccessLogs: class Users(AbstractUser): email = models.EmailField() name = models.Charfield() etc. class UserAccessLogs(AbstractUser): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) anotherField = models.Charfield() etc. with serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' def validate_email(self, value): # validations here def update(self, instance, validated_data): instance.email = validated_data['email'] etc. instance.save() return instance class UserAccessLogsSerializer(serializers.ModelSerializer): class Meta: model = UserAccessLogs fields ='__all__' In my views function I would like to retrieve the actual user class when fetching UserAccessLogs i.e. I would like: UserAccessLogs = { user : { email: myEmail, name: myName, etc. } } instead of UserAccessLogs = { user : 1 } in my views: access_logs = UserAccessLogs.objects.all() serializer = UserAccessLogsSerializer(access_logs, many = True) return Response(serializer.data, status.HTTP_200_OK) I tried adding user = UserSerializer() to UserAccessLogsSerializer class. It works, but then when I try and save a new instance of the UserAccessLogs I get errors related to User model from the validators. If I set read_only = True then it leaves user = null in the database. The below works in my views class but it doesn't seem efficient and needs to be repeated every time I want to get full UserAccessLogs. for data in … -
django to change the value of varible in template based on the number
there is a model books where i want to fetch all the objects and display it to user using django templates books=books.objects.all() and with django template tag im able to fetch the values in the model and display them but is there any way where django can change the variable values based on the number for example this part : {% for b in books %} <tr> <td>{{b.books_id}}</td> </tr> {% endfor %} this will display all the id's but is there any way to override this in django Lets say for instance ,if the b.books_id for any object is 1 then it should display something like "completed" if its 2 then it should display something like "no" is there any possibility to do that ?? using if or for loops in django template tags or through views -
Vertically centering text in a bootstrap card that is being used as a button
As the title says, im trying to vertically align text inside a bootstrap card. I can center it horizontally just fine, just not vertically. I've tried different ways. I would use a button but you can't store links in them I guess. Here is some code <div class="col-sm-4"> <a href="{% url 'manufacturing:view_sections' %}" class="btn btn-primary lift lift-sm h-100 w-100 text-center" style="width: 100vw;" role="button" aria-disabled="true"><h1 class="text-light"><strong>Primary link</strong></h1></a> </div> Here is what it looks like right now The whole card is being used as a button which when pressed it's sent to a different page. -
Is separating django frontend and backend with API viable?
I'm used to Django and already developed website with a whole Django or with Django API + React. For a side project, I'm thinking about creating a Django project with 2 apps: Django API 2) Django Front. I absolutely want to decouple front/back to be able to reuse the API in the future, and I like the view system from Django. Is my idea making sense? -
How i can make the number of page start display the number of page from the second page using wkhtml2pdf
on a django application, using the library wkhtml2pdf to generate a pdf , How i can make the number of page start display the number of page from the second page(2/ total number of pages). this is my parametres in settings.py: WKHTMLTOPDF_CMD = '/usr/local/bin/wkhtmltopdf' WKHTMLTOPDF_CMD_OPTIONS = { 'quiet': True, 'disable-smart-shrinking':True, 'enable-local-file-access':True, 'page-size': 'A4', 'margin-right': '0', 'margin-top': '15', 'margin-bottom': '10', 'margin-left': '3', 'encoding': "UTF-8", 'no-outline': None, "zoom":1, 'javascript-delay':1000, 'footer-center' :'[page]/[topage]', "no-stop-slow-scripts":True, } if is it possible how i can do that ? THANKS IN ADVANCE. -
How to use django-allauth username validation methods in a user update form
I'm using django-allauth system to register users and log them in. My app should allow users to change their usernames if needed. If I use a custom view or form to change a username, no allauth validation happens whatsoever (because default views and forms are not triggered). Thus users can easily set whatever username they wish, ignoring all restrictions specified in settings (like "preserve casing" or "minimum length restriction"). Is there any way to use default validations built in allauth outside signup/login forms? Right now I have to manually create a custom form and use its cleaning methods for validation, which seems to be repetitive and error-prone: def clean_username(self): username = self.cleaned_data.get('username') if username: username = username.lower() if len(username) < settings.ACCOUNT_USERNAME_MIN_LENGTH: raise ValidationError(_("Error text")) if username in settings.ACCOUNT_USERNAME_BLACKLIST: raise ValidationError(_("Error text")) # I need something that works like the code below and validates a username from allauth.account.adapter import DefaultAccountAdapter DefaultAccountAdapter.clean_username(username) return username -
In Django, whitenoise does not show static files
This is my first time using whitenoise. While DEBUG=FALSE, I can't see the images even after doing python manage.py collectstatic. All the static files are transferred to the directory specified in the STATIC_ROOT directory after collectstatic but it shows a Not Found error in the website. My settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = False INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'phonenumber_field', 'ramrobazar.account.apps.AccountConfig', 'ramrobazar.dashboard.apps.DashboardConfig', 'ramrobazar.inventory.apps.InventoryConfig', 'ramrobazar.drf.apps.DrfConfig', 'ramrobazar.demo.apps.DemoConfig', 'mptt', # 'django_elasticsearch_dsl', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt.token_blacklist', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = 'images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') My root urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('ramrobazar.drf.urls')), path('api-auth/', include('rest_framework.urls')), path('demo/', include('ramrobazar.demo.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) When I run 'collectstatic', all the static files are transferred to BASE_DIR/'staticfiles' as that is the path specified in STATIC_ROOT in settings.py. But when I run python manage.py runserver --nostatic and try to access the images in the website, it shows Not Found The requested resource was not …