R
R
Ranc582018-02-13 20:04:23
Django
Ranc58, 2018-02-13 20:04:23

How to call in django admin "Field is required"?

Hello!
How in django admin to cause a situation similar to when we try to save an instance in the admin without filling in a field that is required?
5a831a5530c55082750183.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-02-13
@Ranc58

The most correct way is to redefine the form and check the necessary condition in it:

class SomeForm(forms.ModelForm):
    class Meta:
        model = SomeModel
        fields = ['some_field', 'another_field', 'one_more_field']

    def clean(self):
        if проверка условия:
            raise forms.ValidationError('Существует инстанс модели с некоторыми параметрами!')


class SomeInline(admin.TabularInline):
    model = Book
    form = SomeForm

Or you can perform the same operation in ModelAdmin.save_formset() :
class AnotherModel(admin.ModelAdmin):
    ...

    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for instance in instances:
            if  проверка условия:
                raise forms.ValidationError('Существует инстанс модели с некоторыми параметрами!')
        ...

But not recommended.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question