Created
November 20, 2012 23:16
-
-
Save chriscauley/4121928 to your computer and use it in GitHub Desktop.
reverse inline form
This file contains hidden or 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
class DiabloAccountProductForm(forms.ModelForm): | |
product_name = forms.CharField(max_length=255) | |
sku = forms.CharField(max_length=255) | |
region = forms.ModelChoiceField(Region.objects.all()) | |
account_name = forms.CharField(max_length=64) | |
code = forms.IntegerField() | |
def __init__(self,*args,**kwargs): | |
initial = kwargs.pop('initial',{}) | |
instance = kwargs.get('instance',None) | |
product = getattr(instance,'product',Product()) | |
account = getattr(instance,'account',DiabloAccount()) | |
initial.update({ | |
'product_name': product.name, | |
'sku': product.sku, | |
'region': account.region, | |
'code': account.code, | |
'account_name': account.name, | |
}) | |
kwargs['initial'] = initial | |
super(DiabloAccountProductForm,self).__init__(*args,**kwargs) | |
def save(self,*args,**kwargs): | |
commit = kwargs.pop('commit',True) | |
kwargs['commit'] = False | |
obj = super(DiabloAccountProductForm,self).save(*args,**kwargs) | |
if obj.pk: | |
product = obj.product | |
account = obj.account | |
else: | |
product = Product(site_id=1) | |
account = DiabloAccount() | |
product.name = self.cleaned_data['product_name'] | |
product.sku = self.cleaned_data['sku'] | |
product.save() | |
account.code = self.cleaned_data['code'] | |
account.region = self.cleaned_data['region'] | |
account.name = self.cleaned_data['account_name'] | |
account.save() | |
obj.product = product; obj.account=account | |
if commit: | |
obj.save() | |
return obj | |
class Meta: | |
model = DiabloAccountProduct | |
fields = ('product_name','sku','region','account_name','code') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment