Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Retrieve url origin from view - multiple urls to 1 view
I have several urls mapping to one view. Inside the url, I would like to know the url origin? It is to avoid writing multiple views (DRY). urlpatterns = [ path('path1/', views.IndexView.as_view(), name='index'), path('path2/', views.IndexView.as_view(), name='index') ] class IndexView(generic.ListView): url_origin = ... #would like path1 or path2 I looked for 'reverse' but it does not seem to be a solution to my problem. It returns an error. reverse('index') Thank you in advance -
After refresh the browser the curent user be the admin
I have a djanog project, my problem is in the first time the current user is the logged one but if I refresh the browser, in the request.user if found the admin user, how can the overcame this issue ? -
How to fix "Forbidden (CSRF cookie not set.)"
When I send some data from my front-end via axios, my API give error Forbidden (CSRF cookie not set.) I use csrf_exempt to avoid this error, however it doesn't help me views.py: @csrf_exempt def registration(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) if not is_user_data_valid_for_create(data): return HttpResponseBadRequest() user_role = Role.objects.get(pk=1) user = User.create( first_name=data['first_name'], last_name=data['last_name'], email=data['email'], password=data['password'], role=user_role ) return HttpResponse("Success,{} your account created!".format(user.first_name), status=201) return HttpResponseBadRequest() This is my code on React: constructor(props) { super(props); this.state = { first_name: '', last_name: '', email: '', password: '' } } changeHandler = event => { this.setState({[event.target.name]: event.target.value}) }; submitHandler = event => { event.preventDefault() console.log(this.state); axios .post('http://127.0.0.1:8000/api/v1/user/restration/', this.state) .then(response => { console.log(response) console.log(response.data) }) .catch(error => { console.log(error) }) }; <form onSubmit={this.submitHandler}> <div className="user-data"> <div className="form-group"> <label>First Name</label> <input type="text" placeholder="John" name="first_name" value={first_name} onChange={this.changeHandler} className="form-control"/> </div> ... <div className="sign-up-w"> <button type="submit" className="btn-primary sing-up">SIGN UP</button> </div> </form> When I send data from UI I have the error: Forbidden (CSRF cookie not set.): /api/v1/user/restration/ "POST /api/v1/user/restration/ HTTP/1.1" 403 2868 However, when I send data via Postman everything is okay. -
Display one Form for related models and saving it - Django
I have two related models (Sim and Payment). After searching the requisite Sim, i want to change the status of Sim (model) and using the same form where blank fields of Payment would also be displayed, i want to save data (Payment model). I want that user should be able to see and update the details of Sim including phone number, IMSI and status and from the same form he should be able to save data of payment. class Sim(models.Model): phone_number = models.CharField(max_length=20, blank=True, unique=True, verbose_name ='Phone Number') imsi = models.CharField(max_length=19, blank=True, unique=True, verbose_name ='IMSI') sim_status = models.IntegerField(blank=False, default='1', verbose_name ='Sim Status') def __str__(self): return self.phone_number class Payment(models.Model): deposit_date = models.DateField(blank=True, verbose_name='Deposit Date') sim = models.ForeignKey(Sim, on_delete=models.DO_NOTHING, null=False, blank=False) I am using django crispy-forms class UpdatePayment(forms.ModelForm): phone_number = forms.CharField( label='Phone Number', widget=forms.TextInput(attrs={'readonly': 'readonly'})) imsi = forms.CharField(label='IMSI', widget=forms.TextInput(attrs={'readonly': 'readonly'})) poc = forms.CharField(label='Point of Contact', widget=forms.TextInput(attrs={'readonly': 'readonly'})) sim_status = forms.CharField (label='Sim Status',help_text='Please select type', widget=forms.Select(choices=SIM_STATUS) ) class Meta: model = Sim fields = ('phone_number', 'imsi', 'poc','sim_status',) def __init__(self, *args, **kwargs): super(UpdatePayment, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Div( Div('phone_number', css_class="col-md-6"), Div('imsi', css_class="col-md-6"), css_class='row' ), Div( Div('poc', css_class="col-md-6"), Div('sim_status', css_class="col-md-6"), css_class='row' ), ) I am unable to find out how would … -
URL Displaying Wrong Form and View in Django
I am attempting to render a form where the only field is a dropdown. I have the form, view, .html, url all set up. But when I access this url, it shows a different form and view and I suppose also a different .html. I am so confused on why this is happening as it had been working fine for quite some time so I obviously changed something. forms.py #this is the form for the dropdown class ManifestDropDown(forms.Form): References = forms.ModelChoiceField(queryset=Orders.objects.values_list('reference', flat=True).distinct(), empty_label=None) manifest_references.html <!--html for dropdown--> {% extends 'base.html' %} {% block body %} <div class="container"> <form method="POST" action="manifest"> {% csrf_token %} {{ reference_list }} <button type="submit" class="btn btn-primary" name="button">Submit</button> </form> </div> {% endblock %} views.py #view for dropdown def manifest_references(request): if request.method == 'POST': if form.is_valid(): reference_id = form.cleaned_data.get('References') form.save() query_results = Orders.objects.all() reference_list = ManifestDropDown() context = { 'query_results': query_results, 'reference_list': reference_list, } return render(request, 'manifest_references.html', context) urls.py url(r'^manifest_references', manifest_references, name='manifest_references'), base.html <!--showing the link to this url--> ... <a class="dropdown-item" href="{% url 'manifest_references' %}">Edit Manifests</a> When I access the url above - instead of showing the manifest_references view with the dropdown, it immediately jumps to a different view manifest which is referenced as the action in … -
__init__() got multiple values for argument 'crescator'
I have a ModelForm and in a ModelChoiceField I need to filter objects by request.user. When data is submitted, I got the error "init() got multiple values for argument 'crescator' ". How can I repair that? #My Form class AdaugaPereche(forms.ModelForm): boxa = forms.IntegerField(label="Boxa", min_value=1) sezon = forms.CharField(label="Sezon reproducere", initial=datetime.now().year) mascul = forms.ModelChoiceField(queryset=None, label="Mascul", empty_label="Alege mascul") femela = forms.ModelChoiceField(queryset=None, label="Femela", empty_label="Alege femela") serie_pui_1 = forms.TextInput() serie_pui_2 = forms.TextInput() culoare_pui_1 = forms.ModelChoiceField(queryset=None, label="Culoare pui 1", empty_label="Alege culoarea", required=False) culoare_pui_2 = forms.ModelChoiceField(queryset=None, label="Culoare pui 2", empty_label="Alege culoarea", required=False) data_imperechere = forms.DateInput() primul_ou = forms.DateInput() data_ecloziune = forms.DateInput() data_inelare = forms.DateInput() comentarii = forms.TextInput() # Functie pentru filtrarea rezultatelor dupa crescator def __init__(self, crescator, *args, **kwargs): super(AdaugaPereche, self).__init__(*args, **kwargs) self.fields['mascul'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Mascul", perechi_masculi__isnull=True) self.fields['femela'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Femelă", perechi_femele__isnull=True) self.fields['culoare_pui_1'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) self.fields['culoare_pui_2'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) class Meta: model = Perechi fields = "__all__" #My view def perechenoua(request): if request.method == "POST": form = AdaugaPereche(request.POST, crescator=request.user) if form.is_valid(): obj = form.save(commit=False) obj.crescator = request.user obj.save() return HttpResponseRedirect("/perechi/") else: form = AdaugaPereche(crescator=request.user) context = { 'form': form } template = loader.get_template("adauga-pereche.html") return HttpResponse(template.render(context, request)) May the problem be obj = form.save(commit=False) obj.crescator = request.user obj.save() ? -
how can I upload & play audio files in Django
I have a project where I can upload & view pdf files but i want to upload & play audio files instead . What changes do I need to make ? Please Help This is my models.py What changes do I need to make for audio files ? from django.db import models class PDF(models.Model): title = models.CharField(max_length=100) pdf = models.FileField(upload_to='books/pdfs/') def __str__(self): return self.title This is my views.py of the app . What changes do I need to make for uploading and playing audio files? from django.shortcuts import render, redirect, HttpResponseRedirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from .forms import * from .models import * def upload(request): context = {} if request.method == 'POST': #when request method is POST , the files are being uploaded uploaded_file = request.FILES['document'] fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'upload.html', context) #this function shows the "list of pdfs" in the database on pdf_list.html def pdf_list(request): pdfs = PDF.objects.all() return render(request, 'pdf_list.html', { 'pdf': pdfs }) #this function ensures that the file being uploaded is PDF def upload_pdf(request): if request.method == 'POST': form = PDFForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('pdf_list') else: … -
How to fix TemplateSyntaxError?
I'm trying to render template, but it always get an TemplateSyntaxError error. For solve this I tried to change construction. Instead {% if value %} -some action {% else %} {% endif %} I tried: {% if value_1 %} - some action {% endif %} {% if value_2 %} - some action {% endif %} But it didn't bring success, always the same error. I thought, that I made mistake with '{' or '%', but I didn't found anything, that couldn't be properly. Then I tried to find solve my problem, but all the problems that were considered had problems with the wrong syntax, like '%{' or '{ %'. --- VIEW --- class HumanList(TemplateView): def post(self, request): search_type = request.POST.get('type', False) search_object = request.POST.get('object', False) def separate(search_type, search_object): try: if search_type == 'name': return Human.objects.all().get(name__exact=search_object) if search_type == 'surname': return Human.objects.all().filter(name__contains=search_object) if search_type == 'company': return Human.objects.filter(company=search_object) if search_type == 'position': return Human.objects.filter(position=search_object) if search_type == 'language': return Human.objects.filter(language=search_object) except ObjectDoesNotExist: return None search_result = separate(search_type, search_object) if search_result: context = { 'result': search_result, 'searched': search_object, } else: context = { 'empty': 'We couldn\'t find anything', 'searched': search_object, } return render(request, 'result.html', context) --- HTML TEMPLATE --- {% extends 'human_list.html' … -
django passenger_wsgi issue something went wrong
hosting done successfully but error:we are sorry something went wrong looks like there is error in passenger_wsgi.py file, working on Django framework website should be live -
Disable Delete and Edit on condition
I want my Django program to check if my my entry is authorized and if it's either Manual or Auto. If it is authorized, then I want to prevent it from being deleted so basically disable the delete option for it and if it is Automatic, I want to prevent it from being edited when I click on the model object in the Django admin. Here is an example of my model: class ModelName(models.Model): AUTO_ATT = "AU" MANUAL_ATT = "MA" ENTRY_TYPES = ( (AUTO_ATT, "Auto-Attendance"), (MANUAL_ATT, "Manual-Attendance"), ) AUTHORIZED = "AU" UNAUTHORIZED = "UA" ENTRY_STATUSES = ( (AUTHORIZED, "Athorized"), (UNAUTHORIZED, "Un-Authorized"), ) status = models.CharField(max_length=2, choices=ENTRY_STATUSES, default=WORK_ENTRY_STATUSES[1][0]) type = models.CharField(max_length=2,choices=ENTRY_TYPES) So everytime I click on the object in the Django Admin, I want the program to first see if the entry is authorized and if its auto and display me the functions accordingly. -
How to return a message and redirect users in Django middleware
In my Django application, I pull a user's IP address and set a local city. However, if a user is out of the geographical area that the app covers, I want to raise an error and redirect them to the geographical area that this app covers. I'm trying to do this with middleware, but not sure how to do this. class RestrictUserMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ipaddress = x_forwarded_for.split(',')[-1].strip() else: ipaddress = request.META.get('REMOTE_ADDR') ip = get_client_ip(request) reader = geoip2.database.Reader(path) try: location = reader.city(ip) except: location = True if not response.subdivisions.most_specific.iso_code in 'CA': # raise error message here that it's not available outside CA request.session['city'] = 'Beverly Hills' return HttpResponseRedirect(reverse('index')) response = self.get_response(request) return response -
I'm not understanding this part of the code, need some suggestions to understand it
This part is for street - ##Street street = entry['street'] if entry['street']!=None else '' if street!=''and [{'exportHint':'street','subcategory':'street','value':street}] not in street: street_names.append([{'exportHint':'street','subcategory':'Street','value':street}]) for st in street_names: category.append([st]) This part is for displaying its value in template - <div class="{%if not responses%}span-19 {%endif%} last componentName" style="{%if responses%}width:{{responseDim.totalWidth|add:750}}px;{%endif%}padding-top:5px;"> <b>{{category.label}}</b> {% for entry in category.entries %} {% for group in entry %} {% for kv in group %} But, I'm not understanding how this works. Confused... -
How to filter if a store(point) lies inside a specific rectangle?
I am making an API with django rest framework. The app need to take of 4 corner coordinates and i need to filter all my stores out whether if it is in this rectangle or not. As a result i will filter out stores which is in this rectangle and serve it. How to make it with Django how to filter? thank you in advance. -
Django Wagtail Deployment Static File Server
After deployment today, for some reason, the project no longer shows style from items that would have been collected during the collectstatic process. I have full access to the files from any browser. I have checked all permissions. I have browsed to the site from the development server, and other machines to eliminate software\font possibilities. No idea what's going on here. I serve the files from a different server. Other django projects are unaffected. No other django projects use anything like wagtail though. Pulling my hair out at this point and probably just missing something simple. What am I missing? base.py config STATIC_ROOT = '/var/www/html/static.xxxxxx.net' STATIC_URL = 'http://static.xxxxxx.net/' MEDIA_ROOT = '/var/www/html/media.xxxxxx.net' MEDIA_URL = 'http://media.xxxxxx.net/' Checking for file existence on server: -rw-rw-r-- 1 xxxxxx xxxxxx 13648 Aug 24 09:18 /var/www/html/static.xxxxxx.net/wagtailadmin/css/userbar.3d5222a7eba2.css Checking CSS relative references -rw-rw-r-- 1 xxxxxx xxxxxx 68812 Aug 24 09:18 /var/www/html/static.xxxxxx.net/wagtailadmin/css/../../wagtailadmin/fonts/opensans-regular.45f80416d702.woff2 -
How to serve an image in django without using <img> tag in django?
Recently I started learning Django and at the first actually I want to prepare an API in order to serve images. for this purpose, when anybody requests to access to an image, my program should read raw image data from local library and serve it and prepare an access to this image for anybody who requests that image. notice that i don't want to show image with tag in my html file. just prepare an access to raw data in order to manipulation that image or anything similar. -
How to sanitise image field content to make sure it doesn't contain html form in django?
I have included imagefield in my django app and in the documentation I read that the validation done by the ImageField is not sufficient. I wanted to validate the image content to make user doesn't submit any html form. Is there any way to make sure that the image content is valid that it is not any sort of html under image extension. -
Execute function and print result in template without refresh
I'm using django to develop my website. In this page I have x as input, when i press enter a function will be executed and then the page will refresh and the result will be displayed. I would like to make it dynamic: capture input, execute function and show the result then another tag appears etc.. I will be very thankful. This is my python code: def console (request): import paramiko import time import getpass import re ip = '192.168.43.10' username = 'osboxes' password = 'osboxes.org' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=username, password=password, look_for_keys=False, allow_agent=False) print('Successfully connected to %s' % ip) remote_conn = ssh.invoke_shell() time.sleep(.005) output = remote_conn.recv(65535) print (output) def escape_ansi(line): ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]') return ansi_escape.sub('', str(line)) x=request.GET['x'] time.sleep(1) remote_conn.send(x+'\n') time.sleep(0.1) if remote_conn.recv_ready(): output = remote_conn.recv(5000) op=output.decode() oo=escape_ansi(op) return render(request,'shell.html', {'oo' : oo}) This is my html file: {% extends 'base.html' %} {% block content %} <div class="mb-3 card text-white card-body" style="background-color: rgb(51, 51, 51); border-color: rgb(51, 51, 51);"> <h5 class="text-white card-title">Console log to the gateway</h5> <form action="console"> <div class="position-relative form-group" > <input rows="15" style="color: #FFFFFF; background-color: rgb(51, 51, 51)" name="x" id="x" class="form-control"> </div> </form> </div> <h3>result : {{oo}}</h3> {% endblock %} -
Set session in DRF not called in other request
I try create session in Django Rest API request but session not stored and fail get session in other page. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] 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', ] api.py class PersonApiView(viewsets.ViewSet): permission_classes = (AllowAny,) parser_class = (FormParser, FileUploadParser, MultiPartParser,) # Sub-action send email persons @action(methods=['post'], detail=False, permission_classes=[AllowAny], url_path='send-validation', url_name='send_validation') @transaction.atomic def send_validation(self, request): request.session['user_id'] = 123 # set session request.session.create() return Response('OK!', status=status.HTTP_200_OK) home.py class HomeView(View): template_name = 'web/home.html' context = {} def get(self, request): user_id = request.session.get('user_id', None) print(user_id) # Always None return render(request, self.template_name, self.context) The session always return None Where i missed? -
Python or java script Dynamic maps
please I need help building a map for a ride sharing app ,I will like to build an app that updates the positions of customer on the drivers screen and also shows potential drivers on the passengers screen; So this are what I need 1. A map api that can load maps canvasses dynamically 2. A guide on how to do 1 3. I would like to use python or js -
“Context must be a dict rather than type.” Cannot be resolved
I want to use the obtained URL parameter for filter, but the error cannot be solved. I understand that "context ['group'] = belong.objects.get (user = user) .group" is the cause, but I don't know what to do. "username" has been acquired. #error context must be a dict rather than type. #view def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.kwargs.get('username') print(user) try: context['group'] = belong.objects.get(user=user).group except belong.DoesNotExist: pass except: return HttpResponseBadRequest try: context['count'] = URC.objects.filter(user=user).count() except URC.DoesNotExist: pass except: return HttpResponseBadRequest context['username'] = user return context -
Django forms custom backend validation
I'm trying to run backend validations (which takes ~3-4 seconds) on 1 of the fields (query field) only on POST request (i.e. only after the "Submit" button is clicked). When form is loaded on a GET request - i don't want to make run this validation because it takes lot of time. I tried to look on the django form validation documentation But i couldn't understand a way to run the clean method only on a POST request. Anytime i'm creating a SomeForm instance, the clean method is taking place. forms.py: class SomeForm(forms.Form): is_active = forms.ChoiceField(label='Is Active?', required=False, choices=IS_ACTIVE_DROPDOWN) query = forms.CharField(label='Query',help_text='This is help text', widget=forms.Textarea) last_successful_run = forms.DateTimeField(label='Last Run') def clean(self): ... Execute "regular" cleaning ... return self.cleaned_data views.py def mng_tables_form(request, resource, action, item_id): form = SomeForm() if request.method == 'POST': form = form(data=request.POST) if form.is_valid(): ## UPDATE DB api_driver.run_api_request(item_id, request.fields) return redirect('mng_tables_form_page', resource, 'show_item', item_id) else: form = _get_resource_objects(resource, RESOURCES_MODELS_MAPPING).get(action) ## Get Data from DB item_object = api_driver.run_api_request(resource=resource, item_id=item_id, params={'fields':form}).json().get('response') form = form(item_object) context = {'form': form, 'item_object': item_object, 'item_id': item_id} return render(request, 'mng_tables/form.html', context=context) What i want to do is to somehow recognize the request method when i create the form instance, and run more validation only … -
How to pass raw <html> to xxx.html using dictionary values in python django
After collecting some data in html format I need to display it on base.html using views.py render function. But it shows the raw code instead of showing the proper view (select dropdown). I'm using django python on windows pc models.py class query(models.Model): connection = mysql.connector.connect(host="localhost",database="ameya",user="root",password="") html = '<table class="table table-bordered datatable responsive" id="table-2"><thead><tr><th>Schedule NO.</th><th>Farmer Name</th><th>University</th><th>District</th><th>Taluk</th><th>Panchayet</th><th>Village</th><th>Crop</th></tr></thead><tbody id="tab_tbody">' def __str__(self): htm = '<form action="getFarmer" method="post"><select class="form-control" name="season"><option value="0">-- Select Year --</option><option value="333">All Data</option>' now = datetime.datetime.now() cdt = now.year for i in range( 2017,int(cdt) ): htm += '<option value="'+str(i)+'">'+str(i)+' - '+str(int(i)+1)+'</option>' htm += '</select><input type="submit" value="Search >"></form>' return htm views.py def index(request): t = query() return render(request,"mainapp/base.html",{'html':t}) base.html <html> <head><title>AmeyaKrishi Version 2</title></head> <body> <h2>AmeyaKrishi V2 (testing mode): All University Filter</h2><hr> <p>{{ html }}</p> </body> </html> OUTPUT local server output -
Django / django-templates - how to check if a looped variable exists in the reverse of an object?
I'm working on a webapp that contains the following: A SchoolGroup model, that (among other things) contains various students. A GroupMaterial model that contains educational material that the group can access. This is linked to the SchoolGroup model with an ManyToMany relationship. There are (for now) 3 GroupMaterial objects, (Group 1, Group 2, Group 3) The models are defined as follows: class GroupMaterial(models.Model): name = models.CharField( max_length=255, choices=GROUPMATERIALS.items(), primary_key=True ) order = models.IntegerField(null=True) class SchoolGroup(models.Model): name = models.CharField( max_length=255 ) ( ... ) groupmaterials = models.ManyToManyField('schoolapp.GroupMaterial') I want to create a template that contains a table for SchoolGroup objects (with the columns [name, group1, group2, group3]) where each row show not only the name but also a checkmark if the GroupMaterial object appears in .groupmaterials attribute of the current SchoolGroup. To do so I created the following view and template: class SchoolGroupListView(GroupSettingsMixin, generic.ListView): model = models.SchoolGroup template_name = "templates/settings/group_list.html" def get_context_data(self, *args, **kwargs): data = super(SchoolGroupListView, self).get_context_data(*args, **kwargs) data['groupsmaterials'] = GroupMaterial.objects.all() return data <table> <th>Name</th> {% for material in groupmaterials %} <th>{{ material.name }}</th> {% endfor %} {% for schoolgroup in object_list %} <td>schoolgroup.name</td> {% for material in groupmaterials %} <td> {% if material in schoolgroup.groupmaterials.all %} <div>Div containing 'there … -
How can I upload an InMemoryUploadedFile to Amazon s3
I am trying to uplaod an image onto Amazon s3. The image is in the object "request.FILES['image']" as can be seen in the code below. My problem is that the boto3 "upload_file()" function expects a path to the image and I on the other hand have an in memory image objects and because of that i get this error.raise ValueError('Filename must be a string') ValueError: Filename must be a string My code here. @csrf_protect def file_upload_view(request): if request.method == 'POST': img_list = request.FILES['image'] s3 = boto3.client('s3') s3.upload_file(img_list, settings.AWS_STORAGE_BUCKET_NAME, img_list.name) else: print('not post...') return HttpResponse([{}], content_type='application/json') Any ideas would be appreciated. -
Can't show image uploaded with ImageField in template
So, I have a blog application, when I want to add cover image to article with ImageField file browser my image name is getting red in PyCharm and not showing in template. But when I inspect its HTML codes source, path to image is true. Here are my codes: articles.html: <a href="/"><img src="{{ article.image.url }}" class="image"/></a> settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py: class Article(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=200) content = HTMLField() # image = models.CharField(max_length=2000) image = models.ImageField(upload_to='media') category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) post_date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True, null=True, editable=False) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = latin_slugify(self.title) super(Article, self).save(*args, **kwargs) urls.py: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)