Django fun for the night – Manipulating model-based forms

In my spare time I enjoy simple web development with Django. It’s (sort of) the background I come from and it’s seriously meditative for me. I’m in no way a developer, but typing gibberish and it coming out the other end like something you planned to do is therapeutic for me. The project I’m currently working on is an internal app that will eventually talk to some other applications where I work. Those other applications require passwords, and I don’t want to save those passwords in my database.

I already have a ModelForm object:

class meetingEventForm(forms.ModelForm):
    """
    to create a new meeting event.
    """
    class Meta:
        model = meetingEvent

But I need to get usernames/passwords for these other apps whose APIs I need to talk to!

So I did this, taken from this StackOverflow page:

class meetingEventForm(forms.ModelForm):
    """
    to create a new meeting event.
    """
    app_user = forms.CharField(null=True, blank=True, help_text="app username")
    app_pass = forms.CharField(widget=forms.PasswordInput, null=True, blank=True, help_text="app password")

    def save(self, commit=True):

        self.cleaned_data['app_user'] = 'abc1'
        self.cleaned_data['app_pass'] = 'abc2'

    super(meetingEventForm, self).save(commit=commit)

    class Meta:
        model = meetingEvent

I kept getting a weird error:

__init__ received an unexpected keyword, null

The “null=True, blank=True” in both of those forms tells Django that:

  • It’s OK for the field to be null
  • It’s OK for the database entry to be blank

So the form was passing ‘null’ into Django for the field values, and it doesn’t like that.

Once I removed ‘null=True’ it was happy and works as expected. ‘blank=True’ remained so I can leave the fields empty if someone doesn’t want to put in their username/password. Setting the cleaned_data values to nonsense is just a placeholder for where the real work to validate the form data will happen. It’s then passed back into the Django view where I can link it up to the various API’s and make my life easier.

Something to Add?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s