python - TypeError 试图在 django 中使用 ImageField 上传图像
问题描述
我在尝试使用 ImageField 上传图像时收到此错误:
TypeError at /admin/article/articulo/7/change/
not all arguments converted during string formatting
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/article/articulo/7/change/
Django Version: 2.1.5
Exception Type: TypeError
Exception Value:
not all arguments converted during string formatting
Exception Location:
C:\Users\HOME\ProyectosDjango\weMarket\apps\article\models.py in
upload_location, line 6
这是带有 ImageField 的 models.py 的一部分:
def upload_location(instance, filename):
return "static/img/" %(instance.id, filename)
class Articulo(models.Model):
...
nombre_imagen=models.ImageField(upload_to=upload_location,
null=True, blank=True,
width_field="width_field",
height_field="height_field")
width_field=models.IntegerField(default=0)
height_field=models.IntegerField(default=0)
...
def __str__(self):
return "("+str(self.id)+") " + self.nombre_producto
如果您需要,这是表格的一部分:
class ArticleForm(forms.ModelForm):
class Meta:
model = Articulo
fields = [
'nombre_imagen',
'nombre_producto',
'id_clasificacion_fk',
'Descripcion',
'long_descripcion',
'precio',
'cantidad',
]
以及带有以下形式的 HTML:
<div class="row">
<div class="col-md-10">
<form method="post">
<h5 class="mb-3">Agregar artículo</h5>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-lg btn-success">Guardar
cambios</button>
</form>
</div>
<div class="col-md-2">
<img src="{% static 'img/handpen.png'%}"width="350px" height="310px"
/>
</div>
</div>
如果有人可以帮助我,请告诉我。
谢谢!。
解决方案
Your upload_location
function has an error. You are trying to format a string but have not included "replacement" tokens
def upload_location(instance, filename):
return "static/img/" % (instance.id, filename)
Should probably be
def upload_location(instance, filename):
return "static/img/%s/%s/" % (instance.id, filename)
推荐阅读
- c++ - C++ 为什么我们在 std::cout 使用 << 而不是大括号?
- python-2.7 - 如何在 opensuse (SLES) 15 SP2 上安装 python 2.7.17 的 ssl 模块?
- spring-batch - 如何使用 Spring Batch Integration 同时处理多个大文件和多个实例?
- wpf - EventTrigger 在当前不在视图中的元素上
- java - 总是得到 - 源服务器没有找到目标资源的当前表示或不愿意透露存在的表示
- leaflet - 传单当前位置多个标记
- android - Android Studio“更新和重启”按钮被禁用
- r - 如何在 R 的传单中显示 html 标签?
- android - OWASP MASVS 是否足以显示根检测警告消息,而不是完全终止应用程序?
- google-cloud-platform - 如何在云构建日志上显示作者电子邮件 ID?