while entering the date and submitting,all the files which is in the entered date should display.as i am new to django plz guide me
Different pdf file with different date is stored in table.While entering the date,after submitting,all the files in the entered date should list.
views.py
def select_date(request):
client = Client.objects.all()
process = Client_Process.objects.all()
pdf = Client_files.objects.all()
obj1 = Client_files.objects.values_list('id', 'Date')
if request.method == "POST":
fromdate = request.POST['fromdate']
return render(request,'select_date.html', {'pdf':pdf,'client':client,'process':process})
models.py
class Client_files(models.Model):
Date = models.DateTimeField(default=datetime.now, blank=True)
client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True)
client_process = models.ForeignKey(Client_Process, on_delete=models.CASCADE,null=True)
File_Name = models.FileField()
Pages = models.IntegerField(null=True)
Count = models.IntegerField(null=True)
Status = models.BooleanField(default = False)
class Meta:
db_table : 'client_files'
you can filter it using gte (greater than or equal to)
if request.method == "POST":
fromdate = request.POST['fromdate']
pdf = Client_files.objects.filter(Date__gte=fromdate)
or if you just want to filter equal date, use this instead:
pdf = Client_files.objects.filter(Date=fromdate)
Related
I keep getting this very same type error even though I am using set. Can someone maybe point out what I'm doing wrong in my api endpoint?
views.py
#require_http_methods(["GET", "POST"])
def api_requerimientos(request):
if request.method == "GET":
requerimientos = FormularioCliente.objects.all()
return JsonResponse(
{"requerimientos": requerimientos},
encoder=FormularioClienteEncoder,
)
elif request.method == "POST":
print("POST REQUEST HIT")
try:
content = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponseBadRequest("Invalid JSON in request body")
requerimiento = FormularioCliente(**content) # Create a new FormularioCliente object
if "technicians" in content and isinstance(content["technicians"], list):
try:
technicians_id_list = content["technicians"]
technicians = Technician.objects.filter(employee_number__in=technicians_id_list)
requerimiento.technicians.set(technicians)
requerimiento.save()
print('requerimiento:', requerimiento)
except Technician.DoesNotExist:
pass
requerimiento.save() # Save the object to the database
models.py
class FormularioCliente(models.Model):
empresa = models.CharField(max_length=21, null=True, unique=True)
titulo = models.CharField(max_length=66)
descripcion = models.CharField(max_length=66)
enlace = models.URLField(null=True)
tipo = models.CharField(max_length=17, choices=TIPO_REQUIRIMIENTO, default="tecnologia")
date = models.DateField(null=True, auto_now_add=True)
time = models.TimeField(null=True, auto_now_add=True)
entrega = models.DateField(null=True)
finished = models.CharField(max_length=19, choices=TIPO_FINALIZACION, default="Abierto")
technicians = models.ManyToManyField(Technician, blank=True)
special_hours = models.SmallIntegerField(default=0)
regular_hours = models.PositiveSmallIntegerField(default=1)
total_hours = models.SmallIntegerField(default=1)
importancia = models.PositiveSmallIntegerField(default=1)
file = models.FileField(upload_to='files', blank=True)
updated = models.DateField(auto_now=True)
def __str__(self):
return f'{self.titulo}: {self.descripcion} # {self.date}'
def technicians_as_json(self):
return list(self.technicians.all().values())
class Technician(models.Model):
name = models.TextField()
employee_number = models.SmallIntegerField(unique=True, primary_key=True)
def __str__(self):
return self.name + " - " + str(self.employee_number)
encoders.py
class TechnicianEncoder(ModelEncoder):
model = Technician
properties = ["name", "employee_number"]
class FormularioClienteEncoder(ModelEncoder):
model = FormularioCliente
properties = [
"id",
"empresa",
"titulo",
"descripcion",
# "user",
"enlace",
# "tipo",
# "File",
"tipo",
"date",
"time",
"entrega",
"finished",
"technicians", # <-- Add this
"special_hours",
"regular_hours",
"total_hours",
"importancia",
"updated",
]
encoders = {"technicians": TechnicianEncoder()}
I also tried to loop through technicians queryset and add it to the instance one by one as well via the add() method but that also didn't work.
I even tried this:
techs = list(requerimiento.technicians.filter(employee_number__in=technicians_id_list).all())
requerimiento.technicians.set(techs)
None of it worked
Filtering between the dates is not working,getting from-date and to-date from the user
views.py
def select_date(request):
client = Client.objects.all()
process = Client_Process.objects.all()
pdf = Client_files.objects.all()
fromdate = request.POST.get('fromdate')
todate = request.POST.get('todate')
print(fromdate)
print(todate)
pdf = Client_files.objects.filter(Date__date__range=(fromdate, todate))
print(pdf)
if request.method == "POST":
fromdate = request.POST.get('fromdate')
todate = request.POST.get('todate')
return render(request,'select_date.html', {'pdf':pdf,'client':client,'process':process,'fromdate':fromdate,'todate':todate})
Giving from date and to date, after submitting it should list the files in-between the dates.
views.py
def select_date(request):
client = Client.objects.all()
process = Client_Process.objects.all()
pdf = Client_files.objects.all()
return render(request,'select_date.html', {'pdf':pdf,'client':client,'process':process})
models.py
class Client_files(models.Model):
Date = models.DateTimeField(default=datetime.now, blank=True)
client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True)
client_process = models.ForeignKey(Client_Process, on_delete=models.CASCADE,null=True)
File_Name = models.FileField()
Pages = models.IntegerField(null=True)
Count = models.IntegerField(null=True)
Status = models.BooleanField(default = False)
class Meta:
db_table : 'client_files'
UI Image
In this image I just displayed all the files but I need only the selected date files.
More pdf file is saved in table with different dates,How to filter pdf file between fromdate and todate.
How to filter inbetween dates and list the pdf file.
views.py
def select_date(request):
client = Client.objects.all()
process = Client_Process.objects.all()
pdf = Client_files.objects.all()
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
if request.method == "POST":
fromdate = request.POST.get('fromdate')
todate = request.POST.get('todate')
user = Client_files.objects.filter(Date__range=(fromdate,todate))
print(user)
return render(request,'select_date.html', {'pdf':pdf,'client':client,'process':process})
models.py
class Client_files(models.Model):
Date = models.DateTimeField(default=datetime.now, blank=True)
client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True)
client_process = models.ForeignKey(Client_Process, on_delete=models.CASCADE,null=True)
File_Name = models.FileField()
Pages = models.IntegerField(null=True)
Count = models.IntegerField(null=True)
Status = models.BooleanField(default = False)
class Meta:
db_table : 'client_files'
You should use the __date lookup [Django-doc], to convert a datetime to a date first:
def select_date(request):
client = Client.objects.all()
process = Client_Process.objects.all()
pdf = Client_files.objects.all()
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
if request.method == "POST":
fromdate = request.POST.get('fromdate')
todate = request.POST.get('todate')
pdf = Client_files.objects.filter(Date__date__range=(fromdate, todate))
print(pdf)
return render(request,'select_date.html', {'pdf':pdf,'client':client,'process':process})
Usually however when you filter items, you pass the parameters as GET parameters in a GET request. A POST request usually changes data.
I am building a simple comment app in Django. The app allows replies to comments and uses the same model to store comments and replies. My issues is when I try to insert a new reply, the parentpost(FK to parent comment) inserts as NULL. When I use the admin interface to insert a reply, it properly stores the parentpost ID for the parentpost I choose. So I know the issue is not within my model but within my view.
/MODEL/
class UserPost(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.', editable = False)
post = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255, blank = True, null = True,
help_text='Content for description meta tag')
meta_description = models.CharField(max_length = 255, blank = True, null = True,
help_text = 'Content for description meta tag')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
parentpost = models.ForeignKey('self', blank = True, null = True)
class Meta:
#app_label = ''
db_table = 'userposts'
ordering = ['created_at']
verbose_name_plural = 'UserPosts'
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('lync_posts', (), {'posts_slug': self.slug})
def save(self):
if not self.id:
d = datetime.datetime.now()
s = d.strftime('%Y-%M-%d-%H-%M-%S-%f')
slugfield = str(self.name + s)
self.slug = slugfield
super(UserPost, self).save()
/VIEW/
def reply(request, slugIn):
parentpostIn = UserPost.objects.get(slug = slugIn)
pid = parentpostIn.id
template_name = 'reply.html'
if request.method == 'POST':
form = forms.ReplyPostForm(data = request.POST)
# create a new item
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
if form.is_valid():
nameIn = form.cleaned_data['name']
postIn = form.cleaned_data['post']
newPost = UserPost(name = nameIn, post = postIn, parentpost = pid)
newPost.save()
return render_to_response(template_name, locals(), context_instance = RequestContext(request))
else:
# This the the first page load, display a blank form
form = forms.NewPostForm()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
You are trying to set the parentpost ForeignKey by id.
You should either use:
newPost = UserPost(name = nameIn, post = postIn, parentpost = parentpostIn)
or (see Django: Set foreign key using integer?):
newPost = UserPost(name = nameIn, post = postIn)
newPost.parentpost_id = pid