Trying to implement Django Admin model validation - python

I am a beginner and trying to implement bid system in Django. I want it to work on both Django admin page and and template, therefore I created modelform and modeladmin in Admins.py.
models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class category(models.Model):
category = models.CharField(max_length=50, default='SOME STRING')
def __str__(self):
return f"{self.category}"
class bid(models.Model):
listing = models.ForeignKey('listing', on_delete=models.CASCADE)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
bid = models.DecimalField(max_digits=6, null=True, decimal_places=2)
def __str__(self):
return f"{self.user}, {self.listing} {self.bid}"
class listing(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
Title = models.CharField(max_length=50)
Description = models.CharField(max_length=300)
Price = models.DecimalField(max_digits=6, null=True, decimal_places=2)
category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="categories")
def __str__(self):
return f"{self.Title}"
admin.py
from django.contrib import admin
from .models import User, listing, category, bid
from django.core.exceptions import ValidationError
from django import forms
admin.site.register(User)
admin.site.register(listing)
admin.site.register(category)
class bidForm(forms.ModelForm):
class Meta:
model=bid
fields = ['user', 'listing', 'bid']
def clean(self):
start_price = self.cleaned_data.get('listing.Price')
userbid = self.cleaned_data.get('bid')
if userbid <= start_price:
raise ValidationError('Please place a bid higher than starting price')
return self.cleaned_data
class bidAdmin(admin.ModelAdmin):
form = bidForm
list_display = ('user', 'listing', 'bid')
admin.site.register(bid, bidAdmin)
It returns the following error:
'<=' not supported between instances of 'decimal.Decimal' and 'NoneType'.
Also I want to compare instances of previous and current bid on a listing to place a new bid, also modify any of previously placed bids even if it's lower than highest bid. but I have no idea how to code that. Please, help me...

Related

Filter_horizontal not save django admin 4x

I'm starting a project in django 4.1. and I run into this problem:
many to many relationship: I have a field of this type that is required, and everything is fine, but when I use the filter_horizontal it does not let me insert the chosen value, it tells me that it is required, however I am selecting values
Admin.py:
from django.contrib import admin
from .models import *
from django.contrib.auth.models import User
class CatalejoAdmin(admin.ModelAdmin):
filter_horizontal = ('tematicas',)
admin.site.register(Catalejo, CatalejoAdmin)
admin.site.register(Tematicas)
Model:
from django.db import models
from django.contrib.auth.models import User
class Tematicas(models.Model):
tematica = models.CharField(max_length=500)
fecha = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User,null=True , default=User, editable=False, on_delete=models.DO_NOTHING)
class Meta:
ordering = ["tematica"]
verbose_name_plural = "Temática"
def __str__(self):
return self.tematica
class Catalejo(models.Model):
fecha = models.DateField()
titulo = models.CharField(max_length=500)
tematicas = models.ManyToManyField(Tematicas, related_name='Temáticas')
author = models.ForeignKey(User,null=True , default=User, editable=False, on_delete=models.DO_NOTHING)
fichero = models.FileField(upload_to='gestores/%Y/%m/%d', null=True, blank=True)
class Meta:
ordering = ["fecha"]
verbose_name_plural = "Catalejo"
def Tematicas(self):
return ",\n".join([p.tematica for p in self.tematicas.all()])
def dehydrate_full_title(self, Tematicas):
return '%s by %s' % (Tematicas.tematica)
enter image description here

I have extended the default User table named UserProfile and want to access info from Product model but shown integrity error

UserProfile table: (Extended table of default User)
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE`enter code here`
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=CASCADE)
k_name = models.CharField(max_length=100, default="krishok Name", null=True)
k_address = models.CharField(max_length=300, default="Goes Krishok Address Here", null=True, blank=True)
k_national_id_no = models.CharField(default="1", max_length=50)
k_phone = models.CharField(default="01778956098", max_length=20)
k_email = models.EmailField(default="xxx#gmail.com", max_length=254)
k_image = models.ImageField(default = '', upload_to = 'upload/pkrishokImage/')
national_id = models.ImageField(default= '',upload_to = 'upload/IDImage/')
Product model code:
from Store.models.userprofile import UserProfile
from django.db import models
from .categories import Category
from .unit_type import Unit_Type
class Product(models.Model):
name = models.CharField(max_length=50)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1)
unit= models.ForeignKey(Unit_Type, on_delete=models.CASCADE, default=1)
Unit_price = models.IntegerField(default=0)
#k_name = models.ForeignKey(UserProfile, on_delete=models.CASCADE)#this is the problem
quantity = models.IntegerField(default=0)
description = models.CharField(max_length=200, default='', null=True, blank=True)
image = models.ImageField(upload_to = 'upload/productsImg/')
#staticmethod
def get_all_products():
return Product.objects.all()
#Filtering by Category Id:
# this method will bring all products by its categoryID
#staticmethod
def get_all_products_by_id(category_id):
if category_id:
return Product.objects.filter(category = category_id)
else:
return Product.get_all_products()
#i am trying to get id from extended user table called UserProfile model and want to get access of #all data from Product model, so that i am trying to written my foreignKey at product table from UserProfile table but it's give me integrity error.

I am facing mapping user and profile in django

I am facing a problem with Django profile mapping with user.There is coming None in admin view
This is my models.py
profile_of = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
session = models.CharField(max_length=20, blank=False, null=False )
batch = models.IntegerField() # batch = models.IntegerField(blank=False, null=False)
iit_program = models.CharField(blank=True, choices=IIT_PROGRAM, max_length=10)
college = models.CharField(max_length=50)
graduate_university = models.CharField(max_length=50, default='Dhaka University')
graduate_department = models.CharField(max_length=50, default='Software Engineering')
photo = models.ImageField(blank=True)
is_current = models.BooleanField(default=True)
This is my views.py
from django.shortcuts import render
from .forms import UserProfile
from django.contrib.auth.decorators import login_required
#login_required(login_url= '/accounts/login/')
def userProfileview(request):
form = UserProfile(request.POST or None)
if form.is_valid():
form.save()
context = {'form':form}
return render(request,'userprofile.html', context)
This is my forms.py
from django import forms
from .models import Profile
class UserProfile(forms.ModelForm):
class Meta:
model = Profile
fields =
['iit_program','batch','session','graduate_university','graduate_department','photo']
What you see in the admin list view is the Model converted to a string, you can control how the model is converted with the str function, the return value of this function must be a string
class Profile(models.Model):
profile_of = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
...
def __str__(self):
return self.profile_of.name

How the updating of m2m fields are working? Django Rest Framework

I have code where Product model has M2M field Comment model. I made methods in views.py for getting Product by id and all objects of Product, but there's problem with updating it. I can't fully understand how to update Product comments field. I already tried a lot of different answers and ideas, but nothing helps me. I'm using PUT method for update.
My main questions:
Where and how target Product id in order to update comments field in it?
After I find Product by it's id how I can update M2M field comments in it?
I tried:
Completely Lost: Many To Many with Serializers and Update in Django Rest Framework
Doesn't work at all, screams for 'collections.OrderedDict' object has no attribute 'id'
Django Rest update many to many by id
It's making PrimaryKeyRelatedField which is not correct for me.
How to update many to many Django REST?
Not enough information in answer, got stuck on it.
I read, but found no usefull information on my problem
products/models.py
from django.db import models
from comments.models import Comment
# Create your models here.
class Product(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=150, blank=True)
description = models.TextField(default="No description")
category = models.CharField(max_length=255, blank=True)
price = models.DecimalField(default=100, max_digits=15, decimal_places=2, blank=True)
photo_one = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True)
photo_two = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True)
photo_three = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True)
photo_four = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True)
is_popular = models.BooleanField(default=False)
is_hit = models.BooleanField(default=False)
has_sale = models.IntegerField(default=0)
comments = models.ManyToManyField(Comment, blank=True)
def __str__(self):
return self.name
comments/models.py
import uuid
from django.db import models
# Create your models here.
class Comment(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
username = models.CharField(max_length=255, default="default")
text = models.TextField()
rating = models.IntegerField()
def __string__(self):
return self.username
products/serializers.py
class ProductSerializer(serializers.ModelSerializer):
comments = CommentSerializer(many=True)
class Meta:
model = Product
fields = '__all__'
def update(self, instance, validated_data):
submitted_comments = validated_data.get('comments')
if submitted_comments:
for comment in submitted_comments:
comment_instance = Comment.objects.get(id=comment.id)
instance.children.add(comment_instance)
instance.save()
return instance
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ('id', 'username', 'text', 'rating')
products/views.py
import django_filters
from rest_framework import status
from rest_framework.generics import ListAPIView, RetrieveUpdateAPIView
from rest_framework.response import Response
from .models import Product
from .pagination import CustomPagination
from .serializers import ProductSerializer
class GetProductById(RetrieveUpdateAPIView):
serializer_class = ProductSerializer
filter_class = ProductFilter
queryset = Product.objects.all()
def get_product(self, pk):
try:
product = Product.objects.get(pk=pk)
except Product.DoesNotExist:
content = {
'status': 'Not Found'
}
return Response(content, status=status.HTTP_404_NOT_FOUND)
return product
def get(self, request, pk):
product = self.get_product(pk)
serializer = ProductSerializer(product)
return Response(serializer.data, status=status.HTTP_200_OK)
class ProductFilter(django_filters.FilterSet):
product_id = django_filters.UUIDFilter(name='id')
class Meta:
model = Product
fields = ['id']
class GetProducts(ListAPIView):
serializer_class = ProductSerializer
pagination_class = CustomPagination
def get_queryset(self):
products = Product.objects.all()
return products
def get(self, request):
products = self.get_queryset()
paginate_queryset = self.paginate_queryset(products)
serializer = self.serializer_class(paginate_queryset, many=True)
return self.get_paginated_response(serializer.data)
*products/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/products/', views.GetProducts.as_view(), name='get_products'),
path('api/product/<pk>/', views.GetProductById.as_view(), name='get_put_product')
]
I expect successful target by Product id and finding product.comments field
I expect successful adding new Comment to Product in it's comments field

Django NOT NULL constraint failed: shop_product.user_id

I am new to Django and I am trying to learn by practicing with some project but I am stuck with this problem,
NOT NULL constraint failed: shop_product.user_id
models.py
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='category_created')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created')
category = models.ForeignKey(Category, related_name='products')
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)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
negiotiable = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='product_liked',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products_detail',
args=[self.slug])
Here is my views.py but am not sure if there is problem with my views and I think the problem will have to be with my models....
views.py
from django.views.generic import *
from django.core.urlresolvers import reverse_lazy
from .models import Category, Product
class CategoryList(ListView):
model = Category
class CategoryDetail(DetailView):
model = Category
class ProductList(ListView):
model = Product
class ProductDetail(DetailView):
model = Product
class ProductCreate(CreateView):
model = Product
fields = ("category", 'name', 'image', 'description', 'price', 'stock','available', 'negiotiable')
class ProductUpdate(UpdateView):
model = Product
fields = ('name', 'image', 'description', 'price', 'stock','available', 'negiotiable')
class ProductDelete(DeleteView):
model = Product
success_url = reverse_lazy('product_list')
Please let me know what could be done.
Either Add User into list:
class ProductCreate(CreateView):
model = Product
fields = ["category", 'name', 'image', 'description', 'price','stock','available', 'negiotiable', 'user']
OR make sure Field must be null=true and blank=True.
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created', null=True, blank=True)
Add a form for your product,
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = "__all__"
Also, your user field must be null=True and blank=True.
Then in your create view,
class ProductCreate(CreateView):
model = Product
form_class = ProductForm
def form_valid(self, form):
form.instance.user = self.request.user
form.save()
return super(ProductCreate, self).form_valid(form)
Now, whenever a product is created, the user who created would be added as the user of the product.

Categories

Resources