How to manage form fields in Django dynamically in ModelAdmin?

I have a field (slug) that is “required” in the model, but you want to change the field in the ModelAdmin class so that it is optional. If the user does not fill it out, it is automatically filled in with another field (name).

class SomeModel(model.Model):
  name = model.CharField(max_length=255)
  slug = model.SlugField(unique=True, max_length=255)

I tried to do this in various ways, for example, overriding get_form () in ModelAdmin or using the ModelForm class and specifically specify the form.

class SomeModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(self.__class__, self).get_form(request, obj, **kwargs)
        form.slug.required = False
        return form

However, not a single solution worked for me. Besides manually creating the form, is there an even faster solution?

I have many such forms, and doing it manually can be tedious and difficult to maintain.

+3
source share
3 answers

Google, . ModelAdmin :

def get_form(self, *args, **kwargs):
    form = super(SomeModelAdmin, self).get_form(*args, **kwargs)
    form.base_fields['slug'].required = False
    return form

, ModelFormMetaclass, slug, .

, , - . GoogleDroid , .

+4

get_form form.fields['slug'].required .

- ModelForm.

class SomeModelForm(forms.ModelForm):
    slug = forms.CharField(required=False)

class SomeModelAdmin(admin.ModelAdmin):
    form = SomeModelForm

, super(self.__class__, self). super, , , super.

form.fields, forms.fields.

self.__class__, Python - , . , super - , , , . , , - super(SomeModelAdmin, self).

+1

, .

I could never use the get_formdo method form.fields['slug'].requiredand never understood why. However, I solved my problem by creating a new form inheriting from ModelForm.

I had to override init () to set self.fields['slug'].required = Falseafter calling the parent constructor, then override clean_slug()to change the contents of the bullet field, if necessary, by accessing self.data['slug'].

Hope this helps someone

0
source

All Articles