Unable to get repr for <class 'activities.models.Image'> - django

When I try to load an admin edit page with image inliner, I get a weird object which crashes my page. This thing goes last after all my images are loaded.
What can it be?
Code
models.py
class Image(BaseImage):
article = models.ForeignKey(Article, verbose_name=u'Новость', null=True)
in_preview = models.BooleanField(u'Отображать в превью', default=False)
weight = models.IntegerField(u'Порядок', default=0)
class Meta:
verbose_name = u'Изображение'
verbose_name_plural = u'Изображения'
ordering = ('weight',)
def get_upload_to(self, filename):
return os.path.join('articles', 'image', 'image_file', filename)
def list_thumbnail_tag(self):
source = self.image_file
if source:
thumbnail = get_thumbnailer(source).get_thumbnail({'size': (100, 100), 'crop': True})
return '<img src="{}">'.format(thumbnail.url)
list_thumbnail_tag.short_description = 'Превью'
list_thumbnail_tag.allow_tags = True
class BaseImage(models.Model):
image_file = models.ImageField(u'Файл', upload_to='uploads')
image_alt = models.CharField(u'Атрибут Alt', max_length=255, blank=True)
image_title = models.CharField(u'Название', max_length=255, blank=True)
def __str__(self):
return os.path.basename(self.image_file.path)
def get_upload_to(self, filename):
return os.path.join('images', filename)
class Meta:
abstract = True
verbose_name = u'Изображение'
verbose_name_plural = u'Изображения'

It's like the error message says: the __str__ method on BaseImage calls image_file.path, but the particular instance you're looking at has no image_file set.
You should use a value that doesn't depend on that field being set, or deal with that case somehow.

Related

How do i specify a file upload in django to a folder in reference to one of the model fields

I have the following django models in my Document app
class Section(models.Model):
choices = (
('Haematology', 'Haematology'),
('BloodBank', 'BloodBank'),
('Bacteriology', 'Bacteriology'),
('Parasitoloty', 'Parasitoloty'),
('Chemistry', 'Chemistry'),
('Histopathology', 'Histopathology'),
('Serology', 'Serology'),
('Immunology', 'Immunology'),
)
title = models.CharField(max_length = 50, choices = choices)
class Meta:
verbose_name = "Section"
verbose_name_plural = "Sections"
def __str__(self):
return str(self.title)
class Document(models.Model, instance):
documentSection = models.ForeignKey(Section)
category = models.ForeignKey(DocumentCategory)
title = models.CharField(max_length = 100, default = '')
description = models.TextField(null = True, blank = True, default = '')
documentFile = models.FileField(upload_to = 'uploads/' + instance.documentSection.title)
fileFormat = models.ForeignKey(FileFormat)
uploaded = models.DateField(auto_now_add=True, default=timezone.now)
modified = models.DateTimeField(auto_now=True, default=timezone.now)
uploaded_by = models.ForeignKey(User)
def __str__(self):
return str(self.title)
When i upload Documents i want then to be saved in a folder like 'uploads/documentSection/
or 'uploads/documentSection/%Y/%m/
My problem is i cant figure out how to take the value of the documentSection and parse it to upload_to = 'uploads/documentSection/

I am trying to create a django query that returns the posts that are of post_type "mobiles"

class Entry(models.Model):
title = models.CharField(max_length=200)
post_type = models.CharField(max_length=50, default="others")
author = models.CharField(max_length=30, default = "")
body = models.TextField()
slug = models.SlugField(max_length = 200, unique = True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now_add=True)
objects = EntryQuerySet.as_manager()
def __str__(self):
return self.title
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
The above code is my models.py
class MobilesIndex(generic.ListView):
queryset = models.Entry.objects.get(post_type="Mobile")
template_name = "index.html"
paginate_by = 5
def Mobiles(request):
context = locals()
template = "Mobiles.html"
return render(request,template,context)
The above code is view.py
how do i write the query that has only the posts that are of post_type="Mobile"
Try :
Entry.objects.fitler(post_type="Mobile")
get() return ONE object or exeception if not exists/multiple objects, but filter() returns all objects (or None if no objects).
queryset = models.Entry.objects.filter(post_type="Mobile")
this will give you all the post type and to render in template you need to loop it

Django: How to create object which has ManyToManyField in shell?

I think that showing code is much easier than explanation.
models.py
class Product(TimeStampedModel):
name = models.CharField(max_length=120, unique=True)
slug = models.SlugField(null=True, blank=True)
description = models.TextField(max_length=400, blank=True)
is_active = models.BooleanField(default=True)
place_category = models.ForeignKey(
"PlaceCategory",
related_name="products_by_place", # category.products_by_place.all()
)
subject_category_set = models.ManyToManyField(
"SubjectCategory",
related_name="products_by_subject", # category.products_by_subject.all()
)
objects = ProductManager()
class Meta:
ordering = ('-created',)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse(
"products:product_detail",
kwargs={
"slug": self.slug,
}
)
class Category(TimeStampedModel):
name = models.CharField(max_length=25, unique=True)
is_active = models.BooleanField(default=True)
class Meta:
abstract = True
def __str__(self):
return self.name
class PlaceCategory(Category):
class Meta:
verbose_name = "Place Category"
verbose_name_plural = "Place Categories"
class SubjectCategory(Category):
class Meta:
verbose_name = "Subject Category"
verbose_name_plural = "Subject Categories"
This is what I'm trying to do in shell.
# place category
self.place_category = PlaceCategory.objects.create(name="학교")
# subject category
self.subject_category1 = SubjectCategory.objects.create(name="사람")
self.subject_category2 = SubjectCategory.objects.create(name="꽃병")
# product
self.product = Product.objects.create(
name="product name1",
place_category=self.place_category,
subject_category_set=(
self.subject_category1,
self.subject_category2,
)
)
But it doesn't work. Any idea?
What I could think of is moving ManyToManyField from Product to SubjectCategory.
But I want know as in my code. Thanks.
You need to add subject category to your product.
So do it like this:
# place category
self.place_category = PlaceCategory.objects.create(name="학교")
# subject category
self.subject_category1 = SubjectCategory.objects.create(name="사람")
self.subject_category2 = SubjectCategory.objects.create(name="꽃병")
# product
self.product = Product.objects.create(
name="product name1",
place_category=self.place_category,
)
self.product.subject_category_set.add(self.subject_category1)
self.product.subject_category_set.add(self.subject_category2)
or you can make something like this
list_of_subject_categories = [self.subject_category1, self.subject_category2]
self.product.subject_category_set.add(*list_of_subject_categories)

Three-way query in django

I have the following model:
class Video(models.Model):
name = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
filename = models.CharField(max_length=200)
duration = models.IntegerField(default=0)
votes_up = models.IntegerField(default=0)
votes_down = models.IntegerField(default=0)
width = models.IntegerField(default=0)
height = models.IntegerField(default=0)
def __unicode__(self):
return self.name
class Category(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class VideoCategory(models.Model):
video = models.ForeignKey('Video')
category = models.ForeignKey('Category')
def __unicode__(self):
return u"{} >> {}".format(self.video.name, self.category.name)
And this view:
def video_list(request):
if 'category' in request.POST:
#####
else:
video_list = Video.objects.order_by('pub_date')
context = {}
context['videos'] = []
for video in video_list:
video_data = {'name': video.name,
'file': video.filename,
'duration': video.duration,
'resolution': [video.width, video.height],
}
context['videos'].append(video_data)
return HttpResponse(json.dumps(context), content_type="application/json")
Everything works as expected.
Now I want to filter videos through categories. How can I construct a query like:
"Give me all the 'Videos', which have an entry in 'VideoCategory' with the 'Category'.name like 'xxxxxxx'"
You can do:
videos = Video.objects.filter(videocategory__category__name='xxxx')
(notice the lower case model name to access the reverse relationship)
You can read upon how to query lookups that span relationships here

How to always filter on a field on objects requests

I have two models :
class Album(models.Model):
#Attributes
title = models.CharField(max_length=200)
displayed = models.BooleanField()
created_on = models.DateTimeField(auto_now_add=True)
class Photos(models.Model):
#Attributes
title = models.CharField(max_length=500)
link = models.CharField(max_length=500)
album = models.ForeignKey(Album, unique=False, verbose_name=_('album'))
def upload_path(self, filename):
return 'upload/photos/%s/%s' % (self.id, filename)
def upload_path_thumbnail(self, filename):
return 'upload/photos/%s/%s' % (self.id, "thumnail_" +filename)
thumbnail = models.ImageField(upload_to=upload_path_thumbnail)
photo = models.ImageField(upload_to=upload_path)
created_on = models.DateTimeField(auto_now_add=True)
displayed = models.BooleanField()
And I want to force, when i select Photos, to always filter on displayed=1.
Thank you
Use a custom manager:
class DisplayedPhotoManager(models.Manager):
def get_queryset(self):
return super(DisplayedPhotoManager, self).get_queryset().filter(displayed=1)
class Photos(models.Model):
objects = DisplayedPhotoManager()
...
this will override standard "objects" manager (which can be dangerous).
A nicer pattern is often:
class DisplayedPhotoManager(models.Manager):
def get_queryset(self):
return super(DisplayedPhotoManager, self).get_queryset().filter(displayed=1)
class Photos(models.Model):
objects = models.Manager()
displayed = DisplayedPhotoManager()
...
and use 'displayed' instead of 'objects':
Photo.displayed.all()