gpt4 book ai didi

python - Django ModelForm Imagefield 上传

转载 作者:IT老高 更新时间:2023-10-28 20:57:29 25 4
gpt4 key购买 nike

我对 Django 很陌生,在使用 ModelForm 处理图像上传时遇到了问题。我的模型如下:

class Project(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=2000)
startDate = models.DateField(auto_now_add=True)
photo = models.ImageField(upload_to="projectimg/", null=True, blank=True)

模型形式如下:

class AddProjectForm(ModelForm):
class Meta:
model = Project
widgets = {
'description': Textarea(attrs={'cols': 80, 'rows': 50}),
}
fields = ['name', 'description', 'photo']

而查看功能是:

def addProject(request, template_name):
if request.method == 'POST':
addprojectform = AddProjectForm(request.POST,request.FILES)
print addprojectform
if addprojectform.is_valid():
newproject = addprojectform.save(commit=False)
print newproject
print request.FILES
newproject.photo = request.FILES['photo']
newproject.save()
print newproject.photo
else:
addprojectform = AddProjectForm()

newProposalNum = projectProposal.objects.filter(solved=False).count()
return render(request, template_name, {'addprojectform':addprojectform,
'newProposalNum':newProposalNum})

模板是:

<form class="bs-example form-horizontal" method="post" action="">{% csrf_token %}
<h2>Project Name</h2><br>
{{ addprojectform.name }}<br>
<h2>Project Description</h2>
{{ addprojectform.description }}<br>
<h2>Image Upload</h2><br>
{{ addprojectform.photo }}<br>
<input type="submit" class="btn btn-success" value="Add Project">
</form>

谁能帮助我或者你能举个图片上传的例子吗?谢谢!

最佳答案

好的,谢谢大家。我发现自己犯了一个愚蠢的错误。我应该添加 enctype="multipart/form-data"<form>否则,它不会上传文件。

关于python - Django ModelForm Imagefield 上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19628979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com