Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django forms: how to use optional arguments in form class

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading