【问题标题】:TypeError trying to uploading a image with ImageField in djangoTypeError 试图在 django 中使用 ImageField 上传图像
【发布时间】:2019-09-04 19:18:01
【问题描述】:

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

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

谢谢!

【问题讨论】:

    标签: python django image types upload


    【解决方案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)
    

    【讨论】:

    • 是的,你是对的!但是我还有另一个问题,当我尝试上传文件时,它说“nombre_imagen 属性没有与之关联的文件”并且它没有向我显示图像。当我在 DB 中看到 nombre_imagen 时,那里没有路径。有什么问题?
    • 在 html 表单中,您必须添加 enc_type w3schools.com/tags/att_form_enctype.asp 才能上传文件。
    猜你喜欢
    • 2018-11-27
    • 1970-01-01
    • 2015-02-22
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    相关资源
    最近更新 更多