dependent field of others in django admin - django

I have a model
class Essai_Fluage(models.Model):
name = models.ForeignKey(Material, verbose_name=_('name'))
elongation= models.FloatField(_('allongement'),blank=True, null=False)
t_02 = models.IntegerField(_('t_0.2%'),blank=True, null=False)
t_05 = models.IntegerField(_('t_0.5%'),blank=True, null=False)
t_075 = models.IntegerField(_('t_0.75%'),blank=True, null=False)
tr = models.IntegerField(_('tr'),blank=True, null=False)
T= models.FloatField(_('temperature'),blank=True, null=False)
sigma = models.FloatField(_('contrainte'),blank=True, null=False)
PLM = models.FloatField(_('PLM'),blank=True, null=False)
rep = models.IntegerField(_('indice'),blank=True, null=True)
def __unicode__(self):
return '%s' % (self.name)
class Meta:
verbose_name = _('creep test')
verbose_name_plural = _('creep test')
ordering = ['rep',]
I would like to have the field PLM calculate with the formula
PLM = (T/1000)*(20 + log10(tr))
T and tr are the fields
T= models.FloatField(_('temperature'),blank=True, null=False)
tr = models.IntegerField(_('tr'),blank=True, null=False)
in the admin, is it possible to do this ?

You can override save method of model to calculate the value from the formula.
Try this :
class Essai_Fluage(models.Model):
name = models.ForeignKey(Material, verbose_name=_('name'))
elongation= models.FloatField(_('allongement'),blank=True, null=False)
t_02 = models.IntegerField(_('t_0.2%'),blank=True, null=False)
t_05 = models.IntegerField(_('t_0.5%'),blank=True, null=False)
t_075 = models.IntegerField(_('t_0.75%'),blank=True, null=False)
tr = models.IntegerField(_('tr'),blank=True, null=False)
T= models.FloatField(_('temperature'),blank=True, null=False)
sigma = models.FloatField(_('contrainte'),blank=True, null=False)
PLM = models.FloatField(_('PLM'),blank=True, null=False)
rep = models.IntegerField(_('indice'),blank=True, null=True)
def __unicode__(self):
return '%s' % (self.name)
class Meta:
verbose_name = _('creep test')
verbose_name_plural = _('creep test')
ordering = ['rep',]
def save(self, *args, **kwargs):
if self.PLM is not None:
self.PLM = (self.T/1000)*(20 + log10(self.tr))
super(Essai_Fluage, self).save(*args, **kwargs)

Related

I want to assign a user to my card from the User table, but its not working for me

The error is:
django.db.utils.ProgrammingError: column
user_awaycardholder.assigned_user_id does not exist LINE 1:
...der"."id", "user_awaycardholder"."display_id_id", "user_away...
I am not able to create AwayCardHolder can you please tell me what is the above error ??? and How to fix that ?
class UserData(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
title = models.CharField(max_length=40, default="")
phone = models.CharField(max_length=15)
facebook_id = models.CharField(max_length=400)
youtube_id = models.CharField(max_length=400)
linkedin_id = models.CharField(max_length=400)
instagram_id = models.CharField(max_length=400)
twitter_id = models.CharField(max_length=400)
logo = models.ImageField(upload_to='logo')
profile_image = models.ImageField(upload_to='media/profile')
location = models.CharField(max_length=400)
website = models.CharField(max_length=100)
messanger = models.CharField(max_length=200)
parent_id = models.CharField(max_length=20, blank=True)
is_child = models.BooleanField(default=False)
phone_office = models.CharField(max_length=15, blank=True)
hits = models.IntegerField(max_length=10, default=0)
class Meta:
verbose_name_plural = "User Data"
def __str__(self):
name = self.user.first_name + ' ' + str(self.user.id)
return str(name)
class AwayCard(models.Model):
Away_id = models.UUIDField(default=uuid.uuid4, editable=True)
my_admin = models.ForeignKey(User, on_delete=models.CASCADE)
display_id = models.CharField(default='', max_length=30)
is_assigned = models.BooleanField(default=False)
def __str__(self):
name = str(self.display_id)
return str(name)
class AwayCardHolder(models.Model):
display_id = models.OneToOneField(AwayCard, on_delete=models.CASCADE)
assigned_user = models.ForeignKey(User, related_name="user_awaycardholder", on_delete=models.CASCADE)
def __str__(self):
name = self.display_id
return str(name)

Django: method of model from querying a different one

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

Auto Complete field in django

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

django models getting queryset

how to get status_updation and status_date respect to the order_number
class customer_database(models.Model):
customer_id = models.CharField(max_length=20, unique=True)
customer_name = models.CharField(max_length=20)
customer_email = models.EmailField()
def __str__(self):
return self.customer_id
class order_database(models.Model):
order_number = models.CharField(max_length=10, unique=True, primary_key=True)
order_timestamp = models.DateTimeField()
order_consignment_number = models.CharField(max_length=20)
order_customer = models.ForeignKey(customer_database, on_delete=models.CASCADE)
def __str__(self):
return self.order_number
class track_database(models.Model):
order_status = models.ForeignKey(order_database, on_delete=models.CASCADE)
status_updation = models.CharField(max_length=30)
status_timestamp = models.DateTimeField()
def __str__(self):
return self.status_updation
Try
query_order_number = '1234'
tracker = track_database.objects.filter(order_status.order_number = query_order_number)
print(tracker.status_updation)
print(tracker.status_timestamp)
Let me know if this doesn't work
Or you could go via the order number:
query_order_number = '1234'
order = order_database.objects.filter(order_number = query_order_number)
print(order.track_database.status_updation)
print(order.track_database.status_timestamp)

Using django modelform for 2 instances not saving correctly

In Django 1.6.1 I have a vehicle model which might zero or up to 2 traded-in units. Every time I edit any record, whether the change is trade-in instance #1 or instance 2, both records are updated with values instance #2.
Vehicle model:
class Vehicle(models.Model):
stock = models.CharField(max_length=10, blank=False, db_index=True)
vin = models.CharField(max_length=17, blank=False, db_index=True)
#vinlast8 = models.CharField(max_length=8, blank=False, db_index=True)
make = models.CharField(max_length=15, blank=False)
model = models.CharField(max_length=15, blank=False)
year = models.CharField(max_length=4, blank=False)
registry = models.IntegerField(blank=True, verbose_name='Reg #', null=True)
plate = models.CharField(blank=True, null=True, max_length=10)
tagno = models.IntegerField(blank=True, null=True, verbose_name='Tag #')
tag_exp = models.DateField(blank=True, null=True, verbose_name='Tag Exp')
Tradein model:
class TradeIn(Vehicle):
TradeInVehicle = (
(1, 'First vehicle'),
(2, 'Second vehicle'),
)
vehicle_sale = models.ForeignKey(VehicleSale)
tradeinpos = models.IntegerField(choices=TradeInVehicle)
lienholder = models.CharField(max_length=15, blank=True, null=True, verbose_name='L/holder')
lhdocrequested = models.DateField(blank=True, null=True, verbose_name='D/Requested')
lhdocreceived = models.DateField(blank=True, null=True, verbose_name='D/Received')
class Meta:
db_table = 'tradein'
def __unicode__(self):
return self.stock
def save(self, *args, **kwargs):
self.stock = self.stock.upper()
self.vin = self.vin.upper()
return super(TradeIn, self).save(*args, **kwargs)
The related sections on view is:
These sections are related to request.GET
current_vehicle = VehicleSale.objects.get(pk=pk)
tradeIns = current_vehicle.tradein_set.all().order_by('tradeinpos')
# Also add tradein_form to t_data so it can be rendered in the template
t_count = tradeIns.count()
if t_count == 0:
t_data['tradein1_form'] = TradeInForm()
t_data['tradein2_form'] = TradeInForm()
if t_count >= 1 and tradeIns[0] and tradeIns[0].tradeinpos == 1:
t_data['tradein1_form'] = TradeInForm(instance=tradeIns[0])
t_data['tradein2_form'] = TradeInForm()
if t_count == 2 and tradeIns[1] and tradeIns[1].tradeinpos == 2:
t_data['tradein2_form'] = TradeInForm(instance=tradeIns[1])
Now these are related to request.POST:
if 'tradein-form' in request.POST:
if tradeIns.count() > 0:
if tradeIns[0]:
tradein1_form = TradeInForm(request.POST, instance=tradeIns[0])
if tradein1_form.is_valid():
tradein1_form.save()
if tradeIns[1]:
tradein2_form = TradeInForm(request.POST, instance=tradeIns[1])
if tradein2_form.is_valid():
tradein2_form.save()
While reviewing contents of request.POST, it does contain any change I make in either instance. But always, the 2nd instance is saved.
What am I missing or have wrong?