我有我的表格GoodGet:
class GoodGet(forms.ModelForm):
class Meta:
model = Good_Get
Size = forms.ModelChoiceField(queryset = Good.objects.all())
fields = '__all__'
widgets = {
'Name': forms.TextInput(attrs = {'type': 'hidden'}),
}
def __init__(self, *args, good_id1=None, **kwargs):
super(forms.ModelForm, self).__init__(*args, **kwargs)
if good_id1 is not None:
obj = Good.objects.filter(id = good_id1)
for good in obj:
good_sizes = good.Size.all()
self.fields['Size'].queryset = good_sizes
我使用views.py中的模型“ Good”的数据初始化了此表单:
class Adding(View):
def get(self, request, good_id):
good = Good.objects.filter(id = good_id)
good1 = Good.objects.get(id = good_id)
form = GoodGet(initial = {'Photo': good1.Photo, 'Name': good1.Name, 'Price': good1.Price}, good_id1 = good_id)
return render(request, 'HiPage/add_to_cart.html', context = {'form': form, 'good': good})
def post(self, request, good_id):
good1 = Good.objects.get(id = good_id)
form = GoodGet(request.POST, initial = {'Photo': good1.Photo, 'Name': good1.Name, 'Price': good1.Price}, good_id1 = good_id)
if form.is_valid():
form.save()
return redirect('/cart')
good = Good.objects.filter(good_id1 = good_id)
return render(request, 'HiPage/add_to_cart.html', context = {'form': form, 'good': good})
CharFields“名称”和“价格”保存到数据库中,但不保存到ImageField“照片” ...在现场我可以看到,因此初始化工作很好
但是,当我单击“提交”时,除了“照片”以外的所有内容都已保存。 我该如何解决?
如果需要,可以对“ Good”和“ Good_Get”进行建模:
class Good(models.Model):
Name = models.CharField(max_length = 150)
Type = models.ForeignKey('Type', on_delete=models.CASCADE, null=True)
Available = models.CharField(max_length = 50)
Photo = models.ImageField(upload_to = 'clothes_photos')
Price = models.IntegerField(default = '0')
Discount = models.IntegerField(default = '0')
Size = models.ManyToManyField('Size')
def __str__(self):
return self.Name
class Good_Get(models.Model):
Size = models.ForeignKey(Size, on_delete=models.CASCADE, null=True)
Name = models.CharField(max_length = 150, default = " ")
Photo = models.ImageField(default = " ")
Price = models.CharField(max_length = 10, default = '0')
def __str__(self):
return str(self.Size)