Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving image in media folder via django admin issue
I want to store image by a form. And I want to store it in the media/student_img folder. But it not saving in the database neither into the folder. models.py: class Student(models.Model): photo = models.ImageField(upload_to='student_img/', blank=False) settings.py: MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] -
Function to continuously run for auth user once started - Twitter Bot
I have the following function set up in a Django project to 'like' tweets that contain a particular keyword and therefore automated the account somewhat. The code running in the Django project currently is - def like(request): counter = 0 keyword = request.POST['search'] api = get_api(request) # Getting the user user = api.me() print(user.screen_name) # Adding keyword to search the tweets for search = keyword # Specifying the tweets limit numberOfTweets = 5 # Fetching the tweets and liking them for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): try: tweet.favorite() print('Tweet Liked!') counter = counter + 1 time.sleep(10) except tweepy.TweepError as e: print(e.reason) except StopIteration: break return render(request, "liked.html", {'counter': counter, 'keyword': search}) This likes 5 keywords and then stops. I would like the code to just sleep for a certain period of time and then restart even if the user has closed the web app. Essentially I need it to run like it would on a console if I had it running in a console with the following While loop - while True: like() time.sleep(5000) It essentially is to make a bot that will continuously interact with Twitter for the authorised user until authorisation is withdrawn. -
Django - cannot get the html page to display - NoReverseMatch Error
I have a django app already created and working. I am trying to add another html page. I have added the about page into the home app enter image description here This is home/views.py from django.shortcuts import render, redirect, reverse from hobby_product.models import hobby_product def home(request): """ Return home page """ #return redirect(reverse('home')) return render(request, 'home.html') def not_found(request): """ Return 404 page not found """ return render(request, '404.html') def server_error(request): """ Return 500 internal server error """ return render(request, '500.html') def about(request): return render( request, "about.html" ) Here is the url.py in home: from django.conf.urls import url, include from .views import not_found, server_error, home, about urlpatterns = [ url('/', home, name='home'), url('not_found/', not_found, name='not_found'), url('server_error/', server_error, name='server_error'), url(r'^about$', about, name='about'), ] This is the url.py for the base app: from django.conf.urls import url, include from django.contrib import admin from accounts.views import index, logout, login, registration, user_profile from django.views.generic import RedirectView from django.views.static import serve from .settings import MEDIA_ROOT from accounts import urls as accounts_urls from about.views import about from accounts.views import index from accounts.views import home from hobby_product import urls as urls_hobby_product from cart import urls as urls_cart from home import urls as urls_home from about import urls as urls_about … -
Facing memory error on my Django celery worker instance
I am using django celery with redis (broker). I have observed following error on one of my worker instance. [2020-12-27 02:26:15,920: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx- xxx.ec2.internal [2020-12-27 02:26:40,937: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx-xxx.ec2.internal [2020-12-27 02:27:00,943: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx-xxx.ec2.internal [2020-12-27 02:27:15,955: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx-xxx.ec2.internal [2020-12-27 02:27:45,971: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx-xxx.ec2.internal [2020-12-27 02:28:02,118: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx-xxx.ec2.internal [2020-12-27 02:28:36,496: CRITICAL/MainProcess] Unrecoverable error: MemoryError() Traceback (most recent call last): File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/worker/worker.py", line 205, in start self.blueprint.start(self) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/bootsteps.py", line 369, in start return self.obj.start() File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 596, in start c.loop(*c.loop_args()) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/worker/loops.py", line 83, in asynloop next(loop) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/kombu/asynchronous/hub.py", line 364, in create_loop cb(*cbargs) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/kombu/transport/redis.py", line 1074, in on_readable self.cycle.on_readable(fileno) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/kombu/transport/redis.py", line 359, in on_readable chan.handlers[type]() File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/kombu/transport/redis.py", line 694, in _receive ret.append(self._receive_one(c)) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/kombu/transport/redis.py", line 700, in _receive_one response = c.parse_response() File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/redis/client.py", line 3036, in parse_response return self._execute(connection, connection.read_response) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/redis/client.py", line 3013, in _execute return command(*args) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/redis/connection.py", line 637, in read_response response = self._parser.read_response() File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/redis/connection.py", line 330, in read_response response = [self.read_response() for i in xrange(length)] File … -
How to expand Admin form queryset overriding
Two of my models have a bidirectional relation: class Listing(models.Model): main_photo = models.OneToOneField('ListingPhoto', related_name="listing_photos", on_delete=models.SET_NULL, null=True, blank=True) class ListingPhoto(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) Then I wanted in the admin form each Listing instance to be limited exclusively to the related photos. So I overrode the admin form field to narrow the queryset: forms.py: class ListingForm(forms.ModelForm): class Meta: model = Listing fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['main_photo'].queryset = ListingPhoto.objects.filter(listing=self.instance.pk) Which it works, but only for each instance's admin form. I mean that it doesn't affect the model's admin view that contains all the registered instances, where I have set that field to be editable, without visiting every instances' form. I wonder if there is a way to expand the above queryset overriding, to cover also that usage. Thank you in advance. -
settings for the author in a blog API project
I'm working on a blog project which different users can log in and create their own posts. The problem I have, is that when a user logs in his panel, he can select every other author name from the dropdown menu and post with the name of other users. I want every user to post only with his/her name, and not to be able to select other names Below are my codes: models.py: from django.db import models from django.contrib.auth.models import User class post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title views.py: from .models import post from .serializers import PostSerializer from rest_framework import generics, permissions from .permissions import IsAuthorOrReadOnly, IsAdmin class PostList(generics.ListCreateAPIView): permission_classes = (IsAdmin,) queryset = post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthorOrReadOnly,) queryset = post.objects.all() serializer_class = PostSerializer https://uupload.ir/files/kc9x_6.png -
Loginsystem in TOR browser with no JavaScript in Django
Is there a way to make a loginsystem in Django for an onion site hosted on The Onion Router: https://www.torproject.org/ It is pretty normal for sites to have a loginsystem for users to be able to log in, but it came to my interest how this is possible with no cookies and no JavaScript as most TOR browsers prevent JavaScript from running in Safer & Safest mode according to the TOR settings: about:preferences#privacy. I would like to do this in Django, but other frameworks are accepted, but I don't think that it depends on the framework rather than the methode of storing whether the user is logged in (token/cookie) or not logged in. As said this works when STANDARD safety is enabled and Safer & Safest are disabled. This is not meant for any illegal activities! -
Django multiple image upload taking only last one
Its counting true how many images on page but only saving last one image to data It is probably updating data at each loop, how can i just insert all of them as a new record for i in request.FILES.getlist('pic'): print('check') image = iform.save(commit=False) image.car = Article.objects.get(pk = article.pk) image.pic = i image.save() -
How to output Django form on the browser
I'm learning to create a post and comment session with Django and I'm following a tutorial but I don't know why I'm not getting the same result as the one in the tutorial. The post aspect is working but the form for comments is not being displayed on the browser. Even after going through Django documentation and other resources online, I still don't see where I'm getting it wrong. I have the following directories and files: start is my app directory while education is the main django directory start/models.py class Comment (models.Model): post = models.ForeignKey(Post,related_name = 'comments', on_delete = models.CASCADE) name = models.CharField() email = models.Email() body = models.TextField() createdAt = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['createdAt'] start/forms.py from django import forms from .models import Comment class Meta: model = Comment fields = ['name', 'email', 'body'] start/views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import post_comment def fullPost(request, slug): post = Post.object.all() return render (request, 'start/start.html', {'post': post}) if request.method == 'POST': form = post_comment(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect ('fullPost', slug=post.slug) else: form = post_comment() return render (request, 'start/fullPage.html', {'post': post, 'form': form}) start/templates/start/start.html ••• <h3>Comment</h3> <form method = … -
Django Rest + Djoser: signing in doesn't make user authenticated
I am using Django rest framework and Djoser to handle my users authentication. the problem is that after I Sign in using Djoser jwt-login-endpoint(/jwt/create/), I am still not authenticated. config/setting.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = {'AUTH_HEADER_TYPES': ('JWT',),} DJOSER = { 'LOGIN_FIELD': 'email' 'SERIALIZERS': { 'user_create': 'accounts.serializers.UserCreateSerializer', 'user': 'accounts.serializers.UserCreateSerializer', 'user_delete': 'accounts.serializers.UserDeleteSerializer', }, } config/urls.py urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] -
Twitter OAuth [{'code': 215, 'message': 'Bad Authentication data.'}]
I am running a Django web app and logging in with Twitter so that the user can favourite certain hashtags or words. I am getting the following error when running the app - [{'code': 215, 'message': 'Bad Authentication data.'}] Can anyone see where my code is going wrong? Here is my views, it was cloned from a GitHub project so thought it would translate over to my app but having issues with the Authentication. from django.shortcuts import render from .models import * from django.http import * from django.shortcuts import render from django.urls import reverse from django.contrib.auth import logout from django.contrib import messages from auto_tweet_liker.utils import * # from profanityfilter import ProfanityFilter import tweepy import time import os CONSUMER_KEY = ***** CONSUMER_SECRET = ****** def index(request): # return render(request, "index.html") if check_key(request): return render(request, 'index.html') else: return render(request, 'login.html') def like(request): counter = 0 keyword = request.POST['search'] api = get_api(request) # Getting the user user = api.me() print(user.screen_name) # Adding keyword to search the tweets for search = keyword # Specifying the tweets limit numberOfTweets = 5 # Fetching the tweets and liking them for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): try: tweet.favorite() print('Tweet Liked!') counter = counter + 1 time.sleep(10) except tweepy.TweepError … -
Django Rest update many to many field of multiple objects at once
I'm working on chat app django rest backend. Btw I have a problem to update m2m field of multiple objects at once. Inside the Message model there is an m2m field deleted which represents a list of users who deleted this message. class Message(models.Model): # other fields deleted = models.ManyToManyField(User) So I can implement the delete functionality by adding user inside that field when user deletes a specific message. But the problem is when user deletes a conversation(all messages in it), how can I implement to update the delete field of multiple Message objects at once. Because each object has empty delete field, another user inside delete field, or same user inside delete field(means that user already deleted a message before). Sorry for my poor explanation and please tell me there is any unclear part in my question. -
What should I do when pipenv lock command is not working?
I'm trying to do a command pipenv lock 'cause heroku said my Pipfile.lock is out of date, and I'm trying to upload my django project at heroku. But I constantly got the error like below. PS C:\Users\josep\Documents\nomad academy\Airbnb-Clone> pipenv lock --pre --clear Locking [dev-packages] dependencies... Locking...Building requirements... Resolving dependencies... Locking Failed! [ResolutionFailure]: File "c:\users\josep\.virtualenvs\airbnb-clone-grekw6gp\lib\site-packages\pipenv\resolver.py", line 741, in _main [ResolutionFailure]: resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev) [ResolutionFailure]: File "c:\users\josep\.virtualenvs\airbnb-clone-grekw6gp\lib\site-packages\pipenv\resolver.py", line 702, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: File "c:\users\josep\.virtualenvs\airbnb-clone-grekw6gp\lib\site-packages\pipenv\resolver.py", line 684, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: File "C:\Users\josep\.virtualenvs\Airbnb-Clone-GrEkW6GP\lib\site-packages\pipenv\utils.py", line 1395, in resolve_deps [ResolutionFailure]: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( [ResolutionFailure]: File "C:\Users\josep\.virtualenvs\Airbnb-Clone-GrEkW6GP\lib\site-packages\pipenv\utils.py", line 1108, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "C:\Users\josep\.virtualenvs\Airbnb-Clone-GrEkW6GP\lib\site-packages\pipenv\utils.py", line 833, in resolve [ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. First try clearing your dependency cache with $ pipenv lock --clear, then try the original command again. Alternatively, you can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: Could not find a version that matches pathspec<1,==0.5.9,>=0.6 (from black==20.8b1->-r … -
Problem with handling multiple custom decorator in Django
I am working with some custom made decorator in Django project, named: @inspector_required responsible for inspector's login @employee_required responsible for employee's login @industryowner_required responsible for industryowner's login Now I have a function-based view named EmployeeCorner and I want that this view will activate/work when any of @inspector_required or @employee_required is satisfied. My views.py: @inspector_required @employee_required def EmployeeCorner(request): employee_corner_dict= { 'insert_me' : 'Employee Logged in and this is from Employee Corner', 'rank' : 'Employee', } return render(request, 'app2/employee_corner.html', context=employee_corner_dict) But unfortunately, this view is not working for inspector's or employee's any kind of login. There is no problem in the code of these decorators, cause when I put only one of them they work perfectly. Maybe in this code's EmployeeCorner will activate only when both of two users log-in successfully at a time(which is not possible). How can I code such a way that the EmployeeCorner view will work for any of @inspector_required or @employee_required is satisfied? -
override the save method in django
I want the create field to change when the price field changes, that is, if I change the rest of the fields, the create field will not change and will remain the same. class Product(models.Model): name = models.CharField(max_length=200) price = models.IntegerField() create = models.DateTimeField(auto_now=True) discount = models.IntegerField() information = models.TextField() -
success url in views.py
i was trying to add a success url to my views.py but it didn't work views.py: def register(request): username = request.POST.get('username') email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() else: form = RegisterForm() context = {'forms':form} return render(request, 'register/register.html', context) i want when he click submit to go to the 'home' url -
django error in python No such file or directory
I'm trying to build a website with django and I get this error (venv) C:\Users\Admin\Desktop\Python\py_website_django>django-admin startproject pyshop (venv) C:\Users\Admin\Desktop\Python\py_website_django>python manage.py runserver C:\Users\Admin\AppData\Local\Programs\Python\Python39\python.exe: can't open file 'C:\Users\Admin\Desktop\Python\py_website_django\manage.py': [Errno 2] No such file or directory -
Storing images in sqlite - Django
I'm new to Django and databases. Django used the sqlite database as it's default database. Is it possible to store images in the sqlite database and display it on my webpage? I can't find any documentation on the official Django website for it. -
Using ForeignKey of Django CustomUser giving attribute error
Not using Djnago Default user model. Have created a Custom user model named CustomUser class CustomUser(AbstractBaseUser): GENDER_CHOICE = ( ('MALE', 'MALE'), ('FEMALE', 'FEMALE'), ) BLOOD_GROUP_CHOICE = ( ('A+', 'A+'), ('B+', 'B+'), ('O+', 'O+'), ('AB+', 'AB+'), ('A-', 'A-'), ('B-', 'B-'), ('O-', 'O-'), ('AB-', 'AB-'), ) RELIGION_CHOICE = ( ('ISLAM', 'ISLAM'), ('HINDU', 'HINDU'), ('CHRISTIANITY', 'CHRISTIANITY'), ('OTHER', 'OTHER'), ) email = models.EmailField(max_length=60, unique=True, verbose_name='Email') first_name = models.CharField(max_length=30, verbose_name='First Name') last_name = models.CharField(max_length=30, verbose_name='Last Name') gender = models.CharField(_("Employee Gender"), max_length=6, choices=GENDER_CHOICE, null=True, blank=True) blood_group = models.CharField( _("Employee Blood Group"), max_length=3, choices=BLOOD_GROUP_CHOICE, null=True, blank=True) birth_of_date = models.DateField( _("Employee Birth Date"), auto_now=False, auto_now_add=False, null=True, blank=True) #address = models.CharField(_("Employee Address"), max_length=500, null=True, blank=True) address = models.CharField(_("Employee Address"), max_length=500, null=True, blank=True) phone_number = PhoneNumberField(null=True, blank=True) profile_pic = models.ImageField(_("Employee Profile Picture"), upload_to='profile_pic', height_field=None, width_field=None, max_length=None, null=True, blank=True) religion = models.CharField( _("Employee Religion"), max_length=15, choices=RELIGION_CHOICE, null=True, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('first_name', 'last_name') objects = CustomUserManager() def __str__(self): return self.email def get_short_name(self): return self.first_name def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin class Meta: verbose_name_plural = "Shunno ek Users" Here is my CumstomUser models' CustomUsermanager class CustomUserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise … -
How to filter ListView by requested field on Django
Is there any way to create one ListView class which dynamically filters objects with requested field. or maybe another solutions would be helpful. Thanks viwes.py class OrderStatusList(ListView): template_name = 'app/orders_by_status.html' def get_queryset(self): return OrderItem.objects.filter(status=self.kwargs['pk']) class OrderListView(ListView): template_name = 'app/orders_by_customer.html' def get_queryset(self, *args, **kwargs): return OrderItem.objects.filter(order__customer=self.kwargs['pk']).order_by('order__date_created') urls.py path('orders/<pk>', OrderStatusList.as_view(), name="order_status"), path('orders/customer/<pk>', OrderListView.as_view(), name="order_list"), -
Error when setting DEBUG=False in Django Web application
I have developed my web application in Django Framework. I have also made the 404 and 500 Error pages and understand very much that, they can only work when DEBUG=False. The problem now is that after setting DEBUG=False, my application which I have hosted on Heroku no longer shows. I am also using the whitenoise package for configuring my static files. This are my settings.py as related to this issue DEBUG = True 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' STATIC_ROOT = 'staticfile' STATICFILES_DIRS = [BASE_DIR / "static"] MEDIA_URL = '/media/' MEDIA_ROOT = "media" NOTE: I have collected staticfiles using the command heroku run python manage.py collectstaic -
I get this error unsupported operand type(s) for -: 'method' and 'int'
I want to subtract available_quantity to total_quantity . but i get this error how can i solve it class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) distribute_price = models.IntegerField() mrp_price = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) user_give_quantity = models.IntegerField(null=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.product.item_name def aaa_qqq(self): return self.mrp_price * self.user_give_quantity def available_quantity(self): return self.product.quantity - self.user_give_quantity if all([self.product, self.product.quantity, self.user, self.user_give_quantity]) else 0 def total_quantity(self): return self.available_quantity - self.user_give_quantity -
Can we use both custom validation (using clean()) and inbuilt validators in a single Django-form field ? If /if-not how/why?
I am using an inbuilt validator to check the length of a form element, also using the custom clean() method to check for another logic not present in the inbuilt validators. But getting an error. Is this allowed in Django? if yes, then please show me an example. -
JWT and custom authentication in Django Rest Framework
I have written a very basic custom authentication class in order to implement the simple JWT library for my authentication needs. I generate tokens manually and then send the access token to my API. By default this would be enough but since i do not use the default Django user Model, I need to read that token in order to query the database with the given user id. class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): try: user = vAuthUser.objects.get(pk=42706987) #this should receive the user_id from the token except: raise AuthenticationFailed('No such user') return (user, None) My API looks like: class MyAPI(APIView): authentication_classes = (ExampleAuthentication,) permission_classes = (IsAuthenticated ,) def get()... -
Remove media files after removing an object
Hey Guys I wanna remove media files automatically after removing related objects. What can I do? class Post(models.Model): title = models.CharField() image = models.ImageField(upload_to='post/images')