尝试使用模型 formset 工厂保存得到 'list' 对象没有属性 'event'
Trying to save with model formset factory getting 'list' object has no attribute 'event'
我正在尝试通过 Django 保存相关的模型字段 model_formset
但它给了我这个错误:
AttributeError at /events/event/52/detail
'list' object has no attribute 'fields'
有没有人遇到过这个,知道怎么解决?谢谢。
查看
def event_detail(request, pk):
event = get_object_or_404(Event, pk=pk)
TicketFormSet = modelformset_factory(Ticket,
exclude=('event',),
extra=1, max_num=3)
if request.method == 'POST':
ticket_form = TicketFormSet(request.POST)
if ticket_form.is_valid():
ticket_obj = ticket_form.save(commit=False)
ticket_obj.event = event
ticket_obj.save()
else:
ticket_form = TicketFormSet()
return render(request, 'events/event/event_detail.html',
{'event': event, 'formset': ticket_form})
型号
class Ticket(models.Model):
event = models.ForeignKey(Event, on_delete=models.CASCADE)
name = models.CharField(max_length=120)
quantity = models.SmallIntegerField()
price = models.FloatField()
def __str__(self):
return '{} {}'.format(self.event.name, self.name)
表单集创建了对象的列表,因此ticket_form
是一个列表,而不是模型实例。您需要为列表中的每个项目设置 event
。
但您应该使用 inline formset,它会自动执行此操作:
TicketFormSet = inlineformset_factory(Event, Ticket,
exclude=('event',),
extra=1, max_num=3)
if request.method == 'POST':
ticket_form = TicketFormSet(request.POST, instance=event)
if ticket_form.is_valid():
ticket_form.save()
我正在尝试通过 Django 保存相关的模型字段 model_formset
但它给了我这个错误:
AttributeError at /events/event/52/detail
'list' object has no attribute 'fields'
有没有人遇到过这个,知道怎么解决?谢谢。
查看
def event_detail(request, pk):
event = get_object_or_404(Event, pk=pk)
TicketFormSet = modelformset_factory(Ticket,
exclude=('event',),
extra=1, max_num=3)
if request.method == 'POST':
ticket_form = TicketFormSet(request.POST)
if ticket_form.is_valid():
ticket_obj = ticket_form.save(commit=False)
ticket_obj.event = event
ticket_obj.save()
else:
ticket_form = TicketFormSet()
return render(request, 'events/event/event_detail.html',
{'event': event, 'formset': ticket_form})
型号
class Ticket(models.Model):
event = models.ForeignKey(Event, on_delete=models.CASCADE)
name = models.CharField(max_length=120)
quantity = models.SmallIntegerField()
price = models.FloatField()
def __str__(self):
return '{} {}'.format(self.event.name, self.name)
表单集创建了对象的列表,因此ticket_form
是一个列表,而不是模型实例。您需要为列表中的每个项目设置 event
。
但您应该使用 inline formset,它会自动执行此操作:
TicketFormSet = inlineformset_factory(Event, Ticket,
exclude=('event',),
extra=1, max_num=3)
if request.method == 'POST':
ticket_form = TicketFormSet(request.POST, instance=event)
if ticket_form.is_valid():
ticket_form.save()