Webshim: Initialization for a specific FormID - webshim

How can I initialize webshim only for a specific formID?
webshim.polyfill('#formID forms forms-ext');

Related

Flask-WTF default for a SelectField doesn't work for SQLAlchemy enum types

I have a Flask-SQLAlchemy site which uses the SQLAlchemy enum type for certain columns, to restrict possible input values.
For example, I have a "payment type" enum that has a few payment type options, like so:
class PaymentType(enum.Enum):
fixed = "fixed"
variable = "fixed_delivery"
quantity_discount = "quantity_discount"
When I use this in a dropdown/select I can specify the options like so:
prd_payment_type = SelectField(_('prd_payment_type'), choices=SelectOptions.PaymentTypes.All(0, _('PleaseSelect')))
The All() function I'm calling returns the different enum values as options, and also adds a custom "Please select..." option to the dropdown list. It looks like this:
class PaymentTypes(object):
#staticmethod
def All(blank_value=None, blank_text=None):
ret = [(i.value, _(i.name)) for i in PaymentType]
SelectOption.add_blank_item(ret, blank_value, blank_text)
return ret
So far, so good, I get a nice dropdown, with the correct options. the problem arises when I want to display the form using an already existing SQLAlchemy object from the database.
When I fetch the object from SQLAlchemy, the prd_payment_type property contains the enum PaymentType.quantity_discount, not just a string value 'quantity_discount':
Because WTForms (presumably) matches the pre-selected option in the dropdown to a string value "quantity_discount", it doesn't match the enum in the SQLAlchemy model and the option is not selected in the dropdown.
The SelectField of WTForms accepts a list of tuples containing strings as choices. I can't feed it my enum.
On the other hand, the SQLAlchemy model returns an enum type as the property for prd_payment_type. I could maybe override this property or something, but that feels like a lot of work to support SQLAlchemy's enums in WTForms.
Is there a standard solution for working with SQLAlchemy's enums in a WTForms SelectField or should I abandon using enums altogether and just store strings, maybe from a list of constants to keep them in check?
I have found a solution myself. It seems that when the enum has a
def __str__(self):
return str(self.value)
That's enough for WTForms to match the database value to the SelectField value.
I have made a baseclass that derives from enum.Enum and added the code above to return the enum value as a string representation.
This solution was based on these similar problems I found later on:
https://github.com/flask-admin/flask-admin/issues/1315
Python Flask WTForm SelectField with Enum values 'Not a valid choice' upon validation

Instantiating the SQL implementation of Aggregates in Django 1.8

I've been working on updating the existing code base that was using Django 1.6 to Django 1.8. In the process, I've been facing a particular problem with aggregates.
In this code, PGDAggregate class has a method add_to_query which is intended to instantiate the SQL implementation of the aggregate and sets it as a class variable (aggregate) which i'd be using to call the as_sql method in Default SQL Aggregate(django/db.models.sql.aggregates.Aggregate) from another file.
My code (The first file, how I implement aggregate):
from django.db.models.aggregates import Aggregate
from django.db.models.sql.aggregates import Aggregate as SQLAggregate
class PGDAggregate(Aggregate):
"""
Modified to allow Aggregate functions outside of the Django module
"""
def add_to_query(self, query, alias, col, source, is_summary):
"""Add the aggregate to the nominated query.
This method is used to convert the generic Aggregate definition into a
backend-specific definition.
* query is the backend-specific query instance to which the aggregate
is to be added.
* col is a column reference describing the subject field
of the aggregate. It can be an alias, or a tuple describing
a table and column name.
* source is the underlying field or aggregate definition for
the column reference. If the aggregate is not an ordinal or
computed type, this reference is used to determine the coerced
output type of the aggregate.
* is_summary is a boolean that is set True if the aggregate is a
summary value rather than an annotation.
"""
klass = globals()['%sSQL' % self.name]
aggregate = klass(col, source=source, is_summary=is_summary, **self.extra)
# Validate that the backend has a fully supported, correct
# implementation of this aggregate
query.aggregates[alias] = aggregate
self.aggregate = aggregate
class BinSort(PGDAggregate):
alias = 'BinSort'
name = 'BinSort'
class BinSortSQL(SQLAggregate):
sql_function = ''
sql_template = '%(function)sFLOOR((IF(%(field)s<%(offset).16f,360,0)+%(field)s-%(offset).16f)/%(bincount).16f)-IF(%(field)s=%(max).16f,1,0)'
This is how I'm trying to use the aggregate attribute(an instance of Default SQL Aggregate) from the second file to invoke the as_sql method.
sortx = BinSort(xTextString, offset=x, bincount=xbin, max=x1)
sorty = BinSort(yTextString, offset=y, bincount=ybin, max=y1)
annotated_query.annotate(x=sortx, y=sorty)
cn = connections['default']
qn = SQLCompiler(annotated_query.query, cn, 'default').quote_name_unless_alias
sortx_sql = sortx.aggregate.as_sql(qn, cn)[0]
sorty_sql = sorty.aggregate.as_sql(qn, cn)[0]
The error that I'm getting(in l:6) in this implementation is,
exception 'BinSort' object has no attribute 'aggregate'
As steps of debugging, i've tried to check if the BinSort instance has an attribute "aggregate", using
hasattr(sortx, 'aggregate')
which has returned me False. But when I try to check by printing the aggregate attribute from inside the add_to_query method, I could very much see the attribute getting printed.
Also, I've implemented this in the way specified in Django 1.8 doc, https://github.com/django/django/blob/stable/1.8.x/django/db/models/aggregates.py#L46
Though this is not a solution to explain the unexpected behaviour, but this works. Since I wanted to use the as_sql() method of the Default SQL Aggregate class, i've initialized BinSortSQL directly instead of BinSort class and have used it's as_sql() method.
sortx = BinSortSQL(col, offset=x, bincount=xbin, max=x1)
sorty = BinSortSQL(col, offset=y, bincount=ybin, max=y1)

Django ValidationError - how to use this properly?

Currently there is code that is doing (from with the form):
# the exception that gets raised if the form is not valid
raise forms.ValidationError("there was an error");
# here is where form.is_valid is called
form.is_valid() == False:
response['msg']=str(form.errors)
response['err']='row not updated.'
json = simplejson.dumps( response ) #this json will get returned from the view.
The problem with this, is that it is sending err message to the client as:
__all__"There was an error."
I want to remove the "all" garbage from the error template that is returned. How can I go about doing this? it seems to get added deep in django form code.
It's because the error is not associated with any field in particular, but it's so called non-field error.
If you're only interested in non-field errors, just simply pass this to the response:
response['msg']=str(form.errors['__all__'])
errors is an instance of a subclass of dict with some special rendering code. Most of the keys are the fields of the form, but as the docs describe, raising ValidationError in clean produces an error message that isn't associated with any particular field:
Note that any errors raised by your Form.clean() override will not be associated with any field in particular. They go into a special “field” (called __all__), which you can access via the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you will need to access the _errors attribute on the form, which is described later.
https://docs.djangoproject.com/en/dev/ref/forms/validation/
So you can either generate your string representation of the errors differently (probably starting with form.errors.values() or form.errors.itervalues(), and maybe using the as_text method of the default ErrorList class) or associate your error with a particular field of the form as described in the docs:
When you really do need to attach the error to a particular field, you should store (or amend) a key in the Form._errors attribute. This attribute is an instance of a django.forms.utils.ErrorDict class. Essentially, though, it’s just a dictionary. There is a key in the dictionary for each field in the form that has an error. Each value in the dictionary is a django.forms.utils.ErrorList instance, which is a list that knows how to display itself in different ways. So you can treat _errors as a dictionary mapping field names to lists.
If you want to add a new error to a particular field, you should check whether the key already exists in self._errors or not. If not, create a new entry for the given key, holding an empty ErrorList instance. In either case, you can then append your error message to the list for the field name in question and it will be displayed when the form is displayed.
https://docs.djangoproject.com/en/dev/ref/forms/validation/#form-subclasses-and-modifying-field-errors

Django multi-table inheritance chokes on leaked variable in model definition

class Parent(models.Model):
pass
class RebelliousChild(Parent):
parent_fields = [__x.name for __x in Parent._meta._fields()]
Django 1.3 responds:
django.core.exceptions.FieldError: Local field '_RebelliousChild__x'
in class 'RebelliousChild'clashes with field of similar name from base class 'Parent'
Django 1.5 responds:
FieldError: Local field u'id' in class 'RebelliousChild' clashes with field
of similar name from base class 'Parent'
My second reaction (after trying to make the variable private) was to delete the variable (which worked.)
parent_fields = [__x.name for __x in Parent._meta._fields()]
del __x
List comprehensions leak their control variables in Python 2.
Django prohibits overriding parent field attributes, which seems to be involved somehow, since Django 1.5 has the same issue. But in both cases the leaked attribute name _RebelliousChild__x isn't defined on Parent.
What is going on here?
PS
Using "list(x.name for x in Parent._meta._fields())" is prettier than "del x". See the aforementioned https://stackoverflow.com/a/4199355 about generators not leaking their control variables.
Have a look here: https://docs.djangoproject.com/en/1.5/topics/db/models/#multi-table-inheritance
In short, you don't need to apply the parent fields to the child(they already exist, but in a different table), you can access them directly on a RebelliousChild instance.

Django forms without widgets

I understand that Django want to generate forms automatically so you don't have to do so in your template, and I do understand that many people find it cool.
But I have specific requirements and I have to write my forms on my own. I just need something to parse the data, be it a form submitted using a user interface, or an API request, or whatever.
I tried to use ModelForm, but it doesn't seem to work as I want it to work.
I'd like to have something with the following behavior:
possibility to specify the model of the object I am going to create/update
possibility to specify an object in case of an update
possibility to provide new data in a dictionary
if I am creating a new object, missing fields in my data should be replaced by their default values as specified in my model definition
if I am updating an existing object, missing fields in my data should be replaced by the current values of the object I am updating. Another way of saying is, do not update values that are missing in my data dictionary.
data validation should be performed before calling save(), and it should throw a ValidationError with the list of erroneous fields and errors.
Currently, I prefer to do everything manually :
o = myapp.models.MyModel() # or o = myapp.Models.MyModel.objects.get(pk = data['pk'])
o.field1 = data['field1']
o.field2 = data['field2']
…
o.full_clean()
o.save()
It would be nice to have a shortcut :
o = SuperCoolForm(myapp.models.MyModel, data)
o.save()
Do you know if Django does provide a solution for this or am I asking too much?
Thank you!