Displaying images from model using Django - python
So I would like to simply show multiple images on my homepage with data from the image field of my Product model. The premise is every time I add a new Product with an image it would generate a new li tag with a new image.
I then would like when the user clicks on the image on the homepage it appears in a model window with the slug name of the product in the URL, with the rest of the Product Information throughout the template that appears in the model window.
So can anyone help guide me on how to implement this solution?
Here is what I have so far:
Thank You!
Models.py
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
import datetime
class Designer(models.Model):
name = models.CharField(max_length=254, blank=True, null=True)
label_name = models.CharField(max_length=254, blank=True, null=True)
description = models.TextField(null=True, blank=True)
specialites = models.CharField(max_length=254, null=True, blank=True)
image = models.ImageField(upload_to='images/designers/main',max_length=100, null=True) #For the argument upload_to, will add to the static folder and generated image will be stored in suing that path specified
#For Admin Purposes, to track and see which if still active by for administrative users only
is_active = models.BooleanField(default=True)
#Metadata
class Meta:
verbose_name = _("Designer Information")
verbose_name_plural = _("Designers")
#Helps return something meaningful, to show within the admin interface for easy interaction
def __unicode__(self):
return "{0} {1}".format(self.name, self.label_name)
class Boutique(models.Model):
name = models.CharField(max_length=254, blank=True, null=True)
address = models.CharField(max_length=255, blank=True, null=True)
city = models.CharField(max_length=50, null=True, blank=True)
state = models.CharField(max_length=2, null=True, blank=True)
zipcode = models.IntegerField(max_length=5, null=True, blank=True)
boutique_website = models.URLField(max_length=200, null=True, blank=True)
#For Admin Purposes, to track a product to see which is active by administrative users
is_active = models.BooleanField(default=True)
#Foreign Keys & other relationships
designer = models.ForeignKey(Designer)
#Metadata
class Meta:
verbose_name = _("Boutique Information")
verbose_name_plural = _("Boutiques")
#Helps return something meaningful, to show within the admin interface for easy interaction
def __unicode__(self):
return "{0}, {1}, {2}".format(self.name, self.city, self.state)
class ProductCategory(models.Model):
name = models.CharField(max_length=255L, blank=True, null=True)
slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.')
#For Admin Purposes, to track and see which if still active by for administrative users only
is_active = models.BooleanField(default=True)
#For Admin Purposes, to track when we add each product and each product was updated by administrative users
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#Metadata
class Meta:
verbose_name = _("Product Category")
verbose_name_plural = _("Product Categories")
#Helps return something meaningful, to show within the admin interface for easy interaction
def __unicode__(self):
return "{0}".format(self.name)
class Product(models.Model):
name = models.CharField(max_length=254, blank=True, null=True)
description = models.TextField(blank=True, null=True)
color_name = models.CharField(max_length=254, null=True, blank=True)
size_types = models.CharField(max_length=7, null=True, blank=True)
product_price = models.DecimalField(max_digits=9,decimal_places=2)
old_price = models.DecimalField(max_digits=9,decimal_places=2, blank=True,default=0.00) #To show original price if, new price has been added
product_tags = models.CharField(max_length=254, null=True, blank=True, help_text='Comma-delimited set of SEO keywords for product tag area')
novelty = models.CharField(max_length=254, null=True, blank=True)
product_website = models.URLField(max_length=200, null=True, blank=True) #To show other sites to Users, where they can purchase the particular product
image = models.ImageField(upload_to='images/products/main',max_length=100, null=True) #For the argument upload_to, will add to the static folder and generated image will be stored in suing that path specified
slug = models.SlugField(max_length=255, unique=True, help_text='Unique value for product page URL, created from name.')
#This shows when each item was uploaded & by who, to the User
uploaded_by = models.CharField(max_length=254, blank=True, null=True)
uploaded_at = models.DateTimeField(auto_now=True)
#For Admin Purposes, to track and see which if still active by for administrative users only
is_active = models.BooleanField(default=True)
#Foreign Keys & other relationships
designer = models.ForeignKey(Designer)
boutique = models.ForeignKey(Boutique)
category = models.ForeignKey(ProductCategory)
#Metadata
class Meta:
verbose_name = _("Product")
verbose_name_plural = _("Products")
#Helps return something meaningful, to show within the admin interface for easy interaction
def __unicode__(self):
return "{0}".format(self.name)
Admin.py
from __future__ import unicode_literals
from django.contrib import admin
from products.models import Designer, Product, ProductCategory, Boutique
class DesignerAdmin(admin.ModelAdmin):
list_display = ["name", "label_name", "description", "specialites", "image", "is_active"]
search_fields = ["name", "label_name"]
list_per_page = 50
class ProductAdmin(admin.ModelAdmin):
list_display = ["name", "description", "color_name", "size_types", "product_price", "old_price", "product_tags", "novelty","product_website", "image", "slug", "uploaded_by", "uploaded_at", "is_active"]
search_fields = ["name", "product_price"]
list_per_page = 25
class ProductCategoryAdmin(admin.ModelAdmin):
list_display = ["name", "slug", "is_active", "created_at", "updated_at"]
search_fields = ["name"]
list_per_page = 25
class BoutiqueAdmin(admin.ModelAdmin):
list_display = ["name", "address", "city", "state", "zipcode", "boutique_website", "is_active"]
search_fields = ["name"]
list_per_page = 10
#Register Models below
admin.site.register(Boutique, BoutiqueAdmin)
admin.site.register(Designer, DesignerAdmin)
admin.site.register(Product, ProductAdmin)
admin.site.register(ProductCategory, ProductCategoryAdmin)
Forms.py
from __future__ import unicode_literals
from django import forms
from django.forms import extras, ModelForm
from products.models import Designer, Product, ProductCategory, Boutique
class DesignerForm(ModelForm):
class Meta:
model = Designer
class ProductForm(ModelForm):
class Meta:
model = Product
class BoutiqueForm(ModelForm):
class Meta:
model = Boutique
class ProductCategoryForm(ModelForm):
class Meta:
model = ProductCategory
Views.Py
from __future__ import unicode_literals
from django.http import Http404, HttpResponseForbidden
from django.shortcuts import redirect, get_object_or_404
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.views.generic import DetailView
from django.contrib import auth, messages
from django.contrib.sites.models import get_current_site
from django.shortcuts import render
from products.forms import ProductForm, ProductCategoryForm
from products.forms import BoutiqueForm
from products.forms import DesignerForm
from products.models import Boutique, Product, ProductCategory, Designer
class ProductView(DetailView):
model = Product
Template For Homepage
{% extends "site_base.html" %}
{% load i18n %}
{% block body %}
<div id="main" role="main">
<ul id="tiles">
<li>
<img src=" {{ object.image.url }}" />
</li>
</ul>
</div>
{% endblock %}
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
from products.views import ProductView
from django.contrib import admin
urlpatterns = patterns('',
url(r"^$", TemplateView.as_view(template_name="homepage.html"), name="home"),
url(r"^$", ProductView.as_view(), name="list"),
)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
you can set MEDIA_URL in your settings.py then use <img src="{{ MEDIA_URL }}{{ product.image.url }}" />
IMHO you have a problem of how you access the content in the view. If you're using the formview, you should have the data available via {{ form....}} (e.g. {{form.image.url}}).
If you have the object available and you haven't redefined its alias, then you should have it via {{ object.... }}.
Related
Django + Postgres + UUID
UPDATE: I have got it to work! What I did was: Deleted the app Went into Postgres Admin and deleted the Schema for that app Created the app again (using a diff name) Created the Models, URLs, Admin Registering, Views So I've been trying to add a UUID field to my model, to use it in my URL but I keep getting this error django.db.utils.ProgrammingError: column "id" is of type bigint but expression is of type uuid LINE 1: ..._book" ("id", "title", "author", "price") VALUES ('f6b15400-... ^ HINT: You will need to rewrite or cast the expression. Here is my models.py: from django.db import models import uuid from django.urls import reverse # Create your models here. class Book(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', args=[str(self.id)]) Here is the views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Book # Create your views here. class BookListView(ListView): model = Book template_name = 'books/book_list.html' context_object_name = 'book_list' class BookDetailView(DetailView): model = Book template_name = 'books/book_detail.html' context_object_name = 'book' Here is the urls.py: from django.urls import path from .views import BookListView, BookDetailView urlpatterns = [ path('', BookListView.as_view(), name='book_list'), path('<uuid:pk>/', BookDetailView.as_view(), name='book_detail'), ]
First add the uuid field as a normal field with a different name: from django.db import models import uuid from django.urls import reverse class Book(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) Run makemigrations and migrate Now make it primary key: class Book(models.Model): uuid = models.UUIDField(default=uuid.uuid4, primary_key=True) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) This should generate a migration that removes the id field and makes uuid primary key (makemigrations and migrate again). And finally: class Book(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) You may have to adjust the generated migration.
how to register a model item as a view in django
I have a model named Product class Product(models.Model): date = models.DateField(blank=True, null=False, default=timezone.now) name = models.CharField(max_length=40, blank=False, null=True, default="") item_in_stock = models.IntegerField(blank=False, null=True, default=0) price = models.FloatField(blank=False, null=True, default=0.0) supplier = models.ForeignKey(Supplier, null=True, on_delete=models.CASCADE, blank=False) def __str__(self): return self.name and in my django admin panel i want to add a model item from my product model into the side panel like here in ADMININFO but instead of All Products i want to have a product item. for example if i have a product named Shoes i want it to show on the side bar under ADMININFO and when you click it it shows you it's values? Thanks in advance.❤️
You can use ListView class-based View : in views.py of your app directory from django.views.generic import ListView from .models import Product class ProductView(ListView): template_name = "index.html" model = Product # Just point the model not instantiate it Django expose all data in model to html template automatically with the name object_list you can change the name "object_list" with: context_object_name from django.views.generic import ListView from .models import Product class ProductView(ListView): template_name = "index.html" model = Product context_object_name = "products" if you want specific query to the database use get_queryset() from django.views.generic import ListView from .models import Product class ProductView(ListView): template_name = "index.html" model = Product context_object_name = "products" def get_queryset(self): base_query = super().get_queryset() data = base_query.filter(rating_gt=4) return data
How to show all group content if user is a group member
i am new to programming and doing a small project(simple bug tracker) using django-rest-framework. so far i have a Bugs model and if the user is logged in, he can see the bugs reported by him.Now i created a new model called Team in which one can make a team by adding email ids (i used MultiEmailField to store the list of emails).My requirement is that if the logged in user's email is present in any Team, the user should be able to see all the team members activities.I dont know how to accomplish this .please help me.Thanks in advance #bugs model# from django.db import models from django.contrib.auth.models import User class Bugs(models.Model): issueId = models.PositiveIntegerField(primary_key=True) projectName = models.CharField(max_length=300) name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) description = models.TextField(max_length=3000, blank=True) actualResult = models.TextField(max_length=1000, blank=True) expectedResult = models.TextField(max_length=1000, blank=True) status = models.TextField(max_length=30, blank=True) createdAt = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey( User, related_name="bugs", on_delete=models.CASCADE, null=True) #team model# from django.db import models from multi_email_field.fields import MultiEmailField from django.contrib.auth.models import User class Team(models.Model): projectTitle = models.CharField(max_length=300, blank=False, null=True) durationFrom = models.DateField(null=True) durationEnd = models.DateField(null=True) teamMembers = MultiEmailField() owner = models.ForeignKey( User, related_name="team", on_delete=models.CASCADE, null=True) #api.py# from bugs.models import Bugs from rest_framework import viewsets, permissions from .serializers import BugsSerializer class BugsViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = BugsSerializer def get_queryset(self): return self.request.user.bugs.all() def perform_create(self, serializer): serializer.save(owner=self.request.user)
several images on one app
i try to create news app on django 1.8. And I suppose several images in one news that i can to add from the backend. So this is my models.py from django.db import models class Category(models.Model): category = models.CharField('Category', max_length=255) slug = models.CharField(max_length=255) def __unicode__(self): return self.category class Images(models.Model): image = models.ImageField('Images', upload_to='media/img/news') news = models.ForeignKey('News', blank=True, null=True) class News(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey('Category', blank=True, null=True) teazer_image = models.ImageField(upload_to='media/img/news', blank=True) pub_date = models.DateField(null=True) slug = models.CharField(max_length=255) short_content = models.TextField(max_length=2000, blank=True) content = models.TextField(max_length=10000) image = models.ForeignKey('Images', blank=True, null=True) meta = models.CharField(max_length=255, blank=True) description = models.TextField(max_length=10000, blank=True) def __unicode__(self): return self.title Admin.py from django.contrib import admin from news.models import News, Category, Images from django.shortcuts import get_object_or_404 class ImagesInline(admin.TabularInline): model = Images class NewsAdmin(admin.ModelAdmin): inlines = [ ImagesInline, ] admin.site.register(News, NewsAdmin) admin.site.register(Images) admin.site.register(Category) But I do not understand how to create views and template. Can you help me with it?
Implementing product upload dynamically using Django 1.6
So I am using my admin interface to add product information for different items that will be on my site. I am looking to add the product information from my models to a template view, but I would like for every time I add a new product using my admin interface, for the template to generate a new Li tag with the current product information and picture used of the entered data within the admin interface. I have not yet implemented any template logic in my views.py yet I am stumped on how to really wrap my head around making this whole process happen. So can anyone help guide me on how to implement this solution? Thank You! Here is my code below: Models.py from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ import datetime class Designer(models.Model): name = models.CharField(max_length=254, blank=True, null=True) label_name = models.CharField(max_length=254, blank=True, null=True) description = models.TextField(null=True, blank=True) specialites = models.CharField(max_length=254, null=True, blank=True) image = models.ImageField(upload_to='images/designers/main',max_length=100, null=True) #For the argument upload_to, will add to the static folder and generated image will be stored in suing that path specified #For Admin Purposes, to track and see which if still active by for administrative users only is_active = models.BooleanField(default=True) #Metadata class Meta: verbose_name = _("Designer Information") verbose_name_plural = _("Designers") #Helps return something meaningful, to show within the admin interface for easy interaction def __unicode__(self): return "{0} {1}".format(self.name, self.label_name) class Boutique(models.Model): name = models.CharField(max_length=254, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=50, null=True, blank=True) state = models.CharField(max_length=2, null=True, blank=True) zipcode = models.IntegerField(max_length=5, null=True, blank=True) boutique_website = models.URLField(max_length=200, null=True, blank=True) #For Admin Purposes, to track a product to see which is active by administrative users is_active = models.BooleanField(default=True) #Foreign Keys & other relationships designer = models.ForeignKey(Designer) #Metadata class Meta: verbose_name = _("Boutique Information") verbose_name_plural = _("Boutiques") #Helps return something meaningful, to show within the admin interface for easy interaction def __unicode__(self): return "{0}, {1}, {2}".format(self.name, self.city, self.state) class ProductCategory(models.Model): name = models.CharField(max_length=255L, blank=True, null=True) slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.') #For Admin Purposes, to track and see which if still active by for administrative users only is_active = models.BooleanField(default=True) #For Admin Purposes, to track when we add each product and each product was updated by administrative users created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) #Metadata class Meta: verbose_name = _("Product Category") verbose_name_plural = _("Product Categories") #Helps return something meaningful, to show within the admin interface for easy interaction def __unicode__(self): return "{0}".format(self.name) class Product(models.Model): name = models.CharField(max_length=254, blank=True, null=True) description = models.TextField(blank=True, null=True) color_name = models.CharField(max_length=254, null=True, blank=True) size_types = models.CharField(max_length=7, null=True, blank=True) product_price = models.DecimalField(max_digits=9,decimal_places=2) old_price = models.DecimalField(max_digits=9,decimal_places=2, blank=True,default=0.00) #To show original price if, new price has been added product_tags = models.CharField(max_length=254, null=True, blank=True, help_text='Comma-delimited set of SEO keywords for product tag area') novelty = models.CharField(max_length=254, null=True, blank=True) product_website = models.URLField(max_length=200, null=True, blank=True) #To show other sites to Users, where they can purchase the particular product image = models.ImageField(upload_to='images/products/main',max_length=100, null=True) #For the argument upload_to, will add to the static folder and generated image will be stored in suing that path specified slug = models.SlugField(max_length=255, unique=True, help_text='Unique value for product page URL, created from name.') #This shows when each item was uploaded & by who, to the User uploaded_by = models.CharField(max_length=254, blank=True, null=True) uploaded_at = models.DateTimeField(auto_now=True) #For Admin Purposes, to track and see which if still active by for administrative users only is_active = models.BooleanField(default=True) #Foreign Keys & other relationships designer = models.ForeignKey(Designer) boutique = models.ForeignKey(Boutique) category = models.ForeignKey(ProductCategory) #Metadata class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") #Helps return something meaningful, to show within the admin interface for easy interaction def __unicode__(self): return "{0}".format(self.name) Admin.py from __future__ import unicode_literals from django.contrib import admin from products.models import Designer, Product, ProductCategory, Boutique class DesignerAdmin(admin.ModelAdmin): list_display = ["name", "label_name", "description", "specialites", "image", "is_active"] search_fields = ["name", "label_name"] list_per_page = 50 class ProductAdmin(admin.ModelAdmin): list_display = ["name", "description", "color_name", "size_types", "product_price", "old_price", "product_tags", "novelty","product_website", "image", "slug", "uploaded_by", "uploaded_at", "is_active"] search_fields = ["name", "product_price"] list_per_page = 25 class ProductCategoryAdmin(admin.ModelAdmin): list_display = ["name", "slug", "is_active", "created_at", "updated_at"] search_fields = ["name"] list_per_page = 25 class BoutiqueAdmin(admin.ModelAdmin): list_display = ["name", "address", "city", "state", "zipcode", "boutique_website", "is_active"] search_fields = ["name"] list_per_page = 10 #Register Models below admin.site.register(Boutique, BoutiqueAdmin) admin.site.register(Designer, DesignerAdmin) admin.site.register(Product, ProductAdmin) admin.site.register(ProductCategory, ProductCategoryAdmin) Forms.py from __future__ import unicode_literals from django import forms from django.forms import extras, ModelForm from products.models import Designer, Product, ProductCategory, Boutique class DesignerForm(ModelForm): class Meta: model = Designer class ProductForm(ModelForm): class Meta: model = Product class BoutiqueForm(ModelForm): class Meta: model = Boutique class ProductCategoryForm(ModelForm): class Meta: model = ProductCategory Views.Py from __future__ import unicode_literals from django.http import Http404, HttpResponseForbidden from django.shortcuts import redirect, get_object_or_404 from django.utils.http import base36_to_int, int_to_base36 from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.views.generic.base import TemplateResponseMixin, View from django.views.generic.edit import FormView from django.contrib import auth, messages from django.contrib.sites.models import get_current_site from django.shortcuts import render from products.forms import ProductForm, ProductCategoryForm from products.forms import BoutiqueForm from products.forms import DesignerForm from products.models import Boutique, Product, ProductCategory, Designer class ProductView(FormView): template_name = "product_detail/product.html" form_class = ProductForm template_var={} def __init__(self, *arg): super(ProductView, self).__init__() self.arg = arg class ProductCategoryView(FormView): form_class = ProductCategoryForm template_var={} def __init__(self, *arg): super(ProductCategory, self).__init__() self.arg = arg
The easiest way to do this is a simple ListView from Django's generic class-based views. First, string up your views.py: from django.views.generic import ListView class ProductListView(ListView): model = Product template_name = 'product/list_view.html' # Edit this to whatever your template is. Remember to edit your urls.py: from .views import ProductListView urlpatterns = patterns('', ... url(r'^product/$', ProductListView.as_view(), name='list'), # Edit url path and name as desired ... ) Then, make your template: <div class="jumbotron"> <ul> {% for product in products %} <li>{{ product.name }}: {{ product.description }} <img src="{{ product.image.url }}" > {% endfor %} </ul> </div> This is a very basic template which you'll obviously want to customize. For each Product in your database, it will display the name, description, and the image. You can customize your fields as you desire. Other potential issues: 1) Be sure you provide the correct path to your template in your ListView. 2) Set up your MEDIA_URL and other media settings to allow your Product image to display. 3) Look at other customization options in ListView (see documentation here.)