Sending data through postman problem in django - 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")

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

Ways to change dropdown choices in django-filter

I'm trying to change the dropdown values for the user field. I want to show the email addreses , instead of the nombre + apellido. Because in my models I have the str that returns nombre + apellido, those are the values displayed in the dropdown. How can I change those values without changing the str in the Tutor model? Tryed to do a CustomManager but didn't work.
MODEL:
class Tutor(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, primary_key=True)
nombre = models.CharField(max_length=50, blank=False, null=True)
apellido = models.CharField(max_length=50, blank=False, null=True)
biografia = models.TextField()
curriculum = models.FileField(upload_to="curriculums/", blank=True, null=True)
foto = models.ImageField(blank=True, null=True)
carrera = models.ManyToManyField(Carrera, blank=True)
linea_invest = models.ManyToManyField(Linea_Invest, blank=True)
correo = models.EmailField(blank=True, null=True)
numero_celular = models.CharField(max_length=20, blank=True, null=True)
class Meta:
verbose_name_plural = "Tutores"
verbose_name = "Tutor"
def __str__(self):
return '%s %s' % (self.nombre, self.apellido)
FILTER
class TutorFilter(django_filters.FilterSet):
nombre = CharFilter(field_name="nombre", label="Nombre",lookup_expr='icontains')
apellido = CharFilter(field_name="apellido", label="Apellido",lookup_expr='icontains')
carrera = ModelMultipleChoiceFilter(field_name= "carrera", queryset= Carrera.objects.all())
user = ModelChoiceFilter(field_name = "user", label = "correo", queryset = Tutor.objects.all())
class Meta:
model = Tutor
fields = ("nombre", "apellido", "carrera","user")
In your TutorFilter. Change
user = ModelChoiceFilter(field_name = "user", label = "correo", queryset = user.objects.all())
How I solved:
def get_tutores():
tutores = []
for tut in Tutor.objects.all():
tutores.append((tut.user.id,tut.user.email,))
return tutores
class TutorFilter(django_filters.FilterSet):
nombre = CharFilter(field_name="nombre", label="Nombre",lookup_expr='icontains')
apellido = CharFilter(field_name="apellido", label="Apellido",lookup_expr='icontains')
carrera = ModelMultipleChoiceFilter(field_name= "carrera", queryset= Carrera.objects.all())
user = ChoiceFilter( label = "correo", choices=get_tutores())
class Meta:
model = Tutor
fields = ("nombre", "apellido", "carrera","user")
See how I didn't need to change the str method in the model Tutor to display in the dropdown the tutor's emails as choices, because instead of using ModelChoiceFilter I changed to ChoiceFilter . Didn't know that you can call a function in the choices argument in the ChoiceFilter.

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.

Django - Update a record using a modelform (Table contains Unique_constraint)

The idea would be that the user should be able to go in and update the record using the same form I have provided. I included a unique constraint because the idea was that a Requisition can contain multiple Requisition_lines. For the initial phase I have hard coded sequence=1. It saved the record initially but I am now getting an Integrity error when i try to update the record using update_or_create. Any help would be appreciated! Let me know if any more information is needed.
Models.py
class Requisition(models.Model):
username = models.ForeignKey(
'users.CustomUser', on_delete=models.CASCADE, related_name='req_user')
signature = models.CharField(max_length=10, blank=True, null=True)
status = models.ForeignKey('RequisitionStatus', related_name='req_status', on_delete=models.CASCADE)
class RequisitionLine(models.Model):
parent_req = models.ForeignKey('Requisition', on_delete=models.CASCADE, related_name='par_req_line' )
sequence = models.PositiveIntegerField()
item_code = models.ForeignKey(
'items.ItemMaster', on_delete=models.CASCADE, related_name='req_item', blank=True, null=True)
description = models.CharField(max_length=50, blank=True)
extra_information = models.TextField(blank=True)
quantity = models.PositiveIntegerField(blank=True, default=0,null=True)
price = models.DecimalField(max_digits=19, decimal_places=2, blank=True, default=0.00,null=True)
purchase_order = models.CharField(max_length=9, blank=True,null=True)
po_line = models.PositiveSmallIntegerField(blank=True,null=True)
req_delivery_date = models.DateField(blank=True,null=True)
act_delivar_date = models.DateField(blank=True, null=True)
class Meta:
unique_together = ('parent_req','sequence')
Views.py
def update_requisition(request, id):
current_req = Requisition.objects.get(id=id)
if current_req.username == request.user:
data = { 'parent_req': id }
if request.method == "POST":
req_form = ReqForm(request.POST, instance = current_req)
if req_form.is_valid():
req_form_line, created = RequisitionLine.objects.update_or_create(
parent_req = current_req,
sequence = 1,
description = req_form.cleaned_data['description'],
extra_information = req_form.cleaned_data['extra_information'],
quantity = req_form.cleaned_data['quantity'],
price = req_form.cleaned_data['price'],
defaults = {'parent_req':current_req,
'sequence': 1 })
return(redirect(reverse('requisition:req_history')))
else:
try:
req_form_line = RequisitionLine.objects.get(parent_req=current_req, sequence=1)
req_form = ReqForm(initial=data, instance = req_form_line)
except RequisitionLine.DoesNotExist:
req_form = ReqForm(initial=data, instance = current_req)
return render(request, 'req/update_req.html' , {'current_req': current_req, 'req_form': req_form})
else:
return HttpResponseRedirect(reverse('requisition:req_history'))
Your usage of the update_or_create function is wrong. You misunderstand the keyword defaults (see docs). You need to put all your fields to update into this dictionary:
req_form_line, created = RequisitionLine.objects.update_or_create(
parent_req = current_req,
sequence = 1,
defaults = {
description : form.cleaned_data['description'],
extra_information : req_form.cleaned_data['extra_information'],
quantity : req_form.cleaned_data['quantity'],
price : req_form.cleaned_data['price'],
})

How can I deal with filter object in HTML

I tried with above to see how I can use with objects in showing in homepage.
few people recommend me to use this code below
infos = Info.objects.select_related('user','group', 'user_number').filter(id = newc.id)
and my model code is like this.
class Group(models.Model):
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Type(models.Model) :
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Info(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(null=True, blank=True, unique=True)
memo = models.CharField(max_length=200, null=True)
birthday = models.CharField(max_length=12,null=True, blank=True)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
class Number(models.Model):
number = models.CharField(max_length=11)
info = models.ForeignKey(Info, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
type = models.ForeignKey(Type, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
and in my views.py.
def addcontract(request) :
if request.user.is_authenticated :
pk = request.user.id
name = request.POST['name']
email = request.POST['email']
memo = request.POST['memo']
birthday = request.POST['birthday']
group_id = request.POST['group_id']
type_id = request.POST['type_id']
number = request.POST['number']
user_id = pk
newc = Info(
name = name, email = email, memo = memo, birthday = birthday,
group_id = group_id, user_id = pk)
newc.save()
number = Number(number = number, type_id= type_id, user_id = pk, info = newc)
number.save()
infos = Info.objects.select_related('user','group', 'user_number').filter(id = newc.id)
grouplist = Group.objects.filter(user_id = request.user.id)
typelist = Type.objects.filter(user_id = request.user.id)
return render(request, 'detail.html',
{'infos':infos, 'grouplist':grouplist, 'typelist':typelist})
My previous question was
How to connect all related DB with FK in Django?
it doesn't work in homepage at all to show from object that's why I tried to check in homepage then problem occured.
user_id is only for account. I need to use Info_id as a fk all in query
please help this.