首页 > 解决方案 > 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>

如果有人可以帮助我,请告诉我。

谢谢!。

标签: pythondjangoimagetypesupload

解决方案


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)

推荐阅读