使用Djang中的ImageField上载图像

2024-10-04 05:20:36 发布

您现在位置:Python中文网/ 问答频道 /正文

每次我在表单上单击提交时,我都尝试使用Django的ImageField和表单上传文件。表格有效吗返回false 所以我印刷了表单.错误 上面写着

photo2
This field is required.

photo1
This field is required.

我选择了我想要上传的图像文件,它仍然显示field is required。

这是我的设置.py

^{pr2}$

这是视图.py

 def upload(request):
 if request.method=="POST":
     prod = Product()
     form = UploadForm(request.POST, request.FILES)
     if form.is_valid():
         prod.name = form.cleaned_data.get('name')
         prod.brand = form.cleaned_data.get('brand')
         prod.material = form.cleaned_data.get('material')
         prod.color = form.cleaned_data.get('color')
         prod.price = form.cleaned_data.get('price')
         prod.discount = form.cleaned_data.get('discount')
         prod.sex=form.cleaned_data.get('sex')
         prod.photo1 = form.cleaned_data('photo1')
         prod.photo2 = form.cleaned_data('photo2')
         prod.save()
         return render(request, 'upload.html', {'form': form})
     else:
         x = form.errors
         return render(request,'upload.html', {'alert':x}, {'form': form})

 else:
     form = UploadForm
     return render(request, 'upload.html', {'form': form})

这是我的模型.py

class Product(models.Model):
    name = models.CharField(max_length=200, default='N/A')
    brand = models.CharField(max_length=50, default='N/A')
    material = models.CharField(max_length=50, default='N/A')
    color = models.CharField(max_length=20, default='N/A')
    price = models.IntegerField(default=0)
    discount = models.IntegerField(default=0)
    discountprice = models.IntegerField(default=0)
    photo1 = models.ImageField(upload_to='productphotos/')
    photo2 = models.ImageField(upload_to='productphotos/')

    Male = 'M'
    Female = 'F'
    Both = 'Both'

    Genders = ((Male, 'Male'),(Female, 'Female'), (Both, 'Both'))
    sex = models.CharField(choices=Genders, default=Male, max_length=6)

表单.py 类上载窗体(窗体.ModelForm)公司名称:

    class Meta:
        model = Product
        fields = ['name', 'brand', 'material', 'sex', 'color', 'price', 'discount', 'photo1', 'photo2']

在我的模板中 我只是在用

<div>
 {{form}}
</div>

提前谢谢你的帮助。我可以上传表单.py如果需要的话。


Tags: pyformdefault表单datagetmodelsrequest
1条回答
网友
1楼 · 发布于 2024-10-04 05:20:36

您需要在模板中提供表单标记,因为在呈现{{ form }}时不包括它:

<form action="." method="post" enctype="multipart/form-data">
    {% csrf_token %}  # if needed
    {{ form }}
</form>

当从表单中发布文件时,enctype="multipart/form-data"是必不可少的。请参见docs on forms in general和{a2}上的那些:

Note that request.FILES will only contain data if the request method was POST and the form that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

相关问题 更多 >