Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

python - Django ModelAdmin get_form 'NoneType' object is not callable

I am trying to add a new field to ModelAdmin, but get an error:

@admin.register(FilmWork)
class FilmworkAdmin(admin.ModelAdmin):
fields = ('title', 'plot', 'ratings', 'film_creation_date', 'age_limit', 'link')
    def get_form(self, request, obj=None, **kwargs):
        form_factory = super(FilmworkAdmin, self).get_form(request, obj, **kwargs)
        form_factory.base_fields['Actors'] = forms.CharField(widget=forms.Textarea(), required=False)

The error says:

    form = ModelForm(initial=initial)
TypeError: 'NoneType' object is not callable

I do not initialise any modelform anywhere. What am I doing wrong?

question from:https://stackoverflow.com/questions/65873114/django-modeladmin-get-form-nonetype-object-is-not-callable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So I have solved the problem - one needs to create a form and a custom save method:

class MyModelForm(forms.ModelForm):

    actor = Person.objects.filter(role='actor')
    writer = Person.objects.filter(role='writer')
    director = Person.objects.filter(role='director')
    actors = forms.ModelMultipleChoiceField(widget=forms.SelectMultiple, queryset=actor, required=False)
    writers = forms.ModelMultipleChoiceField(widget=forms.SelectMultiple, queryset=writer, required=False)
    directors = forms.ModelMultipleChoiceField(widget=forms.SelectMultiple, queryset=director, required=False)

    class Meta:
        model = FilmWork
        fields = '__all__'


@admin.register(FilmWork)
class FilmworkAdmin(admin.ModelAdmin):
form = MyModelForm
    fieldsets = (
        (None, {
            'fields': ('title', 'plot', 'ratings', 'film_creation_date', 'age_limit', 'link', 'actors', 'writers', 'directors'),
        }),
    )
    def save_model(self, request, obj, form, change):
        obj.save()
        q1 = form.cleaned_data.get('actors', None)
        q2 = form.cleaned_data.get('writers', None)
        q3 = form.cleaned_data.get('directors', None)
        q1 = q1.union(q2).union(q3)
        obj.person_set.set(q1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...