ljq
ljq

Reputation: 25

Pass a argument to Django meta class

I can alternatively create different types of form, but that's tedious. So is it possible to pass the type to the form,then show the form accordingly? This code shows NameError: name 'review_type' is not defined

class Contest1_for_review(ModelForm, review_type):

    class Meta:

        model = Contest1

        decision = review_type + '_decision'
        comment = review_type +'comment'

        fields = [
            decision,
            comment,
        ]

Is it possible to pass a argument to meta class, like this?

Upvotes: 2

Views: 760

Answers (1)

ruddra
ruddra

Reputation: 51988

Form is a class and when its rendered in the HTML, its rendering an instance of the form class. So when passing a value to that instance, you can use its __init__ method. For example:

class Contest1_for_review(ModelForm):

    def __init__(self, *args, **kwargs):
        review_type = kwargs.pop('review_type')  # <-- getting the value from keyword arguments
        super().__init__(*args, **kwargs)
        self.fields[f'{review_type}_decision'] = forms.CharField()
        self.fields[f'{review_type}_comment'] = forms.CharField()

    class Meta:
        model = Contest1
        fields = "__all__"

Also, you need to send the value of review_type from view to form. Like this in function based view:

form = Contest1_for_review(review_type="my_value")

Or use get_form_kwargs to send the value from a Class based view. FYI: you don't need to change anything in Meta class.


Update:

From discussion in comments, OP should use forms.Form instead of ModelForm as using model form requires fields /exclude value in Meta class.

Upvotes: 1

Related Questions