Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot import module projectname.appname when reading CSV
I have a django project named localassets and in turn have an app called assetlist. I have a directory named scripts at the root of my project (same level of manage.py) in which I have the following script to read data from a csv: load_csv.py import csv from localassets.assetlist.models import BusinessUnit, Branch def run(): with open('scripts/testing_import.csv') as file: reader = csv.reader(file) next(reader) for row in reader: print(row) bu_csv = row[0] bu = BusinessUnit.objects.get(bu=bu_csv) branch_csv = row[1] branch = Branch.objects.get(bu=bu, location_code=branch_csv) print(bu, branch) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'assetlist.apps.AssetlistConfig', 'django_tables2', 'django_filters', 'widget_tweaks', 'django_bootstrap_icons', 'django_extensions', ] assetlist\apps.py from django.apps import AppConfig class AssetlistConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'assetlist' When attempting to run the script through the command line in my environment using the following command: python manage.py runscript load_csv I get the following error: ModuleNotFoundError: No module named 'localassets.assetlist' Cannot import module 'scripts.load_csv': No module named 'localassets.assetlist'. No (valid) module for script 'load_csv' found Try running with a higher verbosity level like: -v2 or -v3 CommandError: An error has occurred running scripts. See errors above. I have re-run migrations and it has resolved successfully but I am unable to get the load_csv script to import my … -
Unhandled Runtime Error Error: Cannot read properties of undefined (reading 'map') Django with Next Js
I am working on a Django Rest Framework with Next Js and I am getting stuck with fetching data from the API. I have data in this url http://127.0.0.1:8000/api/campaigns and when I visit the url I see the data. The problem is when I fetch it and console with Next Js, I get undefined. Also when I try mapping the data, I get the error Unhandled Runtime Error Error: Cannot read properties of undefined (reading 'map'). Here is my Index.js file where the data fetching is done; import React from 'react' export default function Index ({data}) { console.log(data) return ( <div> <main> <h1>Available Campaigns</h1> {data.map((element) => <div key={element.slug}> <div> <div> <img src={element.logo} height={120} width={100} alt="image" /> </div> <div></div> </div> </div>)} </main> </div> ); } export async function getStaticProps() { const response = await fetch("http://127.0.0.1:8000/api/campaigns"); const data = await response.json(); return { props: { data: data }, } } Here is a screenshot of the data I am getting when I visit the url, Also note that I am using the latest version of next js. Any help will be highly appreciated. Thanks. -
How to change the environment variable in when running pytest in django application
Good afternoon! Tell me how not to send a request to a productive server when running pytest. settings.py - import environ env = environ.Env( DEBUG=(bool, False), ) PROD_URL = env('PROD_URL') I use this variable to send a request service.py - import requests requests.post(PROD_URL, json=headers) How can I set this variable to another value when running pytest? -
Django Grab Only First of Each Primary Key in Query
I have a model as below. I want to query it and fetch only the first, newest row of each tagid. So I do something like items = get_model().objects.filter(q).order_by('-t_stamp'). That query works, but it returns several hundred thousand rows that I don't need. I only need the first of each tagid. How can I achieve that kind of query in Django? class TagDataBase(BaseModel): tagid = models.IntegerField(primary_key=True) intvalue = models.BigIntegerField(blank=True, null=True) floatvalue = models.FloatField(blank=True, null=True) stringvalue = models.CharField(max_length=255, blank=True, null=True) datevalue = models.DateTimeField(blank=True, null=True) dataintegrity = models.IntegerField(blank=True, null=True) t_stamp = TimestampField() class Meta: managed = False abstract = True db_table = 'sqlt_data_1_2023_02' unique_together = (('tagid', 't_stamp'),) It's abstract because the db_table changes, and I fetch the model class using a get_model() method. -
My Django react app not render properly after running react build
My Django react app is running ok at react port localhost 3000 but after after running build and integrating inside my Django so that it can render the front end the homepage display without data from database from inspect am seeing unauthorized requests,but when i try to login it rejects this is the Django react app running on react server localhost 3000 this the Django react app that is rendered by Django server after running react build I have added the path to static file to the build static folder And I have also pointed to the index html file in the url Any solution to this problem -
Django populate a listbox from a form with a raw mysql query result
I have a listbox in a form that is populated with a manual list : Forms.py FRUIT_CHOICES= [ ('Oranges', 'Oranges'), ('Cantaloupes', 'Cantaloupes'), ('Mangoes', 'Mangoes'), ('Honeydews', 'Honeydews'), ] class AddRecordForm(forms.ModelForm): testrever = forms.MultipleChoiceField(choices=FRUIT_CHOICES) class Meta: model = Record exclude = ("user",) models.py class Record(models.Model): testrever = models.JSONField(max_length=500) html {{ form.testrever }} I would like to replace the FRUIT_CHOICElist by the result of a raw Mysql query like : "SELECT * FROM website_record WHERE first_name RLIKE %s",[search] How can I achieve that ? -
Synatx issue python3.11.3 in virtual studio [duplicate]
I need assistance figuring out what the error is here. Thank you in advance for your answer, appreciate it. Best Regards, M.T Trying to activate the urls.py in my virtual studio project. However, this syntax issue is not allowing me to run and try to secure the code needed to run the application properly. Any extra contributions on how to be more efficient with the url.py regulations will be appreciated too. -
How to upload file in django and access in another module?
I'm usind django e plotly dash to make a dashboard in my page. In this application we will to make a upload file, but this file have to save in "C:\tmp\Uploads". How can i make this and access with python dash??? I make the form and can make the upload file, but can't access in another module. from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt @csrf_exempt def test_page(request): if request.method == 'POST': upload_file = request.FILES['document'] return render(request, 'index.html') -
Match making method to generate ballot from candidates Django
Building a not completely standard voting app in Django (it's a bit like an online multiplayer game where people join a round on the fly to "vote" against each other), but I can't figure out how to best generate the Ballots for the use case. I'm trying only 2 models currently: Candidate and Ballot. models.py class Candidate(models.Model): link = models.URLField() ballot = models.ForeignKey('Ballot', null=True, on_delete=models.SET_NULL) # other fields def __str__(self): return self.link class Ballot(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # each candidate cand0 = cand1 = cand2 = # other fields def __str__(self): return self.id Requirement: Each Ballot generated has exactly 3 Candidates Users will submit a Candidate (which is a link) via simple form: class UploadForm(ModelForm): class Meta: model = Candidate field = ['link'] def clean(self): #validation stuff I'd like to avoid creating a pool of Candidates from which Ballots are generated and instead my thought is this approach: For each user who submits a Candidate, it creates a Candidate object and updates a "cand" field of a Ballot object. Then, once the 3 candidate fields of a Ballot have a Candidate, the process repeats. Questions: Is this a good/feasible approach? If so, how would I go about implementing … -
Why does I can't log out even if it works on server-side in Django React
I'm new to Django and React and I tried to create auth system. Register and Log In work fine both in server-side and client-side but the Log out one didn't When i send POST method from React it said "POST http://127.0.0.1:8000/user/logout 403 (Forbidden)" even if it work in Django So this is my UserLogOutView in Django class UserLogOutView(APIView): def post(self, request): logout(request) return Response(status=status.HTTP_200_OK) and then urls.py urlpatterns = [ ... path('logout', views.UserLogOutView.as_view(), name='logout'), ] next I send POST method through axios like this in my react component const submitLogout = () => { axios .post( "http://127.0.0.1:8000/user/logout", ) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); } const handleClickLogOut = (e) => { e.preventDefault(); submitLogout(); props.onClose(false); }; and use it like this <form onSubmit={e => handleClickLogOut(e)}> <button className='font-bold text-[20px]'>Log Out</button> </form> I also set the CSRF token in Axios headers in that file axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.defaults.withCredentials = true; any suggestion? I tried to POST api logout and hope it logout for me in React but it said POST http://127.0.0.1:8000/user/logout 403 (Forbidden) -
experiencing slow query performance on my Django app with PostgreSQL on Docker
I have a complex query with multiple subqueries in my Django app that runs in 200-400 ms locally. However, when running Django and PostgreSQL on Docker, the same query takes around 7 seconds. What could be causing this significant performance difference, and how can I improve the query performance on my Docker setup? I'm not sure what is causing the problem, but I have already tried running the project with different thread pools, and the issue persists. UPDATE 1: This is the result from explain in local: https://pastebin.com/haY2s6Wc and this is from docker container: https://pastebin.com/qG8s6myd The structure that im using for my project is to create a custom manager and write functions that each one has a separate queryset for reusablity and then i chain these methods: def get_available_items(self): """ Get necessary items needed to load a page. """ return self.get_actives() \ .get_default_pack_price() \ .get_related_packs() \ .get_active_packs() \ .get_packs_colors_expense()\ .get_packs_warranty()\ .get_total_actual_count_stock() \ .get_picture_choices() \ .count_stock_products() \ .get_total_packs() \ .get_title_of_default_pack_warranty() \ .get_default_pack_sku() \ .show_price_and_currency_for_product_api_list()\ .get_static_discount() # this is the long qs Then i realised if i remove some of these querysets, then its not taking that long.(even with that huge queryset) but i need all these data for my page. What … -
problem deploying site in python any where
I'm trying to deploy my Django project with pythonanywherdotcom. I do exactly like his: creating an account creating API token in bash scripts pip3.8 install --user pythonanywhere and then pa_autoconfigure_django.py --python=3.8 https://github.com/\<your-github-username\>/my-first-blog.git but I face this \< Running collectstatic { \ \~\<:\>\>\>\>\>\>\>\>\> Traceback (most recent call last): File " /home/anieeem/anieeem.pythonanywhere.com/manage.py", line 22, in \<module\> main() File"/home/anieeem/anieeem.pythonanywhere.com/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/anieeem/.virtualenvs/anieeem.pythonanywhere.com/lib/python3.8/site-packages/django/core/management/__init__.py", line 442, in execute\_ from_command_line utility.execute() File "/home/anieeem/.virtualenvs/anieeem.pythonanywhere.com/lib/python3.8/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() } I want to know how to figure this out. -
Heroku build successful but getting "Application error" when trying to open app
The deployment seems to be successful but when I open the app I get the error message above. The deployment looks like the message below. -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the same version as the last build: python-3.11.3 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.11.3 -----> Installing pip 23.1.2, setuptools 67.7.2 and wheel 0.40.0 -----> Installing SQLite3 -----> Installing requirements with pip Ignoring backports.zoneinfo: markers 'python_version < "3.9"' don't match environment -----> Skipping Django collectstatic since the env var DISABLE_COLLECTSTATIC is set. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 41.6M -----> Launching... Released v37 https://gardening-blog.herokuapp.com/ deployed to Heroku I was expecting the app to launch. I am guessing it is because it is ignoring backports.zoneinfo? but unsure how to resolve that. -
Password form style not working in Djangto
I am trying to change the basic sign in form and did the following style from django import forms from django.contrib.auth.forms import UserCreationForm from .models import Product from userprofile.models import Customer from django.forms import TextInput, EmailInput, PasswordInput from django.contrib.auth.models import User class CrateUserForm(UserCreationForm): class Meta: model = User fields= ['username', 'email', 'password1', 'password2',] widgets = { 'username': forms.TextInput(attrs={ 'class': 'w-100 p-3 rounded-4 border border-success shadow', 'placeholder': 'Exemplu1234', }), 'email': forms.EmailInput(attrs={ 'class': 'w-100 p-3 rounded-4 border border-success shadow', 'placeholder': 'exemplu@email.com', }), 'password1': forms.PasswordInput(attrs={ 'class': 'w-100 p-3 rounded-4 border border-success shadow', }), 'password2': forms.PasswordInput(attrs={ 'class': 'w-100 p-3 rounded-4 border border-success shadow', }), } Now my problem is that the field for both password did not change while the other two did. How can I make them work? I tried to reorder the fields but nothing changed. -
Django can't migrate when i make models
whenever i try to add a simple model like this: from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=43) image = models.ImageField(null=True) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) i get this error massage when i try to make migrations. Traceback (most recent call last): File "/Users/rickdegraaf/venv/projects/blog-tutorials/blog/manage.py", line 22, in <module> main() File "/Users/rickdegraaf/venv/projects/blog-tutorials/blog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/rickdegraaf/venv/projects/blog-tutorials/blog/blog1/models.py", line 7, in <module> class Post(models.model): TypeError: function() argument 'code' must be code, not str and i don't know why ? i tried adding this: from .models import Post admin.site.register(Post) to admin.py … -
Categorize posts by months and years in Django
I am a noob in Django, and I am doing a project with lots of trials and errors. Here's a case. I want to implement this on my site: arc asia Each entry will have posts grouped by the months and the years. If I click, I will get to see bunch of posts on that month and year. My site only has 4 posts now, all of which were on last September. The look that I managed to do is the following, which obviously is wrong because Sep 2022 should be a single entry. There has to be some way to do the group by but I can't seem to achieve that: group I wanted to do it with an archive view, as I failed at that attempt, I am doing in this way. I'd like to know both ways. Here are the relevant files: blog/models.py class News(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) news_title = models.CharField(max_length=250) null=True) slug = models.SlugField(max_length=300, unique_for_date='nw_publish') news_author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='news_posts') news_body = RichTextField() image_header = models.ImageField(upload_to='featured_image/%Y/%m/%d/', null=True, blank=True) # this nw_publish = models.DateTimeField(default=timezone.now) nw_status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') tags = TaggableManager() def __unicode__(self): return '%name' % {'name': self.news_title} class Meta: … -
Getting Reverse for 'app_list' not found on custom Admin in Django
My code is as follows: admin.py: from django.contrib.admin import AdminSite from copy import copy from django.apps import apps from django.contrib import admin from .models.badge import * class MyAdminSite(AdminSite): site_header = 'Monty Python administration' admin_site = MyAdminSite(name="myadmin") admin_site.register(Badge) urls.py: from dopplleApi.views.admin.common.adminSite import admin_site app_name = 'dopplleApi' urlpatterns = [ #-- default path('', views.index, name='index'), #-- admin path('myadmin/', admin_site.urls), ... ] When I navigate to my local server /myadmin, I am getting error: Reverse for 'app_list' with keyword arguments '{'app_label': 'dopplleApi'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|authtoken)/$'] What am I doing wrong? -
How to convert objects' fields to a list in Django?
I have a list of Competitors which are grouped into different groups (brackets) using Foreign Keys. Models.py class Group(models.Model): group_label = models.CharField(max_length=20, unique=True) def __str__(self): return self.group_label class Competitors(models.Model): flname = models.CharField(max_length=255) Weight = models.IntegerField(validators=[MinValueValidator(50), MaxValueValidator(300)]) rank = models.CharField(max_length=255) Group_FK = models.ForeignKey(Group, blank=True, null=True, on_delete=models.CASCADE, to_field='group_label') point = models.IntegerField(default=0) After assigning Competitors to their Group, how do I convert all of the flname in a Group into a tuple before using itertools.combinations() to create unique pair (matches) from it? -
Cannot assign "13": "Registerleson.leson" must be a "Classes" instance
I want to do a group registration, everyone who registered in the old leson will be registered in the new leson Help me please error Cannot assign "13": "Registerleson.leson" must be a "Classes" instance. views.py def AddListGroup(request): oldleson = request.POST['termold'] newleson = int(request.POST['termnew']) book = request.POST['book'] price = request.POST['price'] discount = request.POST['discount'] darsad = request.POST['darsad'] leson = Registerleson.objects.filter(leson=oldleson) if leson: for item in leson: register = Registerleson( student=item.student, leson=newleson, book=book, member_add=request.user.id, discount=discount, darsad=darsad, price=price,) register.save() messages.add_message(request, messages.SUCCESS, 'ثبت نام گروهی با موفقیت انجام شد') return redirect('groupRegistration') else: messages.add_message(request, messages.WARNING, 'هیچ زبان آموزی در کلاس مبدا ثبت نام نکرده است') return redirect('groupRegistration') groupRegistration.html page <select class="form-control" name="termold"> {% for item in kelasha %} {% if item.term.termjari != 1 %} <option value="{{ item.id }}">{{ item.sath.name }}</option> {% endif %} {% endfor %} </select> <select class="form-control" name="termnew"> {% for item in kelasha %} {% if item.term.termjari == 1 %} <option value="{{ item.id }}">{{ item.sath.name }}</option> {% endif %} {% endfor %} </select> <label style="margin-top: 20px">کتاب : </label> <select class="form-control" name="book"> {% for item in books %} <option value="{{ item.id }}"> {{ item.name }}</option> {% endfor %} </select> <label style="margin-top: 20px">قیمت : </label> <input class="form-control" type="number" name="price" value="0"> <label style="margin-top: 20px">تخفیف : </label> <input … -
How to call disparate APIs coming from a single View?
Let's say I'm writing a Dashboard View, and on the Dashboard the user can do 3 things: update their name, change their avatar, and add a friend. These are 3 different things that require different API logic for each one. Is it better practice to write 3 different APIs, all at different URIs, to do these functions? Or is it better to put them all at the Dashboard's POST function, with a field sent in to say which one we're working on? I've tried both things and they both work, but I'm kind of self-taught and don't know what's the best practice. -
app.sock failed (2: No such file or directory)
I am running an ec2 intance with ubuntu. I had to update from ubuntu 18.04 to 22.04 and aftr doing it I started to receive the following error. After tail -f /var/log/nginx/error.log I got the following error: [crit] 647#647: *9 connect() to unix:/home/ubuntu/UrRecalls/app.sock failed (2: No such file or directory) The server is done with Django and I don't remember ever seeing the app.sock file. Any ideas about what could be causing this issue? I have tried restarting the server, stopping and starting Nginx, and rebooting the server. I am pretty new at this and would appreciate any help. -
Django User Profile Model get User first_name
I am extending the User table to add new fields. In UserProfile I have column display. I want to set default you to full name from User table How can I access foreign key fields inside the UserProfile ? class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) def get_upload_avatar_to(self, filename): return f"images/avatar/{self.user.id}/{filename}" full_name = '' avatar = models.ImageField(upload_to=get_upload_avatar_to, null=True, blank=True) bio = models.TextField(default="", blank=True) display = models.TextField(default= full_name, blank=True) -
Front and back synchronization failing
I'm creating a web with a Django backend and React frontend. When posting an object from the front and trying to fetch it, it doesn't work unless I restart the backend, when it should update instantly. In the admin view it shows right away, but it cannot fetch it for some reason until I restart Here is the settings file in case is relevant """ Django settings for backend project. Generated by 'django-admin startproject' using Django 4.1.1. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os import xmlrunner # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent MODEL_DIR = os.path.join( BASE_DIR, 'petRecognition', 'model') DEMO_PICTURES_DIR = os.path.join( BASE_DIR, 'petRecognition', 'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-vbkt_liurmfu7$18-v#&n9+!zneamzit*)aeltd+6$*gkpqjgd' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', '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', … -
How to use django-rules predicates with nested serializers
I have a few models in my application which use django-rules to define permissions. More precisely, I have predicates which are used in the rules_permissions (inside the model's Meta) dictionary, under the view key. I am using django-rest-framework for views and serializers. I'd like to restrict the views to not serialize nested data for which the user does not have the view permission. The code works fine for a single level of serialisation, but the predicates for nested objects are never evaluated. For example, I have a Project model, and when querying for /projects/3/, the following data is returned: { "id": 3, "name": "Test Project", "data": [ { "id": 3, "user": 2, "test": "test_adam" }, { "id": 4, "user": 3, "test": "test_eve" } ] } However, as a user Adam, I should not be able to see the Data object which belongs to Eve. I should only see the serialised data for Data object with "id": 3. So I've written a is_data_owner predicate and added it to rules_permissions of my Data class. But that predicate function is never called when querying for /projects/3/, even though the serializer is accessing the Data model to create the above, nested serialisation. I'd expect … -
Uploaded image via django admin not found, altough URL seems correct
as Django newby I am strugling to get an image on screen. After reading tons of questions and answers to problems alike, I am only more puzzled, because it looks like I coded the necesary, but I get an 404 error when clicking on an image link in the admin page or trying to show an image in a template. While the two seem related I will stick to the admin site. This is what I am seeing in the admin site: To me it looks correct from what I have seen/read. But when I click the link I get a 404 error: Altough the media URL seems to work, because the images/Presentation_....jpg is now prefixed by http://.../media/ The image is in the following directory: Where C:\Users\Admin\PycharmProjects\website_andalucia is my BASE_DIR (when I print it from settings.py) The necesary code looks like this: Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Base url to serve media files MEDIA_URL = '/media/' # Path where media is stored MEDIA_ROOT = os.path.join(BASE_DIR, 'media') print("base dir:", BASE_DIR) print("media root:", MEDIA_ROOT) Models.py (see the remark_image) class remark(models.Model): # Fields activity = models.ForeignKey(activity, on_delete=models.CASCADE, null=True) remark_date = models.DateField(default=date.today) remark_desc = models.TextField(help_text='Enter your remark(s) here') remark_image = …