Alex Kehayias's Blog

  • Archive
  • RSS

How to overwrite the save of a Django form like a pro

Use the “super” function to use the save method built into the form plus the extra things you need. Example:

class DebateMediaForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(DebateMediaForm, self).__init__(*args, **kwargs)
        self.fields['image'].required = True
        self.fields['source'].label = "Image Source"
        
    class Meta:
        model = MediaContent
        fields = (
            'image',
            'source',
        )
    def save(self, user, debate):
        media = super(DebateMediaForm, self).save(commit=False)
        media.added_by = user
        media.related_debate = debate
        media.content_type = "P"
        media.save()
        return debate

This is really handy for dealing with a ModelForm where you only want to have the user fill out a couple fields, but additional background information is required. In this case I need to specify who added the media. That’s something you don’t want your users to have to fill out, but you still want the luxury of using a model form because of the beautiful built in save function. Just super that shit and move on :)

    • #django
  • 4 months ago
  • 6
  • Permalink
  • Share
    Tweet

6 Notes/ Hide

  1. keynotetis8 liked this
  2. nickthejam liked this
  3. alexkehayias posted this
← Previous • Next →

About

Blogging about hacking code, life, and music.

Me, Elsewhere

  • @alexkehayias on Twitter
  • Facebook Profile
  • Linkedin Profile

Twitter

loading tweets…

I Dig These Posts

  • Photo via marksbirch

    Every so often in my web ramblings, I come across an interesting tidbit. While not meant to be an endorsement of Automattic, I find it interesting...

    Photo via marksbirch
  • Post via franciscohui
    Some thoughts on pacing your life

    We live with contradictions. Which are okay for the most part, except when we’re not aware of them. It is a source...

    Post via franciscohui
  • Photoset via lifeandcode

    hasablog:

    GitHub stickers! Awesome gift :]

    Photoset via lifeandcode
  • Photo via franciscohui

    skewed. (via Porca Miseria)

    Photo via franciscohui
See more →
  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr