Home > Back-end >  Django forms: how to use optional arguments in form class
Django forms: how to use optional arguments in form class

Time:12-05

I'm building a Django web-app which has page create and edit functionality. I create the page and edit the pages using 2 arguments: page title and page contents.

Since the edit and create code is very similar except that the edit code doesn't let you change the title of the page I want to make some code that can do both depending on the input.

This is the current code I'm using right now.

class createPageForm(forms.Form):
    page_name = forms.CharField()
    page_contents = forms.CharField(widget=forms.Textarea())

class editPageForm(forms.Form):
    page_name = forms.CharField(disabled=True)
    page_contents = forms.CharField(widget=forms.Textarea())

I know that if I wasn't using classes, but functions I could do something like this:

def PageForm(forms.Form, disabled=False):
    page_name = forms.CharField(disabled=disabled)
    page_contents = forms.CharField(widget=forms.Textarea())

PageForm(disabled=True)
PageForm(disabled=False)

That is the kind of functionality I'm looking for^^

I tried the following:

class PageForm(forms.Form):
    def __init__(self, disabled=False):
        self.page_name = forms.CharField(disabled=disabled)
        self.page_contents = forms.CharField(widget=forms.Textarea())

class PageForm(forms.Form, disabled=False):
    page_name = forms.CharField(disabled=disabled)
    page_contents = forms.CharField(widget=forms.Textarea())

Both didn't work and got different errors I couldn't get around. I was hoping someone could lead me in the right direction, since I'm not very familiar with classes.

CodePudding user response:

You can work with:

class CreatePageForm(forms.Form):
    page_name = forms.CharField()
    page_contents = forms.CharField(widget=forms.Textarea())

    def __init__(self, *args, disabled=False, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['page_contents'].disabled = disabled

and call it with:

CreatePageForm(disabled=True)

CodePudding user response:

PrintOrderDetails(orderNum: 31, productName: "Red Mug", sellerName: "Gift Shop"); PrintOrderDetails(productName: "Red Mug", sellerName: "Gift Shop", orderNum: 31);

  • Related