invalid literal for int() with base 10: 'USA' django - django

Good day.
Am having a model called AddInv
AddInv(models.Model):
client = models.ForeignKey(User, null=True)
description = models.CharField(max_length = 100)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField()
sold = models.PositiveIntegerField(default=0)
details = models.CharField(max_length = 100)
country = models.ForeignKey(Signup, null = True)
def __str__(self):
return self.country
Model for Signup is
class Signup(models.Model):
user = models.OneToOneField(User)
phone_number = models.PositiveIntegerField( null=True)
zipcode = models.PositiveIntegerField(null=True)
street = models.CharField(max_length = 75, null=True)
city = models.CharField(max_length = 75, null=True)
state = models.CharField(max_length = 75, null= True)
country = models.CharField(max_length = 32, null=True, choices = CATEGORIES)
def __str__(self):
return self.country
and a views to filter by country
def homepage(request): # Client View
context = {}
items = get_object_or_404(AddInv, country="USA")
print "Items", items
return render(request, "selly/homepage.html", {'items': items})
Am having error pointing to
items = get_object_or_404(AddInv, country="USA")
What could be wrong with the code

Try this. Just an assume
items = get_object_or_404(AddInv, country__country="USA")

I used
items = AddInv.objects.filter(country__country="USA")
which worked

Related

how to add new foreign key in my old django models?

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).

Django models - how to assign as ForeignKey

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

How to link two databases together?

I have 2 databases that are supposed to be linked by a foreign key: DealershipListing and Dealers.
Here are their models:
class Dealer(models.Model):
dealersName = models.TextField(('DealersName'))
zipcode = models.CharField(("zipcodex"), max_length = 15)
zipcode_2 = models.CharField(("zipCode"), max_length = 15)
state = models.CharField(("state"), max_length=5)
address = models.TextField(("Address"))
ids = models.BigIntegerField(("ids"), primary_key=True)
def __str__(self):
return self.dealersName
class DealershipListing(models.Model):
uniqueID = models.IntegerField(("CarID"), primary_key=True)
vincode = models.CharField(('vinCode'), max_length=255)
price = models.CharField(('price'), max_length=30)
msrp = models.CharField(('msrp'), max_length=30)
mileage = models.CharField(('mileage'), max_length=9)
is_new = models.BooleanField(('isNew'))
first_seen = models.CharField(("first_seen"), max_length=15)
last_seen = models.CharField(("last_seen"), max_length=15)
model = models.CharField(("Models"), max_length= 255)
make = models.CharField(("Make"), max_length=255)
year = models.CharField(("Year"), max_length= 4)
ids = models.ForeignKey(Dealer, on_delete=CASCADE)
color = models.CharField(("ExtColor"), max_length=255, null=True, blank = True)
intcolor = models.CharField(("IntColor"), max_length=255, null=True, blank=True)
def __str__(self):
return self.year + " " + self.make + " " + self.model
But when I go check the admin database, the DealershipListing is a dropdown of the names of every dealership in the Dealer model, but the ids on the DealershipListing model is placed in the place of color. What am I doing wrong? How do I connect each car in the DealershipListing to their Dealership by the ids?

How to make query to filter data from database table in Django?

There are three tables which are:
models.py
class Student(models.Model):
gen_choices = (
("Male", "Male"),
("Female", "Female"),
("Third", "Third"),
)
enrollNo = models.IntegerField(default=add_one)
fname = models.CharField(validators=[max_len_check], max_length=26)
lname = models.CharField(validators=[max_len_check], max_length=26)
gender = models.CharField(max_length=6, choices=gen_choices)
dob= models.DateField()
address = models.CharField(max_length=256)
email = models.EmailField()
mobile = models.BigIntegerField()
status = models.BooleanField(null=True)
userID = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.FileField(upload_to="stdimages/", null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Entexaminfo(models.Model):
entexamses = (
("June Session", "June Session"),
("December Session", "December Session"),
)
approve_choice = (
("Pending", "Pending"),
("Accepted", "Accepted"),
("Rejected", "Rejected"),
)
ename = models.CharField(max_length=16, choices=entexamses)
enrollno = models.OneToOneField(Student, on_delete=models.CASCADE)
#programs = models.ManyToManyField(Programs, related_name='proNames', default=0)
program = models.ManyToManyField(Programs, default=0)
center = models.ForeignKey(Excenter, on_delete=models.CASCADE)
remarks = models.CharField(validators=[max_len_check], max_length=256, default="-")
#status = models.BooleanField()
status = models.CharField(max_length=8, choices=approve_choice, default="Pending")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
# for admin pannel to display for correction
def __str__(self):
return self.ename
class Ex_schedule(models.Model):
exDate = models.DateField()
exTime = models.TimeField()
exDuration = models.CharField(validators=[max_len_check], max_length=26)
programs = models.OneToOneField(Programs, on_delete=models.CASCADE)
exRemarks = models.CharField(max_length=256, null=True)
exStatus = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
# for admin pannel to display for correction
def __str__(self):
return self.exDate
class Programs(models.Model):
proName = models.CharField(validators=[max_len_check], max_length=26)
proDuration =models.CharField(validators=[max_len_check], max_length=26)
proFees = models.IntegerField(null=True)
proDetails = models.CharField(validators=[max_len_check], max_length=26, null=True)
proStatus = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
# for admin pannel to display for correction
def __str__(self):
return self.proName
I want to filter data from three tables (i.e. Student, Entexaminfo & Ex_schedule) giving a enrollno of student table, But I am not being able to filter data from Ex_schedule table because a student can choose more than one subject, according to chosen subjects data should be filter from Ex_schedule table. For this I have tried following codes but program id i have given manually, I want to replace it.
views.py
#login_required(login_url='/user/login')
def hall_ticket(request):
query = request.GET['enrollno']
if query:
entedetail = Student.objects.filter(enrollNo=query)
for obj in entedetail:
global id #To avoid 'local variable 'id' referenced before assignment' error message
id = obj.id
ent1 = Entexaminfo.objects.filter(enrollno=id)
esch = Ex_schedule.objects.filter(programs=1)
params = {'entedetails': entedetail, 'ent1': ent1, 'query': query, 'esch': esch, 'title': 'Entrance Exam Hall Ticket'}
else:
params = {'error': 'Please Enter Your Enrollment No.', 'title': 'Entrance Exam Hall Ticket'}
return render(request, 'hall_ticket.html', params)
Please guide me for it.

Create a new model based on two other existing models

I'm setting up a django project, I have 2 existing models Offers and Candidates, what I want to do is to create a new model (Scoring model) based on the two models Offers and Candidates, so i created a function add_line() in my Offer model that should create the Scoring object but it wont work even when I used the post_save signal, any suggestion?
Candidates model:
class Candidates(models.Model):
nom = models.CharField(max_length = 50)
prenom = models.CharField(max_length= 50)
email = models.EmailField()
phone = models.CharField(max_length=100)
niveau_d_experience = models.IntegerField()
etablissement_universitaire= models.CharField(max_length=150)
niveau_options = (('Licence', 'Licence'), ('Master', 'Master'), ("Diplôme d'ingénieur", "Diplôme d'ingénieur"), ('Doctorat', 'Doctorat'))
niveau_educatif = models.CharField(choices=niveau_options, max_length=100)
profil = models.CharField(max_length=100)
sexe_options = (('Mâle', 'Mâle'), ('Femelle', 'Femelle'))
sexe = models.CharField(choices=sexe_options, max_length=100)
offre = models.CharField(max_length= 200)
CV = models.FileField()
date_creation = models.DateTimeField(auto_now_add=True, auto_now=False)
text_resume = models.TextField(editable=False)
language = models.CharField(max_length = 20, editable=False)
Offers model:
class Offers(models.Model):
titre = models.CharField(max_length=120)
description = models.TextField()
technologies = models.TextField()
softskills = models.TextField()
expérience = models.IntegerField()
contrat_options= (('CDI', 'CDI'), ('CDD', 'CDD'), ('Freelance', 'Freelance'), ('Stage', 'Stage'))
contrat = models.CharField(choices=contrat_options, max_length=100)
mission_options = (('Interne', 'Interne'), ('Externe', 'Externe'))
mission= models.CharField(choices=mission_options, max_length=100)
validation_options = (('Offre validée', 'Offre validée'), ('Offre pourvue', 'Offre pourvue'))
validation = models.CharField(choices =validation_options, max_length=100)
def add_line(self, **kwargs):
queryset = Candidates.objects.all()
for candidate in queryset:
scoring, created = Scoring.objects.get_or_create(
offer_id = self,
cand_id = candidate
)
return scoring
def __str__(self):
return self.titre
and Scoring model:
class Scoring(models.Model):
offer_id = models.ForeignKey(Offers, on_delete = models.DO_NOTHING, editable = False)
cand_id = models.ForeignKey(Candidates, on_delete = models.DO_NOTHING, editable= False)