TypeError пытается загрузить изображение с помощью ImageField в django - PullRequest
0 голосов
/ 14 апреля 2019

Я получаю эту ошибку, когда пытаюсь загрузить изображение с 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 Ответ

1 голос
/ 14 апреля 2019

Ваша функция 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)
...