我正在尝试为包含ImageField的模型建立CreateView。我可以从django管理页面成功上传和显示图像。但是,当我从我自己的表单上传图片时,django不会上传图片到"upload_to“文件夹。我写了下面的代码:
models.py
from django.db import models
class Album(models.Model):
title = models.CharField(max_length=127)
artist = models.CharField(max_length=63)
release_date = models.DateField()
logo = models.ImageField(blank=True, upload_to='album_logos', default='album_logos/no-image.jpg')
def __str__(self):
return self.titleforms.py
from django import forms
from .models import Album
class AlbumCreateForm(forms.ModelForm):
class Meta:
model = Album
fields = [
'title',
'artist',
'release_date',
'logo'
]views.py
class AlbumCreateView(CreateView):
form_class = AlbumCreateForm
template_name = 'music/album_create.html'
success_url = '/albums/'album_create.html
{% extends 'base.html' %}
{% block content %}
<form method="post">{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create</button>
</form>
{% endblock %}当我尝试使用"album_create.html“创建相册并使用django的默认表单上传图像时,徽标图像不会上传到"album_logos”文件夹,而是采用默认值。我哪里做错了?
发布于 2017-12-14 05:14:23
我按照django文档中的说明,通过为“album_create.html”标记指定"enctype“属性来更改表单,我的问题就解决了。
文档
forms.py
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()处理此表单的视图将接收request.FILES格式的文件数据,这是一个字典,其中包含表单中每个FileField (或ImageField或其他FileField子类)的键。因此,上述表单中的数据将作为request.FILES‘’file‘进行访问。
请注意,只有当请求方法是POST,并且发出请求的的属性为enctype=“request.FILES /form- data”时,表单才会包含数据。否则,request.FILES将为空。
更新了album_create.html
{% extends 'base.html' %}
{% block content %}
<form method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create</button>
</form>
{% endblock %}发布于 2017-12-13 02:04:45
这可能会对你有帮助
from django.utils.safestring import mark_safe
class PictureWidget(forms.widgets.Widget):
def render(self, name, value, attrs=None):
html = Template("""<img src="$link"/>""")
return mark_safe(html.substitute(link=value)
class AlbumCreateForm(forms.ModelForm):
logo = ImageField(widget=PictureWidget)
class Meta:
model = Album
fields = [
'title',
'artist',
'release_date',
'logo'
]在表单标签中添加并添加此属性
enctype=“多部分/表单数据”
https://stackoverflow.com/questions/47778667
复制相似问题