How to show Variation as a product - django

I am trying to show a variation when clicked on its link it displays information as a product
here is my product model
class Product(models.Model):
brand = TreeForeignKey('Brand', verbose_name='brand', related_name='products' , default='')
category = TreeForeignKey('Category', verbose_name='Category', related_name='products' , default='')
title = models.CharField(max_length=120)
description = models.TextField(max_length = 500 ,blank=True ,null=True)
price = models.IntegerField()
active = models.BooleanField(default=True)
is_verified = models.BooleanField(default=False)
in_stock = models.BooleanField(default=False)
slug = models.SlugField(default='')
objects = ProductManager()
here is my variation model
class Variation(models.Model):
VAR_CATEGORIES = (
('size' , 'size'),
('color' , 'color'),
)
product = models.ForeignKey(Product)
category = models.CharField(max_length=120, choices = VAR_CATEGORIES)
title = models.CharField(max_length=120)
price = models.IntegerField()
discount = models.IntegerField(blank=True ,null =True)
active = models.BooleanField(default=True)
quantity = models.IntegerField(null=True , blank=True)
sales_price = models.IntegerField(blank=True ,null =True)
image = models.ImageField(upload_to=image_upload_to)
slug = models.SlugField(default='')
objects = VariationManager()
def get_absolute_url(self):
return reverse("product_detail" , kwargs={"pk":self.pk})
here is my product view
class ProductDetailView(DetailView):
model = Product
template_name = "products/product.html"
#template_name = "<appname>/<modelname>_detail.html"
here is my variation view
class VariationDetailView(DetailView):
model = Variation
template_name = "products/variation.html"
context_object_name = 'variation'
and here is the urls.py
url(r'^(?P<pk>\d+)/$' , ProductDetailView.as_view() , name = 'product_detail'),
url(r'^((?P<pk>\d+)(?:/(?P<slug>[\w\d-]+))?/$' ,VariationDetailView.as_view() , name = 'variation_detail'),
and here is the template
{% for variation in object.variation_set.all %}
<img src = "{{ variation.image.url }}">
{% endfor %}
it does show all the variations of my product but when i click on some variation then it doesnt do anything
where am i wrong?

Related

How to import a object of another model (A) inside model (B) in Django?

I want to create a new object in ModelB when specific condition are met in ModelA. I am new to Django so that I am unable to figure out how exactly I can achieve this.
For example I have two models(Product and ProductVariant), when specific condition on ProductVariant is met then I want to calculate new object value in Product model.
My Product model is like this:
PRODUCT_TYPE = (
('s', 'simple'),
('v', 'varaible')
)
class Products(models.Model):
name = models.CharField(max_length=250,null=True, blank=True,)
slug = models.SlugField(max_length=200, unique=True,null=True)
short_description = HTMLField()
description = HTMLField()
category = models.ForeignKey(Categories, related_name="products",on_delete=models.SET_NULL,null=True,blank=True,)
brand = models.ForeignKey(Brands,on_delete=models.CASCADE, default=None, null=True, blank=True,)
warranty_support = HTMLField()
product_type = models.CharField(choices=PRODUCT_TYPE, default='simple', max_length=50)
And my Product Attribute Model is like this:
class ProductVariant(models.Model):
product = models.ForeignKey(Products,on_delete=models.CASCADE)
variant = models.ForeignKey(ProductAttribute,on_delete=models.CASCADE, null = True, default=None)
managed_stock = models.IntegerField(choices=STOCK_MANAGED, default=0)
stock = models.IntegerField(default=None)
stock_threshold = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
sku = models.CharField(max_length= 250, default=None)
sale_price = models.DecimalField(max_digits=10, decimal_places=2)
sale_start_date=models.DateField(auto_now_add=False, auto_now=False, default=None)
sale_end_date=models.DateField(auto_now_add=False, auto_now=False,default=None)
I am trying to create regular_price and sale_price on Product model if product_type is variable and if sale_end_date is greater than today. I want to set the price from the variant which has the lowest price.
I tried doing like this on Product model:
def clean(self):
if self.product_type == 'varaible' and ProductVariant.objects.filter(product=self, variant_count__gt = 1):
self.min_price = ProductVariant.objects.filter(product=self).Min('price')
self.max_price = ProductVariant.objects.filter(product=self).Max('price')
but I am not able to achieve what I want,
How can I do this?
After some research and analysis I found solution to my problem, I am posting the solution here so that someone with similar problem could be benefited.
#property
def get_price(self):
result = dict()
variants = ProductVariant.objects.filter(product=self)
count = variants.count()
if count > 1:
min_variant = variants.order_by('price').first()
max_variant = variants.order_by('-price').first()
result['min_price'] = min_variant.price
result['max_price'] = max_variant.price
elif count == 1:
variant = variants.first()
if variant.sale_price:
result['price'] = variant.price
result['sale_price'] = variant.sale_price
sale_variant = variants.order_by('sale_price').first()
result['lowest_sale_price'] = sale_variant.sale_price
result['regular_price'] = sale_variant.price
today = datetime.date.today()
if variant.sale_start_date <= today and variant.sale_end_date >= today:
result['sale_end_date'] = variant.sale_end_date
else:
result['price'] = variant.price

Having issue in handling multipart form data in django rest framework

I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. multipart/form-data is used because there is an image field that needs to be sent in arrays.
But I got the following error.
Category field is required
The data is sent like this
name: Soap
category[0]: 7
category[1]: 23
brand: 7
collection: 11
availability: in_stock
warranty: no_warranty
service: cash_on_delivery
rating: 3
best_seller: true
top_rated: true
featured: true
main_product_image: (binary)
merchant: 2
variants[0][product_id]: fgfdg
variants[0][price]: 127
variants[0][quantity]: 1
variants[0][color]: red
variants[0][size]: M
variants[0][variant_availability]: not_available
variants[0][variant_image]: (binary)
variants[1][product_id]: fgfdg
variants[1][price]: 127
variants[1][quantity]: 1
variants[1][color]: red
variants[1][size]: M
variants[1][variant_availability]: not_available
variants[1][variant_image]: (binary)
The same issue is with the variants.
My models:
class Variants(models.Model):
product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True)
price = models.DecimalField(decimal_places=2, max_digits=20,default=500)
size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True)
color = models.CharField(max_length=70, default="not applicable",blank=True,null=True)
variant_image = models.ImageField(upload_to="products/images", blank=True,null=True)
thumbnail = ImageSpecField(source='variant_image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product
variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available')
class Meta:
verbose_name_plural = "Variants"
def __str__(self):
return self.product_id
#Product Model
class Product(models.Model):
merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
category = models.ManyToManyField(Category, blank=False)
sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
featured = models.BooleanField(default=False) # is product featured?
best_seller = models.BooleanField(default=False)
top_rated = models.BooleanField(default=False)
tags = TaggableManager(blank=True) # tags mechanism
name = models.CharField(max_length=150,unique=True)
main_product_image = models.ImageField(upload_to="products/images", null=True, blank=True)
thumbnail = ImageSpecField(source='main_product_image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
slug = models.SlugField(max_length=200,blank=True)
description = RichTextField(blank=True)
#picture = models.ImageField(upload_to="products/images", null=True, blank=True)
picture = models.ManyToManyField(ImageBucket,null=True,blank=True,verbose_name="Add extra 3 images")
rating = models.IntegerField(choices=((1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5))
)
availability = models.CharField(max_length=70, choices=AVAILABILITY, default='in_stock')
warranty = models.CharField(max_length=100, choices=WARRANTY, default='no_warranty')
services = models.CharField(max_length=100, choices=SERVICES, default='cash_on_delivery')
variants = models.ManyToManyField(Variants,related_name='products')
My view:
class ProductAddAPIView(CreateAPIView):
permission_classes = [IsAuthenticated]
parser_classes = [MultiPartParser,JSONParser,FormParser]
# queryset = Product.objects.all()
serializer_class = AddProductSerializer
Here I have used parser class just in case if it works.
Updated Code:
class AddProductSerializer(serializers.ModelSerializer):
id = serializers.PrimaryKeyRelatedField(read_only=True)
variants = VariantSerializer(many=True)
slug = serializers.SlugField(read_only=True)
class Meta:
model = Product
fields = ['id','merchant','featured', 'top_rated','category','brand','collection','sub_category',
'name','slug','description', 'main_product_image','best_seller','picture',
'rating','availability','warranty','services','variants']
#depth = 1
def create(self, validated_data):
#user = self.context['request'].user
picture_data = validated_data.get('picture')
merchant = validated_data.get('merchant')
category_data = validated_data.get('category')
featured = validated_data.get('featured')
top_rated = validated_data.get('top_rated')
brand = validated_data.get('brand')
collection = validated_data.get('collection')
sub_category = validated_data.get('sub_category')
name = validated_data.get('name')
description = validated_data.get('description')
main_product_image = validated_data.get('main_product_image')
best_seller = validated_data.get('best_seller')
rating = validated_data.get('rating')
availability = validated_data.get('availability')
warranty = validated_data.get('warranty')
services = validated_data.get('services')
#variants_logic
variants_data = validated_data.get('variants')
#breakpoint()
print(variants_data)
# from pudb import set_trace;set_trace()
#products-logic
product = Product.objects.create(featured=featured,top_rated=top_rated,
brand=brand,collection=collection,sub_category=sub_category,
name=name,description=description,
main_product_image=main_product_image,
best_seller=best_seller,rating=rating,
availability=availability,warranty=warranty,
services=services,merchant=merchant)
product.save()
product.category.set(category_data)
# product.variants.set(variants_data)
product.save()
for variants_data in variants_data:
abc = Variants.objects.create(**variants_data)
product.variants.add(abc)
product.save()
return product

Show all products from category parent

im new in django, and im doing an ecommerce website. I have a problem, When I click on a subcategory its okay, it shows all the products of that subcategory. But I want to click on a category parent and show all the products that his children has, and i dont know how to do that.
Here is my models:
class Category(models.Model):
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null = True)
title = models.CharField(max_length= 200, null = True)
slug = models.SlugField(max_length=200, null = True)
ordering = models.IntegerField(default = 0)
class Meta:
verbose_name_plural = 'Categories'
ordering = ('ordering',)
def __str__(self):
return self.title
class Product(models.Model):
name = models.CharField(max_length = 255, null = True)
slug = models.SlugField(max_length=200)
category = models.ForeignKey(Category, related_name='products', on_delete = models.CASCADE)
parent = models.ForeignKey('self', related_name = 'variants', on_delete = models.CASCADE, blank = True, null = True)
brand = models.ForeignKey(Brand, related_name='products', null = True, on_delete = models.CASCADE)
description = models.TextField(blank = True, null = True)
price = models.FloatField(null = True)
disccount = models.BooleanField(default = False)
disccount_price = models.FloatField(blank = True, null = True)
image = models.ImageField(upload_to = 'images/',blank = True, null = True)
thumbnail = models.ImageField(upload_to = 'images/', blank = True, null = True)
date_added = models.DateTimeField(auto_now_add = True)
class Meta:
ordering = ('-date_added',)
def __str__(self):
return self.name
Here is my view:
def category_detail(request, slug):
products = Product.objects.all()
subcategories = []
if slug:
category = get_object_or_404(Category, slug=slug)
products = products.filter(category = category)
subcategories = Category.objects.filter(parent = category)
context = {
'category': category,
'subcategories': subcategories,
'products' : products,
}
return render(request, 'category_detail.html', context)
So please I need some help:(
You can filter on Products that belong to a subcategory of a category category with:
products = products.filter(category__parent=category)
or if you want Products that belong to the category or to a category with as parent the category, you can filter with Q objects [Django-doc]:
from django.db.models import Q
products = products.filter(
Q(category__parent=category) |
Q(category=category)
)

get post by name of user or by id

i have this model
class Post(models.Model):
auth = models.ForeignKey(settings.AUTH_USER_MODEL,default=1)
title = models.CharField(max_length=120)
DESCSPECSOFT = (
(u'Null','Null'),
(u'Phone',u'Phone'),
(u'Car',u'Car'),
(u'Laptop',u'Laptop'),
(u'jops',u'Jops'),
(u'Electronic',u'Electronic'),
(u'Clothes',u'Clothes'),
(u'Makeup',u'Makeup'),
(u'Furnishings',u'Furnishings'),
(u'books',u'books'),
(u'sports',u'sports'),
(u'Property',u'Property'),
(u'Other',u'Other'),
)
City = (
(u'Null','Null'),
(u'Kosti',u'Kosti'),
(u'Khartoum',u'Khartoum'),
(u'Rabbik',u'Rabbik'),
(u'Duwaim',u'Duwaim'),
(u'Sinnar',u'Sinnar'),
(u'Bahri',u'Bahri'),
(u'Omdurman',u'Omdurman'),
(u'Sawakin',u'Sawakin'),
(u'Port Sudan',u'Port Sudan'),
(u'Kasala',u'Kasala'),
(u'Madani',u'Madani'),
(u'Alabid',u'Alabid'),
)
Case = (
(u'Null','Null'),
(u'New',u'New'),
(u'Old',u'Old'),
(u'Second Hand',u'Second Hand'),
(u'Other',u'Other'),
)
Type = models.CharField(choices=DESCSPECSOFT, default='Null',blank = False,null = False,max_length=120)
company = models.CharField(max_length=120)
dis = models.TextField(default="in here you w,ll write all the discribtion about your product")
image = models.ImageField(null=True,blank=True,width_field="width_field", height_field="height_field")
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
case = models.CharField(choices=Case, default=99,blank = False,null = False,max_length=120)
price = models.BigIntegerField(default=0)
city = models.CharField(choices=City, default='Null',blank = False,null = False,max_length=120)
address = models.CharField(max_length=120)
draft = models.BooleanField(default=False)
#pup = models.DateField(auto_now=False,auto_now_add=False ,null=False)
date = models.DateTimeField(auto_now=True ,auto_now_add=False)
puplis = models.DateTimeField(auto_now=False ,auto_now_add=True)
objects = PostManager()
def __str__(self):
return self.title
def __unicode__(self):
return self.title
any user can add a post but i want the user name show in the data base means the user how add the post because every post show the admin name not the user how add the post can someone show me haw can i fix this ???
sorry my en is bad ...

Django Truncated incorrect DOUBLE value:

I'm attempting to pull a user's organization, and provide a queryset to on a context processor that will get filtered through multiple different filter depending on the menu selection. The current error I am getting is as titled: Truncated incorrect DOUBLE value:(followed by the org_name of one of all the organizations databased). I have no problems until I create a news article and attach an organization.
organizations model:
class Organizations(models.Model):
org_name = models.CharField(max_length=200)
org_admin = models.ForeignKey(User) #Defines the admin user account for editing
org_description = models.CharField(max_length=1000)
org_phone = models.CharField(max_length=10)
org_county = models.ForeignKey(County)
org_address = models.CharField(max_length=200, blank=True)
org_address2 = models.CharField(max_length=200, blank=True)
org_city = models.CharField(max_length=200, blank=True)
org_zip = models.CharField(max_length=10, blank=True)
org_type = models.ForeignKey(OrgType, blank=True)
sub_org = models.ForeignKey('self', null=True, blank=True) # defines a heirarchy of organiztions
org_logo = models.ImageField(upload_to = 'pic_folder/', blank=True)
org_web = models.CharField(max_length=500, blank=True)
org_facebook = models.CharField(max_length=200, blank=True)
org_twitter = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return self.org_name
news model:
class News(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User)
slug = models.SlugField(unique=True)
content = models.TextField()
date = models.DateTimeField(default=datetime.now)
category = models.CharField(max_length=1, choices=NEWS_CATEGORIES, blank=True)
news_orgs = models.ManyToManyField(Organizations, blank=True)
news_county = models.ManyToManyField(County, blank=False)
def __unicode__(self):
return self.title
UserOrgConnections model :
class UserOrgConnections(models.Model):
user = models.ForeignKey(User)
orgs = models.ManyToManyField(Organizations)
context processor:
def mynews(request):
now = datetime.now()
if request.user.is_authenticated():
user = request.user.get_profile()
userorgs = UserOrgConnections.objects.filter(user = user)
print userorgs.values('orgs')
county = user.county.all()
MyNews = News.objects.filter(news_orgs__org_name=userorgs)
promotions = OrgPromotion.objects.filter(organization__org_county=county)
dailyspecials = OrgDailySpecials.objects.filter(organization__org_county=county)
newsall = MyNews.all().order_by('-date')
entnews = MyNews.filter(news_county=county, category='E')
technews = MyNews.filter(news_county=county, category='T')
healthnews = MyNews.filter(news_county=county, category='H')
livingnews = MyNews.filter(news_county=county, category='L')
humornews = MyNews.filter(news_county=county, category='H')
travelnews = MyNews.filter(news_county=county, category='R')
moneynews = MyNews.filter(news_county=county, category='M')
return {
'newsall': newsall,
'now': now,
'entnews': entnews,
'technews': technews,
'livingnews': livingnews,
'humornews': humornews,
'travelnews': travelnews,
'moneynews': moneynews,
}
The template snippet:
{% for newsall in newsall %}
{% if newsall.date >= now %}
{{ newsall }}
{{newsall.date }}
{% endif %}
{% endfor %}
The following sequence of code looks suspicious:
userorgs = UserOrgConnections.objects.filter(user = user)
MyNews = News.objects.filter(news_orgs__org_name=userorgs)
This is effectively asking for a sequence of News objects whose news_orgs.org_name value is equal to the list of userorgs. You haven't listed the model for UserOrgConnections so it's not possible to determine a solution with the information provided.
Perhaps you should look at the Django Queryset in operator which is capable of performing a query which filters on a list.