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'>
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 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
I have a “BigPage” model that has an element called “pagename” that has unique set to True. I would like to use the django-sitemaps framework to generate, populate, and continuously update the sitemap.xml file every time a new BigPage model with a new “pagename” element is created by adding the URL myapp.com/pagename to my project’s sitemap.xml file. Here's my BigPage model:
class BigPage(models.Model):
Pagename = models.CharField(max_length=128, blank=True, unique=True, null=True) #they will enter this input into a form field to reserve their unique url at myapp.com/pagename
PageNameOwner = models.CharField(max_length=128, blank=True, null=True) #owner of page enters their name
OwnerGender = models.CharField(max_length=7, choices=(('male', 'Male'), ('female', 'Female')), blank=True, null=True)
PageViewsCounter = models.IntegerField(null=False, default=0)
PageIsRemoved = models.BooleanField(default=False) #true if mods take down a person’s page
def __unicode__(self):
return self.Pagename
I have created the below sitemap.py file and placed it in the folder of my app where the BigPage model resides:
class BigPageSitemap(Sitemap):
changefreq = 'daily'
priority = 0.5
def items(self):
return BigPage.objects.all()
Then, in the main project url.py file (not the app url.py file) I have added this:
sitemaps = {
'Name of Page':BigPageSitemap
}
To the urlpatterns element this:
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps})
My app url.py has the following url pattern where if a term is entered in the URL field that matches a pagename element that can then be queried to retrieve a BigPage object then it loads that page, but if the entered URL is not equal to a pagename element, it will give the user a 404:
url(r'^(?P<url_param>[a-zA-Z0-9_.-]*)/$', views.view_for_all_BigPages, name='view_for_all_BigPages'),)
After all of this, no sitemap file seems to generate if I check the app folder or main project folder. If I go to myapp.com/sitemap.xml I get the following error:
'BigPage' object has no attribute 'get_absolute_url'
What things have I done wrong? I really appreciate any help. I’ve been trying for days.
from the docs:
There is no location method in this example, but you can provide it in
order to specify the URL for your object. By default, location() calls
get_absolute_url() on each object and returns the result.
you didnot define location() method in your Sitemap class, thats why it is trying to call get_absolute_url() on your model. so you need to define get_absolute_url() in your model like this:
class BigPage(models.Model):
Pagename = models.CharField(max_length=128, blank=True, unique=True, null=True)
# ....
def __unicode__(self):
return self.Pagename
def get_absolute_url(self):
return reverse('view_for_all_BigPages', kwargs={'url_param': self.Pagename})
by the way, model attributes are written in small letters, pagename rather than Pagename.
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