I Am trying to give an uploaded image a nicer path, using this code (in models.py):
def get_image_path_photos(instance, filename):
return os.path.join('photos', str(instance.someproperty), filename)
and the model
class Photo(models.Model):
someproperty = models.CharField(max_length=17, blank=False, null=False, default="something")
photo = models.ImageField(upload_to=get_image_path_photos, blank=True, null=True)
When I save this after a new insert, it saves it in the path /photos/something/ (it keeps using the default value).
When I edit it, add a photo and save it, it will save it to the correct path.
So it must have something to do that while saving the new object, it doesn’t exist yet.
I tried the same with instance.id and this keeps being None as well (I read using auto increment on the id solves this, but this sounds as using the default value as well, and using the default pk/id is auto increment).
I found some simular questions, but none with the answer that solves my problem.
I thought of going to use the pre_save signal…. but somehow my guts says this isn’t the right way.
The solution of my problem I found out myselve, please see my answer… A good lesson, don’t use slugname definitions the same as the field name…..
Sorry about this. The problem is a bit more complicated. I use the field someproperty also in the url as a slug on the posts….
I just found out something I didn’t expected.
i did my post (using django rest framework) from the url using the default value in the url… but I filled in the field with something else.
than, because I define the slugname the same as the fieldname, it overwrites anything you fill in in the field with the value from the url….
This isn’t exactly what I meant to be done, but makes sence.
Probably the solution is to call the slug name not the same as the field name……
I keep this question and answer anyway, because for me it was quite a puzzle….. (might be of help to somebody)
as an addition to the answer of jpic:
I used the urls in django rest framwwork, lets say; http:\someurl\api\photos\\
and post there the photo.
posting the photo avatar_big.png using someproperty=bar:
saved the photo in photos\something\ when using the url http\someurl\api\photos\something
and saved the photo in photos\bar\ when using the url http:\someurl\api\photos\bar
the problem is (i guess, still have to check this) that the slug name I use for the url is the same as the fieldname.
this is the code I use in views.py (class based view I use in the django-rest-framework):
and in urls.py:
here you see the problem, it doesn’t listen to the field in ‘someproperty’, but to the value in the url ….
changing it in
url(r’^api/photos/(?P[\w:]+)/$’, PhotoBySomePropertyListOrCreateModelView.as_view(resource=PhotoResource)),
should do the trick…. also adjust the view of course