i have two models: Address and Phone. Inside each model, rests a "Default" boolean field. What I need it to do, is if I submit a True answer in a form, then all other records must be set to False for that user.
How do I accomplish this?
class Address (models.Model):
User = models.ForeignKey(User)
Primary = models.BooleanField(default=True)
Street = models.CharField(max_length=500)
City = models.CharField(max_length=50)
State = models.CharField(max_length=40)
Zip = models.CharField(max_length=20)
County = models.CharField(max_length=20)
Country = models.CharField(max_length=50, default="United States")
Latitude = models.FloatField(null=True, blank=True)
Longitude = models.FloatField(null=True, blank=True)
class Meta:
verbose_name_plural = "Addresses"
def __str__(self):
primary = 'PRIMARY Address for ' if self.Primary else 'Address for '
return primary + self.User.first_name + ' ' + self.User.last_name
def save(self, *args, **kwargs):
geolocator = Nominatim()
location = geolocator.geocode("{} {}, {}, {}".format(self.Street, self.State, self.Zip, self.Country))
self.Latitude = location.latitude
self.Longitude = location.longitude
super(Address, self).save(args, *kwargs)
class Phone (models.Model):
User = models.ForeignKey(User)
Primary = models.BooleanField(default=True)
Country_Code = models.CharField(max_length=5, default="001")
Area_Code = models.CharField(max_length=5, blank=True, null=True)
Number = models.CharField(max_length=20, blank=True, null=True)
def __str__(self):
return self.Country_Code + "-" + self.Area_Code + "-" + self.Number
You can use post_save signal or override save method. Following is a simple snippet. If you want to keep consistent, put the these queries in a transaction.
def save(self, *args, **kwargs):
geolocator = Nominatim()
location = geolocator.geocode("{} {}, {}, {}".format(self.Street, self.State, self.Zip, self.Country))
self.Latitude = location.latitude
self.Longitude = location.longitude
super(Address, self).save(args, *kwargs)
Address.objects.exclude(id=self.id).update(Primary=False)
Related
I have a model name Employee now i want to add a new fields in this model which will be a foreign key of Department model.I try to solve it the following way but i get error like
django.db.utils.IntegrityError: The row in table 'employee_verification_employee' with primary key 'UP-0319001' has an invalid foreign key: employee_verification_employee.department_id contains a value '03' that does not have a corresponding value in employee_verification_department.id.
class Department(models.Model):
name = models.CharField(max_length=100)
id = models.CharField(primary_key=True,max_length=10)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.CharField(max_length=100,choices = Departments)
date_of_joining = models.DateField()
employeed = models.BooleanField(default = True)
email = models.EmailField(max_length = 254)
blood_group = models.CharField(max_length=50)
designation = models.CharField(max_length=100)
image = models.ImageField(upload_to='employee_images',default = "")
number = PhoneField(blank=True, help_text='Enter Contact Number')
emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
id = models.CharField(primary_key=True, max_length=200)
department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)
def save(self, *args, **kwargs):
if not self.id:
nth_member = Employee.objects.filter(department = self.department).count()+1
self.id = "UP-" + self.department + self.date_of_joining.strftime("%y")+"{:03d}".format(nth_member)
print(self.id)
super(Employee, self).save(*args, **kwargs)
def __str__(self):
return self.name + "--"+ self.designation``
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/xdRMd.png
As #trigo said, all you need is:
class Department(models.Model):
name = models.CharField(max_length=100)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.CharField(max_length=100,choices = Departments)
date_of_joining = models.DateField()
employeed = models.BooleanField(default = True)
email = models.EmailField(max_length = 254)
blood_group = models.CharField(max_length=50)
designation = models.CharField(max_length=100)
image = models.ImageField(upload_to='employee_images',default = "")
number = PhoneField(blank=True, help_text='Enter Contact Number')
emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)
And Django will take care of the rest (ids).
My lab has a models.py as below:
class Book(models.Model):
isbn = models.CharField(max_length=10, unique=True)
name = models.CharField(max_length=100)
published_year = models.IntegerField()
total_qty = models.IntegerField()
current_qty = models.IntegerField()
max_duration = models.IntegerField()
author = models.ForeignKey(Author, on_delete=models.PROTECT)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
def __str__(self):
return self.name
class BookCopy(models.Model):
class Status:
AVAILABLE = 1
BORROW =2
LOST = 3
barcode = models.CharField(max_length=30, unique=True)
buy_date = models.DateField(null=True, blank=True)
status = models.IntegerField()
book = models.ForeignKey(Book, on_delete=models.PROTECT)
def __str__(self):
return self.barcode
class User(models.Model):
username = models.CharField(max_length=30, unique=True)
fullname = models.CharField(max_length=100, null=True)
phone = models.CharField(max_length=10, null=True)
def __str__(self):
return self.fullname
class BookBorrow(models.Model):
class Status:
BORROWING = 1
RETURNED = 2
borrow_date = models.DateField()
deadline = models.DateField()
return_date = models.DateField(null=True)
status = models.IntegerField()
book_copy = models.ForeignKey(BookCopy, on_delete=models.PROTECT)
book_name = models.ForeignKey(Book, on_delete=models.PROTECT)
user = models.ForeignKey(User, on_delete=models.PROTECT)
And i wrote the api for borrow_book function like below:
#csrf_exempt
def muon_sach(request):
body = request.POST
username = body.get('username')
barcode = body.get('barcode')
user = User.objects.filter(username=username).first()
bookcopy = BookCopy.objects.filter(barcode = barcode).first()
if not user:
return HttpResponse(json.dumps({
'error':"Nguoi dung khong ton tai"
}))
if not bookcopy:
return HttpResponse(json.dumps({
'error':"ma sach khong ton tai"
}))
book_borrow = BookBorrow()
# resp = []
book_borrow.user = user
book_borrow.book_copy = bookcopy
book_borrow.borrow_date = datetime.now()
book_borrow.deadline = datetime.now() + timedelta(days=bookcopy.book.max_duration)
book_borrow.status = BookBorrow.Status.BORROWING
book_borrow.book_name = bookcopy.book.name
book_borrow.save()
bookcopy.status = BookCopy.Status.BORROW
bookcopy.save()
bookcopy.book.current_qty -=1
bookcopy.book.save()
return HttpResponse(json.dumps({'success':True}))
however when i test with postman (give username and barcode), it gets the error
xxx "BookBorrow.book_name" must be a "Book" instance."
Could you please advise where incorrect and assist me correct it ? Appreciate for any assist
You have to do the following:
#csrf_exempt
def muon_sach(request):
# ... more code here
bookcopy = BookCopy.objects.filter(barcode = barcode).first()
book_borrow.book_name = bookcopy.book
book_borrow.save()
# ... more code here
return HttpResponse(json.dumps({'success':True}))
So in the definition of your model you can see that book_name has the following structure:
class BookBorrow(models.Model):
# ... More code here
book_name = models.ForeignKey(Book, on_delete=models.PROTECT)
user = models.ForeignKey(User, on_delete=models.PROTECT)
It is clear that BookBorrow.book_name must accept a Book instance. So when you pass in you code book_borrow.book_copy = bookcopy it is passing a BookCopy instance so that's the error.
borrow_copy.book is the appropiate.
You have specified book_name to be a Foreign Key to Book, and you try to assign to it the book.name value.
Either you need to set this field as a CharField or you need to rename the field from book_name to book and use book_borrow.book = bookcopy.book
I am using a form that saves to one model to update the most current mileage which is stored in another model. I want to make sure the mileage entered is > or = the current mileage. I havent been able to figure out the right validation or where to write the validation.
I have tried an if statement in the form_valid() of the CreateView and a save() method in the model.
Models.py
class Vehicle(models.Model):
name = models.CharField(blank=True, max_length=100)
make = models.CharField(blank=True, max_length=100)
model = models.CharField(blank=True, max_length=100)
year = models.IntegerField(blank=True, null=True)
vin = models.CharField(blank=True, max_length=17)
gvw = models.IntegerField(blank=True, null=True)
license_plate = models.CharField(blank=True, max_length=100)
purchase_date = models.DateField()
current_mileage = models.IntegerField(blank=True, null=True)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('vehicles:vehicle_detail', kwargs={'pk':self.pk})
#property
def get_current_mileage(self):
return self.current_mileage
class FuelEntry(models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
fuel_choices = (
('EMPTY', 'Empty'),
('1/8', '1/8'),
('1/4', '1/4'),
('1/2', '1/2'),
('3/4', '3/4'),
('FULL', 'Full'),
)
current = models.CharField(max_length=5, choices=fuel_choices)
after = models.CharField(max_length=5, choices=fuel_choices, blank=True)
gallons = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0')
cost = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0')
mileage = models.IntegerField(blank=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['-date', 'vehicle']
def __str__(self):
return self.vehicle.name
def get_absolute_url(self):
return reverse('fuellog:entry_detail', kwargs={'pk':self.pk})
Views.py
class CreateEntry(CreateView):
model = FuelEntry
fields = ('vehicle', 'current', 'after', 'gallons', 'cost', 'mileage')
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.user = self.request.user
vehicle_id = self.object.vehicle.pk
mileage = self.object.mileage
self.object.save()
current_mileage = Vehicle.objects.filter(id=vehicle_id).get('current_mileage')
if current_mileage > mileage:
raise ValidationError('Incorrect mileage reading')
Vehicle.objects.filter(id=vehicle_id).update(current_mileage=mileage)
return super().form_valid(form)
ValueError at /fuel/new
too many values to unpack (expected 2)
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
I have a booking system for bank line :
this is my model for the customer:
class Customer(models.Model):
customer_bank = models.ForeignKey('Bank', on_delete=models.SET_NULL,related_name='coustmer_bank' ,null=True)
customer_branch = models.ForeignKey('Branch', on_delete=models.SET_NULL,related_name='coustmer_branch',null=True)
booking_id = models.CharField(max_length=120, blank= True,default=increment_booking_number)
identity_type = models.ForeignKey('IdentityType',on_delete=models.SET_NULL,related_name='identity_type',null=True)
identity_or_passport_number = models.CharField(max_length=20)
bank_account_no = models.CharField(max_length=15)
Done = models.BooleanField(default=False)
booking_date_time = models.DateTimeField(auto_now_add=True, auto_now=False)
Entrance_date_time = models.DateTimeField(auto_now_add=False, auto_now=True)# Must be modified to work with Entrance Date and Time
def __str__(self):
return self.booking_id
I need to generate a random value for booking_id field depends on bank_number and the branch_number and the Customer id so how can I do that? help please
You can overide the save method of the model
class Customer(models.Model):
customer_bank = models.ForeignKey('Bank', on_delete=models.SET_NULL,related_name='coustmer_bank' ,null=True)
customer_branch = models.ForeignKey('Branch', on_delete=models.SET_NULL,related_name='coustmer_branch',null=True)
booking_id = models.CharField(max_length=120, blank= True,default=increment_booking_number)
identity_type = models.ForeignKey('IdentityType',on_delete=models.SET_NULL,related_name='identity_type',null=True)
identity_or_passport_number = models.CharField(max_length=20)
bank_account_no = models.CharField(max_length=15)
Done = models.BooleanField(default=False)
booking_date_time = models.DateTimeField(auto_now_add=True, auto_now=False)
Entrance_date_time = models.DateTimeField(auto_now_add=False, auto_now=True)# Must be modified to work with Entrance Date and Time
def __str__(self):
return self.booking_id
def get_booking_id(self):
bank_number = self.bank_number
branch_number = self.branch_number
id = # logic for calculating boking ID from bank_number, branch_number and other fields accessible from self.<field_name>
return id
def save(self, *args, **kwargs):
self.booking_id = self.get_booking_id()
super(Customer, self).save(*args, **kwargs)