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
Related
I have the following Python code that I am trying to migrate from mongonaut to the new way of interfacing Django with MongoDB, the djongo package:
# CharField for English and Japanese text
class LocalizedCharField(models.Model):
EN = models.CharField()
JP = models.CharField()
class Meta:
abstract = False
# Details for a character
class CharacterInfo(models.Model):
charName = models.CharField(max_length=128, blank=False, null=False)
displayName = models.EmbeddedField(model_container=LocalizedCharField)
nationality = models.EmbeddedField(model_container=LocalizedCharField)
game = models.EmbeddedField(model_container=LocalizedCharField)
system = models.EmbeddedField(model_container=LocalizedCharField)
voice = models.EmbeddedField(model_container=LocalizedCharField)
graphic = models.EmbeddedField(model_container=LocalizedCharField)
introduction = models.EmbeddedField(model_container=LocalizedCharField)
defaultPalIndices = models.CharField(max_length=128)
groove = models.JSONField(blank=True, null=True)
config = models.JSONField()
moves = models.JSONField()
charConfig = models.JSONField()
def __unicode__(self):
return self.charName
class Meta(object):
verbose_name = "Character"
verbose_name_plural = "Characters"
# Main page post
class Post(models.Model):
title = models.EmbeddedField(model_container=LocalizedCharField)
date = models.DateTimeField(default=datetime.datetime.now)
content = models.EmbeddedField(model_container=LocalizedCharField)
def __unicode__(self):
return self.title["EN"]
However, I get the following error when I try to debug my server:
['Field "lawn.LocalizedCharField.id" of model container:"<class \'lawn.models.LocalizedCharField\'>" cannot be of type "<class \'django.db.models.fields.AutoField\'>"']
And it points to the line where displayName is as the culprit, meaning I for some reason can't embed my own field types in other models? What do I have to do to make this work? As said before, up until this point, I was using an outdated custom build of Mongonaut where this worked fine, so I'm unsure what djongo wants.
i developed a blog project by watching many open-source courses and create my own django custom admin dashboard where i want to add a category option to my blog project, i have watched some tutorial on as well but couldn't find them helpful
models.py
from django.db import models
from django.forms import ModelForm
from farmingwave.models import BaseHeader,Submenu
class Category(models.Model):
mainmenu=models.ForeignKey(BaseHeader,null=True,on_delete=models.SET_NULL)
submenu=models.ForeignKey(Submenu,on_delete=models.CASCADE)
class AdSideMenu(models.Model):
title_id = models.AutoField(primary_key=True)
title_name = models.TextField()
url = models.TextField()
priority = models.IntegerField()
submenu_status = models.TextField()
class Meta:
db_table = 'admin_side'
class CreateBlog(models.Model):
id = models.AutoField(primary_key=True)
blog_Title = models.TextField(max_length=100)
content = models.TextField(max_length=5000)
category = models.ForeignKey(Category,null=True,on_delete=models.SET_NULL)
class Meta:
db_table = 'create_blog'
they are inhereting data from another app
models.py
`class BaseHeader(models.Model):
main_id = models.AutoField(primary_key=True)
title_name = models.TextField()
url = models.TextField()
priority = models.IntegerField()
submenu_status = models.TextField("false")
class Meta:
db_table = 'base_header'
class Submenu(models.Model):
sub_id = models.AutoField(primary_key=True)
main_id = models.IntegerField()
sub_name = models.TextField()
url = models.TextField()
priority = models.IntegerField()
mainmenu=models.ForeignKey(BaseHeader,on_delete=models.CASCADE)
class meta:
db_table = 'base_subheader'`
and the view function:
def create_blog(request):
if request.method =='POST':
form = CreateBlogForm(request.POST)
if form.is_valid():
form.save()
form = CreateBlogForm()
else:
form = CreateBlogForm()
base = BaseHeader.objects.all()
sub = Submenu.objects.all()
create = CreateBlog.objects.all()
category = Category.objects.all()
context = {
'form' : form,
'createblog' : create,
'category' : category,
'menu' : base,
'sub_menu' : sub,
Why not make the category a select item?
CATEGORY_CHOICES = (
('sports', 'sports'),
('tech', 'tech'),
('politics', 'politics')
)
category = models.CharField(max_length=100, choices=CATEGORY_CHOICES, blank=False)
You'd be able to access it like any other field now, so let's say the user clicked on "Politics articles" you can add a .filter(category="politics") and access it in the templates through {{ article.category }}
I don't know why there are all of these lines in your code, nor do I know the scale of your project, but that's how I would go about doing it.
First of all, please forgive for my newbie questions. I did copy most of the code, and try to understand from Django documents.
Code as below:
models.py
class Order(models.Model):
ORDER_CHOICES = (
('import', 'IMPORT'),
('export', 'EXPORT')
)
storage = models.ForeignKey(Storage, on_delete=models.PROTECT)
order_type = models.CharField(max_length=6, choices=ORDER_CHOICES)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
class Item(models.Model):
def random_barcode():
return str(random.randint(10000000, 99999999))
type = models.ForeignKey(Type, on_delete=models.CASCADE)
order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
item_name = models.CharField(max_length=50, help_text='Name of goods, max 50 characters')
barcode = models.CharField(max_length=8, default=random_barcode, unique=True)
production_date = models.DateField()
expired_date = models.DateField()
def __str__(self):
return self.item_type
forms.py
class ItemForm(ModelForm):
class Meta:
model = Item
exclude = ['order',]
fields = ['type', 'brand', 'item_name', 'production_date', 'expired_date']
ItemFormSet = inlineformset_factory(Order, Item, form=ItemForm, extra=1)
views.py
class CreatePO(CreateView):
model = Order
context_object_name = 'orders'
template_name = 'storages/create_po.html'
fields = ['order_type', 'storage',]
*#dun't know how to write below code....*
1st question: how to use inline formset to write the CreatePO view?
2nd question: I need my create PO template as below picture, how to add a "Quantity" field?
This kind of template need Javascript, right? Any alternative solution? I have no knowledge with javascript.
First of all, move the def random_barcode(): before def __str__(self): it looks so ugly formated code.
Then let's have a look in your pic, if you haven't proper experience with Javascript you can use Admin Views from Django, it's much more simple and supported by Django 2.1. Read more if you would like to give permission to everyone in a admin-views page https://docs.djangoproject.com/el/2.1/releases/2.1/#model-view-permission
So quantity will be just added inside Item class
quantity = models.PositiveSmallIntegerField(default=1)
Also for your form, in my opinion, you need modelform_factory, so I suggest to read this one https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#modelform-factory-function
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!
I am working on multiple django sites and have been limited in making my project look nice for clients.
For example in the same app I have two models images and image galleries. It would be so much nicer to just have an admin entry for galleries and in that a table of images.
That's exactly what InlineModelAdmin is for. Taken a models.py like this:
class Gallery(models.Model):
name = models.CharField(max_length=100)
class Image(models.Model):
image = models.ImageField()
gallery = models.ForeignKey(Gallery)
You create an admin.py like this and only register an admin class for the Gallery:
class ImageInline(admin.TabularInline):
model = Image
class GalleryAdmin(admin.ModelAdmin):
inlines = [ImageInline]
admin.site.register(Gallery, GalleryAdmin)
This is my solution thanks to Dirk's help.
from django.db import models
PHOTO_PATH = 'media_gallery'
class Gallerys(models.Model):
title = models.CharField(max_length=30, help_text='Title of the image maximum 30 characters.')
slug = models.SlugField(unique_for_date='date', help_text='This is automatic, used in the URL.')
date = models.DateTimeField()
class Meta:
verbose_name_plural = "Image Galleries"
ordering = ('-date',)
def __unicode__(self):
return self.title
class Images(models.Model):
title = models.CharField(max_length=30, help_text='Title of the image maximum 30 characters.')
content = models.FileField(upload_to=PHOTO_PATH,blank=False, help_text='Ensure the image size is small and it\'s aspect ratio is 16:9.')
gallery = models.ForeignKey(Gallerys)
date = models.DateTimeField()
class Meta:
verbose_name_plural = "Images"
ordering = ('-date',)
def __unicode__(self):
return self.title
import models
from django.contrib import admin
class ImageInline(admin.TabularInline):
model = Images
class GallerysAdmin(admin.ModelAdmin):
list_display = ('title', 'date', 'slug')
inlines = [ImageInline]
admin.site.register(models.Gallerys,GallerysAdmin)