Tuesday, November 1, 2011

Re: Image Model, Form and View -> Easily change "upload_to" path from form.save()?

I'm not sure if there's a better solution, but here's one I kind of
came up with after reading into the documentation and some other
Discussions. Let me know if there's a better solution out there.
Hopefully this will help someone else out as well.

from django.db import models
from django.contrib.auth.models import User

# Provides the Path for User Images
def user_image_folder(instance = None, filename = None):
return 'uploaded/' + instance.user.username + '/images/' +
filename

class Image(models.Model):

date_created = models.DateField(auto_now_add = True)
user = models.ForeignKey(User)
# Note: upload_to is referencing the above function in the same
file.
data = models.ImageField(upload_to = user_image_folder)

On Nov 1, 10:55 pm, Kurtis <kurtis.mull...@gmail.com> wrote:
> Hey,
>
> I've got a very simple setup for a sample application. Basically, I
> have a Model w/ an ImageField. I have a ModelForm using that Model.
> Finally, I have a FormView for using that Form.
>
> In my View, I call my form's .save() method and pass along the request
> user. I'd like to manipulate where this file is stored.
>
> Here's what I tried so far but it did *not* work -- the thing just
> uses the preset upload_to variable.
>
> ImageForm.save(self, user):
>
>     # Grab Model Instance
>     m = super(ImageForm, self).save(commit = False)
>
>     # Try to Change "upload_to" Value
>     # Note: "data" is the name of my ImageField
>     m.data.upload_to = 'some_other_folder'
>
>     # Save the Model
>     m.save()
>
>     # Done
>     return m

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment