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
Related
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)
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'>
Ive been trying to create a profile page for a project, where the user can upload a profile pic and some basic personal information using Django as framework.
The text based information I pass in my code seem to work, but I cant get the user to upload a profile pic from the profile page. But if I go to django-admin page, I can upload and display the profile pic from there. So to models.py file seem to work, and the issue seem to be in forms.py file... Ive search the net for some time and various turtorials, but nothing seem to work. Please help :)
models.py file
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
email_confirmed = models.BooleanField(default=False)
image= models.ImageField(upload_to='profile_image', blank=True)
def __str__(self):
return self.user.username
forms.py file
class ProfileUpdateForm(forms.ModelForm):
YEARS= [x for x in range(1900,2021)]
birth_date = forms.DateField( initial="21-06-1995", widget=forms.SelectDateWidget(years=YEARS))
image = models.ImageField(upload_to='profile_image',blank=True)
class Meta:
model = Profile
fields = ('bio','birth_date','location','image')
views.py file
#login_required
def profile_edit(request):
form = ProfileUpdateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
user = request.user
user.profile.bio = form.cleaned_data.get("bio")
user.profile.birth_date = form.cleaned_data.get("birth_date")
user.profile.location = form.cleaned_data.get("location")
user.save()
return redirect('profile')
else:
form = ProfileUpdateForm()
context = {
'form' : form
}
return render(request, 'webside/profile_edit.html', context)
Static root/url and Media root/url has been implemented in settings and Ive added the static url to the urls.py file. Any help would be greatly appreciated :)
You're only passing the data to the form, not the files:
form = ProfileUpdateForm(request.POST)
Change to:
form = ProfileUpdateForm(data=request.POST, files=request.FILES)
And save your form instead of assigning the data to a user object. You're not saving the user.profile when you do user.save():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
You did not save your image in view after posting from your form object. You save it like this if form is valid
if 'image' in request.FILES:
user.profile.image = request.FILES['image']
I am working with Python 2.7, Django 1.9 and sorl.thumbnail.
I cannot manage to create a view to delete in one time the original picture file, the Picture entry in the database, the thumbnail pictures generated by sorl.thulbnail, and the thumbnail_kvstore entry in the database.
Here is my Picture model:
class Picture(models.Model):
file = models.ImageField(upload_to="pictures")
slug = models.SlugField(max_length=100, blank=True)
user = models.ForeignKey(User, null=True, blank=True)
exiflnglat = models.PointField(dim=3, geography=True, blank=True, null=True)
objects = models.GeoManager()
def __str__(self):
return self.slug
#models.permalink
def get_absolute_url(self):
return ('upload-new', )
And here is my view:
from sorl.thumbnail import delete
def deletepicnthumbs(request, pk):
allpicfromuser = Picture.objects.filter(user=request.user)
pictodelete = allpicfromuser.get(id=pk)
delete(pictodelete)
return redirect(adddetails)
This view does not delete anything.. What I am doing wrong ?
Thanks a lot
It seems that you are trying to use the delete method from sorl to delete an instance of the Picture model instead of the picture itself.
This code should work :
from sorl.thumbnail import delete
def deletepicnthumbs(request, pk):
pictodelete = Picture.objects.get_object_or_404(id=pk, user=request.user)
# Delete the thumbnails, as well as the original image
# If you want to keep the original image, pass ```delete_file=False```
delete(pictodelete.file)
# We use Django's method to delete the Picture instance, if needed
pictodelete.delete()
return redirect(adddetails)
Hope this helps,
Adela
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