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

428
Visualizações
Django ImageField in forms not uploading, works from admin but not from form

So, I have a system where users can either choose from an already existing image gallery, or upload a new image to be processed and saved.

First off, the model:

class Post(models.Model):
    image = models.ForeignKey(Image, null=True, blank=True)
    title = models.CharField(max_length=200)
    slug = models.CharField(max_length=200, unique=True, blank=True)
    description = models.TextField(blank = True)
    text = models.TextField()

    def __str__(self):
        return self.title

and our form

class PostForm(BaseModelForm):
    new_image = forms.ImageField(required=False)

    def clean(self):

        return self.cleaned_data

class Meta:
    model = Post
    fields = ('title','text', 'image', 'new_image', description')

    help_texts = {
       'new_image': _('either upload a new image, or choose from the gallery')
    }

so then our view where it gets processed

def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.slug=slugify(post.title)
            if form.cleaned_data.get('new_image'):
                image = Image(title=post.title, description=post.description, image = request.FILES['new_image'])
                image.save()
                post.image = image


            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

Now what this should be doing is creating a new image object out of the form field, then saving it to the foreignkey constraint on the post model. But what it does is nothing, the post uploads fine with a blank image field, and the image never gets created. This makes me think the if statement for 'new_image' is resolving to False but I can't figure out why it would do that.

Also, for conventions sake, should this be happening in the form class or the view class?

also, my image model

class Image(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    image = models.ImageField(upload_to = 'images/', default =     'images/None/no-img.jpg')
    def __str__(self):
        return self.title
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You need to change

form = PostForm(request.POST)

to:

form = PostForm(request.POST, request.FILES)

you need to add request.FILES in order to upload the file as per the documentation

Django Documentation: File Uploads

You may want to use pre-save/post-save signals to create the new image save when a post/image is saved via the form to the Image model.


You need to add your Image model to this example. Looking at how you are saving the image information via the form, Im going to assume you aren't using the

ImageField()

model on your Image Model. Only way to tell is you showing that model as well.

Django Documentation: Model Field Reference: ImageField()

This field is how Django uploads images through forms.

You may need to add two forms to your view one for the post and the other for the new image upload.

Im still learning this myself so you can look on here and find some assistance with this.

about 4 years ago · Santiago Trujillo Relatório

0

The form template need this: enctype="multipart/form-data", I added that and suddenly we have functional image processing!

about 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