Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serialize Inherited models in Django REST Framework
I'm working on a Django Rest Framework project, in which I have created the following models as: from django.core.exceptions import ValidationError from django.db import models # Base Models... choices = ( ('Single', 'Single'), ('Multiple', 'Multiple'), ) class UserAccountModel(models.Model): deployment_name = models.CharField(max_length=150, blank=True) credentials = models.FileField(upload_to='media/credentials/', name='credentials'), project_name = models.CharField(max_length=150, blank=True) project_id = models.CharField(max_length=100, blank=False, name='project_id') cluster_name = models.CharField(max_length=150, blank=False) zone_region = models.CharField(max_length=150, blank=False) services = models.CharField(max_length=100, choices=choices) def __str__(self): return self.deployment_name class KontainerAccountModel(models.Model): deployment_name = models.CharField(max_length=150) class AwdModel(UserAccountModel): source_zip = models.FileField(upload_to='media/awdSource/', name='awd_source') routing = models.TextField(name='routing', null=True) def __str__(self): return self.deployment_name def save(self, **kwargs): if not self.id and self.services == 'Multiple' and not self.routing: raise ValidationError("You must have to provide routing for multiple services deployment.") super().save(**kwargs) # def clean(self): # if self.services == 'Multiple' and self.routing is None: # raise ValidationError('You must have to provide routing for multiple services deployment.') class AwodModel(UserAccountModel): source_zip = models.FileField(upload_to='media/awodSource/', name='awod_source') routing = models.TextField({'type': 'textarea'}, name='routing') def save(self, **kwargs): if not self.id and self.services == 'Multiple' and not self.routing: raise ValidationError("You must have to provide routing for multiple services deployment.") super().save(**kwargs) I need to serialize these models, Here's how I have implemented serializers for these models: from rest_framework import serializers from .models import UserAccountModel, AwdModel, AwodModel … -
Short incremental uinque id for neo4j
I use django with neo4j as database. I need to use short url based on node ids in my rest api. In neo4j there is an id used in database that didn't recommended to use in app, and there is approach to use uuid that is too long for my short urls. So I add my uid generator: def uid_generator(): last_id = db.cypher_query("MATCH (n) RETURN count(*) AS lastId")[0][0][0] if last_id is None: last_id = 0 last_id = str(last_id) hash = sha256() hash.update(str(time.time()).encode()) return hash.hexdigest()[0:(max(2, len(last_id)))] + str(uuid.uuid4()).replace('-', '')[0:(max(2, len(last_id)))] I have two question, First I read this question in stack overflow and still not sure that MATCH (n) RETURN count(*) AS lastId is O(1) there was no reference to that! Is there any reference for that answer? Second is there a better approach to do in both id uniqueness and speed? -
Django: Can i link 2 model fields instead of the model class?
Here is my code below, class Random(models.Model): Random_name = models.CharField(max_length=250) Rand_ID = models.CharField(max_length=100) class Input(models.Model): Input_name = models.CharField(max_length=250) iref_id = ?? (To be linked with Rand_ID) is_req=models.CharField(max_length=100) Im trying to link Rand_ID to iref_id so that for a particular Rand_ID, i can have Many inputs. I know that i can link Random class using ForiegnKey however can i link Rand_ID in any way? PS- Rand_ID is not the Primary Key of Random. All answers are welcome. -
Issue in Vuejs, Axios and Highcharts integration slow performance
I try to visualize data asynchronously from JSON in django 2.0 using vuejs and Highcharts. I just moved from jquery to vuejs due to its simplicity. I found out the data visualization using vue js and Highcarts is much slower than using JQuery and Highcharts. I generate JSONResponse in different url from the chart and the axios is used to help vuejs fetching data from that url. The data first annoted and grouped by queryset in views.py. The Highcharts options also setted in backend. here's my views.py : def chart_view(request): return render(request,'chart.html') def chart_data(request): dataset = Passenger.objects.values('embarked')\ .exclude(embarked='')\ .annotate(total=Count('embarked'))\ .order_by('embarked') port_name = dict() for choices_tuple in Passenger.PORT_CHOICES: port_name[choices_tuple[0]] = choices_tuple[1] #Hicharts visualization config pie_chart = { 'chart' : {'type':'pie'}, 'title' : {'text' : 'PELABUHAN'}, 'series': [{ 'name' : 'Tempat Berangkat', 'data' : list(map(lambda row: {'name' : port_name[row['embarked']], 'y' : row['total']},dataset)) }] } return JsonResponse(pie_chart) I fetch the data using axios when the el is mounted and visualize the data before update. I try to draw the chart when applicaion is updated before but it's just create forever loop which is imposible to stop the drawing process and impossible to visualize the data. However, by using beforeUpdate lifecycle hook it's still … -
How can you add a secondary ID for a model, based on its association with a particular object?
Example code: class Post(models.Model): ... class Comment(models.Model): ... post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, null=False) post_comment_number = models.PositiveIntegerField(unique=True, null=False) Imagine a blog post with a bunch of comments underneath it. I want to assign a secondary ID to each one of these comments, representing the relationship between the comment and the blog post - for example: Comment #1: ..., Comment #2: ..., etc etc. I don't want to do this on the frontend because, for example, if comment #2 is ever deleted, I don't want to assign another comment associated with this particular blog post the #2 ID again. Any thoughts on how to do this? Thanks so much! -
django with postgres database not connecting
frustrated, need help plz. just installed postgres database service, want to use it for my django project, only for localhost. also installed pgAdmin3LTS, which is like GUI for postgres. postgres was installed on my os c:postgres. with pgAdmin I created a new database name: porfoliodb right now my object browser in pgAdmin look like this: server groups -server(1) -djangoserver(locohost:5432) -databases(2) -porfoliodb -postgres in my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'portfoliodb'), 'USER': 'postgres', 'PASSWORD': 'xxxxxxxx', 'HOST': 'localhost', 'PORT': '5432', } } but somehow it wont connect together, I am total newbie in database, please give me some hands. thx alot! -
How to filter today's date from ListView
I have models called Statistics. From views i made a ListView to display it on template. Now my problem is i would like to see only today's == date_expiry. How do i do this? models.py class Statistics(models.Model): site = models.CharField(max_length=264) name = models.CharField(max_length=264, blank=True) mac_add = models.CharField(max_length=264) minutes_used = models.CharField(max_length=265) date = models.DateTimeField(auto_now=True, blank=True) date_expiry = models.DateTimeField() def __str__(self): return self.name views.py class DisplayStats(ListView): model = Statistics ordering = ['date'] html > <table class="table"> > <tr> > <th>Site</th> > <th>Name</th> > <th>Mac ID</th> > <th>Hours</th> > <th>Date</th> > <th>Date Expired</th> > </tr> > {% for clients in object_list %} > <tr> > <td>{{ clients.site }}</td> > <td>{{ clients.name }}</td> > <td>{{ clients.mac_add }}</td> > <td>{{ clients.minutes_used|cut:".0" }}</td> > <td>{{ clients.date }}</td> > <td>{{ clients.date_expiry }}</td> > </tr> > {% endfor %} > </table> from list view -
Primary Key cannot be displayed on web page
I have a customer table which has 3 columns customer_id, first_name, last_name and the customer_id is the primary key. See my views.py: def addressHome(request): customerList = Customer.objects.raw('select * from customers') print(customerList.columns) return render(request, "Address.html", {'customerList': customerList}) my models.py like this: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class Customer(models.Model): customerId = models.IntegerField(db_column='customer_id', primary_key=True, editable=False) firstName = models.CharField(max_length=30) lastName = models.CharField(max_length=30) And my Address.html is like this: {% extends 'base.html' %} {% block title %} Address List Page {% endblock %} {% block content %} <style> table, th, td { border: 1px solid black; border-collapse: collapse; } </style> <table width="50%" aligh="center"> <tr> <th>Cutomer ID </th> <th>First Name</th> <th>Last Name</th> </tr> {% for row in customerList %} <tr> <td>{{ row.customer_id }} </td> <td>{{ row.first_name }} </td> <td>{{ row.last_name }}</td> </tr> {% endfor %} </table> {% endblock %} below is the effect on the web page: So, can someone tell me why and how to fix this problem? -
Multiple type user's authority is messy when change user profile with UpdateView - Django
I have three user types in user model(create, query and common), multiple type user's authority is messy when I am changing user profile with UpdateView, for example, a user who is admin, when admin clicked a user who is common user, then that user in page is in common user's authority, my UpdateView is as below: class UserUpdateView(UpdateView): model = User form_class = UserForm context_object_name = 'user' template_name = 'general/teachers/user_change_form.html' def get_object(self): return get_object_or_404(User, pk=self.kwargs['pk']) -
Testing Anymail webhook locally, unable to receive signal
I am trying to test my setup for Anymail (using Mailgun) webhooks. Currently using https://ngrok.com/ which redirects an HTTPS address to a local address to properly handle localhost:80 addresses. Mailgun allows to send test requests to a webhook, which points to the temporary ngrok provided addres, something like: https://random:random@somthing.ngrok.io/webhooks/anymail/mailgun/tracking/ Following anymail-webhooks the app is currently able to actually receive the webhook call as shown in the logs: web | "POST /webhooks/anymail/mailgun/tracking/ HTTP/1.1" 200 0 The response code 200 indicates the backend received the webhook correctly and sent an acknowdledge. The url is set here: path('webhooks/anymail/', include('anymail.urls')), and the signal receiver is as simple as: from anymail.signals import tracking from django.dispatch import receiver @receiver(tracking) def handle_signal(sender, event, esp_name, **kwargs): print('[ --- ] {}'.format(event)) I expect to see something in my shell for every POST to /webhooks/anymail/mailgun/tracking/ but apparently the receiver is never receiving the signal and thus not printing anything. I went over this a couple of times and I can't figure what am I missing. -
Form Data not present in Serializer.validated_data
The problem: I'm trying to implement a Serializer that serializes a Profile model. Unfortunately, the image key and its value are not present in validated_data passed to the update() method of the serializer. The setup: This is the request I'm using to PUT to the respective endpoint: curl -vvv \ -XPUT \ -H "Authorization:Bearer ${accessToken}" \ -H "Content-Type:multipart/form-data" \ -F "user=http://${baseURL}/users/2;type=application/json" \ -F "image=@${image1};type=image/png" \ ${url} The serializer code: # profile_serializer.py: from rest_framework import serializers class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ('image',) image = serializers.ImageField(required=True) class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ( 'url', 'user', 'image', ) image = ImageSerializer(required=False, allow_null=True) def update(self, instance, validated_data): return super().update(instance, validated_data) The model code: # profile.py: from django.db import models from django.contrib.auth import get_user_model class Image(models.Model): image = models.ImageField(null=True, default=None) class Meta: abstract = True class ProfileImage(Image): pass class Profile(models.Model): user = models.OneToOneField(get_user_model(), related_name='profile') image = models.OneToOneField(ProfileImage, related_name='profile', null=True, default=None) When I set a breakpoint inside the update() method of the serializer and inspect validated_data, the image key value pair is not present. A possible workaround? I can however retrieve the image from the request data like this and update the model manually: def update(self, instance, validated_data): uploaded_image … -
Django: Display value other than form entry in formset
I have a formset that I can pass in a set of forms. I don't want the user to be able to change the profile associated with the specific form and I am having trouble doing this. {{form.profile}} will display a drop down menu with the user's email. {{form.profile.value}} will display the profile's id (it is a foreign key to another model). In this case it'll display the number 9. I tried creating a function in the model called get_name, but then {{form.profile.get_name}} doesn't bring anything back. What's the right way to display something other than the form item or value when using a formset? HTML {% for form in invoiceupdate_form.forms %} <tr><td>{{ form.profile }}</td> <td>{{ form.start_date.value }}</td> -
How to send image to localhost server from app
I have created a server from Django/pycharm. Now how to send an image to that localhost server Please help me out. -
How to avoid race condition in Django when assigning an integer field a value, based on a value belonging to the VERY LAST similar object in the db?
Some example code showing the issue: class Post(models.Model): ... class Comment(models.Model): ... post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, null=False) post_comment_number = models.PositiveIntegerField(unique=True, null=False) Say every time we create a new Comment object for a Post object, we want to assign the post_comment_number field a value that's +1 of the post_comment_number value of the last comment created for the same Post object. I believe doing something like below could lead to a race condition issue: last_comment_for_post = Comment.objects.filter(post=post).order_by('-post_comment_number')[0] comment = comment_form.save(commit=False) comment.post_comment_number = last_comment_for_post.post_comment_number + 1 comment.save() How can we do this in a thread-safe way that wouldn't lead to a race condition issue? -
django channels: geting two servers to communicate with each other via websockets
First of all I should say I'm pretty new to django and web development in general so there's every likelihood I'm doing something wrong. Basically I have a server (middleware) that should accept a post http request with some data in json then check if my db (which is located on another server) is available and if it is then send that data to that server (which is actually a cluster) via websocket connection if it is not then save it in the local db. Here I'm just trying to get the server communicate with each other the way I'd like them to. So to the best f my understanding I should create a view on the middleware server like so: from rest_framework_mongoengine import viewsets # some other imports class DataView(viewsets.ModelViewSet): def create(self, request): channel_layer = layers.get_channel_layer() async_to_sync(channel_layer.send) ( 'test_channel', request.data ) return Response( status=status.HTTP_200_OK ) But I don't really understand what should be on the cluster. In theory the cluster should accept the incoming data from the middleware server via websockets save it and then emit some information to the client, also through the ws protocol. What I want to understand is how to accept the incoming data from … -
Django Set a Formula for field
class Strategy(models.Model): name = models.CharField(max_length=30, unique=True) class Line(models.Model): strategy = models.ForeignKey(Strategy,on_delete=models.CASCADE) startvalue = models.FloatField(default=0) endvalue = models.FloatField(null=True,blank=True) target = models.FloatField(default=0) alpha = models.FloatField(default=0) So, Here there will be many strategies, And for each strategy I want superuser to map an arithmetic formula for alpha in terms of startvalue, endvalue, target for example if a strategy is s1 then alpha = 100*(startvalue+endvalue*target) s2 then alpha = startvalue-endvalue*target Like this, the superuser needs to set the formula of alpha for a strategy through GUI so that all Lines with that strategy have that formula for alpha. How to implement this? Please help me, I'm stuck here for more than two days. -
Django ModelForm not saving data to database, Form.save is not working?
Hello I am django beginner having tough time could someone please help me I don't know what am I doing wrong ? I am trying to create a form and saving some data through it by using form.save(). And I am new to here also so don't mind any mistakes. Here is my model: from django.db import models from stores.models import Store class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) def __str__(self): return self.name class Product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) price = models.DecimalField(max_digits=5, decimal_places=5) image = models.ImageField() category = models.ForeignKey(Category, default='Default', on_delete=models.CASCADE, blank=False, null=False) store = models.ForeignKey(Store, on_delete=models.CASCADE, blank=False, null=False) Here is my view: from django.shortcuts import render, redirect from .forms import NewPro def pro(request): form = NewPro() if request.method == 'POST': form = NewPro(request.POST) if form.is_valid(): form.save() return redirect('stores_list') else: form = NewPro() return render(request, "default/add_product.html", {'form': form}) def product_list(request): return render(request, 'default/product_list.html') Here is my form: from django import forms from .models import Product class NewPro(forms.ModelForm): class Meta: model = Product fields = ('name', 'price', 'image','category', 'store',) -
Django admin add fields
I have a signup form that works great. One feature of it is users can press "Add more +" and have more identical "instrument" and "level" select fields created. The django user admin only shows the first "instrument"/"level" field under "Experience" and not the further ones created from the javascript function. How can I adjust my django admin model to create further fields when the javascript function is called? I appreciate any help I get. admin.py fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name', 'avatar', 'country', 'child_first_name')}), ('Experience', {'fields': ('instrument', 'level')}), ('Permissions', {'fields': ('student', 'parent', 'teacher', 'admin', 'staff', 'active')}), ) HTML <div> <div class="items"> <div id="ins"> <div> {{ form.instrument }} </div> <div> {{ form.level }} </div> </div> </div> <div id="add_more"> <button type="button" class="no_link" onclick="add_instrument()">Add more +</button> </div> </div> Javascript var i = 0; var original = document.getElementById('ins'); function add_instrument() { var clone = original.cloneNode(true); clone.id = "ins" + ++i; original.parentNode.appendChild(clone); } -
Django select2 dependent dropdown issues
im using Django 2.0, Django_select2 6.0.3 and Select2 4.0.6 to create two dependent list in my project. I followed this documentation to set up the codes. We are not getting any errors but the data is not showing in the fields for the autocomplete. Im trying to chain the list "Provincias" with the list "Regiones" so when you choose an option from regiones, display all the provincias in that Region. Here are my codes. Models.py class region(models.Model): region = models.CharField(max_length=200) class provincia(models.Model): region = models.ForeignKey(region, related_name="provincias", on_delete=models.CASCADE) provincia = models.CharField(max_length=200) Forms.py class Direccion(forms.ModelForm): region = forms.ModelChoiceField( queryset=region.objects.all(), label="Region", widget=ModelSelect2Widget( model=region, search_fields=['region'], dependent_fields={'provincia': 'provincias'}, ) ) provincia = forms.ModelChoiceField( queryset=provincia.objects.all(), label="Provincia", widget=ModelSelect2Widget( model=provincia, search_fields=['region__icontains'], dependent_fields={'region': 'region'}, max_results=500, ) ) comuna = forms.CharField(required=True, label='Comuna') calle = forms.CharField(required=True, label='Calle') numero = forms.CharField(required=True, label='Número') departamento = forms.IntegerField(label='Departamento') class Meta: model = direcciones fields = ('region', 'provincia', 'comuna', 'calle', 'numero', 'departamento') views.py def nuevadir(request): if request.method == 'POST': dire = Direccion(request.POST) if dire.is_valid(): dire2 = dire.save(commit=False) dire2.user = request.user dire2.region = dire.cleaned_data['region'] dire2.provincia = dire.cleaned_data['provincia'] dire2.comuna = dire.cleaned_data['comuna'] dire2.numero = dire.cleaned_data['numero'] dire2.calle = dire.cleaned_data['calle'] dire2.departamento = dire.cleaned_data['departamento'] dire2.save() return render(request, 'perfil-direccion.html') else: dir = Direccion() return render(request, 'perfil-nuevadir.html', {'dir': dir}) HTML {% load widget_tweaks %} … -
Django Admin - "Incomplete response received from application"
I've recently started a Django project - When I go to the Admin page I get an "Incomplete Response Received from Application" message. I only get this error when viewing my project from my A2 hosting domain www.educate-malawi.com. You can access the admin page at the bottom right of the home page. Is this a problem for my host or is it something that I can fix? I've tried looking for answers to this problem but everything mentions Ruby on Rails - This is not a ruby on rails project. If you need to see any of my code let me know - I can post it. -
How to use django forloop.counter0 in a math in template?
I want to use django built-in template tag forloop.counter0 in a math expression. This is I came up with: {% for category in categories %} <li class="wow fadeInUp" data-wow-delay="{{ forloop.counter0 * 0.1 }}s"> //whatever </li> {% endfor %} Which I learn is wrong cause of this error: Could not parse the remainder: ' * 0.1' from 'forloop.counter0 * 0.1' Is it anyway to solve this issue? Isn't there anyway that I could use a built-in function in a math expression? -
django.urls.exceptions.NoReverseMatch: Reverse for 'favorite' not found
Django version 2.0 views.py from django.views import generic from .models import Album class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/details.html' details.html {% extends 'music/base.html' %} {% block body %} <!-- {{album}} --> <img src="{{album.album_logo}}"> <h1>{{album.album_title}}</h1> <h3>{{album.artist}}</h3> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'music:favorite' album.id %}" method="post"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}"> <label for="song{{ forloop.counter }}"> {{ song.song_title }} {% if song.is_favorite %} <img src="http://i.imgur.com/b9b13Rd.png" /> {% endif %} </label><br> {% endfor %} <input type="submit" value="Favorite"> </form> {% endblock %} index.html {% extends 'music/base.html' %} {% block body %} {% if all_albums %} <h3>Here are all my Albums:</h3> <ul> {% for album in all_albums %} <li><a href="{% url 'music:details' album.id %}">{{ album.album_title }}</a></li> {% endfor %} </ul> {% else %} <h3>You don't have any albums</h3> {% endif %} {% endblock %} base.html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Viberr</title> {% load staticfiles %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type="text/css"> <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <nav class="navbar navbar-inverse"> … -
Why Django doesn't see the new files
I uploaded my files to the Web server but the app crashed so I looked to the Traceback and the files are not the same as the one that I have uploaded. it was the old version !! for example look to the installed app on the Traceback So I went to the setting.py on my server and this is what I have found So my question: why Django doesn't see the new files -
Facing issue in building nested URL in Django 1.11
I am trying to create a Hierarchy where in homepage user has option to select Location in their Homepage and then once they select the location they get Respective Managers from that location and next once they select the managers they get respective associate. Diagram -> (Homepage) all locations -on select specific location- > Managers - on select specific Manager- > List of associate (aligned to the manager ) Url Patterns: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<hierarchy_id>[0-9]+)/$', views.managerview, name='managerview'), url(r'(?P<associate_id>[0-9]+)/$', views.associatelist, name='associatelist'), ] Views: def index(request): all_sites = Hierarchy.objects.all() return render(request, "adash/index.html", {'all_sites': all_sites}) def managerview(request, hierarchy_id): all_managers = Hierarchy.objects.get(pk=hierarchy_id) return render(request, "adash/manager.html", {'all_managers': all_managers}) def associatelist(request, associate_id): all_logins = Hierarchy.objects.get(pk=associate_id) return render(request, "adash/associatelist.html", {'all_logins': all_logins}) Manager Html <a class="list-group-item list-group-item-action"><h5 class = "text-monospace">{{ all_managers.direct_manager }}</h5></a> Associate Html <a class="list-group-item list-group-item-action"><h5 class = "text-monospace">{{ all_logins.login }}</h5></a> currently am able to click on location and direct it to respective managers associated with that site but how to proceed to next step i.e click on manager and show list of associate. Below is my model: class Hierarchy(models.Model): site = models.CharField(max_length=250) direct_manager = models.CharField(max_length=250) login = models.CharField(max_length=250) * Note: Thank you for your time and Patience if you are not willing to … -
NoneType seems to be evaluated as True
I am having this error: File "/boo/foot/routing/models.py", line 133, in indexing contact = self.contact.get_full_name() if self.contact else '', AttributeError: 'NoneType' object has no attribute 'get_full_name' my code is: class Visit(models.Model): contact = models.ForeignKey(Contact, on_delete=models.SET_NULL, null=True, blank=True ) def indexing(self): obj = VisitIndex( meta = { 'id' : self.id }, contact = self.contact.get_full_name() if self.contact else '', ) print(obj) obj.save() and the indexing method is attached to the post_save signal: @receiver(post_save, sender = Visit) def index_post(sender, instance, **kwargs): instance.indexing() I am testing if self.contact is not falsy in order to get get_full_name()... yet, it seems even with NoneType it gets to that part. Where could the problem be?