简体   繁体   中英

Save to django imagefield

I'm trying to

1) Take an uploaded image and change it black and white with pillow

2) In the view save the original file to a FileField called "file"

3) In the view save the black and white version to ImageField called "thumbnail_225"

1 and 2 is working great but I cannot seem to figure out #3.

Any feedback is greatly appreciated.

View

def archive_media_upload(request):

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            m = form.save(commit=False)

            m.user = request.user
            m.type = 1

                        # create black and white
            image = Image.open(m.file)
            black_and_white = image.convert("L")

                        #HOW DO I SAVE/ASSIGN BW IMAGE TO the "thumbnail_225" ImageField?

            m.save()

            return HttpResponseRedirect(reverse('archive_media_archive'))

    else:
        form = UploadForm(initial={'user': request.user })

    return render(request, 'archive_app/archive_media_upload.html', {'archive':True, 'show_upgrade_link': show_upgrade_link,'form': form})

Model

class Media(models.Model):
    created_date = models.DateTimeField(default=datetime.now)
    type = models.IntegerField(default=0)

    user = models.ForeignKey(User)

    title = models.CharField(max_length=255, blank=True)
    file = models.FileField(upload_to=get_upload_file_name)

    thumbnail_225 = models.ImageField(upload_to="thumbnail_images/", blank=True)

To keep it short, what you are looking for is (I think) is the clean method. You should defined it in your form:

class UploadForm(forms.Form):

thumbnail_225  = forms.ImageField()

...

def clean_thumbnail_225 (self):
    thumbnail_225 = self.cleaned_data["thumbnail_225"]
    image = Image.open()
    black_and_white = image.convert("thumbnail_225")
    ...
    # return the clean data...

Note the above code is only a general scheme. It won't really work and does not contain all the correct logic and\\or syntax. It was meant only for demonstration. The full hints are found in DJANGO's form and field validation documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM