默认值在formset - django中不起作用



我试图为我的django内联formset设置默认值,但它只显示第一种形式,其他都是空的!

class Booking(models.Model):
admin = models.ForeignKey(User,on_delete=models.CASCADE)
takes_by = models.ManyToManyField('vistors.Vistor',through='BookingVisitor',related_name='vistors')
class BookingVisitor(models.Model):
visitor = models.ForeignKey('vistors.Vistor',on_delete=models.PROTECT,related_name='visitor_booking')
booking = models.ForeignKey(Booking,on_delete=models.PROTECT,related_name='booking_bookingvisitors')
reason = models.CharField(max_length=50,default='some text')

但它不工作!?我也试过在我的视图

initial_data = {'reason':'some text'}
VistorsInlineFormset(prefix='formset',initial=initial_data) 

但是它会抛出这个错误:

KeyError at/en/some/url0

这是form。py

class BookingVisitorForm(forms.ModelForm):
visitor = forms.ModelChoiceField(
queryset=Vistor.objects.all().order_by('-pk'),empty_label='--------',
)
class Meta:
model = BookingVisitor
fields = ['visitor','reason']
VistorsInlineFormset = inlineformset_factory(Booking,BookingVisitor,form=BookingVisitorForm,extra=1,can_delete=True)

From docs:

>>> formset = ArticleFormSet(initial=[
...     {'title': 'Django is now open source',
...      'pub_date': datetime.date.today(),}
... ])
所以你的代码应该是:
initial_data = [{'reason':'some text'},] # a list
VistorsInlineFormset(prefix='formset',initial=initial_data) 

相关内容

  • 没有找到相关文章

最新更新