简体   繁体   中英

django foreign key saving with file name not object

I have a model:

class UserProfile(models.Model):
    thumbnail = models.ForeignKey(Gallery, blank=True, null=True)

and my gallery:

class Gallery(models.Model):
    media_file = models.FileField(upload_to='somewhere)

def __str__(self):
    return self.media_file

in my view:

media = Gallery.objects.create(media_file=form.cleaned_data['thumbnail'])
user_profile = UserProfile.objects.get(user=someuser)
user_profile.thumbnail = media
user_profile.save()

When I look into admin and user profile model there I dont see image url in thumbnail. I just see Media Object . How can I get image url there ?

Thank you

That is because self.media_file will give you the file object not the url to the saved file. Change your code to return the url of the file. The easiest could be -

def __str__(self):
    return self.media_file.url

Read it about here -

https://docs.djangoproject.com/en/1.8/ref/models/fields/#filefield https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.fields.files.FieldFile.url

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