Created
October 29, 2012 11:23
-
-
Save zokis/3973038 to your computer and use it in GitHub Desktop.
Django Form para Generic Relations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django import forms | |
from django.contrib.contenttypes.models import ContentType | |
from generics.models import Documento, Foto | |
class GenericRelationsForm(forms.ModelForm): | |
def __init__(self, *args, **kwargs): | |
self.obj = kwargs.pop('object', None) | |
super(GenericRelationsForm, self).__init__(*args, **kwargs) | |
def save(self, *args, **kargs): | |
is_new = self.instance.pk is None | |
commit = kargs.pop('commit', True) | |
kargs.update({'commit': False}) | |
instance = super(GenericRelationsForm, self).save(*args, **kargs) | |
if is_new: | |
instance.object_id = self.obj.pk | |
instance.content_type = ContentType.objects.get_for_model(self.obj) | |
if commit: | |
instance.save() | |
return instance | |
class FotoForm(GenericRelationsForm): | |
class Meta: | |
model = Foto | |
exclude = ['content_type', 'object_id'] | |
class DocumentoForm(GenericRelationsForm): | |
class Meta: | |
model = Documento | |
exclude = ['content_type', 'object_id'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment