Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python/Html code to extract entire row based on the primary key onclick
I am beginner into python scripting, however I request help to give me a solution or code inorder to extract entire row on a new page based upon onClick my dictionary text. Here is my code from app: from 'display' app, def hyper(request): context2 = {'post2': ddetails.objects.all()} return render(request, 'display.html', context2) class postListView2(ListView): model = ddetails template_name = 'display.html' context_object_name = 'context2' ordering = ['date_published'] ******display.html**** {% extends 'base.html' %} {% block content %} <div> <form method="post"> {% csrf_token %} <table> {% for post2 in post2 %} <tr> <td>{{ post2.id }}</td> <td>{{ post2.username }}</td> <td>{{ post2.email_id }} </td> <td>{{ post2.job }}</td> </tr> {% endfor %} </table> </form> {% endblock content %} however the above display.html is rendering based on the anchor tag of another html file (home.html) <table> <tr> <th>ID number</th> <th>User Name</th> </tr> {% for post1 in post1 %} <tr> <td><a href="display" target="_blank"><center>{{ post1.id }}</center></a></td> <td><center>{{ post1.username }}</center></td> </tr> {% endfor %} </table> after running the command my page displays as ID Number Username 1 xxxxxx 2 yyyyyy 3 uusdfiasifd I made primary key(ID Number) as anchor and by clicking on 1, it should render display.html in new window with relevant details. -
ReactJS POST error to Django Rest Framework server using axios
I use Django Rest framework session authentication,after user logged in I can do successful POST request (/api/post/1/like/) using browsable API. Why can't I post using axios ? (user instance is must for Django server to save the above API ) I hope POST signal may not know logged in user even though I am loggedin as admin user AXIOS FUNCTION const likebutton = (id)=>{ axios.post(`/api/post/${id}/like/`) } ERROR Error: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61) -
MultiValueDictKeyError at /aarm/signup/ 'email'
if request.method == 'POST': try: is_private = request.POST['is_private'] except MultiValueDictKeyError: is_private = False email = request.POST['email'] print(email,99) first_name = request.data['first_name'] last_name = request.data['last_name'] phonenumber = request.data['phonenumber'] avatar = request.data['avatar'] if email is None: return Response({'error': ' please enter your email '}, status=status.HTTP_400_BAD_REQUEST) if first_name is None: return Response({'error': ' please enter your first name '}, status=status.HTTP_400_BAD_REQUEST) if last_name is None: return Response({'error': ' please enter your last name '}, status=status.HTTP_400_BAD_REQUEST) if phonenumber is None: return Response({'error': ' please enter your phone name '}, status=status.HTTP_400_BAD_REQUEST) if avatar is None: return Response({'error': ' please enter your avatar name '}, status=status.HTTP_400_BAD_REQUEST) user = User.objects.create_user(phonenumber, email, first_name, last_name, avatar) token1 = Token.objects.create(user=user) token = token1.key return Response({'message': 'user register success', 'token': token}, status=status.HTTP_201_CREATED) when email was not sent in post request it gives MultiValueDictKeyError same error gives with other field, I want to give my own error message -
How to write QuerySet for Count as to be Zero
class InventoryData(models.Model): CHOICES = [('In Stock', 'In Stock'), ('Issued', 'Issued'), ('Not Issued', 'Not Issued'), ('Unmanaged', 'Unmanaged'), ('Damaged', 'Damaged'),('Theft', 'Theft'), ('Auctioned', 'Auctioned'), ('Disposed', 'Disposed')] AssetID = models.CharField('Asset ID', max_length=30, unique=True) Make = models.CharField(max_length=30, blank=True, null=True) Model = models.CharField(max_length=30, blank=True, null=True) Status = models.CharField(max_length=30, choices=CHOICES, blank=True, null=True, default='In Stock') Comments = models.TextField(max_length=2000, blank=True, null=True, default="None") class Meta: verbose_name = 'Inventory Data' verbose_name_plural = 'Inventory Data' def __str__(self): return self.AssetID views.py def home(request): #------------- For Models -------------# stnd = obj.objects.filter(AssetID__startswith='ASPL-LAPT').order_by('Model').values_list('Model', flat=True).distinct() dev = obj.objects.filter(AssetID__startswith='ASPLB-DEV').order_by('Model').values_list('Model', flat=True).distinct() mac = obj.objects.filter(Make__startswith='Apple').order_by('Model').values_list('Model', flat=True).distinct() desk = obj.objects.filter(AssetID__startswith='ASPLB-DSK').order_by('Model').values_list('Model', flat=True).distinct() #------------- For count -------------# cnt = obj.objects.filter(Model__in=stnd).values('Model').annotate(Count('id')) cnt1 = obj.objects.filter(Model__in=stnd, Status='In Stock').values('Model').annotate(Total=Count('id')) cnt2 = obj.objects.filter(Model__in=stnd, Status='Issued').values('Model').annotate(Total=Count('id')) cnt3 = obj.objects.filter(Model__in=stnd, Status='Theft').values('Model').annotate(Total=Count('id')) cnt4 = obj.objects.filter(Model__in=stnd, Status='Damaged').values('Model').annotate(Total=Count('id')) cnt5 = obj.objects.filter(Model__in=stnd, Status='Auctioned').values('Model').annotate(Total=Count('id')) cnt6 = obj.objects.filter(Model__in=stnd, Status='Disposed').values('Model').annotate(Total=Count('id')) render_out = zip_longest(stnd, cnt1, cnt2 , cnt3, cnt4, cnt5, cnt6, cnt7, fillvalue=0 context = {'render_out': render_out,} return render(request, 'App/home.html', context) ` In my DB i have 4 models laptops [E5470, E5480, T440, T450], each model has 10 laptops but with below query i am getting below table,for below query i getting as below queryset. a = Obj.objects.filter(Model__in=stnd, Status='In Stock').values('Model').annotate(Total=Count('id')) if i don't have any laptops in "In Stock" i have get respective model with "Total: 0" can any … -
Why my html button is not able to execute the method called update_student stored in my views.py file
---------Here is the html code of the Button by clicking which i want to execte the method-------- Update -
Why does Django App return an empty page?
I am learning how to program using the book Python Crush Course 2nd ed. Currently, I am doing a project that involves building a simple web app using Django. The app allows users to make journal entries about specific topics. I am currently stuck at trying to allow users to add a new topic. Basically, I am adding a form-based page using Django form-bulding tools. My problem: when I go to http://localhost:8000/new_topic/ , it returns an empty white page. But it should return a page that allows users to enter a new topic. What I tried: I reviewed every line of code multiple times, but I cannot find a mistake. I am a newbie, so maybe I have missed something that more experienced eyes would see. Appreciate any and all help. Below is my code so far: models.py from django.db import models class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text forms.py from django import forms from .models import Topic class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text': ''} urls.py from django.urls import path from . import views … -
"non_field_errors": [ "No data provided" ]
I am trying to get data from the serializer ,but i have a problem that says "non_field_errors": [ "No data provided" ] Here is the part that i am trying to get the data Serializers class ArticleCreateSerializer(serializers.ModelSerializer): author = serializers.SerializerMethodField('_user') def _user(self, obj): request = getattr(self.context, 'request', None) if request: return request.user.profile else: return HttpResponse("User Not Found") caption = serializers.CharField(required=False) details = serializers.CharField(required=False) class Meta: model = Post fields = ('id','author','caption','details') def create(self, validated_data): article = Post.objects.create(author=author,**validated_data) return article Does anybody have any solution to this? -
Encountring an error while doing django development in pycharm i.e operational error/admin
IAM usin pycharm version 3.8.2 for doing web development. While iam running django 2.1 in pycharm it worked everything fine. At /admin while I was trying to add products it is showing OPERATIONAL ERROR/ADMIN/PRODUCTS/ADD. I tried to install django version 2.1.7 it is showing same error again.I tried again with version 3.0.2 it is showing again the same above error. I even tried python manage.py makemigrations command to see if it works nothing change the same error keeps coming in yellow page I want to know what's the problem that iam facing -
django relation "accounts_user" does not exist after heroku upload
I upload my Django web app to Heroku successfully and login page appears as well as expected but when I try login I getting this error: relation "accounts_user" does not exist LINE 1: ...ser"."is_active", "accounts_user"."is_staff" FROM "accounts_... Also I am getting this error when I try to acces ulrs by typing cursor "_django_curs_140062995079296_sync_1" does not exist I don't know where this error Is generating from. But I am using custom user models that I seems the error to be there here is the custom user model I used class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique=True) name = models.CharField(max_length=200, null=True) staffType = models.ForeignKey(staffType, null=True, on_delete= models.SET_NULL) date_joined = models.DateTimeField( auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField( default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
How can i redirect when person type in url browser?
I have two methods ,(register and confirm methods),when submit register,send message in mobile for verification,then person type and the code is correct return return JsonResponse({'code':1,'url': '/user/confirm'}) in jquery code with window.location() ,it will redirect into confirm page, but i want to when person type this url and Enter ,he can not open this page(confirm page) and redirect into other page. -
how do I import my python script into Django views?
The script is a simple guessing game. The end goal is to keep a log of the results. I have tried importing the script 'from guessItApp import gg.Py' in my views but does not work. I was told I can use the tag and that will put my script in the views but will this still record the users input? I am getting all sort of errors. I want to accomplish this without any frameworks just Vanilla JS. What is the best way to do this and how? like step by step. -
Pass multiple parameters in Django
class Article(models.Model): Title = models.CharField(max_length = 255) writing = models.TextField() category = models.CharField(max_length = 225) published = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(blank=True, editable=False) def save(self): self.slug = slugify(self.Title) super().save() def get_absolute_url(self): url_slug = {'slug':self.slug} return reverse('artikel:ArticleDetail', kwargs = url_slug) def __str__(self): return "{}.{}".format(self.id, self.Title) i want to build a simple website using django where it could post some articles by form. The problem is how could i post multiple category in one article ? this is form.py below. from .models import Article from django.forms import ModelForm class ArticleForm(ModelForm): class Meta: model = Article fields = [ 'title', 'writing', 'category', ] -
request.user returning abstract user
I am trying to type the following: user: Final[CustomUser] = self.request.user Where CustomUser is my custom user model defined in settings.py. My IDE complains that Expected type 'CustomUser', got 'AbstractBaseUser' instead. Looking at the documentation, it says that self.request.user returns an instance of AUTH_USER_MODEL however clearly this is not happening. -
Django: return same data as PostListView in def post()
Is there a simple way for me to return the same data in post method using PostListView? class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def post(self, request, *args, **kwargs): *create like in db* *flash message* return *same data as get request* I have a simple Instagram replica app and this post list view shows all posts. Each posts has a like button. If a user clicks on this button it will create a new like object in db and will show a flash message. After that I want to show the same data as there were before clicking the button. Is there a way to do so? -
Django 3.x Python 3.x Forms - 'NoneType' object has no attribute '_prefetch_related_lookups'
I have this form below that cause the error. class ErkbRamsis(forms.Form): def __init__(self, *args, **kwargs): self.transfer_id = kwargs.pop('transfer_id') transfer = Transfer.objects.get(pk = self.transfer_id) if 'coach_id' in kwargs: self.coach_id = kwargs.pop('coach_id') leg = Leg.objects.get(pk = self.coach_id) else: leg = Leg.objects.filter(service = transfer.service).first() super(ErkbRamsis, self).__init__(*args, **kwargs) self.fields['transfer_clients'] = forms.ModelMultipleChoiceField( queryset=Client.objects.filter(related_pnr = transfer.service.related_pnr), widget=forms.SelectMultiple(), required=False, ) self.fields['coach'] = forms.ModelChoiceField( queryset=Leg.objects.filter(service = transfer.service), widget=forms.Select(), empty_label=None, initial=leg, #### for non assigned legs cause error required=False, ) self.fields['coach_clients'] = forms.ModelMultipleChoiceField( queryset = leg.clients, #### for non assigned legs cause error widget=forms.SelectMultiple(), required=False, ) def clean(self, *args, **kwargs): transfer_clients = self.cleaned_data.get('transfer_clients') coach = self.cleaned_data.get('coach') coach_clients = self.cleaned_data.get('coach_clients') return super(ErkbRamsis, self).clean(*args, **kwargs) Scenario: I have 4 models Transfer<= OneToOne => Service <= OneToMany => Leg<= ManyToMany => Client, The form attach the Client objects to the Leg by clients.add(Client). the form cause error when rendering when the Transfer.Service have no Leg objects created and attached to Service. The lines cause the error is marked by comment. -
Javascript is not executing when javascript
I have created a simple javascript function to run in django that automatically changes text within a svg file. The function works fine if I run it inside the webpage console. But nothing inside the script tags will run and I can't figure out why. Looking at the source the template tag is importing the data correctly and the javascript file is found. But nothing runs inside, not even code unrelated to the function - you can see the console.log code I have added. I am quite new to django and website development, so it is unclear to me where I shoud be looking for why this isnt' executing - is there somewhere that errors should be arising? home.html {% extends 'kb/base.html' %} {% load static %} {% block extrahead %} <link rel="stylesheet" href="{% static 'css/kb.css' %}"> <script type="text/javascript" src="{% static "js/fillKinshipDiagram.js" %}"> console.log(4 + 10); var terms = {{ terms|safe }}; window.onload = function() { main(terms); }; </script> {% endblock %} {% block content %} <div class="home-content"> <div class="kinshipdiagram-container"> <object type="image/svg+xml" data="{% static "img/diagrams/nuclear_diagram.svg" %}" id="kinshipdiagram" width="50%" height="50%"></object> </div> </div> {% endblock %} fillKinshipDiagram.js function main(terms){ var svgDocument svgObject = document.getElementById('kinshipdiagram'); svgDocument = svgObject.contentDocument; for (var i = 0; … -
How to create, update and delete forms in the same template?
I intend to update, create and delete on the same template, as shown below. I currently have the following on my models class Customer(models.Model): TITLE = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Miss', 'Miss'), ('Ms', 'Ms'), ('Dr', 'Dr'), ('Sir', 'Sir'), ('Madam', 'Madam'), ) STATUS = ( ('Active', 'Active'), ('On hold', 'On hold'), ) GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) ROLE = ( ('Customer', 'Customer'), ('Admin', 'Admin'), ) title = models.CharField(max_length=200, null=True, choices=TITLE) first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) country = CountryField() birth_year = models.CharField(max_length=4, null=True) gender = models.CharField(max_length=200, null=True, choices=GENDER) email = models.CharField(max_length=200, null=True) password = models.CharField(max_length=200, null=True) status = models.CharField(max_length=200, null=True,choices=STATUS) date_created = models.DateTimeField(auto_now=True, null=True) profile_pic = models.ImageField(null=True, blank=True, default='images/default.png') role = models.CharField(max_length=200, null=True, choices=ROLE) and my forms is as follows class CustomerProfileForm(forms.ModelForm): class Meta: model = Customer fields = [ 'title','first_name','middle_name','last_name','phone','country','birth_year','gender'] Currently I have my views showing to update each customer, as shown below. @login_required(login_url='login') def CustomerProfile(request, pk): customer = Customer.objects.get(id=pk) formie = CustomerProfileForm(instance=customer) if request.method == 'POST': formie = CustomerProfileForm(request.POST, instance=customer) if formie.is_valid(): formie.save() return redirect('/') context = {'formie':formie} return render(request, 'accounts/customer_profile.html', context) In another template i have a list of customers, with each having an … -
How to use images on database(django admin) in lightbox or modal
i am trying to use images on my django database as a lightbox image but not getting it even in modal gallery too. it only displays the first image when clicked and blanked when next button is pressed. when the user upload an image to the database, the image is displayed on the webpage as modalpopup or lightbox when clicked, i achieved this by using images on my local drive. here is what i have tried {% extends 'base.html' %} {% load static %} {% block title %} G.F. Cakes {% endblock %} {% block content %} {% include 'nav.html' %} {% for post in post.all %} <link rel="stylesheet" href="{% static 'css/cakes.css' %}"> <div class="main"> <div class="row"> <div class="column"> <div class="content"> <img src="{{post.cake_image.url}}" style="width:100%" onclick="openModal();currentSlide(1)" class="hover-shadow cursor"> <div class="imgcaption"> <h3>{{post.cake_name}}</h3> </div> </div> </div> </div> <div id="myModal" class="modal"> <span class="close cursor" onclick="closeModal()">&times;</span> <div class="modal-content"> <div class="mySlides"> <div class="numbertext">1 / 4</div> <img src="{{post.cake_image.url}}" class="modal-img" style="width:100%"> <!-- <br /><p>{{post.cake_name}}</p> --> </div> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> <div class="caption-container"> <p id="caption"></p> </div> </div> </div> </div> {% endfor %} {% include 'foot.html' %} {% endblock %} javascript code function openModal() { document.getElementById('myModal').style.display = "block"; } function closeModal() { document.getElementById('myModal').style.display = "none"; } var slideIndex … -
Django can't map url to view using include method
I have the following urls.py in my project dir, Main project urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.render_calculator, name='render_calculator'), path('calculator/', views.render_calculator, name='render_calculator'), path('disclaimer/', views.render_disclaimer, name='render_disclaimer'), path('cookiepolicy/', views.render_cookiepolicy, name='render_cookiepolicy'), path('privacypolicy/', views.render_privacypolicy, name='render_privacypolicy'), path('dashboard/', views.render_dashboard, name='render_dashboard'), path('about/', views.render_about, name='render_about'), path('admin/', admin.site.urls), path(r'^', include('accounts.urls')) ] Now I created a new app accounts (I added it to my apps in settings.py) where I would like to store the urls of that app in its own dir like so: Accounts app urls.py from . import views from django.urls import path urlpatterns = [ path('register/', views.render_register, name='render_register'), ] Accounts app views.py: from django.shortcuts import render def render_register(request, template="register.html"): return render(request, template) However, this configuration throws me this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/register Using the URLconf defined in CFD.urls, Django tried these URL patterns, in this order: [name='render_calculator'] calculator/ [name='render_calculator'] disclaimer/ [name='render_disclaimer'] cookiepolicy/ [name='render_cookiepolicy'] privacypolicy/ [name='render_privacypolicy'] dashboard/ [name='render_dashboard'] about/ [name='render_about'] admin/ ^ The current path, register, didn't match any of these. Where is the missing piece? -
What is the easiest way to require the user to fill in default fields of the User model like first name and last name in Django in UserCreationForm?
I am using Django built-in authentication views and form to create a registration/login system, and I'm using the UserCreationForm to register a user but only the username is required. I only want to make other User fields required as well. What is the simplest way to do that without creating a new user model? -
get() takes from 2 to 3 positional arguments but 4 were given
Why am i getting this error? I am supposed to declare the author and article details at the same time but the django does not let me do that . Anybody knows how to solve this code problem? class ArticleCreateView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def create(self, request): serializer_context = { 'request': request } serializer_data = request.data.get('article','author',{}) serializer = self.serializer_class( data=serializer_data, context=serializer_context ) serializer.is_valid(raise_exception=True) serializer.save() response = { 'success' : 'True', 'status code' : status.HTTP_200_OK, 'message': 'User registered successfully!', } status_code = status.HTTP_200_OK return Response(serializer.data, status=status.HTTP_201_CREATED) Here is the problem serializer_data = request.data.get('article','author',{}) TypeError: get() takes from 2 to 3 positional arguments but 4 were given [10/May/2020 18:52:28] "POST /api/createpost/ HTTP/1.1" 500 98933 Other positional arguments are 2 arguments that are called "caption,details". -
How to modify Page model view in wagtail admin?
Background: I would like to enhance a page instance during an admin page view with some admin request related information (some pre-population in general). Basically I would need some function like "get_queryset", but not for list view, just for edit view. In my older question related to a similar problem: Wagtail - how to preopulate fields in admin form? I was provided with instructions to use something called CreatePageView However, I cannot import it. Furthermore, I cannot even found any mention about that in google if I search: Wagtail +CreatePageView The closest thing I found is https://docs.wagtail.io/en/v2.1.1/reference/contrib/modeladmin/create_edit_delete_views.html but the page also states: NOTE: modeladmin only provides ‘create’, ‘edit’ and ‘delete’ functionality for non page type models (i.e. models that do not extend wagtailcore.models.Page). If your model is a ‘page type’ model, customising any of the following will not have any effect I am quite confused. What should I do if I need to customize the admin view for Page model extension? I studied the wagtail source codes for Model.admin and Page and I have not found any way. Any ideas? The related code simplified: wagtail hooks: class ItemAdmin(ModelAdmin): pass # some function override here maybe? models: class ItemPage(Page): pass # … -
Unable to connect to gmail smtp linode django apache2 setup
Hello im having difficulties connecting to google smtp server. The context is that whenever a user fills in a form , my program will automatically email me the feedback to my gmail account. Everything is working except for the fact that the program is stuck within the send_mail function. I have tried doing this : telnet smtp.gmail.com 25 Trying 2404:6800:4003:c03::6c... Which will eventually result in a time out. Here is some of my code: settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'xxxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxxxx' EMAIL_PORT = 465 EMAIL_USE_TLS = False EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = DEFAULT_FROM_EMAIL As per out of the box from wagtail(django cms package) I thought it might have to do with my UFW blocking it , however i have tried disabling the UFW and restarting apache2 . This unfortunately does not help. ufw status Status: active To Action From -- ------ ---- 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere 443/tcp ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) 443/tcp (v6) ALLOW Anywhere (v6) I am really lost! Please help . Thanks -
Django can't find Arabic Slug in real host
I have a Django project. This project have Arabic slugs. When i opened my project in localhost , all URLs and slugs worked. But when i uploaded my project in real host, when i opened Arabic slugs i got 404 error. -
ImageField url attribute
Django 3.0.6 models.py class Image(models.Model): def image_tag(self): return mark_safe('<img src="{}" width="150" height="150" alt={} />'.format(self.image_300_webp_1.url, self.alt)) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' Test: >>> from image.models import Image >>> i = Image.objects.first() >>> i.image_tag() '<img src="/media/home/michael/PycharmProjects/pcask/pcask/media/image/1/1_300_1x.webp" width="150" height="150" alt=asdf />' The problem: Real path is /media/image/1/1_300_1x.webp. Could you tell me why it is: media + absolute path to the image? And how to get the correct path?