How to set initial value based on current model instance - django

I am trying to create an edit form to edit current objects using Django. I am having trouble trying to get the current id of the object in order to set the initial value to the current values of the object.
I want to create an edit form that will already show the current data before the user edits a field. How do I go about doing this?
Thanks.
my forms.py:
class AddfooditemForm(forms.Form):
quantity = forms.CharField(label="Quantity")
price_per_pound = forms.CharField(label="price_per_pound")
expiration_date = forms.CharField(label="expiration_date")
price_per_item = forms.CharField(label="price_per_item")
class AddNonFooditemForm(forms.Form):
quantity = forms.CharField(label="Quantity")
price_per_item = forms.CharField(label="price_per_item")
class EditfooditemForm(ModelForm):
quantity = forms.CharField(label="Quantity")
price_per_pound = forms.CharField(label="price_per_pound")
expiration_date = forms.CharField(label="expiration_date")
price_per_item = forms.CharField(label="price_per_item")
def __init__(self, *args, **kwargs):
super(EditfooditemForm, self).__init__(*args, **kwargs)
class Meta:
model = tasks
fields = ['quantity', 'price_per_item', 'expiration_date', 'price_per_pound']
class Edit_non_food_itemForm(ModelForm):
quantity = forms.CharField(label="Quantity")
price_per_item = forms.CharField(label="price_per_item")
def __init__(self, *args, **kwargs):
super(Edit_non_food_itemForm, self).__init__(*args, **kwargs)
class Meta:
model = tasks
fields = ['quantity', 'price_per_item']
my views.py:
#csrf_exempt
def add_item(request):
if request.method == 'POST' and 'add_food_form' in request.POST:
add_food_form = AddfooditemForm(request.POST)
if add_food_form.is_valid():
# Cleaned_data
input_type = 'food'
quantity = add_food_form.cleaned_data['quantity']
price_per_pound = add_food_form.cleaned_data['price_per_pound']
expiration_date = add_food_form.cleaned_data['expiration_date']
price_per_item = add_food_form.cleaned_data['price_per_item']
foodDict = {'price_per_item': price_per_item,
'quantity': quantity,
'price_per_pound': price_per_pound,
'expiration_date': expiration_date}
foodData = pickle.dumps(foodDict)
item = items(input_type=input_type, foodData=foodData)
item.save()
return HttpResponseRedirect(reverse('backup_app.views.items_listing'))
if request.method == 'POST' and 'add_non_food_form' in request.POST:
add_non_food_form = AddNonFooditemForm(request.POST)
if add_non_food_form.is_valid():
# Cleaned_data
input_type = 'non_food'
quantity = add_non_food_form.cleaned_data['quantity']
price_per_item = add_non_food_form.cleaned_data['price_per_item']
non_foodDict = {'quantity': quantity,
'price_per_item': price_per_item}
non_foodData = pickle.dumps(non_foodDict)
item = items(input_type=input_type, non_foodData=non_foodData)
item.save()
return HttpResponseRedirect(reverse('backup_app.views.items_listing'))
else:
'add_food_form': AddfooditemForm()
'add_non_food_form': AddNonFooditemForm()
return render(request, 'backup_app/items_listing.html', {'add_food_form': add_food_form,'add_non_food_form': add_non_food_form})
#csrf_exempt
def edit_item(request, item_id):
item = items.objects.get(id=item_id)
if request.method == 'POST' and 'edit_food_form' in request.POST:
edit_food_form = EditfooditemForm(request.POST, instance=item)
if edit_food_form.is_valid():
print "valid"
# Cleaned_data
item.input_type = 'food'
quantity = edit_food_form.cleaned_data['quantity']
price_per_pound = edit_food_form.cleaned_data['price_per_pound']
expiration_date = edit_food_form.cleaned_data['expiration_date']
price_per_item = edit_food_form.cleaned_data['price_per_item']
foodDict = {'price_per_item': price_per_item,
'quantity': quantity,
'price_per_pound': price_per_pound,
'expiration_date': expiration_date}
item.foodData = pickle.dumps(foodDict)
item.save()
return HttpResponseRedirect(reverse('backup_app.views.items_listing'))
if request.method == 'POST' and 'edit_non_food_form' in request.POST:
edit_non_food_form = Edit_non_food_itemForm(request.POST, instance=item)
if edit_non_food_form.is_valid():
# Cleaned_data
item.input_type = 'non_food'
quantity = edit_non_food_form.cleaned_data['quantity']
price_per_item = edit_non_food_form.cleaned_data['price_per_item']
non_foodDict = {'quantity': quantity,
'price_per_item': price_per_item}
item.non_foodData = pickle.dumps(non_foodDict)
item.save()
return HttpResponseRedirect(reverse('backup_app.views.items_listing'))
else:
context = {
'edit_food_form': EditfooditemForm(instance=item),
'edit_non_food_form': Edit_non_food_itemForm(instance=item)
}
return render(request, 'backup_app/items_listing.html', context)

Try something like this:
forms.py:
class ChangeForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['field1', 'field2']
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ChangeForm, self).__init__(*args, **kwargs)
views.py:
# To render multiple forms, repeat the process
def account_settings(request):
change_form = ChangeForm(request.POST or None,
instance=request.user, user=request.user)
change_form_2 = ChangeForm2(request.POST or None)
if request.method == 'POST':
if change_form.is_valid():
change_form.save()
if change_form_2.is_valid():
change_form_2.save()
context = {
'change_form': change_form,
'change_form_2': change_form_2
}
return render(request, 'change_form.html', context)
That should give you the current data.
Note: Change the attributes to your needs. If you post your code, I can help you with that. However, I don't know what you're working with, but the above should be a good template to follow.
EDIT:
views.py:
#csrf_exempt
def add_item(request):
add_food_form = AddfooditemForm(request.POST or None)
add_non_food_form = AddNonFooditemForm(request.POST or None)
if request.method == 'POST':
if add_food_form.is_valid():
input_type = 'food'
quantity = add_food_form.cleaned_data['quantity']
price_per_pound = add_food_form.cleaned_data['price_per_pound']
expiration_date = add_food_form.cleaned_data['expiration_date']
price_per_item = add_food_form.cleaned_data['price_per_item']
foodDict = {'price_per_item': price_per_item,
'quantity': quantity,
'price_per_pound': price_per_pound,
'expiration_date': expiration_date}
foodData = pickle.dumps(foodDict)
item = items(input_type=input_type, foodData=foodData)
if add_non_food_form.is_valid():
input_type = 'non_food'
quantity = add_non_food_form.cleaned_data['quantity']
price_per_item = add_non_food_form.cleaned_data['price_per_item']
non_foodDict = {'quantity': quantity,
'price_per_item': price_per_item}
non_foodData = pickle.dumps(non_foodDict)
item = items(input_type=input_type, non_foodData=non_foodData)
item.save()
# This needs to be a url name
return HttpResponseRedirect(reverse('url_name_here'))
context = {
'add_food_form': add_food_form,
'add_non_food_form': add_non_food_form
}
# Make this its own template
return render(request, 'backup_app/items_add.html', context)
#csrf_exempt
def edit_item(request, item_id):
item = items.objects.get(id=item_id)
edit_food_form = EditfooditemForm(request.POST or None,
instance=item)
edit_non_food_form = Edit_non_food_itemForm(request.POST or None,
instance=item)
if request.method == 'POST':
if edit_food_form.is_valid():
item.input_type = 'food'
quantity = edit_food_form.cleaned_data['quantity']
price_per_pound = edit_food_form.cleaned_data['price_per_pound']
expiration_date = edit_food_form.cleaned_data['expiration_date']
price_per_item = edit_food_form.cleaned_data['price_per_item']
foodDict = {'price_per_item': price_per_item,
'quantity': quantity,
'price_per_pound': price_per_pound,
'expiration_date': expiration_date}
item.foodData = pickle.dumps(foodDict)
if edit_non_food_form.is_valid():
item.input_type = 'non_food'
quantity = edit_non_food_form.cleaned_data['quantity']
price_per_item = edit_non_food_form.cleaned_data['price_per_item']
non_foodDict = {'quantity': quantity,
'price_per_item': price_per_item}
item.non_foodData = pickle.dumps(non_foodDict)
item.save()
# This needs to be a url name
return HttpResponseRedirect(reverse('url_name_here'))
else:
context = {
'edit_food_form': EditfooditemForm(instance=item),
'edit_non_food_form': Edit_non_food_itemForm(instance=item)
}
# Make this its own template
return render(request, 'backup_app/items_edit.html', context)
def items_listing(request):
# Any data you want to post about the listed items
return render(request, 'backup_app/items_listing.html', {})

Related

signals post_save called twice after updating data in class base view django

So i've been stack on this problem that everytime I update my stock in orders it called twice for updating I use the class base view built in Django but in models I have a post signal which it removing the stock of the product. I already use the dispatch_uid but it's not working or any solution that I found on internet not working on my problem.
here is my class base view for updating:
class ItemQtyUpdateClassBaseView(UpdateView):
template_name = 'components/update/item.html'
form_class = ItemForm
def get_context_data(self, **kwargs):
kwargs['context_title'] = 'Update Order Qty'
return super(ItemQtyUpdateClassBaseView, self).get_context_data(**kwargs)
def form_valid(self, form):
try:
order_item = OrderModel.objects.get(pk = self.kwargs[self.pk_url_kwarg])
fetch_product = ProductsModel.objects.get(product_name = order_item.product_name)
print(fetch_product.qty)
if fetch_product.dough != None:
if int(fetch_product.dough.qty) <= 0:
messages.error(self.request, 'Not enough qty to order.')
return self.form_invalid(form)
if int(fetch_product.qty) <= 0:
messages.error(self.request, 'Not enough qty to order.')
return self.form_invalid(form)
else:
self.object = form.save()
messages.success(self.request, 'Successfully update qty.')
except Exception as e:
messages.error(self.request, e)
return self.form_invalid(form)
return super(ItemQtyUpdateClassBaseView, self).form_valid(form)
def form_invalid(self, form):
return super().form_invalid(form)
def get_queryset(self):
return OrderModel.objects.filter(pk = self.kwargs[self.pk_url_kwarg])
def get_success_url(self):
return reverse_lazy('core:createorder', kwargs = {
'typeoforder': self.kwargs['typeoforder']
})
and here is my model with signal post_save:
class OrderModel(models.Model):
date = models.DateField(auto_now = True)
invoice_no = models.ForeignKey(InvoiceModel, on_delete = models.CASCADE)
product_name = models.CharField(max_length = 150, blank = False, null = True)
price = models.DecimalField(max_digits = 10, decimal_places = 2)
qty = models.FloatField(default = 1)
class Meta:
db_table = 'orders'
ordering = ['-pk']
#receiver(post_save, sender = OrderModel, dispatch_uid='signals.ordermodel_removeqty')
def removeQty(sender, instance = None, created = False, **kwargs):
product = ProductsModel.objects.get(product_name = instance.product_name)
if product.dough != None:
dough = DoughModel.objects.get(pk = product.dough.pk)
dough.qty = abs(dough.qty - (product.qty * instance.qty))
dough.save()
else:
product.qty = abs(product.qty - instance.qty)
product.save()
You are calling save() method two times in form_valid() method :
self.object = form.save()
super(ItemQtyUpdateClassBaseView, self).form_valid(form)
You have to remove the below line from form_valid() method:
self.object = form.save()
See what form_valid(form)(Django Docs) method do:
Saves the form instance, sets the current object for the view, and
redirects to get_success_url().

Validating a formset using data from another form

I'm having to do some validation across both a form and formset. The £££ amount in the form must equal the sum of the amounts in the formset.
After a lot of Googling I found a solution where I add a custom init to the baseformset as follows:
class BaseSplitPaymentLineItemFormSet(BaseFormSet):
def __init__(self, cr=None, *args, **kwargs):
self._cr = cr
super().__init__(*args, **kwargs)
def clean(self):
if any(self.errors):
return
sum_dr = 0
for form in self.forms:
sum_dr += form.cleaned_data.get('dr')
if sum_dr != float(self._cr):
raise forms.ValidationError('The amount entered needs to equal the sum of the split payments.')
I then pass the amount value from the form when the formset is instantiated, so that the value can be used in the formset validation:
lineitem_formset = LineItemFormSet(form.data['amount'], request.POST)
This worked great for the create_new view which uses formset_factory(). This morning I wrote the update view using inline_formsetfactory(), but I now get an error:
__init__() got an unexpected keyword argument 'instance'
I only have a basic understanding of how the custom init works, so I can't find a solution to this error.
Forms.py:
class SplitPaymentForm(forms.Form):
date = forms.DateField(widget=DateTypeInput())
account = GroupedModelChoiceField(queryset=Ledger.objects.filter(coa_sub_group__type='a').order_by('coa_sub_group__name','name'), choices_groupby = 'coa_sub_group')
store = forms.CharField(required=True)
amount = forms.DecimalField(decimal_places=2)
class SplitPaymentLineItemForm(ModelForm):
ledger = GroupedModelChoiceField(queryset=Ledger.objects.all().order_by('coa_sub_group__name', 'name'), choices_groupby = 'coa_sub_group', empty_label="Ledger", required=True)
project = forms.ModelChoiceField(queryset=Project.objects.filter(status=0), empty_label="Project", required=False)
class Meta:
model = LineItem
fields = ['description','project', 'ledger','dr',]
# This init disallows empty formsets
def __init__(self, *arg, **kwarg):
super(SplitPaymentLineItemForm, self).__init__(*arg, **kwarg)
self.empty_permitted = False
class BaseSplitPaymentLineItemFormSet(BaseFormSet):
def __init__(self, cr=None, *args, **kwargs):
self._cr = cr
super().__init__(*args, **kwargs)
def clean(self):
if any(self.errors):
return
sum_dr = 0
for form in self.forms:
sum_dr += form.cleaned_data.get('dr')
if sum_dr != float(self._cr):
raise forms.ValidationError('The amount entered needs to equal the sum of the split payments.')
Views.py:
def split_payments_new(request):
LineItemFormSet = formset_factory(SplitPaymentLineItemForm, formset=BaseSplitPaymentLineItemFormSet, extra=2)
if request.method == 'POST':
form = SplitPaymentForm(request.POST)
lineitem_formset = LineItemFormSet(form.data['amount'], request.POST)
if form.is_valid() and lineitem_formset.is_valid():
q0 = JournalEntry(user=request.user, date=form.cleaned_data['date'], type="SP",)
q1 = LineItem(journal_entry=q0, description=form.cleaned_data['store'], ledger=form.cleaned_data['account'], cr=form.cleaned_data['amount'])
q0.save()
q1.save()
for lineitem in lineitem_formset:
q2 = LineItem(journal_entry=q0,description=lineitem.cleaned_data.get('description'),ledger=lineitem.cleaned_data.get('ledger'),project=lineitem.cleaned_data.get('project'),dr=lineitem.cleaned_data.get('dr'))
q2.save()
messages.success(request, "Split payment successfully created.")
return HttpResponseRedirect(reverse('journal:split_payments_show_detail', kwargs={'pk': q0.id}) )
else:
form = SplitPaymentForm(initial = {'date': datetime.date.today().strftime('%Y-%m-%d')})
lineitem_formset = LineItemFormSet()
return render(request, 'journal/split_payments_new.html', {'form': form, 'formset': lineitem_formset})
def split_payments_update(request, pk):
journal_entry = get_object_or_404(JournalEntry, pk=pk, type="SP")
lineitem = LineItem.objects.get(journal_entry=journal_entry.id, dr__isnull=True)
initial = {
'date': journal_entry.date.strftime('%Y-%m-%d'),
'account': lineitem.ledger,
'store': lineitem.description,
'amount': lineitem.cr,
}
form = SplitPaymentForm(initial=initial)
LineItemFormSet = inlineformset_factory(JournalEntry, LineItem, form=SplitPaymentLineItemForm, formset=BaseSplitPaymentLineItemFormSet, extra=0)
lineitem_formset = LineItemFormSet(instance=journal_entry)
if request.method == 'POST':
lineitem_formset = LineItemFormSet(form.data['amount'], request.POST, instance=journal_entry)
form = SplitPaymentForm(request.POST)
if lineitem_formset.is_valid() and form.is_valid():
lineitem_formset.save()
journal_entry.date = form.cleaned_data['date']
lineitem.ledger = form.cleaned_data['account']
lineitem.description = form.cleaned_data['store']
lineitem.cr = form.cleaned_data['amount']
journal_entry.save()
lineitem.save()
messages.success(request, "Split payment successfully updated.")
return HttpResponseRedirect(reverse('journal:split_payments_show_detail', kwargs={'pk': journal_entry.id}) )
return render(request, 'journal/split_payments_update.html',{'form': form, 'formset': lineitem_formset, 'journal_entry': journal_entry})
Solved. Just had to use BaseInlineFormSet.

Django queryset calling only objects belonging to User

I'm unable to figure out how to only call a queryset of items that belong to a specific User in the django forms.
dropoffs/models.py
class DropoffItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)
dropoff = models.ForeignKey('Dropoff', null=True, blank=True)
product = models.ForeignKey(Product)
location = models.CharField(max_length=120, choices=LOCATION_CHOICES, default="Customer")
def __str__(self):
return str('%s' + " " + "(" + '%s' + ")") %(self.product.title, self.product.sku)
def sku(self):
return self.product.sku
def title(self):
return self.product.title
def dropoff_id(self):
return str(self.dropoff.id)
forms.py
class AddPickupItemForm(forms.ModelForm):
dropoffitem = forms.ModelChoiceField(queryset=DropoffItem.objects.none())
class Meta:
model = PickupItem
# fields = ["product", "quantity"]
fields = ['dropoffitem']
def __init__(self, user, *args, **kwargs):
# self.request = kwargs.pop("request")
the_user = kwargs.pop('user', None)
super(AddPickupItemForm, self).__init__(*args, **kwargs)
if the_user is not None:
self.fields["dropoffitem"].queryset = DropoffItem.objects.filter(user=the_user)
views.py
def add_item_to_pickup_order(request):
request.session.set_expiry(120000)
try:
user = request.user
the_id = request.session['pickup_id']
pickup = Pickup.objects.get(id=the_id)
except:
user = request.user
new_pickup_order = Pickup(user=user)
new_pickup_order.save()
request.session['pickup_id'] = new_pickup_order.id
the_id = new_pickup_order.id
pickup = Pickup.objects.get(id=the_id)
try:
dropoffitem = DropoffItem.objects.filter(user=user)
except DropoffItem.DoesNotExist:
pass
except:
pass
form = AddPickupItemForm(request.POST, user=request.user)
if request.method == "POST":
dropoffitem_id = int(request.POST['dropoffitem'])
pickup_item = PickupItem.objects.create(pickup=pickup, dropoffitem_id=dropoffitem_id)
pickup_item.save()
return HttpResponseRedirect('%s'%(reverse('add_item_to_pickup_order')))
context = {
"pickup": pickup,
"form": form,
}
return render(request, 'pickups/create_pickup_order.html', context)
With the modifications to init, I'm getting a TypeError of: init() got multiple values for keyword argument 'user'.
Could that be because of how I'm requesting a 'session'?
class AddPickupItemForm(ModelForm):
def __init__(self,*args,**kwargs)
the_user = kwargs.pop('user',None)
super(AddPickupItemForm, self).__init__(*args,**kwargs)
if the_user is not None:
self.fields['dropoffitem'].queryset = DropOffItem.objects.filter(user=the_user)
In other words, pass your user to the form when instantiating, if you need to.

Django ModelForm returning a database error on excluded fields

Here is models.py:
class User(TimeStampedModel):
id = models.AutoField(primary_key=True)
class Shoe(models.Model):
size = models.IntegerField(help_text="The shoe\'s size", choices=sizeChoices)
user = models.ForeignKey('User', related_name='shoes')
brand = models.ForeignKey('Brand', related_name='shoes')
class Brand(models.Model):
name = models.CharField(max_length=64, choices = brandChoices)
class ShoeForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ShoeForm, self).__init__(*args, **kwargs)
self.fields['brand'].required = True
self.fields['size'].required = True
class Meta:
model = Shoe
fields = ['brand', 'size']
exclude = ['user']
views.py:
def index(request):
ShoeFormSet = modelformset_factory(Shoe, form=ShoeForm, extra=3)
NewShoeFormSet = modelformset_factory(Shoe, form=NewShoeForm)
if request.method == 'POST':
shoe_formset = ShoeFormSet(request.POST, request.FILES, prefix='shoes')
new_shoe_formset = NewShoeFormSet(request.POST, request.FILES, prefix='new_shoes')
if shoe_formset.is_valid() and new_shoe_formset.is_valid():
#do something with the cleaned data
else:
shoe_formset = ShoeFormSet(prefix='shoes')
new_shoe_formset = NewShoeFormSet(prefix='new_shoes')
return render(request, 'shoes/input_shoes.html', {
'shoe_formset': shoe_formset,
'new_shoe_formset': new_shoe_formset,
})
But I get this error: DatabaseError: no such column: shoes_shoe.user_id, which occurs on the line shoe_formset = ShoeFormSet(prefix='shoes') when the form renders. What's going wrong?

Two model forms in one view/template in Django using CBV

Can someone show the example of usage of two model forms in one view/template? The task is to process more than one form in one CBV, where model of the second form has FK to first form model, so value from select widget from first form must be processed as value for object, created in second form.
My forms looks like this:
class CompanyEditForm(ModelForm):
name = CharField(label="Наименование", required=True)
type = ModelChoiceField(queryset=CompanyTypes.objects.all(), label="Тип компании", empty_label=None, initial=3)
description = CharField(label="Описание компании", required=False, widget=forms.Textarea(attrs={'cols': 40, 'rows':3}))
www = CharField(label="WEB сайт", required=False)
class Meta:
model = Companies
fields = ('type', 'name', 'description', 'www')
class BranchEditForm(ModelForm):
name = CharField(label="Наименование офиса", required=True)
type = ModelChoiceField(queryset=BranchTypes.objects.all(), label="Тип отделения", empty_label=None, initial=1)
class Meta:
model = Branches
exclude = ('company', 'address')
class AddressEditForm(ModelForm):
postalcode = IntegerField(label="Почтовый код", required=False)
city = CharField(label="Город", required=True)
street = CharField(label="Улица", required=True)
app = CharField(label="Дом", required=True)
app_extra = CharField(label="Корпус / Строение", required=False)
comment = CharField(label="Примечание к адресу", required=False)
exclude = ('company',)
class Meta:
model = Addresses
fields = ('postalcode', 'city', 'street', 'app', 'app_extra', 'comment')
UPDATE
I wrote this mixin:
class MultiFormCreate(FormMixin, TemplateResponseMixin, View):
formconf = None
def get_form_classes(self):
form_classes = {}
for key, params in self.formconf.items():
form_classes[key] = params.formclass
return self.form_classes
def get_initial(self, classname):
inicial = {}
if 'inicial' in self.formconf[classname]:
inicial = self.formconf[classname]['inicial'].copy()
return inicial
def get_form_kwargs(self, classname):
kwargs = {'initial': self.get_initial(classname), 'prefix': classname}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
'files': self.request.FILES,
})
return kwargs
def get_forms(self):
for classname, params in self.formconf.items():
log.info("Name: %s, Params: %s" % (classname, params))
return dict(
[(classname, params['formclass'](**self.get_form_kwargs(classname))) for classname, params in self.formconf.items()])
def get(self, request, *args, **kwargs):
forms = self.get_forms()
return self.render_to_response(self.get_context_data(forms=forms))
def get_success_url(self):
if self.success_url:
url = force_text(self.success_url)
else:
raise ImproperlyConfigured(
"No URL to redirect to. Provide a success_url.")
return url
then in a view i only need to write processing in post:
class CompanyCreate(MultiFormCreate):
template_name = 'company/edit.html'
success_url = '/forbidden/'
formconf = {
'company': {'formclass': CompanyEditForm, 'inicial': {'name': "TESTNAME"}},
'branch': {'formclass': BranchEditForm},
'address': {'formclass': AddressEditForm}
}
def post(self, request, *args, **kwargs):
forms = self.get_forms()
cform = forms['company']
aform = forms['address']
bform = forms['branch']
if cform.is_valid() and aform.is_valid() and bform.is_valid():
''' Creating main form form object (by saving tthe form) '''
company_object = cform.save()
''' Creating dependant object '''
address_object = aform.save(commit=False)
branch_object = bform.save(commit=False)
''' assigning dependent fields '''
address_object.company = company_object
''' saving dependent _object_ '''
address_object.save()
''' managing another dependent fields '''
branch_object.company = company_object
branch_object.address = address_object
''' saving last object '''
branch_object.save()
return HttpResponseRedirect(self.get_success_url())
else:
forms = self.get_forms()
return self.render_to_response(self.get_context_data(forms=forms))
Code for view file :
if request.method == "POST":
company_form = CompanyEditForm(request.POST)
if company_form.is_valid():
company_object = company_form.save()
post_data = request.POST.copy()
branch_form = BranchEditForm(post_data)
branch_form.data['company'] = company_object
if branch_form.is_valid():
branch_object.save()
rest implement your business logic ..