Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do i import / export social accounts using django import export package?
I successfully imported and exported other data but not able to import/export social accounts and social application tokens. I am using django allauth for social account creation. There is no other way to login in. -
Optomizing Django API Queries to reduce database hits
This is just on my belief that Django has unlimited possibilities. I have an API, testing it with debug-toolbar, I have up to 13 hits per request. I would like to think there is something I can do to bring down the database hits to 1. Here is my API List View: class ProductsListAPIView(ListAPIView): queryset = Product.objects.active() serializer_class = ProductSerializer filter_backends = [SearchFilter, OrderingFilter] permission_classes = [HasAPIKey | AllowAny] search_fields = ['product_title', 'product_description', 'user__first_name', 'product_type', 'product_price', 'product_city'] pagination_class = ProductPageNumberPagination def get_serializer_context(self, *args, **kwargs): context = super(ProductsListAPIView, self).get_serializer_context(*args, **kwargs) context['request'] = self.request coordinates = self.request.GET.get("coordinates") if not coordinates or len(coordinates) <= 4: coordinates = '0.0,0.0' context['coordinates'] = coordinates return context def get_queryset(self, *args, **kwargs): query = self.request.GET.get("search") lookups = () if query and len(query) > 0: queryArray = query.split() for q in queryArray: lookups = (Q(product_title__icontains=q) | Q(product_description__icontains=q) | Q(product_type__icontains=q) | Q(product_city__icontains=q) | Q(user__first_name__icontains=q) | Q(user__last_name__icontains=q) | Q(product_address__icontains=query) ) # If user is loggedIn and discovery range / point and address is set # Returns products just in that range. uid = self.request.GET.get("uid") queryset_list = self.queryset if uid and len(uid) > 5: try: user = CustomUser.objects.get(uid=uid) from django.contrib.gis.measure import D if user is not None and user.point is not None … -
How can you group a list extracted from queryset many-to-many field?
I have a model that describes the essence of a TV channel: class ChannelCategory(models.Model): name = models.CharField(max_length=200, db_index=True) def __str__(self): return '%s' % self.name class Channel(models.Model): category = models.ForeignKey(ChannelCategory, on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) class Meta: ordering = ['category'] def __str__(self): return '%s: %s' % (self.category, self.name) I also have a model that describes the essence of the tariff. Channels are linked to a tariff using a relationship many-to-many. class Tariff(models.Model): channels_list = models.ManyToManyField(Channel, blank=True, db_index=True, symmetrical=False) def __str__(self): return '%s' % self.name If I call the tariff object, I can get a list of channels that are assigned to it: queryset = Tariff.objects.prefetch_related('channels_list') for tariff in queryset: channels_list = [tariff.channels_list.all()] print (channels_list) And get the next set: <QuerySet [<Channel: channelcategory1: channel1>, <Channel: channelcategory1: channel2>, <Channel: channelcategory2: channel3>]> I want to receive queryset the following form: <QuerySet [<Channel: channelcategory1: channel1, channel2>, <Channel: channelcategory2: channel3>]> How can I do that? -
Django Postgres Search
I may be misunderstanding something after reading the docs but I am confused as to why my search function isn't quite working. The code is as follows: def product_search(request): form = ProductSearchForm() q = '' results = [] if 'q' in request.GET: form = ProductSearchForm(request.GET) if form.is_valid(): q = form.cleaned_data['q'] vector = SearchVector('name', weight='A') + \ SearchVector('artist', weight='B') query = SearchQuery(q) results = Product.objects.annotate(rank=SearchRank(vector, query, cover_density=True)).order_by('-rank') results = Product.objects.annotate(search=SearchVector('name', 'artist')).filter(search=SearchQuery(q)) return render(request, 'my_site/search.html',{ 'q': q, 'results': results }) As far as my understanding is SearchVector() should allow the searching of multiple fields. If I search just for product names it works fine, but if I search for an artist name it returns no results, even if I type the full direct name, and I am not understanding why. Any help would be greatly appreciated! I will also post my product model just in case that may be of some use. model: class Product(models.Model): name = models.CharField(max_length=120) shortened_name = models.CharField(max_length=50) date_of_creation = models.CharField(max_length=20, null=True) history = models.CharField(max_length=255) price = models.DecimalField(max_digits=9, decimal_places=2) discount_price = models.FloatField(blank=True, null=True) style = models.CharField(max_length=50) artist = models.ForeignKey(Artist, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to='images', null=True) slug = models.SlugField() def __str__(self): return self.name def get_absolute_url(self): return reverse('product', args=[self.slug]) def save(self, … -
How to get child objects on condition in Django
I`m trying to fetch data from the parents' model to the child model who fulfills the condition. I have a product model and there is also a product review model. so I need to fetch records from a product model to reviews models that have a rating of 1. class Product(models.Model): name = models.CharField(max_length=250) code = models.IntegerField(unique=True) ... class Review(models.Model): name = models.CharField(max_length=250) rating = models.IntegerField(default=1) message = models.TextField(max_length=2000) ... output:- from all product models get reviews who have a rating of 1. like this MySQL query SELECT * FROM product_product as product INNER JOIN product_productreviews as review ON product.id = review.product_id WHERE review.rating = 1.0 -
Django : Aggregate Functions on nested query many-to-many relationship
My model.py is class Place(models.Model): id = models.IntegerField(primary_key=True) location = models.CharField(max_length=100) class Meta: db_table = 'place' managed=False class Session(models.Model): id = models.IntegerField(primary_key=True) place = models.ForeignKey(Place,related_name='session',on_delete=models.CASCADE, null=True) start = models.DateField(auto_now=True) counts = models.IntegerField() class Meta: db_table = 'session' managed=False class Animal(models.Model): id = models.IntegerField(primary_key=True) sess = models.ForeignKey(Session,related_name='details',on_delete=models.CASCADE, null=True) type = models.CharField(max_length=100) is_active = models.BooleanField() length = models.DecimalField(max_digits=6, decimal_places=2) class Meta: db_table = 'animal' managed=False I need to get a summary table, with min, max, standard_deviation, average and count of animals in the particular location based on selection of particular day, week, month or year. I tried using aggreagate and annotations, but the result was not as expected. Please suggest me how can this be achieved? The output I am trying to get is [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", "count": 600, "details": [ { "id": 1, "length_max": "22.00", "length_min": "10.00", "length_avg": "16.43", "length_std": "16.00", "is_active": false, "type": "dog" } ] }, { "start": "2021-01-02", "count": 400, "details": [ { "id": 2, "length_max": "19.00", "length_min": "12.00", "length_avg": "15.00", "length_std": "13.00", "is_active": true, "type": "dog" } ] }, ] } ] But the output that I am getting is [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", … -
Can I use admin-stylle inlines in my templates?
Is it possible to use admin-style inlines to list the related model instances in a template? For example, if I have a poll and questions... class Poll(models.Model): title = models.CharField(max_length=100) # ... class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name="questions") In the admin, I'd create an inline for the questions and add it to the ModelAdmin. But can I use something similar in the template? Once again, it would be used to list the instances, not to edit them. -
Embedding Spotfire into Django
I am building a website using Django, currently hosted in my local machine. I want to embed Spotfire into my Django website. I use a corporate Spotfire server which is hosted in the corporate intranet network. I am already logged in to the network using Windows authentication. I tried embedding Spotfire into an Html webpage. I tried two ways: 1. Using the JavaScript API: https://community.tibco.com/wiki/spotfire-tipstricks-embed-spotfire-visualizations-webpages The issue I found here is that it shows a blank page. I searched the problem and it seems it is because of SameSite error: The error is further explained here: https://support.tibco.com/s/article/Tibco-Spotfire-JavaScript-Mashup-API-stops-working-in-Chrome-due-to-SameSite-problem?_ga=2.207502931.1596109997.1627212003-1100468487.1624779216 I am new to Django, so I couldn't find a solution to set the SameSite cookie in Django to 'None'. 2. Using iframe: https://youtu.be/dY4_aYd5uZM The iframe solution does display a Spotfire window inside the webpage but it requires login, and when I click login, nothing happens and it gives out the same issue as above (SameSite error). I hope you could help me solve the issue or suggest me a new workaround. -
django save table rows data to database using for loop
I'm new in Django python ,i have a table with some rows which filled with javascript, I have a problem, when click Save button , I want get table rows count and store all rows data to database, and go to specific page; thank you; ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="myform1" name="myform1" action="{% url 'order' %}" method="POST" onsubmit="return validForm()"> {% csrf_token %} <fieldset class="field2"> <div id = "dv3" style="height: 270px; overflow: auto; direction: ltr; text-align: left; padding: 10px; border-radius: 6px; width: 450px; margin-right: auto; margin-left: auto; margin-top: 10px;"> <table id = "tbl3" border="1" > {% for item in range %} <tbody id="tblbody1" style="height: 100px; overflow-y: auto; overflow-x: hidden; border-radius: 6px;"> <tr> <td><input id="name" name= "name-{{ item }}" type="text" ></td> <td><input id="family" name= "family-{{ item }}" type="text" ></td> <td><input id="age" name= "age-{{ item }}" type="text" ></td> <td> <input type="text" onclick="deleteRow(this)" value="Del"> </td> </tr> {% endfor %} </tbody> </table> </div> <div> <button class="buttons buttoning" id="btnsave" name="save" >save</button> </div> </fieldset> </div> </form> </body> </html> view.py if request.method == 'POST': for instance in range(tbl_rows_count): f1 = request.POST.get(name-' + str(instance)) f2 = request.POST.get('family-' + str(instance)) f3 = request.POST.get('age-' + str(instance)) createObj = staff.objects.create( name=f1, family=f2, age=f3, ) createObj.save() … -
Plotly Dash Integration with Django : The current path, welcome.html, didn’t match any of these While Applying Navigation on Sidebar
I have followed this Video Tutorial, and successfully applied all the step and executed. It is working fine. I am now trying to add navigation on the side bar like tables on the bottom of this sidebar navigational menu: but it is giving the following error: My master urls.py is as follows: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('django_plotly_dash/', include('django_plotly_dash.urls')), ] and my application urls.py is this: from django import urls from django.urls import path from . import views from home.dash_apps.finished_apps import simpleexample urlpatterns= [ path('', views.home, name='home'), path('tables/', views.home1, name='home1') ] While my sidebar.html is as follows: <li class="nav-item"> <a class="nav-link" href="{% url 'home1' %}"> <i class="fas fa-fw fa-table"></i> <span>Tables</span></a> </li> Moreover i am rendering this in the views.py def home1(request): def scatter(): x1 = ['PM2.5','PM10','CO2','NH3'] y1 = [30, 35, 25, 45] trace = go.Scatter( x=x1, y = y1 ) layout = dict( title='Line Chart: Air Quality Parameters', xaxis=dict(range=[min(x1), max(x1)]), yaxis = dict(range=[min(y1), max(y1)]) ) fig = go.Figure(data=[trace], layout=layout) plot_div = plot(fig, output_type='div', include_plotlyjs=False) return plot_div context ={ 'plot1': scatter() } return render(request, 'home/welcome.html', context) I am unable to understand how can I correctly locate the welcome.html so that … -
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited.need
I am facing error that i cant make form with field or exculde attribute please help me out to fix this error code from forms.py is : from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CustomerRegistrationForm(UserCreationForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs= {'class':'form-control'})) password2 = forms.CharField(label='Confirm Password (again)', widget=forms.PasswordInput(attrs={'class':'form-control'})) email = forms.CharField(required=True, widget=forms.EmailInput(attrs={'class':'form- control'})) class Meta: model = User fiedls = ['email', 'username', 'password1', 'password2'] labels = {'email': 'Email'} widgets = {'username':forms.TextInput(attrs={'class':'form-control'})} -
Django Rest Framework permissions outside Rest Framework view
I am using Rest Framework Token authentication. Which means I cannot know if a user is authenticated outside a rest framework view eg:(A regular django view). The Rest Framework token authentication is a custom auth system which can only be used in a rest framework view. In a normal rest framework view, I can restrict the endpoint for authenticated users by using this: class ExampleView(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) But how will I do that for a regular django view. eg: def someDjangoView(request): ''' Note that I cannout use request.user.is_authenticated. It will always return false as I am using rest framework token authentication. Which means the request parameter should be of rest framework's and not django's built-in. ''' content = {"detail": "Only authenticated users should access this"} return JsonResponse(content) I am stuck in a situation where I have to know if a user is authenticated (custom auth) outside a rest framework view. Is there any way to do that? -
How to override a default value with other value django models
I have a problem with django. In my model, I have a JSON-Field which stores as default an empty list. When trying to append a value to that list, this doesn´t work. No matter whether it´s another object or a string. Going to the field, its still empty then. I would appreciate any help. Thanks in advance. models.py followers = models.JSONField(default={ "followers": [] }) (the "followers" field is in the Client class) views.py current_user = Client.objects.get(id=response.user.id) current_user.followers["followers"].append("Some Name") -
Deploying python API in heroku without static files
I'm deploying a django API which does not have any static files, When is deploy it using heroku via GitHub without using heroku CLI, I get an error Error while running '$ python Rest_Api/manage.py collectstatic --noinput'. NB In my settings file i have the default django STATIC_URL = '/static/' How can i tell heroku my app does not have any statics thus should not expect it? -
Top 5 Customers in current month (Django)
I have an Order model as below: class Order(models.Model): order_date = models.DateField() value = models.FloatField(default=0.00) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, related_name='orders') customer_city = models.ForeignKey(CustomerCity, null=True, on_delete=models.SET_NULL, related_name='orders_city') I would like to generate a table of Top 5 Customers in current month (based on value of total orders received) in my templates file with ('Customer', 'City', 'Orders Count' and 'Orders Sum') fields. Was totally confused and clueless about how to get this data. But, tried the following code in my views.py file: today = datetime.date.today() top_five_customers = Order.objects.filter(order_date__year=today.year, order_date__month=today.month).values('customer').annotate(orders_count=Count('customer'), orders_sum=Sum('value')).order_by('-orders_sum',)[:5] Then in my templates file, I have the following: {% for customer in top_five_customers %} <tr> <td>{{ customer.customer }}</td> <td>{{ customer.customer_city }}</td> <td>{{ customer.orders_count }}</td> <td>{{ customer.orders_sum }}</td> </tr> {% endfor %} Thanks in advance. -
Django form doesn't validate when init ModelMultipleChoiceField without data
I want to use ModelMultipleChoiceField with select2 in my Django application. this is forms.py : #forms.py class SymbolForm(forms.Form): symbol = forms.ModelMultipleChoiceField(queryset=Symbol.objects.all(), label='symbol') Everything is ok except one thing. Symbol table has about 5 thousand record and when html rendered all data pass to html template. I don't want it. I did change my form to this: # forms.py class SymbolForm(forms.Form): symbol = forms.ModelMultipleChoiceField(queryset=Symbol.objects.all(), label='symbol') def __init__(self, *args, **kwargs): super(SymbolForm, self).__init__(*args, **kwargs) self.fields['symbol'].queryset = Symbol.objects.none() to init form without any data. A new problem arises: when form submitted, it is n't valid and django says that my chosen symbol doesn't valid choice. In fact, my problem is that I want to create the form without the data and then be able to verify it with the data I get from the select2, but Django does not allow this. What can I do? -
Test Django create_user of an AbstractUser without username
I'm trying to test the creation of an user in Django. But my user model is not the standard one (email is the username). models.py from django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager class UserManager(AbstractUserManager): def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user class CustomUser(AbstractUser): objects = UserManager() username = None first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] tests.py from django.contrib.auth import get_user_model class CustomUserTests(TestCase): def test_create_user(self): user = get_user_model() utilisateur = user.create_user( email='test@tester.com', password='testpass123', ) self.assertEqual(utilisateur.email, 'test@tester.com') Error line 10, in test_create_user utilisateur = user.create_user( AttributeError: type object 'CustomUser' has no attribute 'create_user' Something is missing but I don't know how to test well this... Thanks a lot -
import django_filters in filers.py shows "Import "django_filters" could not be resolvedPylancereportMissingImports"
I have tried looking for the solution in other threads but still stuck to the problem. My python version is 3.9.5; I reinstalled django to a lower version (it was 3.2.0, later installed 3.0) INSTALLED_APPS = [ ... ... 'django_filters', ] error in <module> from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (D:\DJPROJ\FINsite-packages\django\utils\__init__.py) installed as pip install django-filter. In my filters.py I am getting the line import django_filters as yellow underlined and on hover shows Import "django_filters" could not be resolvedPylancereportMissingImports Can anyone please guide me through? Thanks. -
Django WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/8_9/' failed:
I am doing a Django project in which I have added a live chat feature using Django channels. When I finished the messaging part I worked on other parts of the project (like posting, liking posts, and in general parts that have nothing to do with the messaging). However now when I test the messaging page I get the following error in my browser console: 8_9:58 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/8_9/' failed: The error has no further explanation after the colon (which is why I don't even know where to start solving it, I've had similar errors but they always had something else after the colon). I also tried rolling back to an older version of my app using GitHub (I went back to the last version that I was sure was working) and it still didn't work. Here is my js code: const roomName = JSON.parse(document.getElementById('room-name').textContent); var chatSocket = ""; if(document.location.protocol == "https:"){ chatSocket = new WebSocket( 'wss://' + window.location.host + '/wss/chat/' + roomName + '/' ); } else{ chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); } chatSocket.addEventListener('open', function(event) { $.ajax({ url: '/ajax/get_msg/', data: { 'room': roomName }, dataType: 'json', success: function (data) … -
Django order by a field from a related model returns duplicate objects
I have these two models: class Product(models.Model): name = models.CharField(max_length=100) ... class ProductPack(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.PositiveIntegerField(default=0) And I have a queryset of Product model: products = Product.objects.all() # <ProductQuerySet [<Product: first product>]> I want to order products queryset by "productpack__price". So I tried to do this by this code: qs = products.order_by("productpack__price") This works partly correctly. But there is one problem. For each object in the products, This code returns objects to the count of foreignkey that they have with ProductPack. Like this: qs <ProductQuerySet [<Product: first product>, <Product: first product>, <Product: first product>]> How to fix this problem. Have you any suggestions? -
User() got an unexpected keyword argument 'firstname'
Hello I'm creating an API to register but I'm receiving this error User() got an unexpected keyword argument 'firstname' I tried many ways but couldn't fix, I'll be thankful if someone helps me fix this. my code : from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import get_user_model User = get_user_model() # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name' ,'username', 'email', 'is_business') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','first_name' ,'last_name' , 'username', 'brand', 'email', 'is_business', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], firstname=validated_data['first_name'], lastname=validated_data['last_name'], brand=validated_data['brand'], email=validated_data['email'], password=validated_data['password']) return user -
update post via ajax django modelform
there i'm trying to update post via ajax request and django ModelForm i want to check validation form before submitting class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) date = models.DateTimeField(auto_now_add=True) class MainGroupForm(forms.ModelForm): class Meta: model = MainGroup fields = ['main_type'] error_messages = { 'main_type':{ 'required':_('required to fill'), 'unique':_('taken'), } } widgets = { 'main_type':forms.TextInput(attrs={'class':'form-control','placeholder':_('main group')}) } my views.py @login_required def update_maingroup(request): id = request.POST.get('eid') object = get_object_or_404(MainGroup,id=id) form = MainGroupForm(instance=object) if request.method == 'POST': form = MainGroupForm(request.POST,instance=object) if form.is_valid(): form.save(commit=True) return JsonResponse({'success':'success','data':form}) else: return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'}) my templates $("tbody").on("click",".btn-edit",function(){ const id = $(this).attr('data-edit'); const csr = $("input[name=csrfmiddlewaretoken]").val(); mythis = this mydata = { eid:id, csrfmiddlewaretoken:csr } $.ajax({ url:'{% url 'products:update_maingroup' %}', method:'POST', data:mydata, success:function(data){ console.log(data) }, }); }); <table id="maingroupid" class="table table-bordered table-striped text-center"> <thead> <tr> <th>#</th> <th>admin</th> <th>main group</th> <th>date</th> <th>actions</th> </tr> </thead> <tbody id="tableData"> {% for i in lists %} <tr> <td>{{i.id}}</td> <td>{{i.admin}}</td> <td>{{i.main_type}}</td> <td>{{i.date | date:'d-m-Y h:i A'}}</td> <td align="center"> <button class="btn btn-info btn-edit bg-info" data-edit="{{i.id}}"><i class="far fa-edit"></i></button> <button class="btn btn-danger btn-del bg-danger" data-did="{{i.id}}" ><i class="far fa-trash"></i></button> </td> </tr> {% endfor %} </tbody> </tfoot> </table> the console always returns required to fill i want to update it within this modal form but i'm not so good in … -
Change css of element inside safe custom template tag- Django
I use the safe template tag to display texts that represents html in Django, but I can not change the style of the html elements in that text. <div class='safeclass'> {{ description|safe }} </div> In style, I can't set any css to any element of that html: <style> .safeclass h1{ background-color:red; } </style> -
Get User detail by access_token by django-oauth-toolkit and django-rest-framework
I am using Django oauth toolkit with rest-framework according this manual Now, I want to get user detail by access_token. acceess tokens are correctly stored in table Access Tokens So, I tried to this,but in vain curl -H "Authorization: Bearer Ad359hPR93g1q0l1tIrmM6EvK1Q68i" http://localhost:8008/users/ I still confused this access_token is for the api permission, not the user detail itself??? BTW, http://localhost:8008/users/1 http://localhost:8008/users/2 returns first and second user correctly. My goal is to get the user detail according to access_token Thanks for any helps. class UserList(generics.ListCreateAPIView): #permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] permission_classes = [] queryset = User.objects.all() serializer_class = UserSerializer class UserDetails(generics.RetrieveAPIView): #permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] permission_classes = [] queryset = User.objects.all() serializer_class = UserSerializer -
How to force a FilerImageField to convert image format
I'm trying to force certain FilerImageFields to be convert to another format on saving. I've created this model class SearchImage(FilerImageField): def convert_to_webp(self): print("in convert") extension = ['jpeg', 'png', 'jpg', 'img', 'gif'] if any(ext in self.file.name.lower() for ext in extension): #try: img = Image.open(self.file) correggi_nome = self.file.name.split('.')[0] img.save(correggi_nome + '.webp','webp') logger.debug('img.save save another copy of the file not repalced the original!') #except Exception as ex: # logger.error(ex) def save(self, *args, **kwargs): self.convert_to_webp() print("Save search image") super().save() class Organisation(models.Model): .... search_image = SearchImage( related_name='+', verbose_name=_('Search thumbnail image'), help_text=_('Search thumbnail image'), on_delete=models.SET_NULL, blank=True, null=True ) .... def save(*args, **kwargs): print('saving') print("just before search thumbnail save") self.search_image.save() print("just after search thumbnail save") super.save() my SeachImage.save() is never called. When I save an image (or organisation) I see the print statements within the Organisation.save() but not the SearchImage.save(). How to I get this to work?