django formset初始数据未来

时间:2012-02-04 12:22:58

标签: django

这是我的模特:

class Member(models.Model):
    profile = models.OneToOneField(Profile, editable=False, null=True)
    title = models.CharField(max_length=4, choices=TITLE_TYPES, null=True)
    name = models.CharField(max_length=100, null=True, verbose_name='Name') 
    lastname = models.CharField(max_length=100, null=True, verbose_name='LastName') 
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True, verbose_name='Gender') 
    dob = models.DateField('dob')
    redressno = models.CharField(max_length=100, null=True, verbose_name='RedressNo') 

这是我的表格

class MemberForm(ModelForm):
  dob = forms.DateField(required=False, input_formats=('%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y'))
  class Meta:
    model = Member
    exclude = ('profile',)    

这是我的观点:

     members = Member.objects.filter(profile=profiles)
data1 = serializers.serialize( "python", members)
        print data1[0]['fields']
        memarr=[] 
        for index, a in enumerate(data1):
          memarr.append(a['fields'])
        print memarr
        MemberFormSet = formset_factory(MemberForm, formset=BaseFormSet)    
        member_formset = MemberFormSet(initial=memarr)
        #here setting intial array of mem 
        mdata['form-TOTAL_FORMS']=u'2'
        mdata['form-INITIAL_FORMS']=u'0'
        mdata['form-MAX_NUM_FORMS']=u''

        member_formset = MemberFormSet(mdata)

        memberform = MemberForm(mdata)

    c = {'form': form, 'memberform': memberform, 'member_formset': member_formset}
    c.update(csrf(request))
    return render_to_response('edit_profile.html', c, RequestContext(request))

m传递初始数据但仍然没有在表格中显示初始数据?

1 个答案:

答案 0 :(得分:4)

这是你的问题:

member_formset = MemberFormSet(initial=memarr)
...
member_formset = MemberFormSet(mdata)

您正在一个FormSet实例上设置初始数据,然后使用初始数据丢弃该实例并使用另一个新的FormSet实例进行覆盖。

您可以简化您的观点:

# If you are not using csrf middleware, use this decorator instead of ghetto magic
@csrf_protect
@render_to('edit_profile.html') # handy decorator from django-annoying
def profile_members_edit(request.profile):

    members = Member.objects.filter(profile=profiles)

    # iterate over the ValuesQuerySet gives a list of dicts for initial data
    member_data = list(members.values())

    # setting extra=<> and max_num=<> is easier than setting internal form data
    MemberFormSet = formset_factory(MemberForm, formset=BaseFormSet, extra=2)

    member_formset = MemberFormSet(initial=member_data)

    return {'member_formset': member_formset }