Not able to diplay images in django - django

Im trying to make a shopping portal with a recommendation system
Not able to display images in the templates...
The HTML pages when opened without running the server opens them though
tried setting the MEDIA_URL and MEDIA_ROOT
settings as given:
MEDIA_ROOT = "/home/jose/Estore/estore/images/"
MEDIA_URL = '/images/'
The Model I defined is as given:
#Model for Books
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
section = models.CharField(max_length=50)
authors = models.CharField(max_length=150)
subject = models.CharField(max_length=50)
publisher = models.CharField(max_length=50)
publication_date = models.DateField(blank=True, null=True)
price = models.DecimalField(max_digits=6,decimal_places=2)
photo = models.ImageField(upload_to='product_photo/books/',blank=True)
description = models.TextField()
rating = models.DecimalField(max_digits=2,decimal_places=1)
def __str__(self):
return self.title

Have you set your urlconf?
http://docs.djangoproject.com/en/dev/howto/static-files/#serving-other-directories
here is how to do that. You need to set this in order for static serving to work.
Did this help?

Related

Default value is not stored in model

class Movie(models.Model):
image = models.ImageField(default='default.jpg')
title = models.CharField(max_length=255)
release_year = models.IntegerField()
number_in_stock = models.IntegerField()
daily_rate = models.FloatField()
genre = models.CharField(max_length=255)
date_created = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
Admin interface
The above code is my models class and i have given a default value to the
ImageField .
After saving the data my image field is still empty.
Whats the prooblem ?
Have you added this in your setting.py :
STATIC_URL = '/static/'
STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static')
]
Also, you will have to add the image in the static folder in your project for it work properly.
Adding on to this answer, the Media URL/Root and Static URL/Root collectively help Django process images for your application.
When you add the default image in models.py, make sure to put '/static/image.jpg' and once you're rending in the template load static with {% load static %}.

How to add multiple model objects on the same admin page Django

The idea is super simple. This is specific to my project, I want to add data to 2 objects of the same model on one Django admin page and have one save button.
My class:
class Data(models.Model):
issuer = models.ForeignKey(Issuers, on_delete=models.CASCADE)
issuer_field = models.ForeignKey(Fields, on_delete=models.CASCADE, null=True)
data_year = models.PositiveSmallIntegerField()
long_term_ar = models.IntegerField()
section_1 = models.IntegerField()
short_term_ar = models.IntegerField()
short_term_investments = models.IntegerField()
cash = models.IntegerField()
To illustrate:I want to have 2 of those on the same page
I am new to Django, and it will be super helpful if you will help me implement this idea
Take a look on "Inlinemodeladmin objects": https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#inlinemodeladmin-objects
You will be able to add more than one record at the same time:
Try this approach. I am still learning Django too. However, I believe that you dont need to specify the save instance since it is already built in django.
models.py
class Data(models.Model):
issuer = models.ForeignKey(Issuers, on_delete=models.CASCADE)
issuer_field = models.ForeignKey(Fields, on_delete=models.CASCADE, null=True)
data_year = models.PositiveSmallIntegerField()
long_term_ar = models.IntegerField()
section_1 = models.IntegerField()
short_term_ar = models.IntegerField()
short_term_investments = models.IntegerField()
cash = models.IntegerField()
admin.py
from django.contrib import admin
from .models import Data
class DataAdmin(admin.ModelAdmin):
list_display = ('issuer', 'issuer_field')
admin.site.register(Data)

django - Get a set of objects from different models field names

Please have a look at my models.
class BackgroundImage(models.Model):
user = models.ForeignKey(User)
image = models.ImageField(upload_to=get_upload_file_name)
caption = models.CharField(max_length=200)
pub_date = models.DateTimeField(default=datetime.now)
class ProfilePicture(models.Model):
user = models.ForeignKey(User)
image = models.ImageField(upload_to=get_upload_file_name)
caption = models.CharField(max_length=200)
pub_date = models.DateTimeField(default=datetime.now)
class Album(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=200)
pub_date = models.DateTimeField(default=datetime.now)
class Meta:
ordering = ['-pub_date']
verbose_name_plural = ('Albums')
def __unicode__(self):
return self.name
class Photo(models.Model):
user = models.ForeignKey(User)
album = models.ForeignKey(Album, default=3)
image = models.ImageField(upload_to=get_upload_file_name)
caption = models.CharField(max_length=200)
pub_date = models.DateTimeField(default=datetime.now)
How do I get all the images of Photo, ProfilePicture and BackgroundImage from their image field in one set. And then filter them by -pub_date to display in the template? Please help me out. Will be much much appreciated! Thank you.
Edit
N.B: I need ProfilePicture and BackgroundImage to work with the UserProfile like this:
from django.db import models
from django.contrib.auth.models import User
from profile_picture.models import ProfilePicture
from background_image.models import BackgroundImage
class UserProfile(models.Model):
user = models.OneToOneField(User)
permanent_address = models.TextField()
temporary_address = models.TextField()
profile_pic = models.ForeignKey(ProfilePicture)
background_pic = models.ForeignKey(BackgroundImage)
def __unicode__(self):
return self.user.username
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
There is an InheritanceManager provided as part of django-model-utils which allows you to do this, see docs.
To install in Linux / Mac:
sudo pip install django-model-utils
Annoyingly, installing using easy_install or pip on windows is not quite as straight forward, see: How do I install Python packages on Windows?. A quick and dirty method is to download the django-model-util/ directory from here into the top directory of your django project, this is handy if you intend to copy the entire project across for deployment to a production webserver.
In order to use the InheritanceManager, the models need to be refactored slightly:
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from model_utils.managers import InheritanceManager
get_upload_file_name = 'images/' # I added this to debug models
class BaseImage(models.Model):
user = models.ForeignKey(User)
image = models.ImageField(upload_to=get_upload_file_name)
caption = models.CharField(max_length=200)
pub_date = models.DateTimeField(default=datetime.now)
objects = InheritanceManager()
class BackgroundImage(BaseImage):
pass
class ProfilePicture(BaseImage):
pass
class Album(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=200)
pub_date = models.DateTimeField(default=datetime.now)
class Meta:
ordering = ['-pub_date']
verbose_name_plural = ('Albums')
def __unicode__(self):
return self.name
class Photo(BaseImage):
album = models.ForeignKey(Album, default=3)
All the Image models now inherit from a common super class which creates an instance of the InheritanceManager. I've also moved up all the duplicated attributes into the superclass, but this isn't strictly necessary, using InheritanceManager means that any attributes which are not present in BaseImage can still be accessed in the template.
To retrieve a list ordered by -pubdate:
BaseImage.objects.select_subclasses().order_by("-pub_date")
To use in a view:
def recentImages(request):
r = BaseImage.objects.select_subclasses().order_by("-pub_date")[:20]
return render_to_response("recentImages.html", { "imageList" : r })
To use in a template:
{% for photo in imageList %}
<img src="{{ photo.image.url }}" />
{% endfor %}
Is this something like what you are looking for?
Edit
The following code will still work fine, with the new models:
class UserProfile(models.Model):
user = models.OneToOneField(User)
permanent_address = models.TextField()
temporary_address = models.TextField()
profile_pic = models.ForeignKey(ProfilePicture)
background_pic = models.ForeignKey(BackgroundImage)
Just make sure the names of the last two models in the ForeignKey relationship are correct!

Why is my image upload failing in django?

I am trying to build a django app and host it on webfaction.
My model looks like this:
class Post(models.Model):
title = models.CharField(max_length=512)
image = models.ImageField(upload_to='blogImages/')
body = models.TextField()
visible = models.BooleanField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField('Tag', null=True, blank=True)
def __unicode__(self):
return self.title
The settings look like this:
MEDIA_ROOT = '/home/myself/webapps/dev_static/media/'
MEDIA_URL = 'http://dev.example.com/static/media/'
STATIC_ROOT = '/home/myself/webapps/dev_static/'
STATIC_URL = 'http://dev.example.com/static/'
When I go to my server and try to upload an image, I get this error:
SuspiciousOperation at /admin/blog/post/add/
Attempted access to '/home/myself/wrong/path/appname/blogImages/Portal2-Logo.jpg' denied.
I'm trying to figure out where the wrong path could come from. Where else should I look for the wrong path?
i have had the same problem, solved with
image = models.ImageField(upload_to='/blogImages/')
instead of (upload_to='blogImages/')
The error is returning the old static media path. It started working correctly using the the correct path after I restarted Apache.

Integrating Photologue

I want to integrate photologue with my Django app and use it to display photos in a vehicle inventory...kinda like what is offered by Boost Motor Group Inc. I've already integrated the app so the next step which I'm trying to figure out is how to hook it up into my vehicle model and also how to display the photos. My vehicle model looks like this BTW
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
feature_sets = models.ManyToManyField(FeatureSet, blank=True)
features = models.ManyToManyField(Feature, blank=True)
def __unicode__(self):
return self.stock_number
For your purposes I would recommend you check out django-imagekit (I wrote both imagekit and photologue). It was designed to be integrated into other applications as opposed to being a stand-alone application itself. After that, as Dominic said, we'll need to know more about your requirements.
I use ImageKit (great!)
model.py
from imagekit.models import ImageModel
class Photo(ImageModel):
name = models.CharField(max_length=100)
original_image = models.ImageField(upload_to='photos')
num_views = models.PositiveIntegerField(editable=False, default=0)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class IKOptions:
# This inner class is where we define the ImageKit options for the model
spec_module = 'cms.specs'
cache_dir = 'photos'
image_field = 'original_image'
save_count_as = 'num_views'
class Vehicle(models.Model):
images = generic.GenericRelation('Photo', blank = True, null = True)
specs.py
from imagekit.specs import ImageSpec
from imagekit import processors
from imagekit.lib import *
# first we define our thumbnail resize processor
class ResizeThumb(processors.Resize):
width = 100
height = 75
crop = True
# now lets create an adjustment processor to enhance the image at small sizes
class EnchanceThumb(processors.Adjustment):
contrast = 1.2
sharpness = 1.1
# now we can define our thumbnail spec
class Thumbnail(ImageSpec):
processors = [ResizeThumb, EnchanceThumb]
in your template you will access this thumbnails like this:
{% for p in vehicle.images.all %}
{{ p.get_thumbnail.url }}
{% endfor %}
admin.py could look like this:
class ImagesInline(generic.GenericTabularInline):
model = Photo
max_num =4
class VehicleAdmin(admin.ModelAdmin):
inlines = [ImagesInline]
All about ImageKit
add the file specs.py to your app and tell ImageKit of it like this
class IKOptions:
# This inner class is where we define the ImageKit options for the model
spec_module = 'cms.specs # ur_app.specs
add a field to your Photo-Model to save what kind of view/ content it shows. i.e. ChoiceField
In view/template you can filter for it