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

i have a model patient and another one exam, now i want to retrieve patient's exams based on the name, but i am stuccoed with the error invalid literal for int() with base 10: 'John Doe'
ValueError at /labtech/John Doe/see_exam
invalid literal for int() with base 10: 'John Doe'
Request Method: GET
Request URL: http://homasoft.com:8000/labtech/John%20Doe/see_exam
Django Version: 1.8
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: 'John Doe'
Exception Location: /Library/Python/2.7/site- packages/django/db/models/fields/__init__.py in get_prep_value, line 985
Python Executable: /usr/bin/python
Python Version: 2.7.5
Python Path:
['/Users/mymacbookpro/Documents/Virtualenvs/hospital/src',
'/Library/Python/2.7/site-packages/pip-1.4.1-py2.7.egg',
'/Users/mymacbookpro/Documents/Virtualenvs/hospital/src',
'/Users/mymacbookpro/Documents/Virtualenvs/hospital/src/django-social-auth',
'/Users/mymacbookpro/Documents/Virtualenvs/hospital/src/django-socialprofile',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat- darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
'/Library/Python/2.7/site-packages']
Server time: Mon, 1 Jun 2015 12:27:27 +0000
here is my view
def see_exam(request, name):
exam = Test.objects.filter(patient__user__exact=name)
context = {
'exam' : exam
}
return render(request, 'account/labtechs/see_results.html', context)
model exam
class Test(models.Model):
exam = models.ForeignKey(Exam)
patient = models.ForeignKey(Patient)
date = models.DateField()
result = models.TextField(default="negative")
done_by = models.CharField(max_length=120)
def __unicode__(self):
return self.exam.name
model for patient
class Patient(models.Model):
"""docstring for Patient"""
user = models.OneToOneField(MyUser)
date_of_birth = models.DateTimeField(blank=True, null=True)
age = models.IntegerField(default=1)
sex = models.OneToOneField(Sex)
religion = models.CharField(max_length=120, blank=True, null=True)
village = models.CharField(max_length=120)
status = models.OneToOneField(Status, blank=True, null=True)
relative = models.CharField(max_length=120)
phone = models.IntegerField(default=1)
allergies = models.TextField(default="", blank=True, null=True)
defficiencies = models.TextField(default="", blank=True, null=True)
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return "%s %s" %(self.user.first_name, self.user.last_name)

Change the query
exam = Test.objects.filter(patient__user__exact=name)
to
exam = Test.objects.filter(patient__user__name__exact=name)
#------------------------------------------^
Note the user__name added. Here I'm assuming your MyUser class has attribute name that you want to compare.
In your query you are trying to compare string name with object user (or rather internally id of that object) which is not compatible.

Related

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

Object of type Modul is not JSON serializable while trying to set the value of another model in the session

i am trying to save the id of a created model in the session so i can update it later in anothe page, but the set function shows me an error
i am using request.session['ORDER'] = serializers.serialize('json', Order.objects.all()) right now but i also used request.session['ORDER'] = order.id, i got the same error
if form.is_valid():
if(form.cleaned_data['paymentmethod'] == "PayPal"):
print("Paypal choosed")
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
phone = form.cleaned_data['phone']
address = form.cleaned_data['address']
zipcode = form.cleaned_data['zipcode']
place = form.cleaned_data['place']
paymentmethod = 'pypnt'
order = checkout(request, first_name, last_name, email, address, zipcode, place, phone,
cart.get_total_cost(), paymentmethod)
print(order.id)
print(order)
request.session['ORDER'] = serializers.serialize('json', Order.objects.all())
return redirect('cart:process')
this is the Order Model
lass Order(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
address = models.CharField(max_length=100)
zipcode = models.CharField(max_length=100)
place = models.CharField(max_length=100)
phone = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
paid_amount = models.DecimalField(max_digits=8, decimal_places=2)
vendors = models.ManyToManyField(Vendor, related_name='orders')
id = models.AutoField(primary_key=True)
class paymentmethod(models.TextChoices):
the error:
Internal Server Error: /de/cart/
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Product is not JSON serializable

Sending data through postman problem in django

I am trying to send data through postman and it takes one field null. So anyone can help me with that. And also I am a beginner to Django.
this is the error
django.db.utils.IntegrityError: null value in column "user_id"
violates not-null constraint DETAIL: Failing row contains (6, MBBS,
Orenburg University, 2019, null).
My models are:
class MyUser(AbstractBaseUser):
gender_type = (('Male','Male'),('Female','Female'))
user_name = (('Doctor','Doctor'),('Patient','Patient'))
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
user_type = models.CharField(choices=user_name, max_length=7)
full_name = models.CharField(max_length=13,null=False)
mobile_number = models.CharField(max_length=13,null=True)
date_of_birth = models.DateField(auto_now_add=True)
gender = models.CharField(choices=gender_type, max_length=10)
blood_group = models.CharField(max_length=25,null=True)
address = models.CharField(max_length=255, null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
class Educations(models.Model):
user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='edu_user')
doctor_degree = models.CharField(max_length=25)
university = models.CharField(max_length=25)
passing_year = models.IntegerField()
def __str__(self):
return self.doctor_degree
here the user is for doctor and i'm taking it's foreign key in education model
And its viewset is:
class EducationViewSet(viewsets.ViewSet):
def list(self,request):
eduss=Educations.objects.all()
edu_data_list=[]
for edu in eduss:
edu_data_list.append({
"doctor_degree" : edu.doctor_degree,
"university" : edu.university,
"passing_year" : edu.passing.year,
"doctor_name" : edu.user.full_name,
"doctor_mobile_number": edu.user.mobile_number,
"doctor_date_of_birth": edu.user.date_of_birth,
"doctor_blood_group": edu.user.blood_group,
"doctor_email": edu.user.email
})
return Response({"eduss":edu_data_list})
def create(self,request):
doctor_degree = request.data.get('doctor_degree')
university = request.data.get('university')
passing_year = request.data.get('passing_year')
user = request.user
education = Educations()
education.doctor = user
education.doctor_degree = doctor_degree
education.university = university
education.passing_year = passing_year
education.save()
return Response("successfully saved")

Django model is inheriting all super model Fields, except for IntegerField

I'm having a weird issue, I have a models' hierarchy, an abstract User class:
class User(AbstractBaseUser):
user_name = models.CharField(max_length=32, unique=True)
email = models.EmailField(max_length=255, unique=True, null=True)
phone = PhoneNumberField()
access_token = models.CharField(max_length=255, unique=True, null=True)
notifications_token = models.CharField(max_length=255, unique=True, null=True)
photo = models.ImageField(null=True)
person_in_contact = models.CharField(max_length=32, null=True)
active = models.BooleanField(default=False)
confirmedEmail = models.BooleanField(default=False)
confirmedPhone = models.BooleanField(default=False)
completedProfile = models.BooleanField(default=False)
visible = models.BooleanField(default=True)
#property
def is_active(self):
return self.active
# def __str__(self):
# return "Client : " + self.user_name + " Email:" + self.email
def get_email(self):
return self.email
USERNAME_FIELD = 'user_name'
REQUIRED_FIELDS = ['user_name', 'phone', 'password']
class Meta:
abstract = True
then a person class and a company (no issue with this one) class that inherit from this one:
class Person(User):
GENDER = (('F', 'FEMALE'), ('M', 'MALE'))
name = models.CharField(max_length=50, null=True)
surname = models.CharField(max_length=50, null=True)
adress = models.CharField(max_length=255, null=True)
birth_date = models.DateField(null=True)
gender = models.CharField(max_length=1, choices=GENDER, null=True)
age = models.IntegerField(null=True)
def age(self):
today = date.today()
return today.year - self.birth_date.year
# def __str__(self):
# return super().__str__() + " Name : " + self.name
class Meta:
abstract = True
as you can see, the only field that's IntegerField() is the age field.
now i have a Traveller and a Driver classes that inherit from the person class,
the issue is the age field, doesn't show in the database, unless i override it in one of the classes, that's what i did, i override it in traveller so it appeared in the database, but didn't override it in the driver, so it didn't show.
Traveller:
class Traveller(Person):
photo = models.ImageField(null=True, upload_to='travellers/profile_pictures')
age = models.IntegerField(null=True)
class Meta:
verbose_name_plural = 'Travellers'
Driver:
class Driver(Person):
rating = models.DecimalField(default=0, decimal_places=1, max_digits=3)
driving_license = models.CharField(max_length=50, null=True)
insurance_number = models.CharField(max_length=50, null=True)
company = models.ForeignKey(TransportCompany, on_delete=models.DO_NOTHING, null=True)
photo = models.ImageField(null=True, upload_to='drivers/profile_pictures')
i need to know how i can fix this, or what's the issue, any help is appreciated.
The reason this happens is because your age field has the same name as the age function. As a result, the age = ... field is ignored by Python in favor of the age function, since that is the last time you defined the age variable.
For the same reason the age field pops up in sublasses: you defined an age variable over there, and that takes precedence over the "inherited" age method.
You should rename one of the two. For example with:
class Person(User):
GENDER = (('F', 'FEMALE'), ('M', 'MALE'))
name = models.CharField(max_length=50, null=True)
surname = models.CharField(max_length=50, null=True)
adress = models.CharField(max_length=255, null=True)
birth_date = models.DateField(null=True)
gender = models.CharField(max_length=1, choices=GENDER, null=True)
_age = models.IntegerField(null=True)
def age(self):
today = date.today()
bod = self.birth_date
before_dob = (today.month, today.day) < (bod.month, bod.day)
return today.year - self.birth_date.year - before_dob
class Meta:
abstract = True
Note that the calculation of the age was not completely accurate: if we are before the birthday of that year, you need to subtract one from the age.

QuerySet in Django - returns exception

I am trying to understand how exactly query works on Django, i followed the tutorials it´s not working I am not sure what i am doing wrong.
When I run
BeneficientePagar.objects.filter(nome__contains="Joao Pedro")
it returns
"Choices are %s" %s (name, ",".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword "nome into field. Choices are: ID, beneficiente, beneficiente_id,join, join_id, moeda
from django.db import models
# Create your models here.
class Moeda(models.Model):
moeda_ficticia = models.FloatField()
class Join(models.Model):
nome = models.CharField(max_length=150)
nascimento = models.DateField()
cpf = models.IntegerField(primary_key=True)
endereco = models.CharField(max_length=150)
email = models.EmailField()
def __str__(self):
return self.nome
class Beneficiente(models.Model):
ID = models.AutoField(primary_key=True)
nome = models.CharField(max_length=150)
CNPJ = models.IntegerField(max_length = 10)
def __str__(self):
return self.nome
class Favores(models.Model):
ID = models.AutoField(primary_key=True)
favor = models.CharField(max_length=150)
dataInserido = models.DateField()
usuarios = models.ForeignKey(Join)
def __str__(self):
return self.favor
class BeneficientePagar(models.Model):
ID = models.AutoField(primary_key=True)
moeda = models.IntegerField()
beneficiente = models.ForeignKey(Beneficiente)
join = models.ForeignKey(Join)
def __str__(self):
return self.ID
Thanks in advance
If using BeneficientPager, you need to do
BeneficientePagar.objects.filter(beneficient__nome__contains="Joao Pedro")
You are getting the error because nome is a field on Beneficiente, not BeneficientePagar.
You can either do
Beneficiente.objects.filter(nome__contains="Joao Pedro")
which will return a queryset of Beneficientes. Or if you need BeneficientePagar you can query through the foreign key.
BeneficientePagar.objects.filter(beneficiente__nome__contains="Joao Pedro")