Hy在那裏,我的第一個問題在這個網站上,所以很抱歉我的英語。所以我嘗試在Django框架中的模型上上傳文件。Django文件上傳使用表格
class banner(models.Model):
#id is made by Django
name = models.CharField(max_length=255)
created_by = models.CharField(max_length=255)
company = models.CharField(max_length=255)
register_date = models.DateField(auto_now_add=True)
file = models.FileField(null=True, blank=True)
file_name = models.CharField(max_length=255)
這是模型
class BannerForm(forms.Form):
name=forms.CharField(max_length=255)
created_by=forms.CharField(max_length=255)
company=forms.CharField(max_length=255)
data_type=forms.CharField(max_length=255)
register_date=forms.DateField()
file=forms.FileField()
file_name=forms.CharField(max_length=255)
這是形式
DEF add_form(請求): 形式= BannerForm() 最後= models.banner.objects.all() .last()
if request.method == "POST":
form = forms.BannerForm(request.POST, request.FILES or None)
if form.is_valid():
form.cleaned_data['created_by']
new_banner=models.banner()
new_banner.id=last.id+1
new_banner.name=form.cleaned_data['name']
new_banner.register_date=form.cleaned_data['register_date']
new_banner.company=form.cleaned_data['company']
new_banner.file=form.cleaned_data['file']
new_banner.file_name=new_banner.file.name
new_banner.created_by=form.cleaned_data['created_by']
new_banner.save()
return render(request, "add_banner.html",{"form":form})
這是view.Now每次我嘗試添加一個banner.I瀏覽文件,但我推送後,它是該文件必須選擇,就像它不識別我瀏覽到表單button.Any建議?
我忘了提:它說,提交的文件是空的。 – Unknown
你是否在表單中設置了enctype? –
我只在add_banner.html模板中擁有enctype enctype =「multipart/form-data」 – Unknown