我想更新ImageField的图像,但它不会更新,因为它一直在使用
这是我的密码
型号.py
class Product(models.Model):
pName = models.CharField(max_length = 30)
owner = models.ManyToManyField(User,blank = True)
ownerName = models.CharField(max_length = 30,blank = True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2,blank = True)
p_image = models.ImageField(upload_to='product_pics',default = 'dafault1.jpg')
p_detail = models.CharField(max_length = 200,blank = True)
p_price = models.CharField(max_length = 6,default = 0)
在视图中添加产品.py
def addproduct(request):
if request.method == 'POST':
tempUser = User.objects.get(pk = request.user.pk)
temp = request.POST.copy()
tempProduct = Product()
pro_form = ProductUpdateForm(request.POST,request.FILES)
if pro_form.is_valid():
tempProduct.pName = temp.get('product_name')
tempProduct.p_detail = temp.get('product_detail') #Detail of product
tempProduct.p_price = temp.get('product_price')
tempProduct.ownerName = tempUser.first_name #ชื่อของคนลงขาย
tempProduct.save()
tempOwner = User.objects.get(pk = request.user.pk)
tempProduct.owner.add(tempOwner)
return redirect('myshop')
else:
pro_form = ProductUpdateForm()
return render(request, 'trader/addproduct.html',{
'pro_form':pro_form
})
forms.py
class ProductUpdateForm(forms.ModelForm):
class Meta:
model = Product
fields = ['p_image']
addproduct.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Product</title>
</head>
<body>
<h1>Add Product here</h1>
<br>
<form method="post" enctype="multipart/form-data" action = "{% url 'addproduct' %}" >
{% csrf_token %}
{{ pro_form }}<br>
<label for="product_name">กรุณาใส่ชื่อสินค้า</label> <br>
<input type="text" id ="product_name" name ="product_name"><br>
<label for="product_detail">รายละเอียดของสินค้า</label> <br>
<textarea name="product_detail" id="product_detail " cols="20" rows="4"></textarea><br>
<label for="product_price">กรุณาใส่ราคาของสินค้า</label> <br>
<input type="text" id ="product_price" name ="product_price"><br>
<button type="submit" >Submit</button>
</form>
</body>
</html>
我认为我的问题是post方法是错误的,但我不知道如何解决它。多谢各位
要使用views.py中的
addproduct
函数,需要保存产品的更新图像类似这样的内容将包含在现有功能中:
我建议写代码而不是图片,这样更容易阅读
相关问题 更多 >
编程相关推荐