password fields in wtform do not populate correctly - flask-wtforms

I've got the Settings page where users can change their data (including the password). They should be able to change some data without providing the password everytime. But it looks like the PasswordField is not populated correctly and I cannot figure out where to look for a problem. I open the settings page and if I want to change anything in the form I receive the "Passwords must match" error everytime. After debugging I can see that the password_change has the correct value but the password_confirm is empty. I need to manually provide password_confirm value every time. It shouldn't be required. How do wtforms populate the PasswordField and why that doesn't work?
view.py
else: # GET
form = UserEditForm(obj=acc)
return render_template('account/view.html', account=acc, form=form)
class UserEditForm(Form):
name = StringField('Account name', [DataOptional(), validators.Length(min=3, max=64)])
email = StringField('Email address', [
IgnoreUnchanged(),
validators.Length(min=3, max=254),
validators.Email(message='Must be a valid email address'),
EmailAvailable(),
validators.EqualTo('email_confirm', message='Email confirmation must match'),
])
email_confirm = StringField('Confirm email address')
password_change = PasswordField('Change password', [
validators.EqualTo('password_confirm', message='Passwords must match'),
])
password_confirm = PasswordField('Confirm password')
<div class="form__question">
{{ render_field(form.password_change, placeholder="********") }}
</div>
<div class="form__question">
{{ render_field(form.password_confirm, placeholder="********") }}
</div>

You could try something like this, making the password field optional, and then only require the password_confirm field if data exist in the password_change field
password_change = PasswordField(
'password',
validators=[DataOptional(), validators.Length(min=6, max=255)]
)
password_confirm = PasswordField(
'Repeat password',
validators=[
RequiredIf('password_change'),
EqualTo('password_change', message='Passwords must match.')
]
)
create a validator class for RequiredIf
source -> How to make a field conditionally optional in WTForms?
class RequiredIf(InputRequired):
# a validator which makes a field required if
# another field is set and has a truthy value
def __init__(self, other_field_name, *args, **kwargs):
self.other_field_name = other_field_name
super(RequiredIf, self).__init__(*args, **kwargs)
def __call__(self, form, field):
other_field = form._fields.get(self.other_field_name)
if other_field is None:
raise Exception('no field named "%s" in form' % self.other_field_name)
if bool(other_field.data):
super(RequiredIf, self).__call__(form, field)

Related

Symfony EntityType - access choice_label after submitting

I have an EntityType field:
->add('topic', null, [
'required' => false,
'class' => Category::class
])
And for new Category 's my js tool creates a new select option marked with __new_option__:
So the value to read is not the value. It is the label.
How can I read this value after submission.
I tried addViewTransformer, addEventListener with preSetData and postSetData.
But when I get the value - it shows everytime just __new_option__ but not the value to persist into the database.
Is there a way to do that?
How can I read this value after submission. I tried
addViewTransformer, addEventListener with preSetData and postSetData.
By reason of the post-data containing the topic-field eq 'new_option'. "It doesn't know anything about the selected value`s label".
I don`t know your implementation, but -> just change-modify the js-behaviour on submitting like:
let topicSelection = document.getElementById('SELECTOR');
topicSelection.options[el.selectedIndex].value = topicSelection.options[el.selectedIndex].innerHTML;
//... submitting

how to show username with user field type in advanced custom fields plugin

i create a user relational type field in acf, after selecting user, acf just returns user id, my question is how to return the selected user "first name" or email address on my page?
i tried User Array and User Object mode, but i did not get the result.
Can anyone guide me to work with User Array / User Object mode.
i cant find documents in acf website about this.
thanks
i use this code:
php the_field('inscourse');
For User Array selected, just put something like this to see the returned vales:
$inscourse = get_field('inscourse');
echo '<pre>';
print_r($inscourse);
echo '</pre>';
This will output a nested array like:
array(
[ID] => 123
[user_firstname] => Joe
[user_lastname] => Jackson
....
[user_nicename] => joe-jackson
[display_name] => Joe
....
)

Symfony custom form field type FQCN to store in a database field

I'm in the process of migration a symfony 2.8 application to 3.4 and then to 4.1. As you know ::getName() of a custom form field type had become deprecated and was removed in 2.8 and 3.x respectively. So now one need to specify a FQCN when adding a custom field to the form. The problem is that we have a Settings table with a set or rows representing form fields. Each row of this type in the DB table has its own field type (a column in the DB table). So it looks like:
'4', '1', NULL, 'password_expiration', '365', 'integer', 'Period of user password expiration, in days', 'Password Expiration'
'6', '1', NULL, 'login_min_length', '3', 'integer', 'Minimum allowable login length', 'Login Minimum Length'
....
'17', '1', NULL, 'help_page', '', 'ckeditor', 'Help page content for users', 'Help page'
where integer and ckeditor are the values used to be passed as custom or native symfony field type name into the ::add() call of a form.
As you can imagine it throws an exception Could not load type "ckeditor": class does not exist under 3.4, because I need to refer to a FQCN of MyBundle\Form\Type\CkEditorType::class somehow. But even if I update the database field values to something like 'MyBundle\Form\Type\CkEditorType::class' (with properly escaped backslashes, obviously) it will be interpreted as string and not eval'ed.
So the question is: how do we store FQCN in a database field and interpret it when rendering a form?

Reordering Fields on Extended Content Type

I have extended a basic Plone content type using archetypes.schemaextender. I need to reorder the fields on the edit page. When I do, the reordered fields appear in a new tab called "content" on the edit interface. How can I get the fields to appear in the "default" tab of the edit interface instead?
Here is the code snippet from my extender.py:
class extenddocument(object):
adapts(IATDocument)
implements(IOrderableSchemaExtender, IBrowserLayerAwareExtender)
layer = IextenddocumentLayer
fields = [
_ExtensionStringField(
name='longTitle',
widget=StringWidget(
label=u'Long Title',
description=u'Optional descriptive title to replace default title as the page heading',
size='50',
),
required=False,
searchable=True,
),
]
def __init__(self, context):
self.context = context
def getOrder(self, schematas):
""" Manipulate the order in which fields appear.
#param schematas: Dictonary of schemata name -> field lists
#return: Dictionary of reordered field lists per schemata.
"""
schematas["Content"] = ['title', 'longTitle', 'description', 'text']
return schematas
def getFields(self):
return self.fields
attached is the edit tab view:
In the getOrder method, assign your list of fields to schematas['default'] instead of to schematas['Content'].
Or, as you actually don't need an extra-fieldset, because and added field will be appended to the default-fieldset anyway, you could also just reorder your field – instead of the whole fieldset – as described here:
http://developer.plone.org/content/archetypes/fields.html#reordering-fields
Here is a nice documentation of Inqbus, which gives you an overview of the possibilities of reordering fields and fielsets, it's in German, but the code-parts are self-explaining:
http://inqbus-hosting.de/support/dokumentation/docs/plone-archetypes-schemata-und-fields

calling user_save from within hook_init failing on Drupal6

I have a module that implements hook_init.
Within that I have a case where I try to call user_save like save
user_save ('');
I figure this should work since I am not setting a uid, so it should create a new one. It also says that the $array should be allowed to be empty.
However, this always returns FALSE. ??
I have also tried setting these values in $array but this doesn't work either:
$foo = array(
'name' => 'the new user',
'mail' => 'the new user mail',
'pass' => user_password(),
'status' => 1,
);
$new_user = user_save ('', $foo);
Look at the documentation:
Parameters
$account The $user object for the user to modify or add. If $user->uid is omitted, a new user will be added.
$array (optional) An array of fields and values to save. For example, array('name' => 'My name'); Setting a field to NULL deletes it from the data column.
So when you call user_save() the first parameter must be a user object. If that user object doesn't have a uid, or is a string like in your case, a new user will be created. Here the 2nd parameter is necessary. It's not required to use the function, but as it holds all the values you want to save, you wont get far trying to create a user with no data at all. What use is a user without password, username etc. So a minimum of data is required as well, so Drupal will know what to save.

Resources