Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in Displaying the content of a txt file through Django
[This is the text file I want to project in the browser screen. The second one is the views file which has the function. path('ShowFile', views.ShowFile, name ='ShowFile') in the last picture in the urls.py -
Django: Inject a string variable from Views.py with HTML and Django template tags into HTML file
So this is my issue: I have a Python string that contains both HTML and Django Template Tags and want to inject it into a base HTML file when I go to that page. Although, when I go to the page, all the HTML renders, but the Django Template Tags do not, and are treated literally as strings? Here is a simplified example of the issue: Views.py def page(request, code): html = { 'code': code 'html': """<p>Hello world {{ code }}</p> <script src="{% static 'appName/javascript_code_example.js' %}"></script>""" } return render(request, 'base.html', html) base.html {% load static %} ... {{ html | safe }} ... And all I will see when I run the app on my local machine with python3 manage.py runserver and go to the URL that renders base.html is Hello world {{ code }}, and the Javascript code is not executed. Instead of {{ code }} I'd like to see the actual value of the 'code' key in the html dictionary in the Views.py file. -
Get latest message in a chat application - Django
I've coded a chat application with Django Channels and it's working fine. The only issue is getting the latest messages and displaying them when coming back to the chat app. This is resolved for the moment by adding a function that gets older messages (old_messages()) in the chatSocket.onopen = function(e) part of the js file. The only problem now is: when user A refreshes the page of chat, the other user (user B) gets the older messages two times (since the connexion is closed and open for a second time by user A). Any idea how to avoid this problem ? Here is a part of js file : var chatSocket = new ReconnectingWebSocket( 'ws://' + window.location.host + '/ws/chat/' + discussion_slug + '/'); chatSocket.onopen = function(e) { console.log("open",e) old_messages(); }; function old_messages() { chatSocket.send(JSON.stringify({'command': 'old_messages', 'discussion_slug': discussion_slug })); }; In consumers.py: def old_messages(self,data): discussion_slug = Discussion.objects.get(slug=data['discussion_slug']) last_msgs = discussion_slug.messages.all()[:15] content = { 'command': 'old', 'message': self.many_msg_to_json(last_msgs) } return content async def receive(self, text_data): data = json.loads(text_data) content = self.commands[data['command']](self,data) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': content } ) Thanks! -
Change variable in views.py after model.method worked - Django
everyone. I have a global variable in views.py: it is a list of users who voted. I want to empty that list, after my Author is deleted. I have a Author.delete method in models.py, which I could use to empty it, but I can't import a list to models.py views.py voted_list=[] models.py class Author(models.Model): def delete(self, *args, **kwargs): Option.objects.filter(author_id=self.id).update(author_id=None, votes=0) super().delete(*args, **kwargs) Or may I import my 'delete' method to views, something like: views.py if Author.delete(): voted_list=[] Thank you. -
Template does not show html content
TemplateSyntaxError at /deals/amp-stories Invalid block tag on line 576: 'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Request Method: GET Request URL: http://localhost:8001/deals/amp-stories?card_ids=1 Django Version: 2.2.7 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 576: 'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I am trying to create a view that will load a template view in django and I am getting the above error. <body> <!-- supports-landscape --> {% if card_list %} <amp-story standalone title="Best islands to visit from Guernsey" publisher="add here" publisher-logo-src="add here" poster-portrait-src="add-logo" poster-square-src="add-logo-here" poster-landscape-src="add-logo-here" supports-landscape> {% for card in card_list %} <amp-story-page id="slide_3" class="i-amphtml-element i-amphtml-layout-container i-amphtml-layout i-amphtml-story-page-loaded" i-amphtml-layout="container" aria-label="null" distance="0" i-amphtml-visited="" active=""> <amp-story-grid-layer template="fill" class="zoomIn i-amphtml-element i-amphtml-layout-container i-amphtml-story-layer i-amphtml-story-grid-template-fill i-amphtml-layout" i-amphtml-layout="container"> <amp-img src="{{card.card_image}}" width="1080" height="1920" class="i-amphtml-element i-amphtml-layout-fixed i-amphtml-layout-size-defined i-amphtml-layout" i-amphtml-layout="fixed" style="width: 1080px; height: 1920px; --loader-delay-offset:6ms !important;" i-amphtml-auto-lightbox-visited=""> <img decoding="async" src="{{card.card_image}}" class="i-amphtml-fill-content i-amphtml-replaced-content"> </amp-img> </amp-story-grid-layer> <div class="i-amphtml-story-spinner" aria-hidden="true" aria-label="Loading video"> <div class="i-amphtml-story-spinner-container"> <div class="i-amphtml-story-spinner-layer"> <div class="i-amphtml-story-spinner-circle-clipper left"></div> <div class="i-amphtml-story-spinner-circle-clipper right"></div> </div> </div> </div> </amp-story-page> (% endfor %) {% else %} <p>There are no cards in the collection.</p> {% endif %} </amp-story> </body> </html> views.py class StoryList(ListView): model = Card context_object_name = "all_cards" template_name … -
I'm working on a django project and anytime i activate the virtual environment the server will not run
I use vscode and it does not highlight any error though...django is also added to path This is the error (myenv) C:\Users\GH\Desktop\Developments\The Blog\blogsite>python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
A way to update data in the database without deleting earlier ones in Django
I have ManyToMany relation in my model and the whole issue is how to only insert a new record (not repleace old one). I mean before update I have for example '1' in this field and after upade it will be '1, 2' instead of only '2' where 1 and 2 are id of other stuff in database -
when I expand my UserAdmin I get an error(__init__() got an unexpected keyword argument 'region') in the admin panel
i'm following a tutorial https://codingwithmitch.com/courses/building-a-website-django-python/ to build a user registration app with django 2.2. my site works just fine exept when I want to add a new user or modify one in the admin panel. this is the traceback that I get: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/account/account/1/change/ Django Version: 2.2.2 Python Version: 3.7.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'rest_framework', 'account'] Installed Middleware: ['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'] Traceback: File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\contrib\admin\options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\contrib\admin\sites.py" in inner 223. return view(request, *args, **kwargs) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\contrib\admin\options.py" in change_view 1637. return self.changeform_view(request, object_id, form_url, extra_context) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\contrib\admin\options.py" in changeform_view 1522. return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\contrib\admin\options.py" in _changeform_view 1551. ModelForm = self.get_form(request, obj, change=not add) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\contrib\auth\admin.py" in get_form 80. return super().get_form(request, obj, **defaults) File "C:\Users\IR-Tech\Anaconda3\envs\ArianaSite\lib\site-packages\django\contrib\admin\options.py" … -
Multiple csrftoken cookies, is it a RFC requirement to only have 1 csrftoken?
I'm trying to find an answer to the following. Under what circumstances would the browser store multiple csrftoken cookies? Is it the correct, or technically valid functionality? And where in the RFC/security documentation passing an array, or trying an array of csrftoken exists, or is technically valid? I've attached an example screenshot of what I'm seeing multiple csrftoken with various cookie paths, and expiry times ( multitenancy, and various form paths ). Related: https://github.com/django/django/blob/5a68f024987e6d16c2626a31bf653a2edddea579/django/middleware/csrf.py#L324 https://github.com/django/django/blob/5a68f024987e6d16c2626a31bf653a2edddea579/django/middleware/csrf.py#L191 Cookie path and its accessibility to subfolder pages -
Django unexplicable routing issue?
I am building a simple news app with posts and I have a seemingly unexplicable error on a routing a request. The URL and the route match perfectly and yet, django complaints about not finding a match, which is obviously matches. The current path, blog/tag/international/, didn't match any of these. My urls.py are... from django.conf.urls import url from . import views # App name app_name = 'blog' # Url Patterns urlpatterns = [ # Default lists all posts url('^$', views.post_list, name='post_list'), # List post by tag url('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), # Post url('(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), ] Please help, what am I missing? Many thanks. -
Javascript & Django Channels: Chat app sign off notification on window close
I am writing a chat app with Javascript and Django Channels. I am trying get a "User has left chat." message to send when the window is closed, maybe also when the websocket is closed. I'm not sure if the websocket is closing too quickly, but the code as I have it currently is not working. It's possible I should be defining within the disconnect function in the chat consumer. I'm not sure of the order some of this stuff is handled in. Javascript // Declare variables var userName; var currentZone = new Date().toTimeString().slice(17); // var roomName = {{ room_name_json }}; document.getElementById("chatname").innerHTML = roomName; // Create Websocket var chatSocket = new ReconnectingWebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); // Send message chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; document.querySelector('#chat-log').value += (message + '\n'); document.getElementById("chat-log").scrollTop = document.getElementById("chat-log").scrollHeight; }; // Set User window.onload = function(){ userName = sessionStorage.getItem("user"); if (userName==null || userName===false) { userName = prompt("Please enter a username:"); }; return userName; } //Join message function chatJoin() { if(chatSocket.readyState == false) { window.setTimeout(chatJoin, 500); /* Wait 500 milliseconds*/ } else { var message = userName + " has joined the chat." chatSocket.send(JSON.stringify({ 'message': message … -
how do i save a model instance that i just created in django views?
in my views.py this is supposed to save a cart item cart = Cart.objects.get_or_create(owner=owner, is_ordered=False, ref_code=ref_code) insert = OrderItem(item_count=item_count, price=total_price, color=color, size=size, product=product, cart=cart) insert.save() but instead, it's giving me an error even though the cart was created Cannot assign "(, False)": "OrderItem.cart" must be a "Cart" instance. -
Django — async_to_sync vs asyncio.run
We can use both functions to run any async function synchronously: import asyncio from asgiref.sync import async_to_sync asyncio.run(asyncio.sleep(1)) async_to_sync(asyncio.sleep)(1) What is the difference? Can we always use asyncio.run instead of async_to_sync? -
Celery chained tasks and django transactions
As many places on the internet say, you have to make sure that if you pass around primary keys from django model instances, the task you're passing them to only gets started after the transaction in the current context has completed. You can do that with django's transaction.on_commit. Otherwise you'll get an ObjectDoesNotExist error in the called task every so often. I've been developing some mildly complex celery workflows using its canvas primitives (chain, chord, group, ...) where the intermediate task calling (say, the next task in a chain) is done by celery itself and I've been running in those kinds of errors, as one of the flows involves passing around such a primary key to the next task in the chain. I can't find any way of making sure the next task is called only when the transaction in the current task finishes. I've tried to turn autocommit off and handle commits and rollbacks myself like: transaction.set_autocommit(False) try: stuff_to_get = Model.objects.first() try: data = very_long_running_query() except ConnectionReset as exc: self.retry(exc=exc) obj = Foo.objects.create(**data) # this is then referred to in a task further in the chain return obj.pk except Exception as e: transaction.rollback() raise e else: transaction.commit() finally: transaction.set_autocommit(True) … -
Error after migration from django 1..x and cms-plugins to djangocms plugins and django 2
When upgrading the old packages in the file requirements.txt of my application, of which the deprecated cms-plugins to the newer djangocms-plugins, I got the following error: <code> (tonhausPZ) root@manelmr-Lenovo-G560:/home/manel-mr/PhilippZ# python manage.py migrate djangocms-picture python: can't open file 'manage.py': [Errno 2] No such file or directory (tonhausPZ) root@manelmr-Lenovo-G560:/home/manel-mr/PhilippZ# python src/manage.py migrate djangocms-picture Traceback (most recent call last): File "src/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/site-packages/djangocms_picture/models.py", line 15, in <module> from cms.models import CMSPlugin File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/site-packages/cms/models/__init__.py", line 3, in <module> from .pagemodel import * # nopyflakes File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/site-packages/cms/models/pagemodel.py", line 24, in <module> from cms.models.managers import PageManager, PageNodeManager File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/site-packages/cms/models/managers.py", line 15, in <module> from cms.utils.i18n import get_fallback_languages File "/home/manel-mr/PhilippZ/src/tonhaus/tonhausPZ/lib/python3.5/site-packages/cms/utils/__init__.py", line 7, in … -
Setting collation and charset per model/table in Django and MySQL
In Django it is really easy to set the collation and charset for a connection to MySQL. Here is an example of how to do that using the mysql-connector-python Django engine: DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'mydatabase', 'USER': 'root', 'PASSWORD': 'secret-password', 'HOST': 'localhost', 'OPTIONS': { 'use_pure': True, 'sql_mode': 'STRICT_TRANS_TABLES', 'charset': 'utf8mb4', 'collation': 'utf8mb4_unicode_ci', }, 'TEST': { 'CHARSET': 'utf8mb4', 'COLLATION': 'utf8mb4_unicode_ci', } } } However, this sets the charset and collation for the whole database (all of the tables). I'd like to be able to specify this on only the tables or even fields/columns that I know need this collation/charset (for emoji for example). The problem I'm having is that I'm depending on some models/tables from other Django apps that specify CharField with max lengths larger than the new collation/charset can handle for indexing a unique field. Specifically, there is an app that defines CharField(max_length=255, unique=True) which causes, django.db.utils.ProgrammingError: Specified key was too long; max key length is 767 bytes error. Is there a way to specify the charset and collation on a column/field or table/model level? -
Import a global variable from views to models - Django
everyone. I have a global variable in models.py, which changes. I want to pass it to views: from .views import File "C:\Users\chainsaw\Desktop\django-locallibrary-tutorial-master\django-loc allibrary-tutorial-master\catalog\models.py", line 6, in <module> from .views import voted_list File "C:\Users\chainsaw\Desktop\django-locallibrary-tutorial-master\django-loc allibrary-tutorial-master\catalog\views.py", line 5, in <module> from .models import Book, Author, BookInstance, Genre, Option ImportError: cannot import name 'Book' from 'catalog.models' (C:\Users\chainsaw\ Desktop\django-locallibrary-tutorial-master\django-locallibrary-tutorial-master\ catalog\models.py) -
How can i edit a Django form in a template?
I'm using this library to handle authentication in my Django app. Now, i'd like to edit the login form's appearance, but i'm having some troubles finding the HTML file where the form is located. For example, i would like to move 'Username' and 'Password' inside the form, make it a little bigger and some other stuff. How can i do it? I've tried to look into the HTML templates but i haven't found anything. Any advice is appreciated. -
During testing, when tested with correct user input, I get "Invalid credentials"
I am using just phone number alone as the only field for login. Authentication does not seem to work well even when supplied with correct user input. @api_view(["POST"]) @permission_classes((AllowAny,)) def logins(request): phone_number = request.data.get("phone_number") if phone_number is None: return Response({'error': 'Please provide your phone number'}, status=HTTP_400_BAD_REQUEST) user = authenticate(phone_number=phone_number) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK) -
why structured menu cannot be rendered in html template?
i would like to make a structure database for a restaurant menu without using mptt or django-tree. here is my models.py: from django.db import models class Menu(models.Model): name = models.CharField(max_length=24, unique=True, verbose_name='menu name') #slug = models.SlugField(max_length=24, unique=True, help_text='The slug is the URL friendly version of the menu name, so that this can be accessed at a URL like mysite.com/menus/dinner/.') additional_text = models.CharField(max_length=128, null=True, blank=True, help_text='Any additional text that the menu might need, i.e. Served between 11:00am and 4:00pm.') order = models.PositiveSmallIntegerField(default=0, help_text='The order of the menu determines where this menu appears alongside other menus.') class Meta: ordering = ['name', 'order'] class MenuCategory(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE,help_text='The menus that this category belongs to, i.e. \'Lunch\'.') name = models.CharField(max_length=32, verbose_name='menu category name') additional_text = models.CharField(max_length=128, null=True, blank=True, help_text='The additional text is any bit of related information to go along with a menu category, i.e. the \'Pasta\' category might have details that say \'All entrees come with salad and bread\'.') order = models.IntegerField(default=0, help_text='The order is the order that this category should appear in when rendered on the templates.') class Meta: verbose_name='menu category' verbose_name_plural='menu categories' ordering = ['order', 'name'] def __unicode__(self): return self.name class MenuItem(models.Model): CLASSIFICATION_CHOICES = ( ('neither', 'Neither'), ('vegan', 'Vegan'), ('vegetarian', … -
What's the best way to plug React-Native with Django in Android Emulator?
This question is to know in general what's the workflow while developing Android apps in React-Native with Django in backend. So, far I got to know that the device emulates in Android Studio so the localhost of Linux Machine and Android Device differ. Want to know from the community what's the best way to develop apps in that scenario? How to connect Backend and Frontend in general then? -
Django envirment variables aren't working
i'm running django on gcloud Ubuntu 18.04 everytime i try to set envirment variable instead of a string i get an error but when i use echo or os.environ.get() from shell it works fine settings.py ... DB_NAME = os.environ.get("DB_NAME") DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': DB_NAME, ... } } ... from bash ~/myproject$ echo $DB_NAME Candlelight from shell >>> import os >>> os.environ.get('DB_NAME') 'Candlelight' >>> .bashrc export DB_NAME = "Candlelight" -
Import dictionary and arrays into Django views from different files
How to import Python files dictionary/array data into the HTML views files to generate views. Those dicts and arrays hold the data that I need to generate HTML <datalist>, <select> fields from. project | |___data.py #contains, many dicts, arrays |___views.py {% import data.py %} #?? -
Authenticate in Django test client with headers
I've overridden the ModelBackend in my django app. My overridden model backend requires that headers be present in the request to log in the user. HEADER = 'testing' class TestingModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): testing_header_value = None if request is not None and request.META is not None: testing_header_value = request.META.get(HEADER, None) if username is None: username = kwargs.get(User.USERNAME_FIELD) try: user = User.objects.get_by_natural_key(username, testing_header_value) except User.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). User().set_password(password) else: # now validate password and whether the user is active if user.check_password(password) and self.user_can_authenticate(user): return user This works perfectly in non test scenarios. However, when I test I'm running into a problem of passing headers with the test client. The Django test client has a login method but it doesn't pass the request when authenticating which means that my model backend can't function correctly - I can't pass the header I need to. Note that one of the parameters in the authenticate function is the current request. I see that I can use force_login but that seems a little hack-y. What is the correct way to do this? I suspect … -
How to serve media files in development?
I have a problem when trying to display in a template a picture from my media file (for example a profil picture from an user). I have already looked at many topics, and everytime the answer is simply adding the line urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in the urls.py file. But I already have it and it still doesn't work. Here are the relevant part of my files : 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('', include('actualites.urls')), path('inscription/', include('inscription.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) views.py def home(request): return render(request, 'actualites/home.html', {'last_meals': Plat.objects.all()}) models.py class Plat(models.Model): titre = models.CharField(max_length = 100) date = models.DateField(default=timezone.now, verbose_name="Date de préparation") photo = models.ImageField(upload_to = "photos_plat/", blank = True) class Meta: verbose_name = "Plat" ordering = ['date'] def __str__(self): return self.titre You can see that the pictures are recorded in the photos_plat directory, which is a subdirectory of the media directory. the template : {% extends "base.html" %} {% block content %} <h2>Bienvenue !</h2> <p> Voici la liste des …