DJANGO POSTGRES matching query does not exist - django

Hi i have a seller model that is related one to one field with user in DJANGO. Seller can create a "deal" and to become seller you first have to create a normal account as a user.
I dont have any idea how to take to the view deals that are from the specyfic seller
MY views.
#user_passes_test(is_seller)
def seller_page(request):
if request.method == "GET":
user = request.user
_seller = Seller.objects.get(user_id=user) # TODO: doesnt work
deals = Deal.objects.get(seller_id=_seller)
form = forms.DealModelForm
context = {'deals': deals, 'form': form}
return render(request, 'seller_page.html', context)
My models
class Seller(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
address = models.CharField(max_length=255)
city = models.CharField(max_length=255)
post_code = models.CharField(max_length=6)
phone = models.CharField(max_length=12)
email = models.CharField(max_length=255)
bank_account = models.CharField(max_length=255)
nip = models.CharField(max_length=255)
is_seller_active = models.BooleanField(default=False)
sells = models.IntegerField(default=0)
class Deal(models.Model):
seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
description = models.TextField()
image = models.ImageField()
is_deal_on = models.BooleanField(default=True)
sell_price = models.DecimalField(default=0, decimal_places=2, max_digits=6, help_text='Cena sprzedaży')
origin_price = models.DecimalField(default=0, decimal_places=2, max_digits=6, help_text='Oryginalna cena',
blank=True, null=True)
time_valid = models.IntegerField(default=12) # ilość miesięcy ile warty jest deal
unique_code = models.CharField(max_length=60, null=True, blank=True)
quantity = models.IntegerField(default=0)
province = models.IntegerField(choices=PROVINCES)
ERROR :
_seller = Seller.objects.get(user_id=user)

If the "user" variable is an integer:
_seller = Seller.objects.get(user__id=user) #Note that is "__" and not "_"
if the "user" variable is an object (User model):
_seller = Seller.objects.get(user=user)

Related

Django: Assign Route to Order Based on User Input of Location

In my create order view, I am trying to automatically assign the respective route based on the location the user inputs. Basically, every location in the system has a FK to a route. There are many locations within a route. If you select a location to send products to, the route should automatically be tied to.
Currently I am able to see the route for an order in my order_list.html page, but when I view the order in the Django admin, the route is not assigned to the order but the location is.
I want it to work similarly to how you would assign the current logged in user to an order:
form.instance.user = request.user
I tried using:
form.instance.company = request.user.company
But I am getting an attribute error:
'WSGIRequest' object has no attribute 'location'
Here is my full order_create function:
orders/views.py:
#login_required(login_url='account_login')
def order_create(request):
"""
A function that takes the users cart with products, then converts the cart into an
OrderForm. Then saves the form/order to the database.
"""
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.instance.company = request.user.company
form.instance.route = request.location.route
order = form.save()
for item in cart:
OrderItem.objects.create(order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
# clear the cart
cart.clear()
return render(request,
'orders/order/created.html',
{'order': order,
})
else:
form = OrderCreateForm()
return render(request,
'orders/order/create.html',
{'cart': cart, 'form': form})
Here are the Location, Route and Order models:
orders/models.py:
class Route(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Locations(models.Model):
"""
A model to represent a location or locations a company has.
"""
name = models.CharField(max_length=100)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
route = models.ForeignKey(Route, on_delete=models.DO_NOTHING)
store_number = models.CharField(max_length=15, blank=True, null=True)
address = models.ForeignKey(Address, on_delete=models.DO_NOTHING, blank=True, null=True)
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
route = models.ForeignKey(Route, on_delete=models.DO_NOTHING, blank=True, null=True)
location = models.ForeignKey(Locations, on_delete=models.DO_NOTHING, blank=True, null=True)
company = models.ForeignKey(Company, on_delete=models.DO_NOTHING, blank=True, null=True)
delivery_date = models.DateField()
address = models.ForeignKey(Address, on_delete=models.DO_NOTHING, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
delivered = models.BooleanField(default=False)
and then finally the company and user model in my accounts app that are used as foreign keys in the orders app.
accounts/models.py:
class Company(models.Model):
"""
A model to represent companies that can operate within the system, which multiple users are apart of.
"""
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
city = models.CharField(max_length=25)
state = USStateField()
zip = models.CharField(max_length=5)
admin = models.ForeignKey("accounts.User", on_delete=models.DO_NOTHING, related_name="company_admin", blank=True, null=True)
class User(AbstractBaseUser, PermissionsMixin):
"""
A model to represent a User of the system.
"""
ROLE_CHOICES = (
('ADMIN', "Admin"),
('MANAGER', "Manager"),
('DRIVER', "Driver"),
('PRODUCTION', "Production")
)
email = models.EmailField(max_length=254, unique=True)
phone = models.CharField(max_length=15, help_text="(123)-123-1234", blank=True, null=True)
first_name = models.CharField(max_length=254, null=True, blank=True)
last_name = models.CharField(max_length=254, null=True, blank=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True)
role = models.CharField(max_length=10, choices=ROLE_CHOICES, default=None, blank=True, null=True)
is_employee = models.BooleanField(default=False, blank=True, null=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)

Django queryset join tables

I am really stuck with merging two tables.
I have tables Item and Transactions
class Item(models.Model):
category_choices = []
item_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
description = models.TextField()
category = models.CharField(max_length=100, choices=category_choices)
image = models.ImageField(upload_to='media')
stock = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
date_added = models.DateTimeField(default=timezone.now())
class Transactions(models.Model):
transaction_id = models.AutoField(primary_key=True)
order_id = models.UUIDField()
item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='transactions')
quantity = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
transaction_date = models.DateTimeField(auto_now_add=True)
username = models.CharField(max_length=100)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
address_str = models.CharField(max_length=100)
address_plz = models.CharField(max_length=100)
address_place = models.CharField(max_length=100)
address_country = models.CharField(max_length=100, choices=[(name[1], name[1]) for name in countries])
Now I want to render template with transactions and images and items info from Item model. I am trying to use prefetch_related, howeve rit does not work and I do not understand how this should be solved.
def order_history(request):
if request.user.is_authenticated:
transaction = Transactions.objects.order_by('-transaction_date').\
filter(username=request.user).prefetch_related('item')
context = {'orders': transaction}
template_name = 'retail/order_history.html'
return render(request, template_name, context=context)
else:
raise Http404('You are not authorised')
In your transactions table, name your Item column item instead of item_id:
item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='transactions')
Then your prefetch_related("item") will work as expected.

How to get the minimum value of an instance of django model

I am trying to get the minimum or the lowest value of a model field in django model. The field is room_Price. I am therefore trying to get the minimum of value of this field for each instance of a model. My model are as as follows
class Hotels(models.Model):
name = models.CharField(max_length=255)
address = models.CharField(max_length=255)
city = models.CharField(max_length=255)
country = models.CharField(max_length=255)
mobile_number = models.CharField(max_length=12)
created_at = models.DateTimeField(default=timezone.now)
last_modified = models.DateTimeField(auto_now=True)
description = models.TextField()
slug = models.SlugField(unique=True)
property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos')
star_rating = models.PositiveIntegerField()
contact_person = models.ForeignKey(UserProfile, on_delete = models.CASCADE, null=True, blank=True,)
class Room(models.Model):
hotel = models.ForeignKey(Hotels,on_delete = models.CASCADE, null=True, blank=True,)
room_photo = models.ImageField(default='default.jpg', upload_to='room_photos')
room_Name = models.CharField(max_length = 200)
room_details = models.CharField(max_length = 500)
room_Capacity = models.PositiveIntegerField(default = 0)
slug = models.SlugField(unique=True)
# guest_numbers = models.IntegerField(default=0)
room_Price= models.PositiveIntegerField(default = 0)
total_Rooms = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, blank=True,)
More details
From the above models, a hotel can have as many rooms as possible. Now i want to fetch the lowest priced room for each hotel. I tried to use Hotels.objects.aggregate(min_price=Min('room__room_Price')) but it is fetching the overall minimum price of all the hotel rooms. Kindly assist
You can try to add ordering to your model and then find lowest price in a loop:
class Room(models.Model):
...
class Meta:
ordering = ['room_Price']
And filter in views:
lowest_prices = {}
for i in Hotels.objects.all():
price = Room.objects.filter(hotel=i.id)[0].room_Price
lowest_prices[i.name] = price
print(lowest_prices)
I put prices in a dict, but you can do anything you want with it.

Django. How to write a filter for the current user?

The listings application has a Listing table:
class Listing(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риэлтор')
region = models.CharField(default="Чуйская", max_length=100, verbose_name='Область')
city = models.CharField(default="Бишкек", max_length=100, verbose_name='Город')
district = models.CharField(blank=True, max_length=100, verbose_name='Район')
title = models.CharField(max_length=200, verbose_name='Заголовок')
address = models.CharField(blank=True, max_length=200, verbose_name='Адрес')
description = models.TextField(blank=True, verbose_name='Описание')
stage = models.IntegerField(blank=True, verbose_name='Этажность')
rooms = models.IntegerField(blank=True, verbose_name='Количество комнат')
garage = models.IntegerField(default=0, blank=True, verbose_name='Гараж')
sqmt = models.IntegerField(blank=True, verbose_name='Площадь')
price = models.IntegerField(blank=True, verbose_name='Цена')
photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Основное фото')
photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 1')
photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 2')
photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 3')
photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 4')
photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 5')
photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 6')
is_published = models.BooleanField(default=True, verbose_name='Публично')
list_date = models.DateTimeField(default=datetime.now, blank=True, verbose_name='Дата публикации')
def __str__(self):
return self.title
class Meta:
verbose_name = 'Объявление'
verbose_name_plural = 'Объявления'
In the realtors application there is a Realtor model:
class Realtor(models.Model):
user_name = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь', related_name='realtor')
name = models.CharField(max_length=20, verbose_name='Имя')
photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Фото')
description = models.TextField(blank=True, verbose_name='Описание')
phone = models.CharField(max_length=20, verbose_name='Телефон')
email = models.CharField(max_length=50, verbose_name='Email')
is_mvp = models.BooleanField(default=False, verbose_name='Реэлтор месяца')
hire_date = models.DateTimeField(default=datetime.now, blank=True, verbose_name='Дата приёма на работу')
def __str__(self):
return self.name
class Meta:
verbose_name = 'Риэлтор'
verbose_name_plural = 'Риэлторы'
In the accounts application, there is a function that in the personal account should only display ads of the current user when he is in the system:
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from listings.models import Listing
from realtors.models import Realtor
def dashboard(request):
listings = Listing.objects.order_by('-list_date').filter(user_name=request.user)
paginator = Paginator(listings, 6)
page = request.GET.get('page')
paged_listings = paginator.get_page(page)
context = {
'listings': paged_listings
}
return render(request, 'accounts/dashboard.html', context
)
How to correctly register this filter so that everything works so that the current user’s ads are displayed:
listings = Listing.objects.order_by('-list_date').filter(user_name=request.user)
At the moment, this error:
Cannot resolve keyword 'user_name' into field. Choices are: address, city, description, district, garage, id, is_published, list_date, photo_1, photo_2, photo_3, photo_4, photo_5, photo_6, photo_main, price, realtor, realtor_id, region, rooms, sqmt, stage, title
Who is not difficult, please help. Thank you in advance.
Since there's no user_name field in Listing, it's an error to try and filter on that.
Instead, you presumably are trying to filter on the realtor, which can done with a lookup that spans relationships:
listings = Listing.objects.order_by('-list_date').filter(realtor__user_name=request.user)
user_name is a field on the Realtor model, not the Listing. Those two models are connected by a ForeignKey, so you need to traverse that relationship using the double-underscore syntax.
Listing.objects.order_by('-list_date').filter(realtor__user_name=request.user)
Note though that user_name is a very odd name for that field; it's not the name, it's the User object itself. It should be called just user.

django model ManyToManyField field join

--models.py--
class Products(models.Model):
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique=True)
price = models.IntegerField(default=100)
image1 = models.ImageField(upload_to='static/images/home', blank=True, null=True)
class Cart(models.Model):
user = models.ForeignKey(User, null=True, blank=True)
product = models.ManyToManyField(Products, blank=True)
--views.py--
#login_required
def cart(request):
try:
cart_user = Cart.objects.filter(user = request.user)
except:
cart_user = False
if cart_user != False:
j = Products.objects.filter(pk=Cart.objects.filter(user=request.user)) #Not getting results in j
now i want the list of products which is selected by user form Cart Model when he or she is logged in.
how to apply join in two models so that i get all the product list in 'p' variable which is in Cart.product model. Thanks
Shang Wang was right about model naming. Let's use those.
class Product(models.Model):
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique = True)
price = models.IntegerField(default=100)
image1 = models.ImageField(upload_to='static/images/home',blank=True,null=True)
class Cart(models.Model):
user = models.ForeignKey(User,null=True, blank=True)
products = models.ManyToManyField(Product, blank=True)
Now you can use filters like this.
products = Product.objects.filter(cart__user__id=1)
carts = Cart.objects.filter(articles__name__startswith="Something").distinct()