Related Field got invalid lookup: icontains Django - python

So I'm trying to make an search option where users can search via categories and name but only name worked, when i used icontains on category it just gave me an error but did not give me an error with name also categories just does not load in HTML. Categories are supposed to load in <select> tag but it is not working, searchall function handles the page I'm talking about and search.html is the page.
this is the complete error
views.py
def searchall(request):
getobject = request.GET['search']
getcategory = request.GET['category']
if getcategory == 'All':
getcategory = ""
search = Book.objects.filter(name__icontains=getobject, category__icontains=getcategory)
oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True)
lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True)
hehe = CartItem.objects.filter(user=request.user)
category = Category.objects.all()
fianlprice = 0
for item in hehe:
fianlprice += item.book.price
books = Book.objects.all()
return render(request, 'main/search.html', {'books':search, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category})
search.html
<h1>search</h1>
<h1>{{ error }}</h1>
<h1>Your cart currently costs ${{ price }}</h1>
<form method="GET" action="">
<input type="text" placeholder="Search here" name="search" id="search">
<button type="submit">Search</button>
</form>
{% for book in books %}
<h3>{{ book.name }}</h3>
<img src= "/media/{{ book.image }}" alt="">
<p>{{ book.description }}</p>
{% if book.id in cart %}
<form method="POST" action="/removefromcartforproducts/">
{% csrf_token %}
<button type="submit" name="removeid" value="{{ book.id }}">remove item from cart</button>
</form>
{% elif book.id in order %}
<h3>You already own this</h3>
{% else %}
<form method="POST" action="/addtocartforproducts/">
{% csrf_token %}
<button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button>
</form>
{% endif %}
{% endfor %}
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
class Book(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
image = models.ImageField()
price = models.IntegerField()
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
class OrderItem(models.Model):
order_id = models.CharField(max_length=10)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user.username
class CartItem(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user.username

In your searchall method, you are trying to filter category. But, as your Book model have category property which is object not a string. So, you have to go further inside it and compare the name of that category.
So:
def searchall(request):
getobject = request.GET['search']
getcategory = request.GET['category']
if getcategory == 'All':
getcategory = ""
search = Book.objects.filter(name__icontains=getobject, category__name__icontains=getcategory)
oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True)
lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True)
hehe = CartItem.objects.filter(user=request.user)
category = Category.objects.all()
fianlprice = 0
for item in hehe:
fianlprice += item.book.price
books = Book.objects.all()
return render(request, 'main/search.html', {'books':search, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category})
Refs on span relationship lookups(__).

Related

Filter Django-Function-View Queryset for User.Request

Models.py
class Experience(models.Model):
user = models.ForeignKey(User, null=True, on_delete = models.CASCADE)
company_name = models.CharField(max_length=100)
company_address = models.CharField(max_length=200)
post_held = models.CharField(max_length=30)
year_from = models.CharField(max_length=20)
year_to = models.CharField(max_length=20)
info = models.TextField()
def get_absolute_url(self):
return reverse('resume')
def __str__ (self):
return self.company_name
Views.py
def Resume(request):
experience = Experience.objects.filter(user = request.user)
return render(request, 'resume.html', {'experience': experience})
Template
<ul>
{% for an_experience in experience %}
<li ><h5>{{ an_experience }},</h5> {{ an_experience.company_address }} - {{ an_experience.post_held }}</li>
<small>{{ an_experience.year_from }} - {{ an_experience.year_to }}</small>
<div>
{{ an_experience.info }}
</div>
{% endfor %}
</ul>
if I use .all(), it is working perfectly but while trying to filter it using request.user nothing is displaying in the template file.

Django TypeError when accessing a link by get_absolute_url()

Good day.
So i'm going through Django 2 by Example and i've encoutered a strange error when visiting a object from list of objects.
TypeError at /1/black-tea/
product_detail() got an unexpected keyword argument 'id'
The type it recieves is correct so small help would be appriciated.
code from views.py
def product_detail(request, product_id, slug):
product = get_object_or_404(Product, slug=slug,
id=product_id, available=True)
return render(request, 'shop/product/detail.html',
{'product': product})
models.py
class Product(models.Model):
category = models.ForeignKey(Category,
related_name='products',
on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d',
blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'))
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail',
args=[self.id, self.slug])
urls.py
path('<int:id>/<slug:slug>/', product_detail, name='product_detail'),
Code from template
<div id="main" class="product-list">
<h1>{% if category %} {{ category.name }}{% else %}Products{% endif %}</h1>
{% for product in products %}
<div class="item">
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}{{ product.image.url }}
{% else %}{% static 'img/images.jpeg' %}{% endif %}">
</a>
{{ product.name }}
<br>
${{ product.price }}
</div>
{% endfor %}
</div>
product_detail arguments should match your url mapping parameters in urls.py. The function definition should has arguments id, slug:
def product_detail(request, id, slug):
...

cleaned_data() returns empty objects, when I try to upload multiple images in Django

models.py:
class Object(PolymorphicModel):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2)
created_date = models.DateTimeField(default=timezone.now)
approved_object = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
def __str__(self):
return f"{self.title}"
class Restaurant(Object):
seats = models.IntegerField()
bulgarian_kitchen = models.BooleanField(default=False)
italian_kitchen = models.BooleanField(default=False)
french_kitchen = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='restaurants')
category_bg_name = models.CharField(max_length=100, default='Ресторанти')
bg_name = models.CharField(max_length=100, default='Ресторант')
is_garden = models.BooleanField(default=False)
is_playground = models.BooleanField(default=False)
class Images(models.Model):
object = models.ForeignKey(Object, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='attachments',
verbose_name='Image')
forms.py:
class RestaurantForm(forms.ModelForm):
class Meta:
model = Restaurant
fields = [
'title',
'content',
'city',
'address',
'phone',
'email',
'site',
'facebook',
'instagram',
'seats',
'bulgarian_kitchen',
'italian_kitchen',
'french_kitchen',
'is_garden',
'is_playground'
]
class ImageForm(forms.ModelForm):
image = forms.ImageField(label='Снимка')
class Meta:
model = Images
fields = [
'image'
]
template (html):
<form method="post" id="dialog_addObject_part">
{% csrf_token %}
{% for hidden in postForm.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form %}
<div class="fieldWrapper">
<div class="errorcode{{field.html_name}}">
{{ field.errors }}
</div>
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
<div class="utf_addObject_form">
<button type="submit" value="Изпрати">Изпрати</button>
</div>
</form>
views.py:
def add_object(request, category):
if not request.user.is_authenticated:
messages.info(request, 'За да добавите нов Обект, трябва да сте регистриран потребител!')
return redirect('account_login')
form = RestaurantForm(request.POST or None);
ImageFormSet = modelformset_factory(Images,
form=ImageForm, extra=3)
if request.method == 'POST':
formset = ImageFormSet(request.POST, request.FILES)
if form.is_valid() and formset.is_valid():
obj = form.save(commit=False)
obj.author = ProfileUser.objects.get(user=request.user)
obj.save()
print(formset.cleaned_data)
for form in formset.cleaned_data:
if form:
image = form['image']
photo = Images(post=form, image=image)
photo.save()
messages.success(request, 'Успешно добавихте нов Обект, може да видите вашите обекти във вашия профил!')
return redirect('home')
else:
formset = ImageFormSet(queryset=Images.objects.none())
context = {
'form': form,
'formset': formset
}
return render(request, "add_object.html", context)
This row print(formset.cleaned_data) returns me empty objects, so it doesn't upload images.
You missed enctype="multipart/form-data" in html form.
from docs:
Note that request.FILES will only contain data if the request method
was POST and the that posted the request has the attribute
enctype="multipart/form-data". Otherwise, request.FILES will be empty.
Form should be,
<form method="post" id="dialog_addObject_part" enctype="multipart/form-data">
</form>

IntegrityError at /add_to_cart/ NOT NULL constraint failed:

I have a view which adds the items to the cart, but when I try to add the items to the cart Item model rising an error NOT NULL constraint failed: cart_item.product_id
I have created a model Item to capture the selected items
Here is my models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Product(models.Model):
product_title = models.CharField(null=True, blank=True,max_length=200)
product_price = models.IntegerField(null=True, blank=True,)
product_image = models.ImageField(upload_to='cart/products/', null=True, blank=True)
def __str__(self):
return self.product_title
class Cart_Bucket(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
create_date = models.DateTimeField(null=True, blank=True,verbose_name='create_date', auto_now=True)
checked_out = models.BooleanField(default=False, verbose_name='checked_out')
def __unicode__(self):
return unicode(self.create_date)
class Item(models.Model):
cart = models.ForeignKey(Cart_Bucket, verbose_name='cart', on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(verbose_name='quantity')
product = models.ForeignKey(Product, verbose_name='product', related_name='product', on_delete=models.CASCADE)
def __str__(self):
return u'%d units' % (self.quantity)
Views.py
def add_to_cart(request):
user = request.user
if not user.is_authenticated:
chars = string.ascii_uppercase + string.digits
user_name = ''.join(random.choice(chars) for _ in range(9))
password = '1234567a'
user = User.objects.create(username=user_name, first_name='guest', last_name='guest', email='guest#gmail.com', is_active=True, is_staff=True)
user.set_password(password)
user.save()
user = authenticate(username=user_name, password=password)
if user:
login(request, user)
product_id = request.GET.get('product_id')
cart = Cart_Bucket.objects.filter(checked_out=False, user=user)
cart = cart[0] if cart else ''
if not cart:
cart = Cart_Bucket.objects.create(user=user)
Item.objects.create(cart=cart, product_id=product_id, quantity=1)
print(Item.objects.all)
return render(request, 'products/products.html')
my products.html
{% extends 'home/base.html' %}
{% block body %}
<div class="row">
{% for products in product %}
<div class="col-md-6 col-centered">
<img src="{{ products.product_image.url }}" style="width: 30%;display:block;margin:0 auto;">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-6">
<br>
<p>{{ products.product_title }} Price : $ {{ products.product_price }} </p>
</div>
<div class="col-md-6"></div>
<div class="col-md-4">
Add to Cart
</div>
<div class="col-md-2"></div>
</div>
<hr>
</div>
{% endfor %}
</div>
{% endblock %}
I want to see the add_to_cart items on the cart page
I think that raises the problem because Item.objects.create() tries to save the model to the database first, before parsing all arguments. Based on Django documentation, .save() method has some advantages over create() method. This problem should be resolved if you change your code like:
newItem = Item()
newItem.cart = cart
newItem.product_id = product_id
newItem.quantity = 1
newItem.save()

how to display all the reviews for the particular product?

With the below code i am adding reviews for some particular product in the database and it is doing good but the problem is while displaying the reviews for the selected product.I get confused how can i display the all reviews of some product and which review done by which user at what time?
models.py
class Product(models.Model):
name = models.CharField(max_length=250)
description = models.TextField(blank=True)
featured = models.BooleanField(default=False)
def __str__(self):
return self.name
class Review(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
review = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.review
views.py
def detail(request,pk):
product = College.objects.get(pk=pk)
form = ReviewForm()
return render(request,'products/detail.html',{'product':product,'form':form})
#login_required(login_url='products:signin')
def review(request,pk):
if request.method == "POST":
form = ReviewForm(request.POST)
if form.is_valid():
review = form.save(commit=False)
review.product = Product.objects.get(pk=pk)
review.user = request.user
review.save()
messages.success(request, "Review saved")
return redirect('products:detail',pk)
else:
messages.error(request,'error in form')
return redirect('products:detail', pk)
detail.html
<h3>All reviews(total.no. of reviews?)</h3>
# Here i want to display all reviews and which is done by which user and at what time
<div class="col-lg-6 col-md-6 mb-6">
<form method="post" action="{% url 'products:review' product.pk %}">
{% csrf_token %}
{% form.as_p %}
<input type="submit" class="btn btn-success">
</form>
</div>
You can do it like this using reverse relation:
<h3>All reviews {{ product.review_set.count }}</h3>
{% for review in product.review_set.all %}
{{ review.review }}
{{ review.date }}
{% endfor %}

Categories

Resources