how do i validate a field conditionally based on the presence of another field. for example, only make "state" required only if "country" is "US".
thanks,
steve
EDIT:
so i figured to do this:
chained_validators = [validators.RequireIfPresent('state', present="country")]
but the error message is associated with "_the_form" instead of "state". is there a way to link it to the field instead?
Had the same problem during a project in my company. We wrote our own Formencode validator for this. We currently try to merge it with the main project. In the meantime you can download it here: https://github.com/GevatterGaul/formencode
There is also a Howto in, well, german: http://techblog.auf-nach-mallorca.info/2014/08/19/dynamische_formulare_validieren_mit_formencode/
But let me give you a quick rundown in the context of your example:
from formencode import validators
v = validators.RequireIfMatching('country', expected_value='US', required_fields=['state'])
v.to_python(dict(country='US', state='Virginia'))
The main benefit is, that in comparison to validators.RequireIfPresent, validators.RequireIfMatching only requires a field when a given field matches a given value. In your example, only if 'country' is 'US', then it requires the 'state' field.
Hope I could help.
Related
I'm using Facebook's Python SDK to extract Ads Insights, but I can't find the right way to retrieve ALL fields without having to declare them, which is pretty cumbersome.
My current code looks like this:
ads = tempaccount.get_insights(
params={'date_preset': 'yesterday',
'level': 'ad'},
fields=[AdsInsights.Field.account_id,
AdsInsights.Field.account_name,
AdsInsights.Field.ad_id,
AdsInsights.Field.ad_name,
AdsInsights.Field.adset_id,
AdsInsights.Field.adset_name,
AdsInsights.Field.campaign_id,
AdsInsights.Field.campaign_name,
AdsInsights.Field.cost_per_outbound_click,
AdsInsights.Field.outbound_clicks,
AdsInsights.Field.spend])
Is there a way to force the "fields" attribute to bring all possible fields without declaring them?
Unfortunately, you will need to specify all the required fields. It's not possible to get all fields without explicitly specifying them.
My code also looks similar to yours when querying the insights endpoint.
This worked for me:
from facebookads.adobjects.adsinsights import AdsInsights
for property, value in vars(AdsInsights.Field).items():
print(property, ":", value)
Got from this post: How to enumerate an object's properties in Python?
When using the jira python library and creating issues, non mandatory fields are being enforced on create_issue call.
Response on create issue attempt:
text: No issue link type with name 'Automated' found.
Response on create meta call to check mandatory fields:
'hasDefaultValue': False,
u'key': u'issuelinks',
u'name': u'Linked Issues',
u'operations': [u'add'],
u'required': False,
I had a similar issue and after a bit of digging around, this is what I did.
Open a jira and using developer tools (F12), find out the id of the mandatory custom fields. They should be named somewhat like "customfield_10304"
Once you have these field ids, just use them the way you set other fields while creating an issue. For eg.
new_issue = jira.create_issue(project={'key': project},
summary='{}'.format(summary),
description='{}'.format(description),
issuetype={'name': 'Bug'},
labels=labels,
versions=[{"name": affect_version[0]}],
customfield_10304=[{"value": env}],
customfield_10306=[{"value": customer}],
priority={'name': priority})
Jira behaves strange many times.
createmeta call returns you all the possible issuetypes, and their all fields, and which field is mandatory or not.
But even after this, there are certain fields which are mandatory but createmeta wont tell you this. You need to rely on the exception message that you got after filing create_issue().
In the exception message, exception_obj.response.text gives you the json having key/value of exact field required.
Then, you can search in response of createmeta about its schema type, and may be the allowedValues set.
And, then try again.
Basically, you need to do retry of above mechanism.
I need a help please.
So I wanted when I change the Internal Category (field name is categ_id) value to 500 final product,
and then the Routes field changes to :
Manufacture checked,
Make To Order checked,
Buy checked
and also the Value of Tracking field is changes as well to:
By Lots checked
How can I do that? Any suggestion ? Or my is it my question are not clear enough ?
Sorry for asking , I never done this before so yeah kind a confusing.
Here I got the picture the interface and the information about the field as well.
Routes field name
Tracking field name
Please anyone kindly to help me. I am so confused.
You could achieve this by using api onchange in Odoo 9.
#api.onchange('categ_id')
def onchange_categ_id(self):
for record in self:
# I prefer to check by id, but here I show how to check by string name in case you want it
if record.categ_id.name == '500 final product':
# because route_ids is many2many field,
# you need special commands to change the value
# here I use (6, _, ids) to set value.
# But before that, you have to get the ids of the routes you want from model stock.location.route
# (you could use search method to get the ids)
record.route_ids = [(6,0, list_of_id)]
record.tracking = 'lot'
...
You could refer to Odoo Doc to learn more about O2m and M2m commands
I wish to add custom input field attributes to the default event page template (or rather extend it). I don't know which is the template for the same and where is it located in ZMI.
F.e. I wish to add custom metadata like client name, lawyer name etc. I know how to add the metadata for the same but how to extend the event's default template.
Other option: If I use ploneformgen for the same, how can I get the calendar view for the events created? Finally wish to have calendar view for the custom data input with the start and end date for input created, which is searchable. The data for the collection should be searchable and should have 'hyperlinks to the folders' containing the related documents in the tabular view?
I am using zettwerk.fullcalendar for plone 4.1
To add extra fields to the existing Event type, using http://pypi.python.org/pypi/archetypes.schemaextender
It's not something you can do TTW.
Found the template at /site/portal_skins/event_view which you can customize. At least know where to start with. But when I use the customize tab, I get the error for the python expression witout changing the code as :
Macro expansion failed : widget
On testing, it shows error with the python expression:
Module Products.PageTemplates.ZRPythonExpr, line 48, in call
__traceback_info__: context.start().Date() == context.end().Date()
Module PythonExpr, line 1, in
The template code is :
<tal:differentday tal:condition="python:context.start().Date() == context.end().Date()"
i18n:translate="event_when_differentday">
Can anyone guide as to what the error in the above expression is?
I'm trying to parse an html form using mechanize. The form itself has an arbitrary number of hidden fields and the field names and id's are randomly generated so I have no obvious way to directly select them. Clearly using a name or id is out, and due to the random number of hidden fields I cannot select them based on the sequence number since this always changes too.
However there are always two TextControl fields right after each other, and then below that is a TextareaControl. These are the 3 fields I need access too, basically I need to parse their names and all is well. I've been looking through the mechanize documentation for the past couple hours and haven't come up with anything that seems to be able to do this, however simple it should seem to be (to me anyway).
I have come up with an alternate solution that involves making a list of the form controls, iterating through it to find the controls that contain the string 'Text' returning a new list of those, and then finally stripping out the name using a regular expression. While this works it seems unnecessary and I'm wondering if there's a more elegant solution. Thanks guys.
edit: Here's what I'm currently doing to extract that info if anyone's curious. I think I'm probably just going to stick with this. It seems unnecessary but it gets the job done and it's nothing intensive so I'm not worried about efficiency or anything.
def formtextFieldParse(browser):
'''Expects a mechanize.Browser object with a form already selected. Parses
through the fields returning a tuple of the name of those fields. There
SHOULD only be 3 fields. 2 text followed by 1 textarea corresponding to
Posting Title, Specific Location, and Posting Description'''
import re
pattern = '\(.*\)'
fields = str(browser).split('\n')
textfields = []
for field in fields:
if 'Text' in field: textfields.append(field)
titleFieldName = re.findall(pattern, textfields[0])[0][1:-2]
locationFieldName = re.findall(pattern, textfields[1])[0][1:-2]
descriptionFieldName = re.findall(pattern, textfields[2])[0][1:-2]
I don't think mechanize has the exact functionality you require; could you use mechanize to get the HTML page, then parse the latter for example with BeautifulSoup?