My template renders the tag {{ test.date}} in the following format -
2015-12-15T23:55:33.422679
When I try to format it using django's built in template tag date, it doesn't display anything.
Variations I've tried:
{{ test.date|date:"SHORT_DATE_FORMAT" }}
{{ test.date|date:"D d M Y" }}
models.py:
class Human(models.Model):
name = models.CharField(max_length=50,default='',blank=False)
class Test(models.Model):
human = models.ForeignKey(Human)
date = models.DateTimeField(default=datetime.now)
views.py:
def list(request):
h = Human.objects.all()
s=[]
for her in h:
t = h.test_set.all()
s.extend(t)
context = RequestContext(request, {'test_list': s,})
return render_to_response('template.html', context)
I am then using it in template like this:
{% for test in test_list %}
{{test.date}}
{% endfor %}
What am I missing?
Answering an OLD post... but, the answer doesn't seem (to me) to be answering the original question - which was WHY isn't the Django inline template date formatting working...
The answer is (I believe) that the author was trying to output to his page something like:
"This is my date:{{test.date|date:"D d M Y"}}."
The problem, if this is truly what was being tried, is that the double quotes don't work in this situation. You need to do the following instead:
"This is my date:{{test.date|date:'D d M Y'}}."
Note the single quotes...
I'm not sure what you want from this logic, but I think you can use this:
def list(request):
test = Test.objects.all()
return render(request, 'template.html', {'test':test})
and in template:
{% for t in test %}
{% t.date %}
{% endfor %}
if you want display human, just add in cycle {% t.human.name %}
Related
Depending on the arguments I pass to the form I want to return different form fields.
class TestForm(FlaskForm):
"""Test Form."""
if one:
field1 = StringField('Field 1')
if two:
field2 = StringField("Field 2")
if three:
field3 = StringField("Field 3")
submit = SubmitField("Add Service")
def __init__(self, one=None, two=None, three=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.one = one
self.two = two
self.three = three
I am not able to see the arguments when doing the if statements.
I am aware of the option to have logic in html when rendering the form, however due the nature of the project have opted to use quick_form on the html side.
Here is the html code I am using.
{% import 'bootstrap/wtf.html' as wtf %}
<h3 >Add Service</h3>
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
Instead of creating this logic in your form class. I would recommend to create all the fields you need and then dynamically choose which to show the user using jinja2 in your html file.
Here's an example.
{% for fields in fields_list %}
{% if field == '1' %}
{{ form.field1.label(class="form-control-label") }}
{{ form.field1(class="form-control form-control-lg") }}
{% endif %}
{% if field == '2' %}
{{ form.field2.label(class="form-control-label") }}
{{ form.field2(class="form-control form-control-lg") }}
{% endif %}
{% if field == '3' %}
{{ form.field3.label(class="form-control-label") }}
{{ form.field3(class="form-control form-control-lg") }}
{% endif %}
{% endfor %}
And then when you render or redirect to your .html from your routes code, don't forget to send
the proper arguments, such as
# create your fields list, which do I want to show?
# Make it a list of integers
fields_list = [1, 2, 3]
return render_template('insert-name.html', fields_list , form=form)
If my answer helped you, please consider accepting my answer.
I am new to this site and trying to build up some reputation :)
Thank you! Happy Coding!
If someone ever comes accross the same question, here is a quick solution I came upon some times ago.
It is in part inspired from the accepted answer here.
In your forms.py or wherever you declare your TestForm class, put the class declaration inside a function that takes your parameter as an argument and returns the class object as output.
The argument will now be accessible within the class itself, allowing for any test you may want to perform.
Here's a working example based on your original question (I just added a default value to get at least one StringField in case the parameter is ommited):
def create_test_form(var='one'):
class TestForm(FlaskForm):
"""Test Form."""
if var == 'one':
field1 = StringField('Field 1')
if var == 'two':
field2 = StringField("Field 2")
if var == 'three':
field3 = StringField("Field 3")
submit = SubmitField("Add Service")
return TestForm()
Then simply create the form in your routes like so:
form = create_test_form('two')
Finally pass it to your HTML to render the form with quick_form like you did.
This example will render a form with a single StringField named "Field 2" and a "Add Service" submit button.
I have a problem with displaying currency by django-money module.
In template I used 2 options:
{{ object.balance }} and {% money_localize object.balance %}.
I expected to see on website $100.00, but I got US$100.00.
The same with GBP - > GB£100.00, but I want to get £100.00.
Any ideas, why it's display this way?
My model class has field:
balance = MoneyField(_('Balance'), max_digits=25, decimal_places=2, default=Money(0, "USD"))
Define this template tag format_money.py:
from moneyed.localization import format_money as fm
#register.tag
def format_money
return fm(myModel.price, locale='en_US')
Then in your template:
{% import format_money %}
...
{% format_money object.balance %}
Should work. Stolen from here
I have a database with blog style documents, i.e., author's name, publication date, body text, etc.
I have built a django framework to output entries from the database as a result of a search term. That part is ok. The problem is that I want to show sections of the body text with the matched search terms highlighted (equivalent to a google search result). This means that I can't create a template tag with the body_text attribute only, because that text is not highlighted. I already did a function that receives as input the query and the body text and outputs the same text with the found search terms in bold.
My problem now is how do I pass this result to the html template?
Using the tutorial from Django documentation suppose you have the following views.py:
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
and the correspondent template:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Now suppose you have the function in views.py:
def signal_tokens(text,query_q):
...
return new_text
What should be the best way to replace the {{ question.question_text } with the output from signal_tokens? My solution was to replicate the context variable with a list of dictionaries, where each dictionary is a copy of each entry, except for the 'question_text' key, where I used signal_tokens result:
def index(request):
query_q = 'test'
latest_question_list = Question.objects.order_by('-pub_date')[:5]
new_context = []
for entry in latest_question_list:
temp_d = {}
temp_d['id'] = entry.id
temp_d['question_text'] = signal_tokens(entry.question_text,query_q)
new_context.append(temp_d)
context = {'latest_question_list': new_context}
return render(request, 'polls/index.html', context)
But the problem is that I need to copy all entries. Is there a more elegant way to solve this problem?
This is an ideal use case for a template filter. Move your highlight code to a file in the templatetags directory, register it as a filter, then you can call it from the template:
{{ question.question_text|highlight:query_q }}
Obviously you will need to pass query_q to the template context as well.
I want to add a help text to a Django app.
To do this, I am going to create a Django template which may be included into another templates.
The trouble is that I do not know what the title tag for my title should be. For example, it can be <h1> or <h2> or <h3>. How to handle the possibility to easily change the tag?
You can create the html in your views, although I wouldn't say it's the best solution you should do.
Try something like this:
views.py:
def foo(request):
...
html_val = None
if something:
html_val = '<h1>something here</h1>'
elif another_try:
html_val = '<h2>something else here</h2>'
else:
html_val = '<h3>it has to be this one</h3>'
return response(request, 'template.html', {'html_val': html_val})
template:
{% if html_val %}
{{ html_val }}
{% endif %}
{{ html_val|safe }}, safe as a filter to ensure that browser doesn't transfor the < as < > as >
My Django Model:
class myModel(models.Model):
myIntA = models.IntegerField(default=0)
My View:
myModelList = myModel.objects.all()
for i in range(len(myModelList)):
myModelList[i].myIntB = i
return render(
request,
'myApp/myTemplate.html',
Context(
{
"myModels": myModelList,
}
)
)
Is the above legal? You can see that I added a variable myIntB to each myModel object.
However when I try to print myIntB in the template below, nothing shows up.
How can I access myIntB from the template? It is not a field I have defined for this model, nor do I want it to be. I just want myModel to be augmented with this extra variable during rendering of this particular template.
My Template:
{% for currModel in myModels %}
{{currModel.myIntA}}<br/>
{{currModel.myIntB}}<br/>
{% endfor %}
Replace following line:
myModelList = myModel.objects.all()
with:
myModelList = list(myModel.objects.all())
Otherwise, new queries are performed everytime you access myModelList[i]; you lose the change you made.
Alternatively, what you want is simply counter, you can use forloop.counter or forloop.counter0 in the template.
No that won't do what you are thinking; try this instead:
enriched_models = []
myModelList = myModel.objects.all()
for i in myModelList:
enriched_models.append((i, 'foo'))
return render(request, 'myApp/myTemplate.html', {"myModels": enriched_models})
Then in your template:
{% for currModel,extra in myModels %}
{{ currModel.myIntA }}<br/>
{{ extra }}<br/>
{% endfor %}