(edit added more code)
Keep getting an error here where its asking me to convert bound method to decimal. I think the problem is this line:
order_item = OrderItem(item=item.item_id, quantity=item.quantity, price=item.price, order=order)
I think Django wants me to convert item.price into a decimal, but I've been unable to figure out how. I tried decimal.Decimal(str(item.price)) which didn't work, and float(item.price) didnt work as well. As always, thanks in advance.
#cart.get_cart_items
def get_cart_items(request):
return Cart.objects.filter(cart_id=_cart_id(request))
#models
class Cart(models.Model):
cart_id = models.CharField(max_length=50)
item_id = models.ForeignKey('store.Item', unique=False)
date_added = models.DateTimeField(auto_now_add=True)
quantity = models.IntegerField(default=1)
class Item(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=75)
slug = models.SlugField(max_length=50, unique=True)
is_active = models.BooleanField(default=True, blank=True)
image1 = models.ImageField(upload_to='img')
image2 = models.ImageField(upload_to='img', blank=True)
image3 = models.ImageField(upload_to='img', blank=True)
image_caption1 = models.CharField(max_length=200, blank=True)
image_caption2 = models.CharField(max_length=200, blank=True)
image_caption3 = models.CharField(max_length=200, blank=True)
price = models.DecimalField(max_digits=8, decimal_places=2)
quantity = models.IntegerField(default=1)
description = models.TextField()
created = models.DateTimeField(auto_now_add=True)
shipping_price = models.DecimalField(decimal_places=2, max_digits=6)
categories = models.ManyToManyField(Category)
#views
def express_payment(request):
user = request.user
cart_subtotal = cart.cart_subtotal(request)
if request.method == "POST":
form = PaymentForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
order.buyer = request.user
order.transaction_id = "12345678901234567890"
order.save()
if order.pk:
cart_items = cart.get_cart_items(request)
for item in cart_items:
order_item = OrderItem(item=item.item_id, quantity=item.quantity, price=item.price, order=order)
order_item.save()
Please provide more error info, or we just cannot provide any meaning help..
Edit:
Assume that the class Item and OrderItem is the same thing, then I think user, name, is required to save a OrderItem instance.
Related
While creating new products I'm getting such kind of error. Can someone help me?
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
name_geo = models.CharField(max_length=200, null=True, blank=True)
image = models.ImageField(null=True, blank=True, default='/placeholder.png')
brand = models.CharField(max_length=200, null=True, blank=True)
category = models.ForeignKey(Category, null=False, default=0, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
countInStock = models.IntegerField(null=True, blank=True, default=0)
createdAt = models.DateTimeField(auto_now_add=True)
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return self.name_geo
class Category(models.Model):
_id = models.AutoField(primary_key=True, editable=False)
name = models.CharField(max_length=200, null=True, blank=True)
createdAt = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
#api_view(['POST'])
def createProduct(request):
user = request.user
product = Product.objects.create(
user=user,
name_geo="Sample Name",
category="Sample Category",
price=0,
brand='Sample Brand',
countInStock=0,
)
serializer = ProductSerializer(product, many=False)
return Response(serializer.data)
Without separating category class in models.py everything works fine. I mean If i didn't use ForeignKey in Products class for category
It just has to be a Category Instance/Object
product = Product.objects.create(
user=user,
name_geo="Sample Name",
category=Category.objects.get_or_create(name="Sample Category"),
price=0,
brand='Sample Brand',
countInStock=0,
)
Notes:
You could just do a .get() or a .filter().first() if you don't want to create
If you use a form, you can get away with just the Category's PK/_id in the POST
this type of thing: f = form(request.POST) f.is_valid() f.save()
At the end that field will hold the PK/_id/Row# of the Category Obj
Hello everyone I'm trying top build a task manager web app using django, I need to assign task to one or multiple users I'm using manytomany relation in models.py and in views.py I'm adding created_by user automatically.
My problem is that when I do that I see that no users selected in assigned users but if I add created by user from the form it worked well.
class Task(models.Model):
task_id = models.AutoField(primary_key=True)
shortcode = models.CharField(max_length=15, unique=True, blank=True, null=True)
task_name = models.CharField(max_length=200)
task_progress = models.ForeignKey(TaskProgressStatus, on_delete=models.CASCADE, blank=True, null=True)
customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=True, null=True)
task_priority = models.ForeignKey(TaskPriority, on_delete=models.CASCADE)
assigned_to_employee = models.ManyToManyField(User)
paid = models.BooleanField(default=False)
on_account = models.BooleanField(default=False)
currency = models.ForeignKey(Currency, on_delete=models.CASCADE, blank=True, null=True)
net_amount = models.DecimalField(decimal_places=2, max_digits=20, blank=True, null=True)
vat = models.IntegerField(default=11)
quote_validity = models.CharField(max_length=200, default='1 Month from offer date')
delivered = models.BooleanField(default=False)
delivered_date = models.DateTimeField(null=True, blank=True)
creation_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
due_date = models.DateTimeField(null=True, blank=True)
created_by = models.ForeignKey(User, related_name='created_by_username', on_delete=models.CASCADE, null=True, blank=True)
project = models.ForeignKey(Project, null=True, blank=True, on_delete=models.CASCADE)
file_name = models.FileField(upload_to='projects_files', null=True, blank=True)
notes = models.TextField()
def __str__(self):
return str(self.task_name)
#login_required
def addtask(request):
form = taskForm()
if request.method == 'POST':
form = taskForm(request.POST)
if form.is_valid():
newform = form.save(commit=False)
newform.created_by = request.user
newform.save()
return HttpResponseRedirect(request.path_info)
else:
context = {'form':form}
return render(request, 'tasks/add_task.html', context)
Update
As well pointed out by Ahmed I. Elsayed there is some inconsistency in the title of the question, since the created_by field is actually a ForeignKey, not a ManyToManyField.
That being said, your issue is actually with the foreign key.
My suggestion is to first of all be sure that your form is actually valid. You can do that by printing something inside the if form.is_valid() block.
I'm trying to build an auctions website that allows users to bid on listings. For a user to successfully place a bid they must input an amount higher than the current highest bid and if there is no current highest bid because no user has placed a bid yet, that first bid input must be higher than the listing start price.
I want to add a form validation to my BidForm to raise an error if the input doesn't fit these conditions but I have a pylint error on listing.id in def clean_bid_input and it says it is an undefined variable so I feel my form validation isn't quite right. Please could someone have a look and see if my form validation is following the logic I'm hoping it will?
models.py
class Listing(models.Model):
class NewManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='active')
options = (
('active', 'Active'),
('closed', 'Closed'),
)
title = models.CharField(max_length=64)
description = models.TextField(max_length=64)
start_price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)])
image = models.URLField(max_length=200, blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings")
lister = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="lister_user")
date_added = models.DateTimeField(default=timezone.now)
status = models.CharField(max_length=10, choices=options, default="active")
winner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET(get_sentinel_user), related_name="winner_user", null=True)
favourites = models.ManyToManyField(User, related_name="favourite", default=None, blank=True)
objects = models.Manager()
listingmanager = NewManager()
def __str__(self):
return f"{self.title} ({self.pk}, £{self.start_price}, {self.lister})"
class Bid(models.Model):
bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidders")
bid_item = models.ManyToManyField(Listing, related_name="bid_items", default=None)
bid_input = models.DecimalField(max_digits=9, decimal_places=2, default=None)
time = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"Bid amount: {self.bid_input}"
forms.py
class NewListingForm(forms.ModelForm):
class Meta:
model = Listing
fields = ["title", "description", "start_price", "image", "category"]
title = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}))
description = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}))
start_price = forms.DecimalField(label='Starting Bid Price (£)')
image = forms.URLField(widget=forms.URLInput(attrs={'autocomplete':'off'}))
category = forms.ModelChoiceField(queryset=Category.objects.all())
class BidForm(forms.ModelForm):
class Meta:
model = Bid
fields = ["bid_input"]
labels = {"bid_input": ""}
widgets = {
"bid_input": forms.NumberInput(attrs={'placeholder': 'Enter bid (£)'})
}
def clean_bid_input(self):
data = self.cleaned_data['bid_input']
highest_bid = Bid.objects.filter(bid_item=listing.id).aggregate(Max('bid_input'))
listing_price = Listing.start_price.get(bid_item=listing.id)
if highest_bid is None:
if data < listing_price:
raise ValidationError('Bid must be higher than listing start price')
if data < highest_bid:
raise ValidationError('Bid must be higher than current highest bid')
In clean_bid_input method replace this:
listing_price = Listing.start_price.get(bid_item=listing.id)
with this
listing_price = Listing.objects.get(bid_item=listing.id).start_price
I am still learning to use Django and so I am a bit unclear on something.
I have a product model and category model. A product can lie in multiple categories and multiple categories can have the same product.
So, its a many to many relationship. Now, I want to allow the user to select multiple categories from the html and then I want to save the categories and link them to the category object in my product model. I am completely lost about it.
One way would be to use Modelform but I dont want to go that way. Is there any other way I can accomplish this?
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']
part of views.py:
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()
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')
Try to save the above way gives me error.
product=Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls)
category_queryset = []
for x in categories:
category = Category.objects.filter(name=x).first()
category_queryset.append(category)
product.categories.set(category_queryset)
i have some row in table i want to get only 2 record that have bigger count value that others . for now according the my picture count 50 and 80 shoud be return.
i should have a list of product_ids (only 2 record)
that have count more that others.. so i should try values_list
i know this is wrong how can i fix it?
prod_ids = ProductViewCount.objects.all().aggregate(Max('count')).values_list('product', flat=True)
this is my full code :
class ViewTopLiked(APIView):
def get(self, request):
prod_ids = ProductViewCount.objects.all().aggregate(Max('count')).values_list('product', flat=True)
obj = Product.objects.filter(product_id__in=prod_ids).order_by('-created_date')
serializer = ProductSerializer(instance=obj, many=True, context={'request': request})
return Response(serializer.data)
productViewcount model:
model:
class ProductViewCount(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id',
related_name='count')
count = models.IntegerField(null=True, blank=True, default=0)
product model:
class Product(models.Model):
PRO = 'P'
INTER = 'I'
BEGINER = 'B'
ALL = 'A'
TYPE_CHOICE = ((PRO, 'P'), (INTER, 'I'), (BEGINER, 'B'), (ALL, 'A'))
product_id = models.AutoField(primary_key=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True)
title = models.CharField(max_length=200)
video_length = models.IntegerField(null=True, blank=True)
mini_description = models.CharField(max_length=1000, null=True, blank=True)
full_description = models.TextField(null=True, blank=True)
price = models.IntegerField(null=True, blank=True)
free = models.BooleanField(default=False)
video_level = models.CharField(max_length=20, choices=TYPE_CHOICE, default=ALL)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
publish = models.BooleanField(default=False)
draft = models.BooleanField(default=False)
slug = models.SlugField(allow_unicode=True, null=True, blank=True)
image = models.FileField(upload_to=upload_to_custom_p, null=True, blank=True)
lecture = models.IntegerField(null=True, blank=True)
def __str__(self):
return self.title
#property
def owner(self):
return self.author
For ordering you can use count related_name in product queryset, to get only first two elements use slicing [:2]:
obj = Product.objects.order_by('-count__count')[:2]
serializer = ProductSerializer(instance=obj, many=True, context={'request': request})
return Response(serializer.data)