Django ImageField on non-loadable forms works from admin but not from form

So I have a system where users can choose from an existing image gallery or upload a new image to process and save.

First, 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 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 do is create a new image object from the form field and then save it to constrain the external key in the post model. But what it does is nothing, the post loads fine with an empty image field and the image is never generated. This makes me think that the if statement for new_image resolves to False, but I can't figure out why it would.

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

also, my image model is

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

      

+3


source to share


2 answers


You need to change

form = PostForm(request.POST)

      

in

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

      

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

Django Documentation: Uploading Files

You can use pre-save / post-save signals to create a new snapshot when a message / image is saved via a form in an image model.




You need to add your image model to this example. Considering how you are storing image information through a form, I am assuming you are not using

ImageField()

      

on your model images. The only way to tell is to show this model.

Django documentation: model field reference: ImageField ()

In this field, Django loads images through forms.

You may need to add two forms to your view for posting and another one for uploading a new image.

I'm still researching this myself, so you can take a look here and find some help on this.

+2


source


The form template needs this: enctype = "multipart / form-data", I added that we have functional image handling too!



+2


source







All Articles