1
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']
Source:stackexchange.com