我有一个ModelForm的HTML视图,我正在尝试使用一个名为scanner_input
的单独用户输入,在其上运行一些代码,然后用代码I中的结果替换request.post['product_id']
刚跑了
Everywhere I look,它说同样的事情,使用.copy()可以使request.post对象可变,但我收到以下错误消息:< / p>
'SerialInstanceForm' object does not support item assignment
从我看来,此行中出现错误:
post['product_id'] = scanner_input_list[i]
以下是我的观点:
def SerialMulti(request):
if request.method == "POST":
form = SerialInstanceForm(request.POST)
if form.is_valid():
scanner_input = request.POST['scanner_input']
scanner_input_list = scanner_input.splitlines()
for i in range(0, len(scanner_input_list)):
post = SerialInstanceForm(request.POST.copy())
post['product_id'] = scanner_input_list[i]
post.save()
return render(request, 'serial_multi.html', {'form': form})
else:
form = SerialInstanceForm()
return render(request, 'serial_multi.html', {'form': form})
我的模特:
class ProductSerialInstance(models.Model):
STATUS_CHOICES = (
('in_inventory', 'In Stock'),
('given_out', 'Given Out'),
('repair', 'Repair')
)
name = models.ForeignKey(ProductSerial)
employee = models.ForeignKey(Employee, blank=True, null=True)
it_dep = models.ForeignKey(ItDep)
product_id = models.CharField(max_length=50)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
我的表格:
class SerialInstanceForm(forms.ModelForm):
# duplications = forms.IntegerField()
class Meta:
model = ProductSerialInstance
fields = ['name','employee','it_dep','status']
答案 0 :(得分:1)
根据您的说法,我根据自己的想法编辑了您的观点, 我不知道这项工作是否成功,但肯定能帮助你理解一些事情。
您不需要发出request.POST可变,以获取数据。
def SerialMulti(request):
if request.method == "POST":
form = SerialInstanceForm(request.POST)
if form.is_valid():
scanner_input = request.POST.get('scanner_input')
scanner_input_list = scanner_input.splitlines()
for i in range(0, len(scanner_input_list)):
#edited here to make multiple instances save.
post = ProductSerialInstance.objects.create(**form.cleaned_data)
post.product_id = scanner_input[i]
post.save()
return render(request, 'serial_multi.html', {'form': form})
else:
form = SerialInstanceForm()
return render(request, 'serial_multi.html', {'form': form})