Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send a queryset from Django views to JQuery
I want to send a JsonResponse of a queryset from Django views to JQuery but I am not getting any data from the JQuery side. This is my views file add_field_views.py : from django.http import JsonResponse def drop_down_requests(request): text = request.POST['text'] print("---->", text) from captiq.financing_settings.models import ChoiceGroup response = ChoiceGroup.objects.get(slug="Ja/Nein") output = JsonResponse(response,safe=False) print("output -", output) return output this is where I declared the URL in urls.py inorder for the Jquery to GET the data from the views : urlpatterns = [ path('my-ajax-test/', add_field_views.drop_down_requests, name='ajax-test-view'), ] then is my JQuery which is waiting for the queryset data or JSON data : window.addEventListener('load', function () { (function ($) { "use strict"; $(document).ready(function () { $("#id_depending_field").change(function (event) { console.log("am here man"); const valueSelected = this.value; $.ajax({ type: "POST", url: 'my-ajax-test/', data: { csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, text: valueSelected }, success: function callback(response) { console.log("____________", response) } }); }) }); })(django.jQuery); }); With the code above am not able to get JSON data in JQuery. What am I doing wrong here ? -
Linking two models automatically in django
I would like when i create new order to be linked to this company. now, i have to choose it manually class Company(models.Model): name = models.CharField(max_length=64) address = models.TextField(max_length=250) class Order(models.Model): company = models.ForeignKey('Company', on_delete=models.CASCADE) order_date = models.CharField(max_length=64) order_notes = models.TextField(max_length=250) -
Is Celery still necessary in Django
I'm creating a web app with Django 3.1 and there's lots of DB interactions mostly between three tables. The queries mostly use results that are recent inputs. So query1 will run and update table1, query2 will use table1 to update2 table2 and query3 will use the column updated by query2 to update other columns of table2. All these run every time users input or update info. Perhaps a visual will be clearer. query1 = Model1.objects.filter(...).annotate(...) query2 = Model2.objects.filter(...).update(A=query1) query3 = Model2.objects.filter(...).update(B=A*C) I'm beginning to worry about speed between python and PostgreSQL and can lose data when multiple users start using it same time. I read about celery and Django Asynchronous support, but it's not clear if I need celery or not. Can someone help me out here please. -
Annotating a count of a superset of fields with Django
So the setup here is I have a Post table that contains a bunch of posts. Some of these rows are different versions of the same post, which are grouped together by post_version_group_id, so it looks like something like: pk | title | post_version_group_id 1 | a | 123 2 | b | 789 3 | c | 123 4 | d | 123 so there are two "groups" of posts, and 4 posts in total. Now each post has a foreign key pointing to a PostDownloads table that looks like post | user_downloaded 1 | user1 2 | user2 3 | user3 4 | user4 what I'd like to be able to do is annotate my Post queryset so that it looks like: pk | title | post_version_group_id | download_count 1 | a | 123 | 3 2 | b | 789 | 1 3 | c | 123 | 3 4 | d | 123 | 3 i.e have all the posts with the same post_version_group_id have the same count (being the sum of downloads across the different versions). At the moment, I'm currently doing: Post.objects.all().annotate(download_count=models.Count("downloads__user_downloaded, distinct=True)) which doesn't quite work, it annotates a download_count which looks like: … -
DRF add non model fields just to update or create model instance
I have this issue at the moment with DRF. I'm recieving extra fields that the model is not using. But those values will define the fields within the model. { "file_name": "test", "file_type": "jpg", "file": basex64 file, "url_img": null } And i got this model class imageModel(models.Model): id = models.AutoField(primary_key=True) url_img = models.textField(null=False) All I need is to parse file_name and file_type to upload img to create a url_img and upload it on cloud. Is there a way to do this via DRF? -
I am downloading a file from google drive and want to save to the django model with s3 configured, how should i save it?
i mean it didn't uploaded to s3. Note this is an automation task. -
Build completed, but View Docs links broken
I have installed a local ReadTheDocs server and think I am very close to having it working. However, while the build of my documentation project says that it is complete, and I can see the generated files under the readthedocs.org/media/html/cadd-faq/latest directory, the View Docs links from the build page generate a 404 page with the following debugging information. Using the URLconf defined in readthedocs.urls, Django tried these URL patterns, in this order: ^$ [name='homepage'] ^support/ [name='support'] ^security/ ^.well-known/security.txt$ ^search/$ [name='search'] ^dashboard/ ^profiles/ ^accounts/ ^accounts/ ^notifications/ ^accounts/gold/ ^builds/ ^500/$ ^projects/ ^api/v2/ ^api/v2/docsearch/$ [name='doc_search'] ^api/v2/search/$ [name='search_api'] ^api-auth/ ^api/v3/ ^wipe/(?P<project_slug>(?:[-\w]+))/(?P<version_slug>(?:[a-z0-9A-Z][-._a-z0-9A-Z]?))/$ [name='wipe_version'] ^i18n/ ^admin/ ^media/epub(?P.)$ ^media/htmlzip(?P.)$ ^media/json(?P.)$ ^media/pdf(?P.*)$ style-catalog/$ ^media/(?P.+)$ [name='media-redirect'] ^debug/ The current path, docs/cadd-faq/en/latest/, didn't match any of these. I can manually point my browser at the URL ".../media/html/cadd-faq/latest/index.html" which redirects to ".../static/html/cadd-faq/latest/index.html" and view the sphinx generated content, so the build appears to really have succeeded. But those pages do not have the ReadTheDocs wrapping content that I would expect the View Docs button to have sent me to, so those URLs are certainly not the right ones either. That all would seem to indicate that the problem is with something in my ReadTheDocs and/or Django configuration. Any pointers to how … -
Django/Python - How to show "task" ONLY if the user is author or responsable of this task
I'm new to python and django and I need some help, please. What I'm trying to do is to only show a certain "task" if the user is responsable or author of the "task" in question. I was trying to do that with a if statement in html template: {% for task in task_list %} <h2>title - {{task.title}}</h2> {% endfor %} {% endif %} But does not return what I expected since: {% for task in task_list %} <h2>author --- {{task.author}}</h2> <h2>responsable --- {{task.responsable}}</h2> {% endfor %} Returns me the same user... I think the problem is that when I refer user.username it goes to the db and returns a query, and when I user {{task.blablabla}} its a string, I'm right? How I can fix that? models.py: title = models.CharField(max_length=50) content = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, default=User) responsable = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author", default=User) STATUS_CHOICES = [('D', 'Done'),('P','Doing'),('N','Not done')] Status = models.CharField(max_length=1,choices=STATUS_CHOICES, default='N') IMPORTANCE_CHOICES = [('H', 'High'),('M','Medium'),('L','Low')] importance = models.CharField(max_length=1,choices=IMPORTANCE_CHOICES, default='M') DEPARTAMENT_CHOICES = [('D', 'Dev'),('M','Marketing'),('H','Human Resources'),('L','Legal'),('F','Financial'),('O','Others')] departament = models.CharField(max_length=1,choices=DEPARTAMENT_CHOICES, default='M') def __str__(self): return self.title views.py def dashboard_taskapp(request): task = Task.objects.all() context = { "task_list": task, } return render(request, "task_app/task_dashboard.html", context) Thanks in advance and … -
Django Foreign Key Mismatch; Two FKs in one table, first FK works, second does not
I have a Model Form that is taking drop down inputs from 2 models for Car Make and Car Model. Car Make FK works fine but when I added the FK for Car Model it did not work, since they are essentially the same code I'm really puzzled. Below I will show the Car Make and Car Model Models, as well as a Model for Garage Inventory and it's related Model Form. Any help much appreciatted. Models.py class MotorMakes(models.Model): MotorMakeName = models.CharField(max_length=50, unique=True, default=False) def __str__(self): return self.MotorMakeName or '' def __unicode__(self): return u'%s' % (self.MotorMakeName) or '' class MotorModelsV2(models.Model): MotorMakeName = models.CharField(max_length=50, default=False,) MotorModelName = models.CharField(max_length=100, unique=True, default=False) Mkid = models.ForeignKey(MotorMakes,on_delete=models.CASCADE, default=False, null=True) Mlid = models.IntegerField(default=False, unique=True) MotorImage = models.ImageField(upload_to='Car_Pics', default='Car_Pics/default.png',blank=True) class GarageInventory(models.Model): MotorDetailRef = models.ForeignKey(MotorDetail, on_delete=models.CASCADE, null=True) GarageID = models.CharField(max_length=5, default='',) ListMake= models.ForeignKey(MotorMakes,on_delete=models.CASCADE, to_field='MotorMakeName', default=False, null=True) ListModel= models.ForeignKey(MotorModelsV2,on_delete=models.CASCADE, to_field='MotorModelName', default=False, null=True) ListSeries = models.CharField(max_length=50, default='', null=True) Title = models.CharField(max_length=100, default='', null=True) BodyType = models.CharField(max_length=25, default='', null=True) GaragePrice = models.DecimalField(max_digits=10, decimal_places=2, default='0') FuelType = models.CharField(max_length=15, default='') Colour = models.CharField(max_length=15, default='') CarEngine = models.CharField(max_length=10, default='', null=True) DoorType = models.CharField(max_length=10, default='', null=True) Year = models.CharField(max_length=10, default='', null=True) created_date = models.DateTimeField(default = timezone.now) Forms.py ##############Garage Car Input Forms############### class GarageCarForm(ModelForm): GarageID = … -
How to order queryset based on best match in django-rest-framework?
I am trying to order results of a query with parameters by number of matches. For example, let's say we have a Model: class Template(models.Model): headline = CharField(max_length=300) text = TextField() image_text = TextField(max_length=500, blank=True, null=True) tags = TaggableManager(through=TaggedItem) ... With a Serializer: class TemplateSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Template fields = (...) And a ViewSet: class TemplateViewSet(viewsets.ModelViewSet): """ API endpoint that allows Templates to be viewed or edited. """ queryset = Template.objects.all() serializer_class = TemplateSerializer def get_queryset(self): queryset = Template.objects.all() tags = self.request.query_params.getlist('tags', None) search_text = self.request.query_params.getlist('search_text', None) if tags is not None: queries = [Q(groost_tags__name__iexact=tag) for tag in tags] query = queries.pop() for item in queries: query |= item queryset = queryset.filter(query).distinct() if search_tags is not None: queries = [Q(image_text__icontains=string) | Q(text__icontains=string) | Q(headline__icontains=string) for string in search_tags] query = queries.pop() for item in queries: query |= item queryset = queryset.filter(query).distinct() What I need to do is count every match the filter finds and then order the queryset by that number of matches for each template. For example: I want to find all the templates that have "hello" and "world" strings in their text, image_text or headline. So I set the query parameter "search_text" to hello,world. Template with … -
AttributeError at /posts/create/ : 'str' object has no attribute 'set' when trying to parse hashtags from title field and save it in tags field
I am trying to parse hashtags from title field and save to tags field with a post_save signal in django. I am using django-taggit package for tags but getting this error while saving the form.save_m2m. Can someone help to solve this error? this is the link to the package: https://django-taggit.readthedocs.io/en/latest/getting_started.html signal.py def parse_hash_tags(sender, instance, created, **kwargs): post_save.disconnect(parse_hash_tags, sender=Post) instance.tags = ','.join(re.findall(r'(?:#(\w+))', instance.title)) instance.save() post_save.connect(parse_hash_tags, sender=Post) post_save.connect(parse_hash_tags, sender=Post) traceback Traceback: File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py" in dispatch 52. return super().dispatch(request, *args, **kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "C:\danny\Study\test\posts\views.py" in post 231. form.save_m2m() File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\forms\models.py" in _save_m2m 441. f.save_form_data(self.instance, cleaned_data[f.name]) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\taggit\managers.py" in save_form_data 517. getattr(instance, self.name).set(*value) Exception Type: AttributeError at /posts/create/ Exception Value: 'str' object has no attribute 'set' -
How to activate virtual envirooment for existing django project using pipenv in python 3.8
I developed a Django webapp project using Django 2.2.1 in python 3.7.2 in a pipenv version 2018.11.26 virtual environment in MacBook Air. After an unintentional update to python 3.8 using brew upgrade, there were problems to work on my webapp and launching it. I installed pipenv pip3 install pipenv, and copied and pasted project folder, and used it with an another name, deleted Pipfiles, and ran pipenv install, but there were error: ✘ Locking Failed! ERROR:pip.subprocessor:Command errored out with exit status 1: .... .... After several hours of trial and error, I found the problem is with the version of some packages in my requirements.txt. I have these packages in my project: backports.csv==1.0.7 certifi==2019.3.9 chardet==3.0.4 defusedxml==0.6.0 diff-match-patch==20181111 Django==2.2.1 django-allauth==0.39.1 django-ckeditor==5.6.1 django-crispy-forms==1.7.2 django-finalware==1.0.0 django-import-export==1.2.0 django-js-asset==1.2.2 django-recaptcha==2.0.5 et-xmlfile==1.0.1 gunicorn==19.9.0 html5lib==1.0.1 idna==2.8 jdcal==1.4 numpy==1.16.3 oauthlib==3.0.1 odfpy==1.4.0 openpyxl==2.6.1 pandas==0.24.1 Pillow==5.4.1 psycopg2==2.7.7 psycopg2-binary==2.7.7 pycparser==2.19 pyparsing==2.3.1 PyPDF2==1.26.0 Pyphen==0.9.5 python-dateutil==2.8.0 python3-openid==3.1.0 pytz==2019.1 PyYAML==3.13 reportlab==3.5.21 requests==2.21.0 requests-oauthlib==1.2.0 six==1.12.0 sqlparse==0.3.0 tablib==0.13.0 urllib3==1.24.3 webencodings==0.5.1 whitenoise==4.1.2 xhtml2pdf==0.2.3 xlrd==1.2.0 xlwt==1.3.0 The first problem was for pandas 0.24.1, and I removed its version number, then pipenv succeeded to lock but it failed to install two other packages Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Building requirements... Resolving dependencies... ✔ Success! … -
How to limit add to a model in django
How to limit add to a model in django ? i would like to create only one company on this model, only one, so if user want to add more, it s not possible. class Company(models.Model): name = models.CharField(max_length=64) address = models.TextField(max_length=250) -
How to manage python file from views.py
I am collecting data from a form. How can I pass data to a python file containing an infinite loop from views.py? How can I run this file from views.py? How can I stop this file from views.py? If I want to run many similar files(inf.py) at the same time, should I create them in a separate folder / application? Something like this : views.py: def index(request): if request.method == "POST": genform=Gen_info_form(request.POST) if genform.is_valid(): geninfomodel = GeneralInfo() geninfomodel.email = genform.cleaned_data["email"] geninfomodel.password = genform.cleaned_data["password"] geninfomodel.name = genform.cleaned_data["name"] geninfomodel.X= genform.cleaned_data["X"] geninfomodel.Y= genform.cleaned_data["Y"] geninfomodel.Z= genform.cleaned_data["Z"] geninfomodel.save() #send X, Y, Z to inf.py and execute it time.sleep(36000) #stop inf.py return HttpResponseRedirect("/") inf.py: X=#get value for variable X Y=#get value for variable Y Z=#get value for variable Z while True: X=X+Y X=X*Z -
django formset: "add" button creates form but dont display it
I have a formset rendered in template and everything works. there is only one (big) problem. When clicking on "add" button, a form gets created but does not show up. Therefore, when the user click on the "save" button to save the formset, then the second form appears with django error messages about submitting null values. I don't understand what is wrong about my code causing this issue and I have been banging my head on the wall for a while so i attach it here, hoping that someone could see where I am messing up <section class="no-padding-top no-padding-bottom"> <div class="container-fluid"> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">{% trans 'RECORD NEW SALE' %}</h1> </div> <form method="POST" class="form-validate" id="formset"> {% csrf_token %} {{ formset.management_form }} <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle row1 row2 %}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} … -
Is it possible to download Django ORM somewhere?
I really like how easy it is to create a database (models) in Django. But I do not need Django, I need a base (or ORM) to work with a very simple script (one .PY file). Can I download Django ORM? If not, is there any very similar ORM for Python? I would hate to write SQL code by hand. -
Can't get page_published signal
Following the docs found here but I'm not receiving the signal. Is there more to add? community/signals.py from wagtail.core.signals import page_published from wagtailPages.models import CommunityArticle from notification.models import Notification def notify_article_author(sender, **kwargs): print("Processing page_published signal") ... page_published.connect(notify_article_author, sender=CommunityArticle) -
No simple solution for Django multiple select field . It is Django limitation
It is really sorry that Django still can not use multiple select fields.Anyone can provide a simple solution. A simple form which will capable to take name, address and multiple select choice fields to be saved . -
Create variable in Django template
I have this in my template: {% for category in menu_categories %} {% with menu_button = "menu_"{{category}} %} <button class="button {{menu_button}}" onclick="showItem(menu_button)">{{category}}</button> {% endwith %} {% endfor %} I am trying to create a series of buttons with class name by iterating a queryset of model categories. I create a variable menu_button so that I could systematically name them, and pass the name to a JavaScript function showItem(). But I get the error 'with' expected at least one variable assignment. What am I doing wrong? Thanks. -
How can I deal with Django problem if the view function takes long time (about 4~5minutes)?
Hello it's my first time to ask question here. I'm developing websites by Django with some Machine Learning codes. But I faced a problem while designing my view function. Firstly I'll explain about how my websites works. My website page will get input url from user. And with that url our Machine Learning code will return some output data. The problem is my machine learning code needs some time to return output contents, and during that time input url page cannot do any thing without waiting for output contents of Machine learning code. I want to make user free to do anything while machine learning code is working, and how to make this possible? I'm really waiting for your answers. thanks. -
Nginx not serving django 3 through wsgi
I am trying to serve a Django 3 build from nginx through wsgi and I cannot seem to get the last stage. I can browse to the Django site by a runserver and launching the uwsgi.ini, but, when I try to browse to the site through nginx I get a 502 error (bad gateway)(firefox). If I try from a remote site it renders the nginx home page. I have a build of Apache on the same server. I had to spoof an IP and use a unique port to get them running side by side. the nginx/error.log does not register any problem. Below is the uwsgi.ini. [uwsgi] # variables projectname = website base = /opt/website/ # configuration master = true http = :8000 uid = nginx virtualenv = /opt/website/djangoprojectenv pythonpath = %(base) chdir = %(base) env = DJANGO_SETTINGS_MODULE=%(projectname).settings.pro #module = %(projectname).wsgi:application module = website.wsgi:application socket = /tmp/%(projectname).new.sock chown-socket = %(uid):nginx chmod-socket = 666 And below is the conf file from nginx/conf.d server { listen 192.168.1.220:81; server_name willdoit.com; access_log off; error_log /var/log/nginx_error.log; location / { uwsgi_pass unix:/tmp/website.sock; include /etc/nginx/uwsgi_params; uwsgi_read_timeout 300s; client_max_body_size 32m; } } The /tmp/website.sock file is owned by nginx:nginx. If there are additional details I need to post, … -
Django-Tables2 with Checkbox Prefilled Value
I am trying to pre-render checked checkboxes using django-tables2 but cannot successfully do so. This is my tables.py file. id is the field I need to store as it's used to update the database, setting the selected field to true on a form submission. How can I get the checked parameter to work with this and properly reference the selected field? class SomeTable(tables.Table): add = tables.CheckBoxColumn(accessor='id',checked='selected') class Meta: model = SomeModel template_name = "django_tables2/bootstrap.html" fields = ['name','add'] Thanks! -
Django - AttributeError: 'NoneType' object has no attribute 'pk'
In short I'm making ToDo app where user can store his todos and projects. Projects consist of todos and can be shared with other users. I'm displaying all todos and projects belonging to a user but when I try to access user todo I get: AttributeError: 'NoneType' object has no attribute 'pk' When accessing todo inside project and even todo inside someone else project everything works fine. Here's log: Traceback (most recent call last): File "C:\Users\dknapik\.virtualenvs\todo-licencjat-_Vlumx_M\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\dknapik\.virtualenvs\todo-licencjat-_Vlumx_M\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dknapik\.virtualenvs\todo-licencjat-_Vlumx_M\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\dknapik\Documents\Software\Python\lic\todo-licencjat\task\views.py", line 126, in viewtask project = get_object_or_404(Project, pk=task.project_id.pk) Exception Type: AttributeError at /task/4 Exception Value: 'NoneType' object has no attribute 'pk' view: def displayTask(request, task_pk, task): if request.method == 'GET': form = TaskForm(instance=task) return render(request, 'task/viewtask.html', {'task': task, 'form':form}) else: try: form = TaskForm(request.POST, instance=task) form.save() return redirect('currenttasks') except ValueError: return render(request, 'task/viewtask.html', {'task': task, 'form':form, 'error': 'Something went wrong'}) @login_required def viewtask(request, task_pk): task = get_object_or_404(Task, pk=task_pk) project = get_object_or_404(Project, pk=task.project_id.pk) if request.user == task.task_owner: return displayTask(request, task_pk, task) elif task.project_id and project.participant1 == request.user: return displayTask(request, task_pk, task) else: raise Http404 and … -
Django - repeatedly send API call result via websocket on events (REST Framework + Channels)
I came with a problem while integrating Django REST Framework with Django Channels. I have a viewset with retrieve (GET) method that prepares information from several different models in tricky way and sends this "complex" result to the frontend. So when client sends GET request with entity primary key to this endpoint (like /complex_entity/1) he instantly receives everything he needed. And now guys on the frontend side want to have another feature - backend should be able to send results of this complex request to the frontend each time when some of relevant underlying models were changed. Like this: browser subscribes for the changes of ComplexEntity with primary key 1 and when ComplexEntity 1 is changed (or its linked entities which is not a problem) server sends the result of this complex request via websocket. So the request can be executed many times during one websocket connection (on each model change signal). I see two intuitive ways to provide this behaviour: Good(?): somehow execute requests to this viewset retrieve method from the django itself - either by calling this method internally or by executing "loopback" HTTP request. Bad/ugly: copy all complex logic from viewset retrieve method to websocket consumer Also … -
Django model calls an API before save
I have a Django model that needs to call an external API just before saving. The API call is irreversible so I want to call it only before the DB save happens. My code looks something like this: class Model1(models.Model): some_string = models.CharField(max_length=100) class Model2(models.Model): model1 = models.OneToOneField(Model1, on_delete=models.CASCADE) num1 = models.IntegerField() num2 = models.IntegerField() api_output = models.models.JSONField() def save(self, *args, **kwargs): self.api_output = API.call_method(self.num1, self.num2, self.model1.some_string) super().save(*args, **kwargs) Model2 objects can be created from Django Admin but also from the code using Model2.objects.create(). I have 2 questions: When creating an instance of Model2 from Django Admin - if the API call fails (throws an exception) I'd like Django Admin to show a human-readable error instead of the 5xx error page. One way to do that is to have a clean() method but I don't want to call the API before the object is actually saved. Also, when using Model2.objects.create() the clean() method is not called. Is there a way to call the API inside save() and still have Django Admin print a nice error if the call fails? I noticed that during save(), if the OneToOneField constraint is violated (for example trying to create 2 instances of Model2 with …