Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ImageField in forms not uploading, works from admin but not from form

Tags:

forms

django

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
like image 936
Owen Percoco Avatar asked Apr 21 '17 15:04

Owen Percoco


People also ask

What is uploadedfile in Django forms?

It normalizes to: An UploadedFile object that wraps the file content and file name into a single object. This article revolves about how to upload images with Django forms and how can you save that to the database.

What is Geeks_field imagefield in Django forms?

Thus, an geeks_field ImageField is created by replacing “_” with ” “. It is a field to input image files from the user. How to upload Files using ImageField – Django Forms ?

What is the use of image field in Django?

The image column is an ImageField field that works with the Django’s file storage API, which provides a way to store and retrieve files, as well as read and write them. The upload_to parameters specify the location where images will be stored which for this model is MEDIA_ROOT/images/

How to create a form in Django?

Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html. Finally, a URL to map to this view in urls.py Thus, an geeks_field ImageField is created by replacing “_” with ” “. It is a field to input image files from the user.


2 Answers

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.

like image 193
Corey Gumbs Avatar answered Oct 23 '22 13:10

Corey Gumbs


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

like image 7
Owen Percoco Avatar answered Oct 23 '22 13:10

Owen Percoco