I am using a macro for if condition to check if a field is null or not, in a form email notification. I tried this one:
{% if(City != string.Empty) { $$value:City$$ } #%}
It did not work, and I am not getting the city value in the email body.
Use {%City%} instead of $$value:City$$
If you're simply not going to render the value of the "City" field if it's empty, you might as well just replace the whole block of code with just {%City%}
Assuming your code is just a simplified example of what you are trying to accomplish, it should look like this:
{% if(City != string.Empty) { return City; } %}
Related
I am really stuck on this: (sorry, newbie problems)
Following the method exposed in this post I need to render the tags in a page, but I am not able to get the tag values through the #property
The code is as follow, the models:
class TagsBlock(blocks.FieldBlock):
"""
Basic Stream Block that will use the Wagtail tags system.
Stores the tags as simple strings only.
"""
def __init__(self, required=False, help_text=None, **kwargs):
# note - required=False is important if you are adding this tag to an existing streamfield
self.field = forms.CharField(widget=AdminTagWidget, required=False)
super().__init__(**kwargs)
class ServicesPage(Page):
services = StreamField([
('services',blocks.StructBlock([
('entries',PortfolioBlock()),
('tags',TagsBlock(required=False)),
]))], null=True, blank=True)
#property
def get_tags(self):
"""
Helpful property to pull out the tags saved inside the struct value
Important: makes some hard assumptions about the names & structure
Does not get the id of the tag, only the strings as a list
"""
tags_all = [block.value.entries.get('tags', '').split(',') for block in self]
tags = list(chain.from_iterable(tags_all))
return tags
content_panels = Page.content_panels + [
StreamFieldPanel('services'),
]
Then in the template im just doing:
<div class="row-4">
{% for tag in page.services.get_tags %}
{{tag}}
{% endfor %}
</div>
However, I can't get any result. I have really tried everything, but I can't figure how to call the property to give me the list of values.
Thank you very much in advance for your time,
Francisco
In your template, the line
{% for tag in page.services.get_tags %}
would be trying to access a property named get_tags on the 'services' field of the page. However, get_tags isn't defined there - it's defined as a property of the page object - so this line should be
{% for tag in page.get_tags %}
Secondly, in the line
tags_all = [block.value.entries.get('tags', '').split(',') for block in self]
you're intending to loop over all the items in the StreamField, but the self in for block in self refers to the page object. This should be for block in self.services.
Finally, in the same line, block.value will give you the value of each block, which in this case will be a dictionary of two items, entries and tags. If you wanted to access entries (the PortfolioBlock), you would write block.value['entries'] or block.value.get('entries') rather than block.value.entries - but really you don't want that, you want to access the tags item instead - so block.value.entries.get('tags', '').split(',') should be block.value.get('tags', '').split(',').
I am trying to populate a page built in Flask from items in MongoDB. My route looks like:
#app.route('/job/<posting>', methods=["GET"])
def job_post(posting):
posting = db.openings.find({'Id': posting})
title = db.openings.find_one({'Id': posting}, {'Title': 1, '_id':0})
return render_template('post_page.html', posting=posting, title=title)
My template page for post_page.html is:
{% extends "layout.html" %}
{% block content%}
<div class="container">
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<h3><a class="mr-2" href="#">{{ title }}</a></h3>
</div> -->
</article>
</div>
{% endblock content %}
When I attempt to access a page, I get an error saying "bson.errors.InvalidDocument: cannot encode object: <pymongo.cursor.Cursor object at 0x10dd402e8>, of type: <class 'pymongo.cursor.Cursor'>"
When I research that error, most of the issues have come from using find instead of find_one. I am using find_one here, and when I test it in a Python shell, the variable type for title is a dictionary, so I'm confused as to why it's passing a cursor object to the template.
You are passing posting in to the function and then immediately setting it in the first function posting = db.openings.find({'Id': posting}). I suspect you don't mean to do this.
find() return a cursor which you're then passing into the find_one() function which is causing the error you see.
Not sure what you are trying to achieve by calling find() then find_one() on the same collection. My suggestion is you remove the line posting = db.openings.find({'Id': posting})
mailjet mjml blank array throws error
In my var:low_price_low_stock_goods is empty array for loop should not execute but it throws error: No value for "var:low_price_low_stock_goods"
{% for item in var:low_price_low_stock_goods %}
{% endfor %}
As answered on Github and your other StackOverflow question: it's a known issue on Mailjet's templating language side, sorry for that. To avoid it, just pass a valid object in the API call for the low_price_low_stock_goods value. This will work:
{
item.good_name: "",
item.value: "",
item.count: ""
}
I have a "Thing" domain class, where each Thing has an record number (which is not the automatically generated id), that the user will use to access a Thing:
class Thing {
...
String recordNumber
...
}
There is a form to look for a Thing, knowing its recordNumber:
<g:form action="search">
<input name="recordNumber">
<g:submitButton name="btn" value="go to this Thing"/>
</g:form>
I would like to use a validation process in this form: if the recordNumber is not found (Thing.findByRecordNumber(recordNumber) == null), then the input field must turn in red, and a tooltip must show the error message "record number not found".
As far as I know/read (I'm a grails rookie), this has to be written as a constraint in the Thing class:
static constraints = {
recordNumber validator: { n -> Thing.findByRecordNumber(recordNumber) }
}
The problem is: I do not have in this form all the "Thing" properties to populate, just the recordNumber one, so I just can't call
new Thing(params).validate()
How to call validation on just one field, not on the whole object ?
If this is your main question, although I see others there:
"How to call validation on just one field, not on the whole object ?"
You can pass a list of values to validate and it will only validate those properties
new Thing(params).validate(["recordNumber"])
http://grails.org/doc/latest/ref/Domain%20Classes/validate.html
Validation is for constraints for domain class properties. You need an action in your controller:
def search = {
if(params.recordNumber && Thing.findByRecordNumber(params.recordNumber)){
redirect(action: "show", params:[id:Thing.findByRecordNumber(params.recordNumber).id])
}else{
flush.message = "No record found"
render(view:'VIEW_WITH_SEARCH_FORM')
}
}
If you want to validate without refreshing page, write a javascript code.
I have a scala form with several fields.The fields in the form map to the member variables of a Java class. I want to bind one of the fields(say userId) with a value (I dont want the user to enter values for this field. Instead i want to pass this as a parameter to the scala template). However, i was unable to manually bind a form field. Any help is highly appreciated.
See the sample below for easier understanding :
`#(itemForm: Form[Item], user: User)
#import helper._
#main("Item list") {
#if(user != null) {
#form(routes.Application.newItem()) {
#itemForm("userId") = #user.id /**I want to bind the userId form field */
#inputText(itemForm("title"))
#inputText(itemForm("description"))
#inputText(itemForm("price"))
<input type="submit" value="Create">
}
}
}`
In this case it would be better to pass it as action's argument (remember to modify routes declaration)
#form(routes.Application.newItem(user.id)){
....
you can also just use common html
<input type="hidden" name="userId" value="#user.id" />
edit:
Validation in action.Note: it doesn't make sense to display errors on the page next to hidden field, so you do not need placeholders for error messages. It's up to you to pass VALID value into the hidden field. Displaying validation errors to user who can not change the value of hidden field is bad conception.
public static Result newItem(){
Form<ItemModel> itemForm = form(ItemModel.class).bindFromRequest();
if (itemForm.hasErrors(){
return badRequest(newItemView.render(itemForm));
}
itemForm.get().save();
return ok("Your new item is saved...");
}