• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

616
Views
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 3 years ago · Santiago Trujillo
2 answers
Answer question

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 3 years ago · Santiago Trujillo Report

0

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

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error