Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

434
Vistas
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
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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.

over 4 years ago · Santiago Trujillo Denunciar

0

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

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda