Django clean method cause is_valid() false - python

here is my model:
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
objects = models.Manager()
available = ProductStockManager()
and I have a form like this:
class ProductForm(ModelForm):
name = forms.CharField(max_length=200)
price = forms.DecimalField(decimal_places=2)
description = forms.Textarea()
class Meta:
model = Product
fields = ['category', 'name', 'description', 'price', 'stock']
def clean_description(self):
pass
def clean_price(self):
pass
def clean_name(self):
pass
in my form when I use clean_field() for each field it makes is_valid() False except clean_description() what is this for ?
why when I use clean_price(), clean_name() my is_valid() returns False?
and why it doesn't when I use clean_description() ?

Related

django AttributeError when saving data with DRF

I have a problem when I make a POST.
the entry is created (I can see it in django Admin panel) but DRF is throwing me an error
AttributeError at /api/v1/reviews/
'Review' object has no attribute 'review_score'
review_score beeing a SerializerMethodField in serializer.py needed for the frontend (GET is working perfectly)
model.py
class Review(models.Model):
company = models.ForeignKey(Company, related_name='company_review', on_delete=models.CASCADE)
title = models.CharField(max_length=255)
comments = models.TextField()
validated = models.BooleanField(default=False)
note_quality = models.DecimalField(max_digits=5, decimal_places=2)
note_timing = models.DecimalField(max_digits=5, decimal_places=2)
note_qualprix = models.DecimalField(max_digits=5, decimal_places=2)
note_react = models.DecimalField(max_digits=5, decimal_places=2)
note_followup = models.DecimalField(max_digits=5, decimal_places=2)
note_clean = models.DecimalField(max_digits=5, decimal_places=2)
created_at = models.DateField(auto_now_add=True)
created_by = models.ForeignKey(User, related_name='created_review', on_delete=models.CASCADE)
def __str__(self):
return self.title
views.py
class ReviewViewSet(viewsets.ModelViewSet):
serializer_class = ReviewSerializer
queryset = Review.objects.all()
def get_queryset(self):
company_id = self.request.query_params.get('company_id', None)
return self.queryset.filter(company_id=company_id, validated=True).annotate(
review_score = Sum(F('note_quality')+F('note_timing')+F('note_qualprix')+F('note_react')+F('note_followup')+F('note_clean'))/6,
)
def perform_create(self, serializer):
obj = serializer.save(created_by=self.request.user)
serializer.py
class ReviewSerializer(serializers.ModelSerializer):
created_by = UserCreateSerializer(read_only=True)
review_score = serializers.SerializerMethodField()
def get_review_score(self, obj):
rounded = round_up(obj.review_score, 0.5)
return rounded
class Meta:
model = Review
read_only_fields = ('created_at'),
fields = ('id','company','title','comments','validated','note_quality','note_timing','note_qualprix','note_react','note_followup','note_clean','created_at', 'created_by', 'review_score')
review_score at ReviewSerializer should be a serializers.ReadOnlyField(). Change that and it should work.
You should remove row
obj.save()
in the perform_create function. Model saving is already happening in the line
obj = serializer.save(created_by=self.request.user)

django manytomany user auto fill the user field

I have 2 tables in my models.py. I'm trying to auto fill the user filed in the second table whatever user I select in my first table I tried to override the save_model in admins.py but it didn't work. Here is my models.py file:
class Company(models.Model):
company_name = models.CharField(max_length = 50)
slug = models.SlugField(unique = True)
user = models.ManyToManyField(User, related_name='company_user')
objects = models.Manager()
published = PublishedManager()
def __str__(self):
return self.company_name
class Group(models.Model):
company_name = models.ForeignKey(Company, related_name = 'co_name',
on_delete=models.CASCADE)
count = models.CharField(max_length = 50)
real_count = models.CharField(max_length = 50)
entry_date = models.DateTimeField()
exit_date = models.DateTimeField()
code = models.CharField(max_length = 10)
code_date = models.DateTimeField()
manifest = models.ImageField(upload_to='manifest/%m/%y', blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
user = models.ManyToManyField(User, related_name='group_user', blank=True)
objects = models.Manager()
published = PublishedManager()
class Meta:
ordering = ('-code_date',)
def __str__(self):
return str(self.id)
my admins.py file
#admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
list_display = ['id', 'company_name', 'code', 'code_date', 'count',
'real_count', 'entry_date', 'exit_date',
'manifest', 'created'
]
autocomplete_fields = ('user',)
#admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
list_display = ['company_name']
autocomplete_fields = ('user',)
prepopulated_fields = {'slug': ('company_name',)}
views.py
#login_required
def main_approval(request):
groups = Group.objects.filter(user=request.user)
context = {'groups': groups}
return render(request, 'approval/main_list.html', context)
I'm trying to get the user in the Company class to be auto inserted in my Group class
Any advice?
Try to do this in views.py
user = self.company_name.user.all()

Filtering issue in DRF

The problem I'm having looks like:
TypeError: init() got an unexpected keyword argument 'name'
"GET /apartmentimages/ HTTP/1.1" 500 136691
I have such a model.py class:
class Apartment(models.Model):
apartment_title = models.CharField(max_length=200)
apartment_description = models.TextField()
apartment_location = models.CharField(max_length=200)
apartment_people_quantity = models.PositiveIntegerField()
apartment_price = models.CharField(max_length=200)
apartment_type = models.CharField(max_length=50, null=True)
def __str__(self):
return self.apartment_title
class ApartmentImage(models.Model):
apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE)
image = models.ImageField(upload_to='images/', null=True, blank=True)
And serializers.py class:
class ApartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Apartment
fields = (
'id',
'url',
'apartment_title',
'apartment_description',
'apartment_location',
'apartment_people_quantity',
'apartment_price',
'apartment_type',
)
class ApartmentImageSerializer(serializers.ModelSerializer):
class Meta:
model = ApartmentImage
fields = ('id', 'url', 'apartment', 'image',)
in views.py:
apartment_id = django_filters.CharFilter(name="apartment__id",
queryset=Apartment.objects.all())
class Meta:
model = ApartmentImage
fields = ('apartment_id',)
class ApartmentImageView(viewsets.ModelViewSet):
queryset = ApartmentImage.objects.all()
serializer_class = ApartmentImageSerializer
filter_backends = (DjangoFilterBackend,)
filter_class = ApartmentImageFilter
You have no name as an attribute in django-filters. Maybe what are you looking for is field_name and neither do you need queryset=Apartment.objects.all(). If you are looking for a field that is field_name then your CharFielter should look like this apartment_id = django_filters.CharFilter(field_name="apartment__id", lookup_expr='iexact') and maybe if you haven't overwritten the id generation it should probably be a NumberFilter() if I am not wrong.

model linked with model through M2O relation which is further linked with model through M2O relation raises error

I am working on an online-shop in django.
I have linked the order model with the cart model through ForeignKey which is further linked with products model through ForeignKey.
models.py:
class products(models.Model):
image = models.ImageField(upload_to='products/')
name = models.CharField(max_length=50)
slug = models.SlugField(blank=True, unique=True)
title = models.CharField(max_length=50)
price = models.FloatField()
def __str__(self):
return self.name
class cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item = models.ForeignKey(products, on_delete=models.CASCADE) ###
slug = models.CharField(max_length=50, default='#')
quantity = models.IntegerField(default=1)
created_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.quantity} of {self.item.name}'
def get_total(self):
total = self.item.price * self.quantity
floattotal = float("{0:.2f}".format(total))
return floattotal
class order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item = models.ForeignKey(cart, on_delete=models.CASCADE) ###
slug = models.SlugField()
quantity = models.IntegerField()
created_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.quantity} of {self.item.item__name}'
I wanted to create object of order as:
def order_view(request, slug):
cart_qs = cart.objects.filter(user=request.user, slug=slug)
cart_item = cart_qs[0]
order.objects.create(user=request.user, item=cart_item.item.name, slug=slug, quantity=cart_item.quantity) ####
It raises error as:
Cannot assign "'The latest one'": "order.item" must be a "cart" instance.
Why this error arises and how can I resolve this?
You are trying to assign string on Order instance creation where it's expecting a Cart instance. The error raised here:
item=cart_item.item.name
It should be simply:
item=cart_item
, because your model schema expect this:
item = models.ForeignKey(cart, on_delete=models.CASCADE) ###

Foreign Key Error to Itself on Django

So I am trying to create an inline set similar to this image (http://oi48.tinypic.com/4gm5w2.jpg) so I can add multiple prices for different sizes for a product. I can't get it to even display the area in the django admin. On top of that by doing so I get the error:
<class 'apps.main.admin.PriceInline'>: (admin.E202) 'main.Apparel_Price' has no ForeignKey to 'main.Apparel_Price'.
models.py:
#python_2_unicode_compatible
class Apparel_Product(models.Model):
product_name = models.CharField(_("Name"), max_length=255)
default='media/None/no-img.jpg')
product_gender_type = models.CharField(max_length=256, choices=[('male', 'Male'), ('female', 'Female'), ('unisex', 'Unisex')])
product_brand = models.CharField(_("Brand"),max_length=25)
product_sizes = models.CharField(_("Sizes"),max_length=25)
product_colors = models.CharField(_("Colors"),max_length=25)
product_price = models.CharField(_("Price"),max_length=10)
product_description = models.CharField(_("Description"),max_length=500)
product_shipping_options = models.CharField(_("Shipping Options"),max_length=250)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Apparel Product")
verbose_name_plural = _("Apparel Products")
def __str__(self):
return self.album_name
#python_2_unicode_compatible
class Apparel_Picture(models.Model):
master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
product_caption = models.CharField(_("Caption"), max_length=255)
product_photo = models.ImageField(_("Picture"), upload_to='media/')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Picture")
verbose_name_plural = _("Pictures")
def __str__(self):
return self.photo_caption
#python_2_unicode_compatible
class Apparel_Price(models.Model):
# master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
master_apparel_product = models.OneToOneField(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
product_price = models.CharField(_("Price"), max_length=255)
product_size = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Price")
verbose_name_plural = _("Prices")
def __str__(self):
return self.product_price
admin.py:
from django.contrib import admin
from .models import Apparel_Product, Apparel_Picture, Apparel_Price
# Register your models here.
def get_picture_preview(obj):
if obj.pk: # if object has already been saved and has a primary key, show picture preview
return """<img src="{src}" alt="{title}" style="max-width: 200px; max-height: 200px;" />""".format(
src=obj.photo.url,
title=obj.photo_caption,
)
return ("(choose a picture and save and continue editing to see the preview)")
get_picture_preview.allow_tags = True
get_picture_preview.short_description = ("Picture Preview")
class PictureInline(admin.StackedInline):
model = Apparel_Picture
extra = 0
fields = ["get_edit_link", "product_caption", "product_photo", get_picture_preview]
readonly_fields = ["get_edit_link", get_picture_preview]
def get_edit_link(self, obj=None):
if obj.pk: # if object has already been saved and has a primary key, show link to it
url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name), args=[force_text(obj.pk)])
return """{text}""".format(
url=url,
text=_("Edit this %s separately") % obj._meta.verbose_name,
)
return ("(save and continue editing to create a link)")
get_edit_link.short_description = ("Edit link")
get_edit_link.allow_tags = True
class PriceInline(admin.TabularInline):
model = Apparel_Price
extra = 0
fields = ["price",]
#admin.register(Apparel_Product)
class Apparel_ProductAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["product_name", "product_gender_type", "product_brand", "product_sizes", "product_colors", "product_price", "product_description", "product_shipping_options",]
inlines = [PictureInline]
#admin.register(Apparel_Picture)
class Apparel_PictureAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["master_apparel_product", "product_caption", "product_photo", get_picture_preview]
readonly_fields = [get_picture_preview]
#admin.register(Apparel_Price)
class Apparel_PriceAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["master_apparel_product", "product_price",]
inlines = [PriceInline,]
So I am really confused how main.Apparel_Price would need a foreign key to itself. The one for the picture works but the one for the prices do not and I tried copying them and it didn't work. Help would greatly be appreciated.
PriceInline has model Apparel_Price same as Apparel_PriceAdmin. Just use PriceInline as inline in Apparel_ProductAdmin.

Categories

Resources