Nips
Nips

Reputation: 13860

how to generate various forms in Django with one model?

I have one model and depending on the person will be able to edit fields. Example:

class myForm(forms.ModelForm):
    fieldone = forms.CharField()
    fieldtwo = forms.CharField()
    fieldthree = forms.CharField()

    class Meta:
        model = myModel
        fields = (...???...)

Person 1 can edit: fieldone Person 2 can edit: fieldone, fieldtwo Person 3 can edit: fieldone, fieldtwo, fieldthree

How to do this without creating new forms, changing only "fields" field?

Upvotes: 0

Views: 43

Answers (1)

Klaas van Schelven
Klaas van Schelven

Reputation: 2528

You could simply use a factory of some kind, for example a function, like so:

def myFormFactory(fields):
    class myForm(forms.ModelForm):
        fieldone = forms.CharField()
        fieldtwo = forms.CharField()
        fieldthree = forms.CharField()

        class Meta:
            model = myModel
            fields = fields
    return myForm

I'm not sure fields hides fields that are not in the original model as well; if not you may need to do some tweaking in the form's init based on the same parameter 'fields'

Upvotes: 1

Related Questions