There are models, why after python manage.py makemigrations is created only by 1 field in migrations, how to fix it? I tried doing manage.py migrate --fake zero, and doing the migrations again, but nothing.The app is registered in settings.
from django.db import models
from django.urls import reverse
class Category(models.Model):
image = models.ImageField(default='default.png', upload_to='category_image'),
title = models.CharField(max_length=50, db_index = True),
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('category_detail_url', kwargs={'title': self.title})
class Provider(models.Model):
name = models.CharField(max_length=50, db_index = True),
phone_number = models.CharField(max_length=12, db_index = True),
address = models.CharField(max_length=50, db_index = True),
def __str__(self):
return self.name
class Product(models.Model):
title = models.CharField(max_length=50, db_index = True),
receipt_date = models.DateTimeField(auto_now_add=True, blank=True),
quantity_stock = models.IntegerField(),
quantity_store = models.IntegerField(),
purchase_price = models.IntegerField(),
image = models.ImageField(default='default.png', upload_to='product_image'),
provider = models.ForeignKey(Provider, null = True ,related_name='to_provider',on_delete=models.CASCADE),
category = models.ForeignKey(Category, null = True ,related_name='to_category',on_delete=models.CASCADE),
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('product_detail_url', kwargs={'title': self.title})
class Sale(models.Model):
product = models.ForeignKey(Product, related_name='to_product',on_delete=models.CASCADE),
date_of_sale = models.DateTimeField(auto_now_add=True, blank=True),
quantity_goods_sold = models.IntegerField(),
retail_price = models.IntegerField(),
def __str__(self):
return self.id
Your fields should not end with a comma (,). If you add a trailing comma, it will wrap the field in a singleton tuple, and thus Django is then not able to detect the field:
from django.db import models
from django.urls import reverse
class Category(models.Model):
image = models.ImageField(default='default.png', upload_to='category_image')
title = models.CharField(max_length=50, db_index = True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('category_detail_url', kwargs={'title': self.title})
class Provider(models.Model):
name = models.CharField(max_length=50, db_index=True)
phone_number = models.CharField(max_length=12, db_index=True)
address = models.CharField(max_length=50, db_index=True)
def __str__(self):
return self.name
class Product(models.Model):
title = models.CharField(max_length=50, db_index = True)
receipt_date = models.DateTimeField(auto_now_add=True, blank=True)
quantity_stock = models.IntegerField()
quantity_store = models.IntegerField()
purchase_price = models.IntegerField()
image = models.ImageField(default='default.png', upload_to='product_image')
provider = models.ForeignKey(
Provider,
null=True,
related_name='products',
on_delete=models.CASCADE
)
category = models.ForeignKey(
Category,
null=True,
related_name='products',
on_delete=models.CASCADE
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('product_detail_url', kwargs={'title': self.title})
class Sale(models.Model):
product = models.ForeignKey(
Product,
related_name='sales',
on_delete=models.CASCADE
)
date_of_sale = models.DateTimeField(auto_now_add=True, blank=True)
quantity_goods_sold = models.IntegerField()
retail_price = models.IntegerField()
def __str__(self):
return self.id
Related
I want to display the trainer for a course date. A course can have several dates and a different trainer can be used on each date. A trainer can have a different role on each course date. (Instructor, helper...)
How do I make the correct query? Are the models correct for this?
Models:
class Course_dates(models.Model):
date = models.DateField()
start = models.TimeField()
end = models.TimeField()
def __str__(self):
return str(self.id)
"""return self.date.strftime("%d.%m.%Y")"""
class Course(models.Model):
course_number = models.CharField(max_length=24, blank=True)
course_location = models.ForeignKey(Course_location, on_delete=models.CASCADE)
course_dates = models.ManyToManyField('Course_dates', through="Course_Course_dates")
def __str__(self):
return self.course_number
class Trainer_Course_Course_date_role(models.Model):
trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE)
role = models.CharField(max_length=24, blank=True)
def __str__(self):
return str(self.id)
class Course_Course_dates(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
course_dates = models.ForeignKey(Course_dates, on_delete=models.CASCADE)
trainer = models.ForeignKey(Trainer_Course_Course_date_role, on_delete=models.CASCADE, null=True)
def __str__(self):
return str(self.id)
class Trainer(models.Model):
salutation = models.CharField(max_length=8,choices=GENDER_CHOICES)
last_names = models.CharField(max_length=56)
first_names = models.CharField(max_length=56)
date_of_birth = models.DateField()
address = models.ForeignKey(Address, on_delete=models.CASCADE)
email = models.EmailField()
phone = models.CharField(max_length=56, blank=True)
mobile = models.CharField(max_length=56, blank=True)
def __str__(self):
return self.last_names
View:
def course(request):
courses = Course.objects.all()
course_list = []
for course in courses:
sorted_date_list = course.course_dates.all().order_by('date')
course_list.append({'course': course, 'sorted_date_list': sorted_date_list })
context = { 'course_list': course_list, }
return render(request, 'kursverwaltung_tenant/course.html', context)
'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'.
i am getting error on 'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'. any help, would be appreciated.
'DemoAppProductUpdateDestroySerializer' object has no attribute
'get_image'
models.py
class Product(models.Model):
title = models.CharField(max_length=30)
slug= models.SlugField(blank=True, null=True)
sku = models.CharField(max_length=30)
description = models.TextField(max_length=200, null=True, blank=True)
instruction = models.TextField(max_length=200, null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits= 10,)
discount_price= models.DecimalField(decimal_places=2, max_digits= 10, null=True, blank=True)
brand = models.ForeignKey("Brand", null=True, blank=True, on_delete=models.CASCADE)
waist = models.ForeignKey("Waist", null=True, blank=True, on_delete=models.CASCADE)
occasion = models.ForeignKey("Occasion", null=True, blank=True, on_delete=models.CASCADE)
style = models.ForeignKey("Style", null=True, blank=True, on_delete=models.CASCADE)
neck = models.ForeignKey("Neck", null=True, blank=True, on_delete=models.CASCADE)
fit = models.ForeignKey("Fit", null=True, blank=True, on_delete=models.CASCADE)
pattern_type = models.ForeignKey("Pattern_Type", null=True, blank=True, on_delete=models.CASCADE)
color = models.ForeignKey("Color", null=True, blank=True, on_delete=models.CASCADE)
size = models.ManyToManyField("Size", null=True, blank=True)
sleeve = models.ForeignKey("Sleeve_Length", null=True, blank=True, on_delete=models.CASCADE)
material = models.ForeignKey("Material", null=True, blank=True, on_delete=models.CASCADE)
category = models.ManyToManyField('Category', )
default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True, on_delete=models.CASCADE)
created_on = models.DateTimeField(default=timezone.now)
updated_on = models.DateTimeField(null=True, blank=True)
status = models.BooleanField(default=True)
class Meta:
ordering = ["-id"]
def __str__(self): #def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("product_detail", kwargs={"pk": self.pk})
def get_image_url(self):
img = self.productimage_set.first()
if img:
return img.image.url
return img #None
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(pre_save_post_receiver, sender=Product)
def image_upload_to(instance, filename):
title = instance.product.title
slug = slugify(title)
basename, file_extension = filename.split(".")
new_filename = "%s-%s.%s" %(slug, instance.id, file_extension)
return "products/%s/%s" %(slug, new_filename)
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
image = models.ImageField(upload_to=image_upload_to)
created_on = models.DateTimeField(default=timezone.now)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.product.title
views.py
class ProductUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
model = Product
queryset = Product.objects.all()
serializer_class = DemoAppProductUpdateDestroySerializer
permission_classes = [IsAdminUser]
authentication_classes = [BasicAuthentication]
serializers.py
class DemoAppProductUpdateDestroySerializer(serializers.ModelSerializer):
image = serializers.SerializerMethodField()
class Meta:
model = Product
fields=[
"id",
"title",
"slug",
"sku",
"price",
"discount_price",
"image",
]
def get_image(self, obj):
return obj.productimage_set.first().image.url
I have a model CartItem that has a ForeignKey to a Product model.
Because from Product model I get the description, image, etc.
However, I want to have a method called sub_total that returns and integer. I use this to calculate total to be paid for this CartItem.
This sub_total method query a different model costo_de_los_productos using some of the properties of CartItem. like: self.product.category.name, self.product.name, self.size, self.quantity.
I need to return an Integer from sub_total method.
However, something is not right with me query, if I comment it and return 0 it works, but total is 0.
def sub_total(self):
product_price = costo_de_los_productos.objects.filter(category=self.product.category.name,
product = self.product.name,
size=self.size,
quantity=self.quantity).values_list("price", flat=True)
What could be wrong?
class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
size = models.CharField(max_length=20, choices=TAMANIOS)
quantity = models.CharField(max_length=20, choices=CANTIDADES)
file = models.FileField(upload_to='files', blank=True, null=True)
comment = models.CharField(max_length=100, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
step_two_complete = models.BooleanField(default=False)
# def __str__(self):
# return str(self.id) + " - " + str(self.size) + " por " + str(self.quantity)
def sub_total(self):
product_price = costo_de_los_productos.objects.filter(category = self.product.category.name,
product = self.product.name,
size=self.size,
quantity=self.quantity).values_list("price", flat=True)
# print(type(product_price))
return product_price
costo_de_los_productos model:
class costo_de_los_productos(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.IntegerField(default=30)
size = models.CharField(max_length=20, choices=TAMANIOS)
quantity = models.CharField(max_length=20, choices=CANTIDADES)
product model:
class Product(models.Model):
name = models.CharField(max_length=250, unique=False)
slug = models.SlugField(max_length=250, unique=False)
description = models.TextField(blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
image = models.ImageField(upload_to='product', blank=True, null=True)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def get_url(self):
return reverse('shop:ProdDetail', args=[self.category.slug, self.slug])
def __str__(self):
return '{}'.format(self.name)
category model:
class Category(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to='category', blank=True, null=True)
video = EmbedVideoField(null=True, blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_url(self):
return reverse('shop:allCat', args=[self.slug])
def __str__(self):
return '{}'.format(self.name)
Image of "costo_de_los_productos" from Admin Panel:
UPDATE 1
Cannot print anything after the product_price query.
def sub_total(self):
print("Enters Subtotal")
print(self.product.category.name)
print(self.product.name)
print(self.size)
print(self.quantity)
product_price = costo_de_los_productos.objects.filter(category=self.product.category.name,
product=self.product.name,
size=self.size,
quantity=self.quantity).values_list("price", flat=True)[0]
print("Line after product_price query")
print(type(product_price))
return product_price
Hard coding the values doesn't return expected integer:
def sub_total(self):
print("Enters Subtotal")
print(self.product.category.name)
print(self.product.name)
print(self.size)
print(self.quantity)
product_price = costo_de_los_productos.objects.filter(category="Stickers",
product="Stickers transparentes",
size="5cm x 5cm",
quantity=300).values_list("price", flat=True)[0]
print("Line after product_price query")
print(type(product_price))
return product_price
prints results:
Enters Subtotal
Stickers
Stickers transparentes
5cm x 5cm
300
here are my models
class TimeSlots(models.Model):
start = models.TimeField(null=True, blank=True)
end = models.TimeField(null=True, blank=True)
class Meta:
ordering = ['start']
def __str__(self):
return '%s - %s' % (self.start, self.end)
class Event(models.Model):
event_date = models.DateField(null=False, blank=True)
start = models.OneToOneField(TimeSlots)
end = models.TimeField(null=True, blank=True)
available = models.BooleanField(default=True)
patient_name = models.CharField(max_length=60, null=True, blank=True)
phone_number = PhoneNumberField(blank=True, null=True)
stripePaymentId = models.CharField(max_length=150, null=True, blank=True)
stripePaid = models.BooleanField(null=False, blank=True, default=True)
key = models.UUIDField(primary_key=False, default=uuid.uuid4,
editable=False)
sites = models.ManyToManyField(Site, null=True, blank=True)
class Meta:
verbose_name = u'Scheduling'
verbose_name_plural = u'Scheduling'
def __unicode__(self):
return self.start
def get_absolute_url(self):
url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.pk])
return u'%s' % (url, str(self.start))
What I want is that end value of Event Model should be auto filled by the selected Timeslot
like when I choose a start value from timeslot for the event model the end value should automatically be filled
Ok I solved it by adding a clean function in my model
def clean(self):
self.end = self.start.end
It was that simple
I try to chain material and categorie with django smart select but it does not work
What is wrong in my code ?
class Demande_Expertise(models.Model):
user = models.ForeignKey(User)
material = models.ForeignKey("Material")
categorie = ChainedForeignKey("material.Category",
chained_field="material",
chained_model_field="name",
show_all=False,
auto_choose=True)
droits_acces = models.CharField(_('val_champ'), max_length=150, choices = DROITS)
groupe = models.ForeignKey(Group, blank = True, null= True, default = None)
etat = models.CharField(_('val_champ'), max_length=150, choices = ETAT, default = '2')
class Category(models.Model):
name = models.CharField(_('name'), max_length=50)
slug = models.SlugField()
class Material(models.Model):
name = models.CharField(_('name'), max_length=50)
description = models.TextField(_('description'), blank=True)
slug = models.SlugField()
category = ChainedForeignKey(Category, verbose_name=_('category'),
chained_field="name",
chained_model_field="name",
show_all=False,
auto_choose=True)
created = models.DateField(_("creation date"), auto_now_add=True)
Try Django Clever Selects
https://github.com/PragmaticMates/django-clever-selects
I use it in my Django 1.6 project
Your structure is incorrect I am giving you an example that works
class Continent(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Country(models.Model):
continent= models.ForeignKey(Continent)
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class City(models.Model):
continent= models.ForeignKey(Continent)
country= ChainedForeignKey(Country, chained_field="continent", chained_model_field="continent", show_all=False, auto_choose=True, sort=True)
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Neighborhood(models.Model):
continent= models.ForeignKey(Continent)
country= ChainedForeignKey(Country, chained_field="continent", chained_model_field="continent", show_all=False, auto_choose=True, sort=True)
name = models.CharField(max_length=255)
city= ChainedForeignKey(City, chained_field="country", chained_model_field="country", show_all=False, auto_choose=True, sort=True)
name = models.CharField(max_length=255)
def __str__(self):
return self.name