Pergunta

I am using Django 1.5 and I want users to be able to upload photos. I want the photos to be stored in a different location depending on what the users ID is. So for example, if a user uploads a file and the users ID is 1 (the ID / unique primary key given to each user when a user object is created from the Django generic User model), then I want the image to be saved in the directory

myPorjectFolder/myApp/static/site_media/images/1(the users ID)/uploadedPhotos

This is how I think I am supposed to do it. In settings.py, add this line:

MEDIA_ROOT = '/home/userName/myProject/myApp/site_media/static/images/'

and then in the models.py, create the model like this:

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

class UserImages(models.Model):
    user = models.OneToManyField(User)
    photo = models.ImageField(upload_to=currentUsersID/uploadedPhotos) #I know this won't work.. how would I make it work?

Am I right? Or is it done a totally different way than what I am thinking?

Edit: my forms.py is this:

class UploadImageForm(forms.Form):
    image = forms.ImageField()
Foi útil?

Solução

If you want to use the id of the user, you can create a function to upload the image like so:

def get_file_path(instance, filename):
  return os.path.join('%s/uploadedPhotos' % instance.user_id, filename)

Then in your model's ImageField you'll do

class UserImages(models.Model):
  user = models.ForeignKeyField(User)
  photo = models.ImageField(upload_to=get_file_path)

Also note that I used a ForeignKeyField for the user property. There is no OneToManyField, just ForeignKey, OneToOne and ManyToMany.

Edit:

For your form usage, you could do:

form = UploadImageForm(request.POST)
form.instance.user = request.user
user_image = form.save()

But you'd need to modify your forms.py to the following:

class UploadImageForm(forms.ModelForm):
  class Meta:
    model = UserImages
    fields = ['photo']
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top