Reputation: 7752
I am using Inline formset with these two models:
class Address(models.Model):
STATE_CODES = (
('CA', 'California'),
('AL', 'Alaska'),
('FL', 'Florida')
)
street1 = models.CharField(max_length=128)
street2 = models.CharField(max_length=128)
city = models.CharField(max_length=48)
state = models.CharField(max_length=2, choices=STATE_CODES, default='California')
zipcode = models.IntegerField(max_length=5)
class Friend(models.Model):
name = models.CharField(max_length=30)
address = models.ForeignKey(Address)
email = models.EmailField()
form = inlineformset_factory(Address, Friend)
When I call {{form}}
in template it shows name, address and email
thrice but nothing related to address. What's wrong?
Template code:
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary" name="add_address">Submit</button>
<a href="/xcard/address_book/" role="button" class="btn btn-primary" data-toggle="modal">Cancel</a>
</form>
Upvotes: 1
Views: 139
Reputation: 9828
You need to pass "extra" into inlineformset
inlineformset_factory(Address, Friend, extra=MAX_ADDRESS)
Extra can be any number as per your requirement.
I will suggest you to follow below process to use Inline formset.
#models.py class Address(models.Model): STATE_CODES = ( ('CA', 'California'), ('AL', 'Alaska'), ('FL', 'Florida') ) street1 = models.CharField(max_length=128) street2 = models.CharField(max_length=128) city = models.CharField(max_length=48) state = models.CharField(max_length=2, choices=STATE_CODES, default='California') zipcode = models.IntegerField(max_length=5) class Friend(models.Model): name = models.CharField(max_length=30) address = models.ForeignKey(Address) email = models.EmailField() #forms.py from django import forms from .models import Address, Friend from django.forms.models import inlineformset_factory MAX_ADDRESS = 1 #updated AddressFormSet = inlineformset_factory(Address, Friend, extra=MAX_ADDRESS) #updated class UserSubmittedAddressForm(forms.ModelForm): class Meta: model = Address ------------------------------------------- view.py from django.shortcuts import render_to_response from .models import * from .forms import UserSubmittedAddressForm, AddressFormSet def submit_recipe(request): if request.POST: #processing else: form = UserSubmittedAddressForm() address_formSet = AddressFormSet(instance=Address()) # render response #template code {{ form.as_table }} {{ address_formset.as_table }}
Please let me know if any issue .
Upvotes: 1