M
M
Mikhail2018-08-17 20:08:40
Django
Mikhail, 2018-08-17 20:08:40

How not to allow the page to be saved if all fields are empty?

Good evening, you need to save if at least one field is filled, otherwise give an error, how to implement it?
Fields - Text, Audio, Video

from django.contrib import admin
from main_page.models import Page, Text, Audio, Video
# Register your models here.

class PageInline_Text(admin.StackedInline):
    model = Text
    extra = 0

class PageInline_Audio(admin.StackedInline):
    model = Audio
    extra = 0

class PageInline_Video(admin.StackedInline):
    model = Video
    extra = 0

class PageAdmin(admin.ModelAdmin):
    fields = []
    inlines = [PageInline_Text, PageInline_Audio, PageInline_Video]

admin.site.register(Page, PageAdmin)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
tema_sun, 2018-08-18
@TheMaxai

Somehow, no?

class PageAdminForm(forms.ModelForm):
    class Meta:
        model = Page
    def clean(self):
         if not list(filter(None, self.data.values())):
            msg = 'Не заполнено ни одно поле'
            self.add_error(None, msg)

class PageAdmin(admin.ModelAdmin):
    form = PageAdminForm
    fields = []
    inlines = [PageInline_Text, PageInline_Audio, PageInline_Video]

Although it won’t work this way, because Django will send the token as a minimum csrf, and something in values() will still arrive. But the idea as a whole should work.

S
SubGANs, 2018-08-17
@SubGANs

https://docs.djangoproject.com/en/2.1/topics/forms/

F
FulTupFul, 2018-08-17
@FulTupFul

At model levels add blank=True, null=True
And in forms check something like this

if request.method == 'POST:
    if request.POST:
        if request.POST['something_field']:
             something_actions...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question