我尝试使用数据上传来执行仪表板。上传时我没有收到任何错误,新产品已保存,但没有图像。 下面是代码。 如何解决?
模型:
class Product(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
rating = RatingField(range=5) # 5 possible rating values, 1-5
photo = models.ImageField(verbose_name=u'Photo', upload_to="product_pic", blank=True)
形式:
class Addproduct(forms.ModelForm):
class Meta:
model = Product
html的
<form action="/addproduct/" method="post">{% csrf_token %}
{{ form.non_field_errors }}
<div class="inputBloc">
<p>
{{form.name.errors}}
<label class="txtField" for="id_subject">Product name:</label>
{{ form.name }}
</p>
<p>
{{form.slug.errors}}
<label class="txtField" for="id_subject">Slug:</label>
{{ form.slug }}
</p>
<p>
{{form.photo.errors}}
<label class="txtField" for="id_subject">Product photo:</label>
{{ form.photo }}
</p>
</form>
设定:
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
views.py
def ProductsAll(request):
products = Product.objects.all().order_by('name')
context = {'products': products}
return render_to_response('productsall.html', context, context_instance = RequestContext(request))
def SpecificProduct(request, productslug):
product = Product.objects.get(slug = productslug)
context = {'product': product}
return render_to_response('specificproduct.html', context, context_instance = RequestContext(request))
答案 0 :(得分:2)
您需要将enctype="multipart/form-data"
添加到html模板中的表单定义。
答案 1 :(得分:1)
method="POST"
代码中使用form
。enctype="multipart/form-data"
代码中使用form
。upload_to
目录(使用admin上传文件)。MyForm(request.POST, request.FILES)
。