Implementing product upload dynamically using Django 1.6 - python
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.)
Related
an Inline class isnt working in django admin
I created a ProductAttributes model that have a ForeignKey from Product model now i'm trying to create an admin panel for adding product using django admin i'm adding ProductAttributes to Product admin with TabularInline but its not working this the models and admin classes #models class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) introduction = models.TextField(null=True, blank=True) unit_price = models.DecimalField( max_digits=12, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField(validators=[MinValueValidator(0)]) last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT, related_name='products') promotions = models.ManyToManyField(Promotion, blank=True) def __str__(self) -> str: return self.title class Meta: ordering = ['title'] class ProductAttributes(models.Model): Product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="attributes") attribute = models.CharField(max_length=255) #admin class ProductAttributesInline(admin.TabularInline): model = models.ProductAttributes #admin.register(models.Product) class ProductAdmin(admin.ModelAdmin): autocomplete_fields = ['collection'] prepopulated_fields = { 'slug': ['title'] } actions = ['clear_inventory'] inlines = [ProductAttributesInline] list_display = ['title', 'unit_price', 'inventory_status', 'collection_title'] list_editable = ['unit_price'] list_filter = ['collection', 'last_update', InventoryFilter] list_per_page = 10 list_select_related = ['collection'] search_fields = ['title'] def collection_title(self, product): return product.collection.title #admin.display(ordering='inventory') def inventory_status(self, product): if product.inventory < 10: return 'Low' return 'OK' #admin.action(description='Clear inventory') def clear_inventory(self, request, queryset): updated_count = queryset.update(inventory=0) self.message_user( request, f'{updated_count} products were successfully updated.', messages.ERROR ) class Media: css = { 'all': ['store/style.css'] } the ProductAttributes isnt shown in Product admin in the orginal project i created another inline for ProductImage and its working but when i try to delete that inline its not gone from product admin
Firstly, do not forget checking all migrations, and It would be more good to keep your models in models.py and do not mix them with admin related changes. I would recommend you to write them in admin.py. You can use both images and attributes like that: class ProductAttributesInlineAdmin(admin.TabularInline): model = ProductAttributes extra = 2 #admin.register(models.Product) class ProductAdmin(admin.ModelAdmin): ... inlines = [ProductAttributesInlineAdmin, ProductImageInlineAdmin]
How can I Properly use Django Class Based View UserPassesTestMixin in UpdateView
I am working on a Django project where users would have one bank record. And I don't want them to be able to update another one's bank record except their own. I want to use Django UserPassesTestMixin to perform this restriction but I am getting 403 Forbidden error any time I try to access the UpdateView. Here is my Models code: class BankDetails(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) bank = models.CharField(max_length=30, choices=BANK, blank=True, null=True) account = models.CharField(max_length=20, blank=True, default=None, null = True) name = models.CharField(max_length=60, blank=True, null=True) branch = models.CharField(max_length=60, blank=True, null = True) date = models.DateTimeField(auto_now_add=True) Here is Class based views code: from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin, UserPassesTestMixin class UpdateBank(LoginRequiredMixin, UserPassesTestMixin, UpdateView): template_name = 'user/edit_bank.html' model = BankDetails form_class = ApplicantBankForm def get_success_url(self): return reverse_lazy('bank-detail',kwargs={'pk': self.get_object().id}) def test_func(self): return self.get_object().applicant_id == self.request.user.pk class BankDetailView(LoginRequiredMixin, DetailView): template_name = 'user/bank_detail.html' model = BankDetails def get_success_url(self): return reverse_lazy('app-submit', kwargs = {'pk' : self.get_object().id}) my urls.py code: path('<int:pk>/update/', UpdateBank.as_view(), name = 'edit-bank'),
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)
Displaying images from model using Django
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.... }}.