我正在为表单使用基于类的视图,但图像不在db中上传,没有显示任何错误。 这是我的models.py
class ProductCreateModel(models.Model):
user = models.ForeignKey('accounts.SellerProfileModel',
related_name='product_seller',
on_delete=models.CASCADE,editable=False)
title = models.CharField(max_length=120)
slug = models/.SlugField(max_length=255,unique=True,blank=True)
description = models.TextField(max_length=250)
orignal_price = models.DecimalField(decimal_places=2, max_digits=8)
discount = models.DecimalField(decimal_places=2,max_digits=4)
discount_price = models.DecimalField(decimal_places=2,max_digits=8)
image1 = models.ImageField(upload_to=upload_image_path,blank=True,null=True)
这是我的forms.py
from django import forms
from .models import ProductCreateModel
class ProductCreateForm(forms.ModelForm):
class Meta:
model = ProductCreateModel
fields = '__all__'
这是我的views.py
class ProductCreateView(views.LoginRequiredMixin,ActiveSellerOnlyMixin,generic.CreateView,):
template_name = 'products/create_new_product.html'
model = ProductCreateModel
form_class = ProductCreateForm
success_url = reverse_lazy('home')
def form_valid(self, form):
product = form.save(commit=False)
user = get_current_user(self.request)
image1 = form.cleaned_data['image1']
form.instance.user = request.user
return super(ProductCreateView, self).form_valid(form)
# product.save()
现在表单已成功提交,但图片为空。
答案 0 :(得分:0)
<form class="firstform" method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn default" value="Submit"> </form>
到
<form class="firstform" enctype="multipart/form-data" method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn default" value="Submit"> </form>
在html中添加enctype="multipart/form-data"
表单。
当您编写客户端代码时,当您的表单包含任何multipart/form-data
元素时,您需要知道的只是<input type="file">
。如果您想知道为什么会看到here。