how to save dates into database using django? - django

this is my code
views.py
def guardar(request):
if request.method == "POST":
idpersona = int(request.POST.get('id'))
persona = personal.objects.get(id=idpersona)
idep = int(request.POST.get('dependencia'))
dep = dependencia.objects.get(id=idep)
idcon = int(request.POST.get('concepto'))
con = concepto.objects.get(id=idcon)
fecha = request.POST.get('fecha')
print(fecha)
db_registro = lista_registro(
personal_id=persona,
fecha_registro=fecha,
dependencia_id=dep,
concepto_id=con,
descripcion=request.POST.get('descripcion'),
monto=request.POST.get('monto'),
)
db_registro.save()
return render(request, 'registro/exito.html')
Models.py
class lista_registro(models.Model):
personal_id = models.ForeignKey(personal, on_delete=models.CASCADE)
dependencia_id = models.ForeignKey(dependencia, on_delete=models.CASCADE)
concepto_id = models.ForeignKey(concepto, on_delete=models.CASCADE)
fecha_realizado = models.DateField()
fecha_registro = models.DateField(auto_now_add=True)
descripcion = models.CharField(max_length=1000)
pago_id = models.ForeignKey(pago, on_delete=models.CASCADE, default=2)
monto = models.CharField(max_length=100)
def __str__(self):
return "===> " + self.descripcion + " <==="
well my problem is that I get a NOT NULL constraint error. I get that this is a date error but I don't know how to solve this

when you define a field that will not be required just set null=True, blank=True on your models file
fecha_realizado = models.DateField(null=True, blank=True)

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

I want to store my primarykey values into foreignkey field

This is my models
class Tasklist(models.Model):
clientname= models.CharField(max_length=100,null=True,blank=True)
task = models.CharField(max_length=100)
startdate = models.DateField(default=timezone.now, blank=True, null=True)
enddate = models.DateField(blank=True, null=True)
assignee = models.CharField(max_length=30)
status = models.CharField(max_length=30)
fstatus = models.BooleanField(default=False)
def __str__(self):
return self.task + " - Task - " + str(self.fstatus)
class edit_page(models.Model):
old_id = models.ForeignKey(Tasklist,on_delete=models.CASCADE)
updatedate = models.DateField(blank=True, null=True)
time_from = models.TimeField(blank=True, null=True)
time_to = models.TimeField(blank=True, null=True)
messagelogs = models.TextField(blank=True, null=True)
def __str__(self):
return self.messagelogs
This is My Views page
def edit_task(request, task_id):
if request.method == "POST":
updatedate=request.POST.get("updatedate","")
time_from=request.POST.get("time_from","")
time_to=request.POST.get("time_to","")
messagelogs=request.POST.get("messagelogs","")
test_list=edit_page(updatedate=updatedate,time_from=time_from,time_to=time_to,messagelogs=messagelogs)
test_list.save()
task = Tasklist.objects.get(pk=task_id)
form = TaskForm(request.POST or None, instance = task)
if form.is_valid():
form.save()
messages.success(request,("Task Edited "))
return redirect('email_updatetask', (task_id))
return redirect('todolist')
else:
task_obj = Tasklist.objects.get(pk=task_id)
return render(request, 'edit.html', {'task_obj': task_obj})
can u pls how can i store my primary keys into the second foreign key field via HTML files....

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'],
})

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)