尝试在Django中上传带有ImageField的图像时出现TypeError

时间:2019-04-14 18:13:59

标签: python django image types upload

我在尝试使用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

这是来自models.py的具有ImageField的部分:

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>

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

谢谢!。

1 个答案:

答案 0 :(得分:1)

您的upload_location函数有错误。您正在尝试格式化字符串,但未包含“替换”标记

def upload_location(instance, filename):
    return "static/img/" % (instance.id, filename)

应该是

def upload_location(instance, filename):
    return "static/img/%s/%s/" % (instance.id, filename)