Django admin: How to get path of uploaded file - python

I have created model field for User Pic and User_pic_url, what i'm trying to do is when i upload image it's path should get populated in user_pic_url.
Note that i'm uploading image from django admin itself. any idea.
snapshot for ref:
Snapshot
Model.py:
class Main(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=100)
about = models.TextField()
contact = models.CharField(default='0', max_length=12)
email = models.CharField(default='-', max_length=50)
linkedin = models.CharField(default='-', max_length=50)
github = models.CharField(default='-', max_length=50)
site_name = models.CharField(default='-', max_length=50)
resume = models.FileField()
cover_letter = models.FileField()
user_pic = models.ImageField()
user_pic_url = models.TextField(default="-")

From Django documentation regarding managing files
Consider the following model, using an ImageField to store a photo:
class Car(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=5, decimal_places=2)
photo = models.ImageField(upload_to='cars')
Any Car instance will have a photo attribute that you can use to get
at the details of the attached photo:
car = Car.objects.get(name="57 Chevy")
car.photo
<ImageFieldFile: cars/chevy.jpg>
car.photo.name
'cars/chevy.jpg'
car.photo.path
'/media/cars/chevy.jpg'
car.photo.url
'http://media.example.com/cars/chevy.jpg'

if you want to get the uploaded path first make sure you have configure you MEDIA_URL MEDIA_ROOT in settings.py and also you have to put your put url patterns for media url given in the documentation
if you have already done that you have to simply put the query set
obj = Main.objects.all().first()
like this when you get any object you have to go to the imagefield and add url after that like this
you have to only put url after all the configuration in the imagefield
print(obj.user_pic.url) <---------you can get your url like this

You don't need a user_pic_url field. You can fetch the data from the user_pic field itself
class Main(models.Model):
# rest of your fields
user_pic = models.ImageField()
#property
def user_pic_url(self):
return self.user_pic.url
Now, you can access the URL directly as,
model_instance = Main.objects.first()
print(model_instance.user_pic_url)

Related

Cant Upload Images to Django Admin

I am working on e-commerce project and i am stuck at this. Whenever admin adds new product,it should also add image related to the product. So i added the the column with ImageField but i am getting error again and again. Here is my code for models
class Product(models.Model):
product_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100, blank=True, null=True)
image = models.ImageField(db_column='image' , blank=True, null=True)
info = models.CharField(max_length=500, blank=True, null=True)
def image_tag(self):
if self.image:
return mark_safe('<img src="%s"/>' % self.image.url)
else:
return 'No Image Found'
image_tag.short_description = 'Image'
and in admin.py
class ProductAdmin(admin.ModelAdmin):
list_display = ('product_id', 'name','image_tag', 'info')
readonly_fields = ('image',)
admin.site.register(Product, ProductAdmin)
But every time i get this error
Exception Type: AttributeError
Exception Value:'bytes' object has no attribute 'url'
I tried using escape but it still not displaying images.I am using MySQL existing database. I could really use the help. Thanks
Currently you are storing image in your database as bytes, which Django does not prefers instead you should first specify MEDIA_ROOT this is folder where your image will be saved and only the URL will be saved in the database. Docs [SOURCE]
I assume you have already setup MEDIA settings and have installed Pillow.
Your ImageField will look like,
# No need to specify db_column as Django already stores by default field's name.
image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True, null=True)
Now in your templates you can get the image by,
<img src="http://127.0.0.1:8000/media/{{ profile.photo }}" id='profile-photo'>

Simply Image in Django doesnot work

I am trying to add a field image in the class of my model using the next code
setting.py
MEDIA_ROOT = 'photo_movies/'
model.py
class Movie(models.Model) :
code = models.IntegerField()
title = models.CharField(max_length=200, primary_key=True)
movie_image = models.ImageField(upload_to='photos/', blank=True, null=True)
def __str__(self):
return self.title
def __unicode__(self):
return self.title
Using that, it is posible to see the upload button
The problem is when I want to access to the upload picture I get the next error
Request URL: http://127.0.0.1:8000/admin/films/movie/Pantaleon%20y%20las%20Visitadoras/photos/pantaleon.jpg/
movie object with primary key u'Pantaleon y las Visitadoras/photos/pantaleon.jpg' does not exist.
Could you help me please to fix that?
you need to define MEDIA_URL to handle it.
docs: https://docs.djangoproject.com/en/1.9/ref/settings/#media-url
also, check TryDjango Tutorial: https://www.youtube.com/watch?v=M-4xmVk6xrg
it provides good explanations about both MEDIA and STATIC files

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

Image download with registered user in django

i have image field in my model just like that..
class Photo(models.Model):
name = models.CharField(max_length = 100)
photo = models.ImageField(upload_to = 'photos', blank=False,null=True)
approved = models.BooleanField()
uploaded_time = models.DateTimeField(auto_now_add = True,auto_now = False)
description = models.CharField(max_length = 80 , blank = False , null = True)
approved_by = models.CharField(max_length = 100)
user = models.ForeignKey(User)
and i have make another model where the Photo model is foreign key
class PhotoDownload(models.Model):
dowloaded_photo = models.ForeignKey(Photo)
first,i want to make a view where all the uploaded image will be shown with a download link for each image,then when the user click the link it will download automatically,how can i do that,in mention, i am very new in django,so i have no idea about this.
see django models API
At first, you should know how the database store and read photos
go to your project directory
run
python manage.py shell
>>from appname.models import Photo
>>Photo.objects.all()
>>Photo.objects.create(name=....)
more see here
https://docs.djangoproject.com/en/1.6/topics/db/models/
Then you may know how urls work
url(r'^(.+)$', 'mysite.views.photo', name='photo-list'),
views function, templates
you need learn these.
You can download some django packages from github to see how others write
An example:
http://lightbird.net/dbe/photo2.html

Image Path Returning a 404 on Django Admin

Whenever I visit the path for an uploaded image in the admin, I get a 404. The image is successfully uploaded in the specified path but I don't know what URL structure to use to access the image. There is not URL structure specified yet for the image (that's what I want to know, or am I missing anything else?). Here are the details:
My models.py
class Product(models.Model):
category = models.ForeignKey('CatalogCategory', related_name='products')
name = models.CharField(max_length=300)
slug = models.SlugField(max_length=150)
description = models.ImageField(upload_to='product_photo', blank=True)
manufacturer = models.CharField(max_length=300, blank=True)
price_in_dollars = models.DecimalField(max_digits=6, decimal_places=2)
this is the error:
Request
URL: http://localhost:8000/admin/products/product/1/product_photo/soy_candles.jpg/
product object with primary key
u'1/product_photo/soy_candles.jpg'
does not exist.
this is the dir struct
product_photo
products
->templates
->models.py
->views.py
->...
manage.py
settings.py
urls.py
EDIT
I have not touched the details regarding the admin on the settings
Your MEDIA_URL defines this.
You either have it defined to '' and the admin is generating a relative URL or you have it set to http://localhost:8000/admin/products/product/1/ which is unlikely :P

Categories