how to add photo - python

I have a simple model, witch is used as a form .
class Test(models.Model):
name = models.CharField(max_length=100, unique=True, db_index=True)
location = models.CharField(max_length=300)
details = models.TextField()
def __unicode__(self):
return self.image.name
I would like to add the following class Album as a foreign key to Test :
class Album(models.Model):
title = models.CharField(max_length=60)
public = models.BooleanField(default=False)
def __unicode__(self):
return self.title
class Tag(models.Model):
tag = models.CharField(max_length=50)
def __unicode__(self):
return self.tag
class Image(models.Model):
title = models.CharField(max_length=60, blank=True, null=True)
image = models.FileField(upload_to="images/")
tags = models.ManyToManyField(Tag, blank=True)
albums = models.ManyToManyField(Album, blank=True)
created = models.DateTimeField(auto_now_add=True)
rating = models.IntegerField(default=50)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
user = models.ForeignKey(User, null=True, blank=True)
def __unicode__(self):
return self.image.name
Questions:
How to add class Album as a foreigh key to class Test?
How to put this relation on the form? - e.g. user is selecting multiple images for uploads wich results in unique Album related to Test class.

Do you mean something like this for the foreign-key
class Test(models.Model):
name = models.CharField(max_length=100, unique=True, db_index=True)
location = models.CharField(max_length=300)
details = models.TextField()
album = models.ForeignKey(Album, null=True, blank=True)
def __unicode__(self):
return self.name

Related

How to filter Many to Many field in django admin page using a foreign key value?

I am trying to filter my many to many variation fields with respect to the product. means, I only want the variations related to the current product to show in the admin page. now its showing all the variations available for every product.
I added formfield_for_manytomany() function to my admin.py but how can I get the current product(id) in the cart or order to filter the variations?
most of the questions in stack overflow Is based on the current user, which is easy to get? but how should I get the specific product(id) that is opened in the admin panel.
admin.py
from django.contrib import admin
from .models import *
from products.models import Variation
class CartAdmin(admin.ModelAdmin):
list_display = ('cart_id', 'date_created')
class CartItemAdmin(admin.ModelAdmin):
list_display = ('user','cart', 'product', 'quantity','is_active')
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "variation":
product = Products.objects.get(id='??') # how I get the current product in the cart or order
kwargs["queryset"] = Variation.objects.filter(product=product.id)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Cart, CartAdmin)
admin.site.register(CartItem, CartItemAdmin)
CartItem Model
class CartItem(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True)
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation = models.ManyToManyField(Variation, blank=True)
quantity = models.IntegerField()
is_active = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
def item_total(self):
return self.product.price * self.quantity
def __str__(self):
return self.product.name
Product and Variation Model
class Products(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = AutoSlugField(populate_from='name', max_length=100, unique=True)
isbn = models.CharField(max_length=20, unique=True, blank=True, null=True)
sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True)
author = models.CharField(max_length=100)
Publisher = models.CharField(max_length=100, blank=True, default=None)
release_date = models.DateField(blank=True, null=True, default=None)
price = models.IntegerField(default=None)
stock = models.IntegerField(default=None)
is_available = models.BooleanField(default=True)
cover_image = models.ImageField(upload_to='images/products')
image1 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image2 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image3 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
description = models.TextField(max_length=2000, blank=True, default=None)
create_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
number_of_pages = models.IntegerField(blank=True, null=True)
weight = models.IntegerField(blank=True, null=True)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
spine_width = models.IntegerField(blank=True, null=True)
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
def get_url(self):
return reverse('product-view', args=[self.slug])
def __str__(self):
return self.name
class Variation(models.Model):
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation_category = models.CharField(max_length=100, choices=variation_category_choice)
variation_value = models.CharField(max_length=100, choices=variation_value_choice)
is_available = models.BooleanField(default=True)
date_added = models.DateTimeField(auto_now_add=True)
objects = VariationManager()
def __str__(self):
return self.variation_value

How to short down this code to create django model so it works the same in term of functionality

Just imagine Netflix Site, I want to store video links of multiple seasons of TV shows with multiple episodes, I want to increment number of seasons and episode of a certain tv show on the need specifically from admin area. I don't know ho to do that instead of just creating variable of every episode link and season model. Please Help ! Thanx in adv
class Tv_Shows(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
author = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='blog_posts')
body = models.TextField()
episode1 = models.CharField(max_length=100, null=True)
episode2 = models.CharField(max_length=100, null=True)
episode3 = models.CharField(max_length=100, null=True)
episode4 = models.CharField(max_length=100, null=True)
episode5 = models.CharField(max_length=100, null=True)
episode6 = models.CharField(max_length=100, null=True)
episode7 = models.CharField(max_length=100, null=True)
episode8 = models.CharField(max_length=100, null=True)
episode9 = models.CharField(max_length=100, null=True)
episode10 = models.CharField(max_length=100, null=True)
imdb_rating = models.DecimalField(null=True, max_digits=12, decimal_places=1)
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
views = models.IntegerField(default=0)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day, self.slug])
objects = models.Manager() # The default manager.
published = PublishedManager() # Our custom manager.
tags = TaggableManager()
You need to create an Episode model with a foreign key which represents the show.
this would be the normal db design and you don't need to alter your model every time.
This is how it would look like.
class TvShow(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
imdb_rating = models.DecimalField(null=True, max_digits=12, decimal_places=1)
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
views = models.IntegerField(default=0)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])
objects = models.Manager() # The default manager.
published = PublishedManager() # Our custom manager.
tags = TaggableManager()
class Episode(models.Model):
title = models.CharField(max_length=250)
show = models.ForeignKey(TvShow, on_delete=models.CASCADE, related_name='episodes')
...
objects = models.Manager()
If an episode can have more than one tv-show as it's parent, then you can go for a many to many field.
Now, to access all the episodes that a show has, you can do
tv_show = TvShow.objects.get(**kwargs)
tv_show.episode_set
# returns a django queryset object
relevant docs regarding the same is here:
django documentation
Create a new table episode, create a one-to-many relationship between the two tables.
Think like this:
Episodes has the main content. Seasons and Tv show details are just the meta data. So start from the main content (very small child).
Episodes > Seasons > Tv Show
So how the database design looks like:
Class TvShow(models.Model):
name = models.CharField(max_length=30)
...
def get_all_seasons(self):
return self.tv_show_seasons.all().order_by('-created') # all seasons for particular tv show
Class Season(models.Model):
tv_show = models.ForeignKey('TvShow', on_delete=models.CASCADE, related_name='tv_show_seasons')
number = models.CharField(max_length=30)
...
def get_all_episodes(self):
return self.season_episodes.all().order_by('-created') # all episodes for a particular season
Class Episode(models.Model):
season = models.ForeignKey('Season', on_delete=models.CASCADE, related_name='season_episodes')
...
This is the suggestive approach to do it.

django admin page customization

This is what I did in my models.py folder
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank=False)
image = models.ImageField(null=True, blank=True)
def __str__ (self):
return self.name
But am getting this as my result in my django admin page
And I want to display the products by their name
PRODUCT
Product object (2)
Product object (1)
2 products
Make sure __str__ is a method of your Product class and not a function of your models file.
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank=False)
image = models.ImageField(null=True, blank=True)
def __str__ (self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank=False)
image = models.ImageField(null=True, blank=True)
def __str__ (self):
return self.name
def__Str__(self):
return self.name
it's return objects.name

Django: How to import model from same app?

I've an app called lists.
This has 3 main models: List, ListItem and School.
Every list could be related to 1 school, or this field could be empty.
But when I'm trying to update my model List to have a school field I'm getting:
ImportError: cannot import name 'School' from 'lists.models' (D:\web_proyects\scolarte\lists\models.py)
(scolarte)
Even thought both models are in the same models.py file.
I've tried:
from .models import School
And:
from lists.models import School
lists/models.py:
from django.db import models
from products.models import Product
from roles.models import User
from .models import School
# Create your models here.
class List(models.Model):
LISTA_STATUS = (
('recibida_pagada', 'Recibida y pagada'),
('recibida_no_pagada', 'Recibida pero no pagada'),
('en_revision', 'En revision'),
('en_camino', 'En camino'),
('entregada', 'Entregada'),
('cancelada', 'Cancelada')
)
lista_id = models.CharField(max_length=100)
name = models.CharField(max_length=100)
user = models.OneToOneField(User, on_delete=models.CASCADE)
school = models.OneToOneField(School, on_delete=models.CASCADE)
status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_pagada')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.id)
class ListItem(models.Model):
lista = models.ForeignKey(List, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
comment = models.CharField(max_length=100, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
step_two_complete = models.BooleanField(default=False)
def sub_total(self):
return int(self.product.price)
class School(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=False)
address_reference = models.CharField(max_length=100, blank=False)
provincia = models.CharField(max_length=100, blank=False, null=True)
canton = models.CharField(max_length=100, blank=False, null=True)
parroquia = models.CharField(max_length=100, blank=False, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.name)
You don't need to import School since its already in the same model. However you do need to define School first before you can then reference it in another class in the same model file. Update your model so School is defined before List
from django.db import models
from products.models import Product
from roles.models import User
from .models import School
# Create your models here.
class School(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=False)
address_reference = models.CharField(max_length=100, blank=False)
provincia = models.CharField(max_length=100, blank=False, null=True)
canton = models.CharField(max_length=100, blank=False, null=True)
parroquia = models.CharField(max_length=100, blank=False, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.name)
class List(models.Model):
LISTA_STATUS = (
('recibida_pagada', 'Recibida y pagada'),
('recibida_no_pagada', 'Recibida pero no pagada'),
('en_revision', 'En revision'),
('en_camino', 'En camino'),
('entregada', 'Entregada'),
('cancelada', 'Cancelada')
)
lista_id = models.CharField(max_length=100)
name = models.CharField(max_length=100)
user = models.OneToOneField(User, on_delete=models.CASCADE)
school = models.OneToOneField(School, on_delete=models.CASCADE)
status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_pagada')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.id)
class ListItem(models.Model):
lista = models.ForeignKey(List, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
comment = models.CharField(max_length=100, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
step_two_complete = models.BooleanField(default=False)
def sub_total(self):
return int(self.product.price)

How to link a select category from template to django model object?

I have a many to many relationship in my product model (category field). I am able to display the category data in a select box which is a multiple selection. What I want to do is have the user select one or more categories from the template and then save the data in my product model. Here is my code:
if request.method =='POST':
print ('entered')
name = request.POST['name']
brand = request.POST['brand']
sku = request.POST['sku']
price = request.POST['price']
quantity = request.POST['quantity']
description = request.POST['description']
imageurls = request.POST['urls']
print('imageurls',imageurls)
categorylist = request.POST['categories']
print('categorylist',categorylist)
categories = re.findall(r"[\w']+", categorylist)
print categories
imageurls = imageurls.split('~')
print('iageurls',imageurls)
for x in categories:
categoryobj = Category.objects.filter(name=x).values()
_id = categoryobj.id
print('_id',_id)
print ('categoryobj',categoryobj)
# Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls,categories=categoryobj)
return HttpResponse('success')
models.py
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255,
help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField("Meta Description", max_length=255,
help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('catalog:categories', kwargs={'category_slug': self.slug})
class Meta:
ordering = ['-created_at']
verbose_name_plural = 'Categories'
class Product(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255, unique=True,
help_text='Unique value for product page URL, created from name.')
brand = models.CharField(max_length=50)
sku = models.CharField(max_length=50)
price = models.DecimalField(max_digits=9, decimal_places=2)
old_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
thumbnail = models.FileField(upload_to='static/images/products/thumbnails')
imageurls = models.CharField(max_length=1000)
is_active = models.BooleanField(default=True)
is_bestseller = models.BooleanField(default=False)
is_featured = models.BooleanField(default=False)
quantity = models.IntegerField()
description = models.TextField()
meta_keywords = models.CharField(max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField(max_length=255, help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
categories = models.ManyToManyField(Category)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('catalog:products', kwargs={'product_slug': self.slug})
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
class Meta:
ordering = ['-created_at']
You should use Django ModelForms. So you only need to check if form.is_valid() and then do form.save().
Save method authomatically creates a new object for you.
Let me know if this works!

Categories

Resources