Django forms: how to use optional arguments in form class

Question:

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.

Asked By: Lario Sedic

||

Answers:

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)
Answered By: Willem Van Onsem

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

Answered By: Prince Raj
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.