Check whether datetime object agrees with today in jinja2 - html

I would like to test whether a python datetime object agrees with today within the browser, using jinja2
Something like
{% if current_user.last_seen_datetime.date() == TODAY %}
how would I get TODAY?

I found the simples solution is to add a function to the User class
def show_paper_suggestions(self):
if self.last_seen_datetime is None:
return 1
else:
return (datetime.datetime.utcnow() - self.last_seen_datetime).days

Related

I'm trying to show python data in my HTML and the output is not what I expected

Here's a function in my application that returns a number from a database and I'm trying to display it on my webpage using flask
def handler():
increment_visitor()
return retrieve_visitor_count()
#app.route('/')
def home():
handler()
return render_template("index.html", count=handler)
I assign the name count to handler and try displaying count in my index.html file like so:
<p>{{count}}</p>
When I load my webpage, here's what the output is
<function handler at 0x7f8c70069a60>
When I print my handler function, it outputs the appropriate number, so how do I get that number to display on my webpage correctly?
count is handler, which is a function. Add parentheses to call it in the template like so:
{{count()}}
Looking at your logic though, I think you may want something like this:
#app.route('/')
def home():
result = handler()
return render_template("index.html", count=result)
Otherwise you would presumably increment the visitor count twice

control the empty data in django filter

I was coding the backend using Django. I am a beginner in Django. I used a filter to filter some post requests from the HTML form. here is the code.
#api_view(["POST"])
def program_search(request):
Data_List = []
MyFilter = CreateProgram.objects.filter(price__lte=request.POST['price'],
days=request.POST['days']).values()
...
but if I send a request from HTML form that one field of data be null the filter function cant handle it.
I hope you can make use of a simple if... clause to handle the situation
#api_view(["POST"])
def program_search(request):
price = request.POST.get('price')
days = request.POST.get("days")
if price and days:
qs = CreateProgram.objects.filter(price__lte=price, days=days)
else:
# in case of empty filter params from HTML, return empty QuerySet
qs = CreateProgram.objects.none()
# `qs` variable holds your result

How can I have a global custom macro use context implicitly?

I want to add a custom global macro to Airflow, I found this answer that outlines how this can be done. But I'm wondering if I can get the context implicitly (just like the built-in macros) e.g:
def ds_ny(**context):
"""
Custom macro that returns ds in NY timezone
"""
return context.get("execution_date").in_timezone("America/New_York").format("%Y-%m-%d")
Usage:
select * from table where some_date = '{{ macros.ds_ny }}'
Currently I have to pass a parameter to the macro for it to render {{ macros.ds_ny(execution_date) }}

How to call a function with less arguments that is set (Python 3)

I am making a terminal emulator in Python 3. The commands are being stored in functions, like:
def rd(os_vartmp, os_vartmp2):
if os_vartmp == None:
print('rd [path] [-S]')
print('Delete a folder')
else:
if os.path.isfile(os_vartmp) == True:
if os_vartmp2 == '-S': print('a')
else:
print(ERR5)
a = input('Command: ')
The terminal works like this:
Asks user for input
Splits the input
Uses the first part of input to search a function in locals
If there is one, uses the rest part of input as argument
Calls the function
The thing here is, when i call the function 'rd' with, for example, 'rd "boot.py" -S' it works just fine. But if i need to call it like this: rd "boot.py", it throws me a error about 1 argument given when 2 are required. Is there a fix for that?
You can make an argument optional by assigning a value in the method definition. For example:
def Add(x=0, y=0):
return x+y
If you input only one value, y will default to 0. If I wanted to give y a value but have x fall back on it's default value I could do Add(y=10). I hope this helped!
Have you tried this?
def rd(os_vartmp, os_vartmp2="-S"):
Instead of trying to get null value, which would require rd("boot.py",null), you can ser default value and then you can do rd("boot.py").
Hope it works.

Transforming data in Django. Want to be able to apply sums to a decimal field

I have a model like this.
#models.py
class Payment(models.Model):
unit_price = models.DecimalField(max_digits=12, decimal_places=2)
discount = models.DecimalField(max_digits=12, decimal_places=2)
payment_terms = models.CharField(max_length=80)
amount = models.DecimalField(max_digits=12, decimal_places=2)
VAT = models.DecimalField(max_digits=4, decimal_places=2)
def __unicode__(self):
return unicode(self.unit_price)
class Invoice(models.Model):
client = models.ForeignKey(Client)
payment = models.ForeignKey(Payment)
date = models.DateField()
invoice_no = models.CharField(max_length=16)
work_orders = models.ManyToManyField(Work_Order)
contract_info = models.ForeignKey(Contract_Info)
def __unicode__(self):
return self.invoice_no
What I want to focus is payment so try forgetting everything else. Here is my views.py.
#views.py
#login_required
def invoice_details(request, id=1):
invoices_list = Invoice.objects.filter(pk=id)
invoice = get_object_or_404(Invoice, pk=id)
client = invoices_list[0].client
work_orders = invoices_list[0].work_orders
payment = invoices_list[0].payment
return render_to_response(('invoice_details.html', locals()), {'work_orders': work_orders,'payment':payment,'client': client, 'invoice': invoice ,'invoices_list': invoices_list}, context_instance=RequestContext(request))
And here is my template.
<h1>invoice_details.html<h1>
{{ payment.amount }}
The template displays the payment amount in a decimal value. What I want to be able to do is some sums with {{payment.amount}}. Suppose if I wanted to multiply whatever the value
{{payment.amount}} by let say 2. How would I do this?
I would do this in the view,
new_amount = paymount.amount * 2
return render_to_response(('invoice_details.html', locals()), {'work_orders': work_orders,'payment':payment,'client': client, 'invoice': invoice ,'invoices_list': invoices_list, 'new_amount':new_amount}, context_instance=RequestContext(request))
But if there's some reason you cannot or do not want to, you can acheive something similar in the template by using template tags. I do not think there is a multiply tag, but there is an add:
{{ payment.amount|add:"2" }}
Would simply add 2 to your payment amount, similarly
{{ payment.amount|add:payment.amount }}
Would double the value displayed. Adding is likely not exactly what you wanted to do, so you can attempt to make your own template tag to use multiply or whatever function you'd like, see http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
I don't know why you need this to be done inside the template and not in the view, but here is my go at a solution. There is a long discussion about arithmetic in Django templates about not supporting this feature for specifically the use case you described.
If you still want to proceed, this might help. In the Django docs, there is an |add built-in template filter that seems to be a primitive form of arithmetic. Unfortunately, there is no |multiply filter. You can probably find the filter in the template/defaultfilters.py under your Django installation.
Copy it, change what you need to make it a product instead of a sum. When you're done, you might want to submit it to the Django project to make it a buil-tin in future releases.
Here is the answer:
#views.py
subtotal = payment.amount * 2
return render_to_response(('invoice_details.html', locals()), {'work_orders': work_orders,'payment':payment,'client': client, 'invoice': invoice ,'invoices_list': invoices_list, 'subtotal':subtotal}, context_instance=RequestContext(request))
In a template put this custom tag (I think that what it is) to represent the value.
{{ subtotal }}