Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
Having troubles uploading image through model form

I am having trouble uploading the image field on my model form.

views.py:

@user_passes_test(lambda x: x.is_superuser)
def add_books(request):
    if request.method == 'POST':
        form = BooksForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            redirect('/')
    else:
        form = BooksForm()
    return render(request, 'library/books/addbook.html', {'form': form})

models.py:

class Books(models.Model):
    picture = models.ImageField(upload_to='images/')
    name = models.CharField(max_length=100)
    publisher = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    member = models.ForeignKey(Member, related_name="books", null=True)

    def get_absolute_url(self):
        return reverse('library:detail_book', kwargs={'book_id': self.id})

    def __unicode__(self):
        return "%s %s" % (self, self.name, self.author)

    def __str__(self):
        return "{0} {1}".format(self.name, self.author)

forms.py:

class BooksForm(ModelForm):
    class Meta:
        model = Books
        fields = ('picture', 'name', 'publisher', 'author')

    def clean_name(self):
        name = self.cleaned_data['name']
        if Books.objects.filter(name=name).exists():
            raise ValidationError("A Book with that name already exists!")
        return name

addbook.html:

{% extends "library/base.html" %}
{% block content %}
    <div align="center">
        <tr>
                <form method="POST">
                {% csrf_token %}
                <h2>Book:</h2>
                {{ form.as_p }}
                <input type="submit" value="submit">
            </form>
        </tr>
    </div>
{% endblock %}

settings.py:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

Once, I try to add a book and i add the image field and hit the button, the form tells me that the image field is required and it does not let me upload the image. Thank you ahead for your help!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

To upload files in your form you need to add the following attribute to the form element:

<form method="POST" enctype="multipart/form-data">

Without this, the file is not being uploaded, which is why Django's form API is raising an error (as it is a required field).

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda