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 :)
6 Notes/ Hide
-
keynotetis8 liked this
-
nickthejam liked this
-
alexkehayias posted this