Django中的内联formset奇怪行为

时间:2013-11-19 09:08:47

标签: django django-forms

我正在使用带有这两个模型的Inline formset:

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)

当我在模板中调用{{form}}时,它会显示name, address and email三次,但与地址无关。怎么了?

模板代码:

<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>

1 个答案:

答案 0 :(得分:1)

您需要将“extra”传递给inlineformset

inlineformset_factory(Address, Friend, extra=MAX_ADDRESS) 

根据您的要求,额外可以是任何数字 我建议您按照以下流程使用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 }}

如果有任何问题,请告诉我。