Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django crop already loaded image (without using the input tag)
This solution lets the user crop the image when he uploads it. What I want to do is to let him do the crop on an already loaded image after clicking on a "crop" button for example. The big picture here is that the user uploads a pdf file, I convert it into images, he selects the one he wants to work on, THEN, I need him to select the Region Of interest for me to work on by cropping that selected image. Any approach on how I can do that? -
How do I get Python to execute a command the same way I run it on the command line (bash)?
I'm using Mac Mojave. I can run this command from my termianl (bash) successfully ... PATH=/Users/davea/Documents/workspace/starter_project/selenium/dev/:$PATH selenium-side-runner -c "goog:chromeOptions.args=[--headless,--nogpu] browserName=chrome" /tmp/81a312ad-8fe1-4fb0-b93a-0dc186c3c585.side I would like to run this from Python (3.7)/Django, so I wrote the below code SELENIUM_RUNNER_CMD = "/usr/local/bin/selenium-side-runner" SELENIUM_RUNNER_OPTIONS = 'goog:chromeOptions.args=[--headless,--nogpu] browserName=chrome' SELENIUM_WORKING_DIR = "/Users/davea/Documents/workspace/starter_project/selenium/" SELENIUM_DRIVER_PATH = "/Users/davea/Documents/workspace/starter_project/selenium/dev" ... def execute_selenium_runner_file(file_path): print("runner cmd:" + settings.SELENIUM_RUNNER_CMD) new_env = os.environ.copy() new_env['PATH'] = '{}:' + settings.SELENIUM_DRIVER_PATH + ':/usr/local/bin'.format(new_env['PATH']) out = Popen([settings.SELENIUM_RUNNER_CMD, "-c", settings.SELENIUM_RUNNER_OPTIONS, file_path], cwd=settings.SELENIUM_WORKING_DIR, env=new_env, stderr=STDOUT, stdout=PIPE) t = out.communicate()[0], out.returncode return t But when running through Python, the process dies with the following error ... Running /tmp/c847a3ce-c9f2-4a80-ab2a-81d9636c6dab.side Error: spawn find ENOENT at Process.ChildProcess._handle.onexit (internal/child_process.js:248:19) at onErrorNT (internal/child_process.js:431:16) at processTicksAndRejections (internal/process/task_queues.js:84:17) The exit code is "1". I'm not clear on what I need to do to get Python to execute my command line the same way I'm able to run it the same way I do through bash. Any advice is appreciated. -
How to override Model.delete() so that no cascade deletion ever happens for an instance?
I need to customize a Model.delete() so that it doesn't perform any cascade deletes and instead raises an exception if there are any objects that reference the instance. It seems the default implementation doesn't allow to skip the deletion of related objects: def delete(self, using=None, keep_parents=False): using = using or router.db_for_write(self.__class__, instance=self) assert self.pk is not None, ( "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname) ) collector = Collector(using=using) collector.collect([self], keep_parents=keep_parents) return collector.delete() How can I make sure Django doesn't cascade delete any related objects? -
How to update the total score in a trivia game backend efficiently?
I am trying to implement a trivia game backend in Django. I have several models but I will mention two of them which are Score and Player. Here is the important part of Player: class Player(BaseModel, AbstractUser): overall_score = models.PositiveIntegerField(default=0) class Meta: ordering = ['-overall_score'] and here is the important part of Score: class Score(BaseModel): score = models.PositiveSmallIntegerField() player = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='scores') def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.player.overall_score += self.score There are other fields in Score and Player but I did not mention them. What I am trying to do is letting the player to solve a quiz, and after saving the single quiz score to the database, I want to calculate the all-the-time overall score which is the sum of all of his scores. It is just a sum, not an average. Is my implementation of save method correct? I am afraid that the saving procedure will fail for any reason, but the overall_score would be already updated. Also, I am afraid that if I used aggregation, it will not be an efficient way because every time the user will access the leaderboard, the sum will be calculated which can be avoided by saving the sum so … -
django extending Abstract User, not allowing non-unique username
I have a model like so: class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I am creating multiple instances of User, without passing a username. I am hitting this error: def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: return self.cursor.execute(sql) else: return self.cursor.execute(sql, params) django.db.utils.IntegrityError: duplicate key value violates unique constraint "app_user_username_key" DETAIL: Key (username)=() already exists. How do I fix this? -
periodic task on user using celery or iterate all users with celery beat
I want to perform certain operations on the Django "User" model once the last time since logging in is more than 60 days. I want to know what is the best practice for these kinds of operations. I thought of the following: 1- when the user logs in I start a Celery task that activates after 60 days to do the operation from datetime import datetime, timedelta send_date = datetime.utcnow() + timedelta(days=2) email_user.apply_async([user], eta=send_date) 2- set up a Celery Beat task that runs everyday at a certain time and iterate over all the users in the database to check every user's last login time and if the last login time is > 60 the perform the operation users = User.objects.all() for user in users: email_user(user) first method would cause too many tasks to be open at the same time and I don't know what would happen in case of system failures will the tasks remain or not? and the second method would iterate all the users in the DB everyday but it will be only 1 task I am not sure which way is the best or if there is a 3rd better way. -
Django newly created instance - DateTime field is type 'str'
I am using Django 2.2.3 and Celery 4.3.0 One of my celery tasks creates a new instance of one of my django models and saves it. After I have saved that new instance, if i access one of the fields of the saved instance called DateTimeStamp which is a DateTimeField, the value returned is a string object. However, if i return the same instance from the database, the value of DateTimeStamp is a datetime.datetime object. my model in models.py: class StgAvailabilityConfirmation(models.Model): ServiceType = models.CharField(max_length=50) ContractID = models.CharField(max_length=20) Confirmation = models.CharField(max_length=8) FileReason = models.CharField(max_length=200, blank=True, null=True) DateTimeStamp = models.DateTimeField() status = models.TextField(null=True, blank=True) the code in django_tasks.py (where top_level_record is a dictionary new_instance = target_model(**top_level_record) new_instance.save() print(top_level_record) print(new_instance.pk) created_instance = target_model.objects.get(pk=new_instance.pk) print(new_instance.DateTimeStamp) print(type(new_instance.DateTimeStamp)) print(created_instance.DateTimeStamp) print(type(created_instance.DateTimeStamp)) output from worker: [2019-07-24 14:27:32,670: WARNING/ForkPoolWorker-16] {'ServiceType': 'STOR_FLEXIBLE', 'ContractID': '35.41', 'Confirmation': 'ACCEPTED', 'DateTimeStamp': '2018-07-25T13:01:00.000'} [2019-07-24 14:27:32,670: WARNING/ForkPoolWorker-16] 62 [2019-07-24 14:27:32,693: WARNING/ForkPoolWorker-16] 2018-07-25T13:01:00.000 [2019-07-24 14:27:32,693: WARNING/ForkPoolWorker-16] <class 'str'> [2019-07-24 14:27:32,693: WARNING/ForkPoolWorker-16] 2018-07-25 13:01:00+00:00 [2019-07-24 14:27:32,693: WARNING/ForkPoolWorker-16] <class 'datetime.datetime'> What is the cause of this behaviour? -
why this variable(userinfo.user.addinfo) is not defined in react graphql?
I want to get information about addinfo of user. if i coding { userinfo(token: "token") { user { id addinfo } } } in 127.0.0.1:8000/graphql, i get the data like that { "data": { "userinfo": { "user": { "id": "4", "addinfo": false } } } } but below code show me user is undefined. console.log(userinfo) show me the correctly data. export default () => { const { data: { isLoggedIn } } = useQuery(QUERY); const { data: { userinfo } } = useQuery(Addinfo_QUERY, { variables: { token: localStorage.getItem("jwt") } }); return ( <React.Fragment> {console.log(userinfo.user.addinfo)} <HashRouter> <AppPresenter isLoggedIn={isLoggedIn} addinfo={addinfo} /> </HashRouter> </React.Fragment> ); }; why user is not defined? i cannot understand. -
Dynamically update form_list to point to some subclass(known at run time only) for a step, and render that form
I have a scenerio where the forms to be used for steps are known at runtime only. Currently, form_list is static for every step. But in the updated requirements, Each step has some runtime logic to determine the corresponding form_class. I was thinking of a way to update the form_list dynamically. I have tried overriding get_form_list, which uses the runtime logic to determine the form, and modifies form_list accordingly. urls.py named_forms = views.FormView.form_list contact_wizard = views.FormView.as_view(named_forms, url_name=<the url name>, done_step_name='finished') url-patterns = [ path('path', contact_wizard, name='form1') ] Wizard class FormView(NamedUrlSessionWizardView,): form_list = ( //static one ("step-one", FormStepOne), ("step-two", FormStepTwo), ("step-three", FormStepThree), ) def get_form_list(self): //updates form_list according to some logic self.form_list = OrderedDict() self.form_list["step-one"] = self.integration_class.step_one_form_class self.form_list["step-two"] = self.integration_class.step_two_form_class self.form_list["step-three"] = self.integration_class.step_three_form_class return super().get_form_list() Form_list is getting updated correctly,but the form is not getting rendered according to the new form-list. Rendered form is getting picked up from old static form_list only. -
Django - context modified when passing to template
I have a function which return a presign url for a S3 object, and I want to use it in my template. Here is my function in views.py: def player_index(request): mpd_url = update_file.mpd_url() vtt_url = update_file.vtt_url() context = { 'mpd_url': mpd_url, 'vtt_url': vtt_url, } return render(request,'index.html',context) and here is a part of my template with context: var url = '{{ mpd_url }}'; player.vttThumbnails({ src: '{{ vtt_url }}' }); But it seems like urls doesn't match in my function and in my template: when I print it in views.py : https://realtime-video-logs.s3.amazonaws.com/test/manifest.mpd?AWSAccessKeyId=AKIAVT3T733IUIUYBBMB&Signature=ZA9mgVjXvBShKAdvjw6hgeOwC1o%3D&Expires=1563980730 and in my template : https://realtime-video-logs.s3.amazonaws.com/test/thumbs.vtt?AWSAccessKeyId=AKIAVT3T733IUIUYBBMB&amp;Signature=jqDfi15GLB77DmzrNkVn743HPdA%3D&amp;Expires=1563981729 the '&' is replace by ';' and I don't understand why. -
recognizing template file names in PyCharm
When looking at a typical view in Django, there's usually an icon in the margin beside the template filename passed to render. You can also click on the string and hit "Ctrl+B" to jump to the template. I have my own methods that I pass a string defining which template to use and it'd be nice if I could have PyCharm recognize that and allow me to quickly jump to the file. Is there a way to get PyCharm to recognize that method argument as being a template filename? -
How to render a custom form in a django inline block?
I like to render a custom form in a TabularInline. On this form I want to have some custom fields which I will write to a model inside the save method. The custom form should not be assoziated to a model. I hope the following code will make it more clear: class MyInLine(admin.TabularInline): form = MyForm class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['name'] = forms.CharField(max_length=100) def save(self): # do something with name pass -
KeyError in city name
I have made an small weather web app in django & it is working properly but when a wrong city name is entered it start showing KeyError page. from django.shortcuts import render, redirect from django.contrib import messages import requests # Create your views here. #search page def search(request): return render(request, 'index.html') #forecast result page def forecast(request): c = request.POST['city'] url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=7fee53226a6fbc936e0308a3f4941aaa&units=metric'.format(c) r = requests.get(url) data = r.json() weather = { 'description': data['weather'][0]['description'], 'icon': data['weather'][0]['icon'], 'city': c.title(), 'temperature': data['main']['temp'] } print(r) return render(request, 'weather.html', {'weather': weather}) On entering wrong city name it is giving KeyError,So I want that instead of giving KeyError django will redirect it to my homepage i.e index.html with an error message below it. -
\u0000 cannot be converted to text in django/postgreSQl
i have a project with django .on the host when i want to upload an image sometime error occurred(problem with specific images)! the below show how i resize uploaded images: def save_files_to_media(request, is_public=False, klass=None, conversation=None): from apps.file.models import File fs = FileSystemStorage() file_items = {} for data_item in request.data: file_match = re.search('^fileToUpload\[(\d+)\]$', data_item) if file_match and file_match.groups(): item_index = file_match.groups()[0] if item_index not in file_items: file_items[item_index] = {} file_items[item_index]['file_to_upload'] = request.data[data_item] else: optimize_match = re.search('^optimizeType\[(\d+)\]$', data_item) if optimize_match and optimize_match.groups(): item_index = optimize_match.groups()[0] if item_index not in file_items: file_items[item_index] = {} file_items[item_index]['optimize_type'] = request.data[data_item] files = [] for file_item_key in file_items: input_file = file_items[file_item_key]['file_to_upload'] # TODO: checking validation. if input_file.name is not exist optimize_type = file_items[file_item_key].get('optimize_type') file_uuid = str(uuid4()) if is_public: orig_filename, file_ext = splitext(basename(input_file.name)) directory_name = join(settings.MEDIA_ROOT, file_uuid) filename = file_uuid + file_ext else: directory_name = join(settings.MEDIA_ROOT, file_uuid) mkdir(directory_name) filename = input_file.name filepath = join(directory_name, filename) fs.save(filepath, input_file) is_optimized = False if optimize_type == 'image': is_success, filepath = image_optimizer(filepath) filename = basename(filepath) is_optimized = is_success file_obj = File( orig_name=filename, uuid=file_uuid, md5sum=get_md5sum(filepath), filesize=get_filesize(filepath), meta=get_meta_info(filepath), is_optimized=is_optimized, creator=request.user ) if is_public: file_obj.is_public = True else: file_obj.klass = klass file_obj.conversation = conversation file_obj.save() files.append(file_obj) return files here is the error i got with … -
How do I check if users belongs to a certain model
I have models: Student, Teacher, and CustomUser. A CustomUser belongs either to student or teacher. When logged in, I want to check if the user is instance of student or teacher in the template html. I've tried the following, but it doesn't work. {% if user is a student %} <a class="dropdown-item" href="{% url 'edit_student_profile' %}">Profile</a> {% elif user is a teacher %} <a class="dropdown-item" href="{% url 'edit_teacher_profile' %}">Profile</a> {% else %} <a>Error. Go signup as teacher or student!</a> {% endif %} -
This is a number guess generator, Please help to pass arguments to checker() function
This is a program for matching out input with random number generated by a function. There are three functions, 'index()' for display the webpage, there we can input a value to check with the random number generated by rangen() , 'rangen()' for generating the random number, 'checker()' for checking the values. here I need to pass the value generated by 'rangen()' to my 'checker()' how it is possible? views.py from django.shortcuts import render from django.http import HttpResponse import random # Create your views here. def rangen(request): rannumber= random.randint(1,3) print(rannumber) return rannumber def index(request): return render(request,'generator/index.html') def checker(request): print(rannumber) if request.method=='POST': innum = int(request.POST['inputnumber']) print(innum) if (rannumber==innum): flag = 'Congratulation!!! Number Matched' return render(request,'generator/index.html',{'flag':flag}) elif(innum>rannumber): flag = 'Oops!!! You Entered a High Value, Try Again!!!' return render(request,'generator/index.html',{'flag':flag}) else: flag = 'Oops!!! You Entered a Low Value, Try Again!!!' return render(request,'generator/index.html',{'flag':flag}) index.html <div class="formclass"> <h1>Random Generator</h1> <form action="checker" method="post"> {% csrf_token %} <h3>Enter you guess</h3> <input type="text" name="inputnumber" placeholder="Enter Your Guess" required><br><br> <button type="submit" name="button">Submit</button> <h1>{{flag}}</h1> </form> </div> No errors when I run the server, but when i provide my guess value it showing ' NAME ERROR: name 'rannumber' is not defined' -
Geting a user object without using request in django signals
From my research online there are many questions related to what i am about to ask. Solutions i saw do not solve my problem because mine is related with django channels and signals . Here is a post save signal code in my consumer(channels). private chat consummer class ChatConsummer(AsyncConsumer): async def websocket_connect(self,event): await self.channel_layer.group_add( "private_chat", self.channel_name, ) data={ 'chats':data_array } def Create_Notify(sender,instance,**kwargs): data={'notificat':'notication'} notification_data={ 'notify':data, } async_to_sync(get_channel_layer().group_send)("private_chat", {"type": "Send_Message",'text':json.dumps(notification_data)}) post_save.connect(Create_Notify,sender=notifyall) So in my code, i am accessing the channel layer outside the consumer function meaning i can not use self.scope['user'] to get the current login user . I am using post_save signal function making it impossible to use request to access the current login in user . So please help me, i need to access the current login user in my post_save signal which calls channel layer out outside a channel consumer function . -
Django is ignoring filters
I am trying to create a simple "Search" feature for my e-commerce website project which has several products in its database. models.py INR='₹' USD='$' CURRENCY_LIST=[(INR,'INR'),(USD,'USD')] subcategory=models.ForeignKey(Subcategory,on_delete=models.CASCADE) category=models.ForeignKey(Category,on_delete=models.CASCADE) name=models.CharField(max_length=50) price=models.DecimalField(max_digits=8,decimal_places=2,db_column='price') currency=models.CharField(max_length=3,choices=CURRENCY_LIST,default=INR,db_column='currency') view_count=models.IntegerField(default=0) @property def combined(self): return self.price+self.currency class Meta: db_table='Products' verbose_name_plural='products' def __str__(self): return self.name serializers.py class Meta: model=Products fields='__all__' views.py def get(self,request): if request.method=="GET": search=request.query_params['search'] sort=request.query_params['sort'] start,end=request.query_params['filter'].split('-') q1=Products.objects.filter(name__icontains=search) q2=Products.objects.filter(subcategory__name__icontains=search) q3=Products.objects.filter(category__name__icontains=search) q1=q1.union(q2,q3) if sort=="low to high": q1=q1.filter(price__gte=start,price__lte=end).order_by('name','price') serializer=ProductsSerializer(q1,many=True) return JsonResponse({"response":serializer.data}) elif sort=="high to low": q1=q1.filter(price__gte=start,price__lte=end).order_by('-price','name') return JsonResponse({"response":serializer.data}) elif sort=="most popular": q1=q1.filter(price__gte=start,price__lte=end).order_by('views') return JsonResponse({"response":serializer.data}) Before the second 'if' block starts(in views.py file), I am getting correct search results. But after that, Django simply returns the same unfiltered queryset. -
Invalid connecting string when using IP adress, hostname seems not an option
Recently I transferred a Django project to a windows server with IIS. Locally on my development workstation everything runs fine. Now on the IIS server, when I'm using manage.py to locally test the site, it trows upon starting the local server an error: "django.db.utils.OperationalError: (com_error(-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for SQL Server', 'Invalid connection string attribute', None, 0, -2147467259), None)" Initially I can get it to startup by switching from IP to hostname. If I then proceed to try and browse the site I come upon the following error: "When using DATABASE PORT, DATABASE HOST must be an IP address." Due to this I'm unable to use both the host name or IP address. I've tried different drivers, different ways of creating the connection dictionary. ('ip,port', only IP, only host name) Nothing works when initiating the test server, except for when I use the port and host name. But as said above it then later on runs into a problem with a port nr expecting an IP address and not a hostname. On my dev workstation this db dictionary is working fine, the website runs and data can be accessed: 'default': { 'NAME' : 'database_name', 'ENGINE': 'sqlserver_ado', … -
Render form inside topbar in all routes
I just wanna ask about the best approach to render a form in all routes. Basically what I want is to allow users to login from anywhere within the site by putting the login form in the topbar. Currently, I have a /login/ route whose form is built-up from forms.py and rendered thru a view function. I want to redesign the login flow to the one specified above. Any suggestion would be awesome. Thanks! -
CryptoControl - Python Crypto News API Integration in Python Django
[{ "hotness": 70862.60323026273, "activityHotness": 4.601980262729618, "primaryCategory": "General", "words": 1444, "similarArticles": [ { "_id": "5b363b525b113200191a1d5f", "publishedAt": "2018-06-29T13:42:44.000Z", "title": "Op-Ed: Challenge of Mining Centralization Unveils Bitcoin’s Elegant Design", "url": "https://cryptocontrol.io/r/api/article/5b363b525b113200191a1d5f?ref=5ac11440ec0af7be35528459", "source": { "_id": "59d8c361ef8bf95cc2bfb66f", "name": "Bitcoin Magazine", "url": "https://bitcoinmagazine.com/" }, "sourceDomain": "bitcoinmagazine.com", "thumbnail": null }, { "_id": "5b3865405c5681000f2f7407", "publishedAt": "2018-06-30T14:58:00.000Z", "title": "Arbitration on a Governed Blockchain: EOS’ Crisis of Dispute Resolution", "url": "https://cryptocontrol.io/r/api/article/5b3865405c5681000f2f7407?ref=5ac11440ec0af7be35528459", "source": { "_id": "59d70be3ef8bf95cc2aa2b4f", "name": "CoinTelegraph", "url": "https://cointelegraph.com/" }, "sourceDomain": "cointelegraph.com", "thumbnail": null } ], }] -
How to filter queryset for foreign key that is inherited
I have a class A: class A(models.Model): name = models.CharField(max_length=255) class B that has a foreign key of class A: class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) then I have class C that is inherited from class B: class C(models.Model): class Meta: managed = True text = models.CharField(max_length=255) Is class C also has foreign key of class A. If it has, how can I get class A objects that satisfies certain requirements of object of class C. I tried to do something like: A.objects.filter(c_text='Hello') But it doesn't work. I can't even get right filter with Pycharm tips. -
django model to access database
Request some help from django community. Iam new to Django. My requirement is 1 - create a DRF which will execute a stored procedure in an existing database( Master data management in MS SQL database) and list down the records . 2 - further when we navigate to each record from point number 1 we display the details of the records with more fields. I have already created a function which uses pyodbc in my view.py file to achive the result and the display the values. But I have read some where that as a best practice it is always better to define a model and then a serializer to define the data structure and display them. Question : 1)Is it a correct approach to define a model for the above senario. 2) As per my knowledge when ever we create a model it creates a database table which I don't want it to be created (as I have the database already with all the necessary table and data). so if point 1 is yes then can you give reference build the model which will not create the table. 3)Further to the above requirement I like to connect multiple database … -
How to list instances in django annotate?
I'm trying to do a Django annotate and want to list some of the object instances by filtering a field. I have two model, which is Category and Article. This Category model has a field called super_category which is a choice field and the coices are "ACADEMIC, OTHER" class Category(models.Model): name = models.CharField( max_length=128, null=False, blank=False, default=None, verbose_name=_("Name"), ) super_category = models.CharField( blank=False, null=False, choices=SC_CHOICES, max_length=10, default=None, ) And now, this is my current annatation result: [ { 'article_count': 716, 'super_category': u'ACADEMIC', 'category_count': 5, }, { 'article_count': 800, 'super_category': u'OTHER', 'category_count': 2, } ] the query for this : Category.objects.only( "id", "articles__id", "super_category", ).values( "super_category", ).annotate( category_count=Count("id", distinct=True), article_count=Count("articles"), ).order_by( "super_category", ) What I wanna do is, adding the articles to the result So at the end, I want something like this: [ { 'article_count': 716, 'super_category': u'ACADEMIC', 'category_count': 5, 'categories': [ { "id": 1, "name": "COMPUTER SCIENCE", "article_count": 15, }, ... ] }, { 'article_count': 800, 'super_category': u'OTHER', 'category_count': 2, 'categories': [ { "id": 1, "name": "MAGAZINE", "article_count": 15, }, ... ] } ] Now, since the additional "categories" is the same object type which I am trying to annotate, I seriously do not know how to do it. -
Celery Worker exited prematurely: signal 9 (SIGKILL) on serializer.is_valid()
I know that there are some questions already about this topic, so I understand the general idea, but this is more specific. In some job that runs on our celery worker, we're creating a lot of objects (about 2000). Seems like every time, at some point, around the 2000th object (1700-1900) we get this error: Worker exited prematurely: signal 9 (SIGKILL) And it always seems to happen around this part of the code: serializer = ModelSerializer(data=model_data) Logger.info("serializer created") if serializer.is_valid() is True: Logger.info("serializer valid") I do see the first log, so I guess the serializer is created successfully, but I don't see the second log. And it's not that the serializer is not valid, because that case is covered as well. I just stop seeing any logs from the job after that line of code (if serializer.is_valid()). When trying to create less objects it seems fine. So my question is why would using a lot of serializer.is_valid() in one celery job cause that process killing?