How to conditionally call django admin add_view

I need to display more error information when there is an integrity error. currently i have

def save_model(self, request, obj, form, change):
try:
    if not change:
        instance = MyModel(user=request.user)
        instance.some_field = form.cleaned_data.get('some_field')
        """ save logic """
        instance.save()
except IntegrityError:
    messages.set_level(request, messages.ERROR)
    messages.error(request, 'some-msg')

IntegrityError occurs when the same user tries to insert the same value in some_field

This works but the user is taken to the change_list page. Client now wants me to set it up in such a way that the error message is shown in the add_view itself.

I tried setting up a custom change_form.html and passing in a variable in extra_context for add_view but i am getting recurssion error.

change_form.html

{% extends "admin/change_form.html" %}
{% load i18n admin_urls static admin_list %}

{% block content %}
{% if integrity_error %}
    {{ integrity_error }}
{% endif %}
  {{ block.super }}
{% endblock %}

admin.py

def save_model(self, request, obj, form, change):
try:
    if not change:
        instance = MyModel(user=request.user)
        instance.some_field = form.cleaned_data.get('some_field')
        """ save logic """
        instance.save()
except IntegrityError:
    extra_context = {'integrity_error': 'some-msg'}
    return self.add_view(request, form_url='',extra_context=extra_context}

But this gives me RecursionError

I have no idea how to solve this. Help is appreciated. if there is a more elegant way to do this please do teach me.

To add more details. this is a complete separate admin site that only a select client can access. I extended the admin.AdminSite to create this.

For situations such as this, I rely upon the official Django docs:

The admin’s recommended use is limited to an organization’s internal management tool. It’s not intended for building your entire front end around.

and

If you need to provide a more process-centric interface that abstracts away the implementation details of database tables and fields, then it’s probably time to write your own views.

So, to answer your direct question:

Create your own views for this process. It’s really not that hard if you build them around the generic CBVs.

1 Like