社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

在django中尝试上载带有ImageField的图像时出现类型错误

Luis Bermúdez • 5 年前 • 1679 次点击  

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

如果有人能帮我让我知道。

谢谢您!.

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53762
 
1679 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Iain Shelvington
Reply   •   1 楼
Iain Shelvington    6 年前

你的 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)