GithubHelp home page GithubHelp logo

jazzband / django-floppyforms Goto Github PK

View Code? Open in Web Editor NEW
836.0 836.0 148.0 1.94 MB

Full control of form rendering in the templates.

Home Page: http://django-floppyforms.readthedocs.org/

License: Other

Python 86.04% JavaScript 4.30% CSS 4.53% HTML 5.12%

django-floppyforms's People

Contributors

artscoop avatar bmihelac avatar brutasse avatar caacree avatar carljm avatar dmclain avatar dmpayton avatar drmeers avatar fladi avatar gregmuellegger avatar jezdez avatar jonashaag avatar luzfcb avatar magopian avatar maraujop avatar melinath avatar mrjmad avatar natim avatar ouhouhsami avatar poswald avatar rmoch avatar rtpg avatar ryanmrubin avatar scardine avatar stefanfoulis avatar tangent avatar timgates42 avatar tomturner avatar ulope avatar victor-o-silva avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-floppyforms's Issues

Template loader

Hi guys and gals,

Is there any way to pass in a custom template loader to floppyforms?

We have a very intricate template loading procedure and would like to plumb django-floppyforms into our processing so that we can make use of the custom form rendering. I see that in the floppy form template tags you are importing and using the standard template loader from django

from django.template.loader import get_template

However, we need to be able to specify our own. Is there anyway to do this currently? If not would this be a feature that you would consider implementing into floppyforms?

Cheers,
Rob

PS. Thanks for the great package!

Openlayers not loading in the template .

I have an app called openmaps.
The forms page looks like this

from django import forms
from openmaps.models import Open_Layers
from django.contrib.admin import widgets
import floppyforms as forms

class GeoForm(forms.Form):
point = forms.gis.PointField()
class PointWidget(forms.gis.PointWidget, forms.gis.BaseGMapWidget):
pass

class OpenLayersAdmin(admin.OSMGeoAdmin):
list_display = ('name','interestingness')
list_filter = ('name','interestingness',)
fieldsets = (
('Location Attributes', {'fields': (('name','interestingness'))}),
('Editable Map View', {'fields': ('geometry',)}),
)

# Default GeoDjango OpenLayers map options
 scrollable = False
 map_width = 700
 map_height = 325

admin.site.register(Open_Layers,OpenLayersAdmin)

The views look like this

from django.shortcuts import render_to_response
from django.contrib.gis.shortcuts import render_to_kml
from openmaps.models import *

def all_kml(request):
locations = Open_Layers.objects.kml()
return render_to_kml("gis/kml/placemarks.kml" , {'places' : locations})

def map_page(request):
lcount = Open_Layers.objects.all().count()
return render_to_response('maps.html', {'location_count' : lcount})

The template code is this

{# template.html #}

{{ form.media }} {% csrf_token %} {{ form.as_p }}

But nothing shows up apart from the submit button . Any help would do .

small bug in decompress for datetimefield

In the following code 'microseconds' should be 'microsecond':

def decompress(self, value):
if value:
return [value.date(), value.time().replace(microseconds=0)]
return [None, None]

(widgets.py, line 280).

Setting a default for a datetimefield value does not work atm because of this bug.

Rendering fails with non-empty TEMPLATE_STRING_IF_INVALID

I've just started evaluating floppyforms, please forgive me if this report is bogus.

I've installed django-floppyforms and added it my project's INSTALLED_APPS. Then, in a simple contact app. replaced the import in forms.py with the floppyforms version, ie:

import floppyforms as forms
#~ from django import forms

class ContactForm(forms.ModelForm):
    class Meta:
        model = models.Message

(I haven't overridden any widgets in the Metaclass yet as when I do, per the docs, I run into an issue relating to a missing is_hidden attribute, which I'm still investigating...)

Anyway, with just those changes the form becomes a mess. We use a non-empty value of TEMPLATE_STRING_IF_INVALID during development, and now the form has two of those per input. one for the help text, one for the label. The expected behaviour is restored by either downgrading floppyforms to 0.4.7 or setting TEMPLATE_STRING_IF_INVALID to an empty string under 1.0.0.

TEMPLATE_STRING_IF_INVALID = '<INVALID>'
class ContactForm(forms.ModelForm):
    class Meta:
        model = models.Message
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Send Now" />
</form>

django-floppyforms 1.0.0

...
<p>
    <label for="id_subject">&lt;INVALID&gt;:</label>
    <input id="id_subject" type="text" name="subject" maxlength="255" />
    <span class="helptext">&lt;INVALID&gt;</span> 
</p>
...

django-floppyforms 0.4.7

(Newline added to avoid wrapping)

<p><label for="id_subject">Subject:</label> 
<input id="id_subject" type="text" name="subject" maxlength="255" /></p>

Plain Django form

(Newline added to avoid wrapping)

<p><label for="id_subject">Subject:</label> 
<input id="id_subject" type="text" name="subject" maxlength="255" /></p>

on bootstrap3 support

I've tried to make floppyform to work with bootstrap3. After minor modifications
to the templates, I realized that every input widget needed the "form-control" class.

So I naively patch the Input.get_context method in widgets.py to add this simple code:

    if 'class' in context['attrs'].keys():
        context['attrs']['class'] += " form-control"
    else:
        context['attrs']['class'] = "form-control"

Then, I needed something to apply does changes to the modelForms.
But because of how Django handled modelForm it was not easy.
Fortunately, I found that code to me help out:

https://github.com/pydanny/django-admin2/blob/develop/djadmin2/forms.py

But I still need to do something like:

Class MyForm(forms.ModelForm):
....

MyForm = floppify_form(MyForm)

So I was wondering if there is something that could be done to make bootstrap3
simpler. (Note: the modelForms problem might be better in an other issue...)

Browser caching bug for map widget

Hi
Quite an interesting bug. The problematic behaviour is that loading a page with a map works fine, but then using the back/forward buttons breaks the page when it returns to it.

Steps to Reproduce:

  • Load a page containing a floppyforms map widget
  • Press back button
  • Press forward button

Expected Result:
Map loads
Actual Result:
Javascript error because read_wkt returns undefined

I think what is happening is that the javascript is modifying the wkt text element, and then the browser is caching that new value element when it reopens the page.

The net effect is that the wkt parameter passed to MapWidget.prototype.read_wkt contains an SRID=... ; when the page is first loaded, but does not contain an SRID when back, next is used.

My solution is to change the regex used to
this.re = new RegExp("^(SRID=\d+;)*(.+)", "i");

And change the read_wkt method to use:
MapWidget.prototype.read_wkt = function(wkt) {
var match = this.re.exec(wkt);
if (match) {

  •           wkt = match[2];
    }
    return this.wkt_f.read(wkt);
    
    };

IntegerField should set min / max attributes on NumberInput widget

The floppyforms IntegerField uses a NumberInput widget by default, which should use the values of the IntegerField's min_value and max_value properties (documented here) as default values for its min and max attributes.

E.g.:

how_many = IntegerField(min_value=0, max_value=10)

should, by default, render as:

<input type="number" min="0" max="10" name="how_many">

I think the widget's attr property should still be able to override these, e.g.:

how_many = IntegerField(min_value=0, max_value=10,
    widget=NumberInput(attrs={'min': 5, 'max': 20})
)

=>

<input type="number" min="5" max="20" name="how_many">

{% widget form.some_field using "custom_widget.html" %}

Here is a feature request: as a template designer, I can use a custom template for some widget, without having to edit Python code.

An example:

{% widget form.some_field using "custom_widget.html" %}

Another example with local context override:

{% with "input-large" as css_classes and "Search something" as placeholder %}
  {% widget form.q using "bootstrap_search_widget.html" %}
{% endwith %}

Some motivations:

  • when I just need to customize the template of one widget, I'd like to do it in template code.
  • sometimes I can't (or don't want to) override a form class to change widgets, but I can override the templates. When form definition and views using this form live in some external dependency, it may be simpler to override the template instead of both form class and views.
  • consistency with other template tags.

HTML5 "required" validation breaks formset empty forms.

The empty forms on a formset may have multiple extra empty forms. If one of the extra forms remains empty, but has any "required" fields, browsers that support HTML5 pre-submit validation (like Chrome) will refuse to submit the formset (even though it would be valid according to Django's logic.)

Django's admin doesn't have this problem because it just doesn't set the "required" attribute on any form fields. Maybe floppyforms should just do the same? Seems less complicated than the alternatives.

CheckboxInput rendered the wrong way when the form is bound

When re-displaying a form with a BooleanField and rendered with a CheckboxInput, the generated <input> has a value attribute with the value of "False" (the string False). This results in a cleaned_data value of False when it was checked. (are you still following me ;-)

If you compare floppyforms CheckboxInput.render with django CheckboxInput.render very closely, you can see that the django version never adds value to the attrs, unless it is not one of the known standard values that are considered true or false. floppyforms always passes in value wich sometimes ends up being False instead of None.

Extend nullbooleanselect with custom choices

Hello,

I was trying to extend NullBooleanSelect widget, having custom choices, but, as init doesn't have choices attribute (https://github.com/brutasse/django-floppyforms/blob/master/floppyforms/widgets.py#L460), I wasn't able to use my custom choices like this:

class IndifferentNullBooleanSelect(NullBooleanSelect):
    def __init__(self, attrs=None):
        choices = ((u'1', _(u'Indifferent')),
                   (u'2', _(u'Oui')),
                   (u'3', _(u'Non')))
        super(IndifferentNullBooleanSelect, self).__init__(attrs, choices)

May be there is a better way to achieve my goal ?

Regards,

select input and required

Hello,

I took a look at this file : floppyforms/templates/floppyforms/select.html and didn't find {% if required %} required{% endif %}
(so that if this type of field is required and the user don't set a value, he will not get a red border around the select input)

Is there a reason for that ?

Thanks

Can not install 1.1 or dev versions as per docs.

As per docs: http://django-floppyforms.readthedocs.org/en/latest/ can not install latest 1.1 or the dev version:

(virtualenv)root@klisrv10:/srv/www/django/development.FOO.com# pip install django-floppyforms==1.1
Downloading/unpacking django-floppyforms==1.1
  Could not find a version that satisfies the requirement django-floppyforms==1.1 (from versions: )
No distributions matching the version for django-floppyforms==1.1
Storing complete log in /root/.pip/pip.log
(virtualenv)root@klisrv10:/srv/www/django/development.FOO.com# pip install django-floppyforms==1.1
Downloading/unpacking django-floppyforms==1.1
  Could not find a version that satisfies the requirement django-floppyforms==1.1 (from versions: )
No distributions matching the version for django-floppyforms==1.1
Storing complete log in /root/.pip/pip.log
(virtualenv)root@klisrv10:/srv/www/django/development.FOO.com# yolk -V django-floppyforms
django-floppyforms 1.0
(virtualenv)root@klisrv10:/srv/www/django/development.FOO.com# pip install -U django-floppyforms==1.1
Downloading/unpacking django-floppyforms==1.1
  Could not find a version that satisfies the requirement django-floppyforms==1.1 (from versions: )
No distributions matching the version for django-floppyforms==1.1
Storing complete log in /root/.pip/pip.log
(virtualenv)root@klisrv10:/srv/www/django/development.FOO.com# pip install -U django-floppyforms==dev
Downloading/unpacking django-floppyforms==dev
  Downloading master (1.1MB): 1.1MB downloaded
  Running setup.py egg_info for package django-floppyforms
  Requested django-floppyforms==dev, but installing version 1.0
Installing collected packages: django-floppyforms
  Running setup.py install for django-floppyforms
Successfully installed django-floppyforms
Cleaning up...

Pull missing django forms definitions into floppyform namespace

Let me first say that I really love the approach you're taking with this. I'm trying it out and I think it has a lot of potential.

In your instructions, you imply that installation is as simple as replacing the import and then creating new fields using the object included. While this is true, some of the fields available in django.forms are missing in the floppyforms.forms module. The ModelChoiceField is one example of that. If you are converting a project that is already using that field and simply switch the import you will get 'module' object has no attribute 'ModelChoiceField'.

If you imported each of the fields in django.forms into your namespace, it would be a drop-in replacement. They are all listed in the django forms reference. Later, if you decide to implement it in floppyforms, you can simply remove the import and add a class definition and people will get the updated version without having to change their code. They still have a way to opt-out and pick-and-choose.

What do you think of this approach? I'm not sure if this goes against any sort of python best practice or not. You're already dependent on the django.forms module.

Support for <datalist>

It'd be great to add baked-in support for HTML5 , e.g.:

favourite_fruit = forms.TextField(options=(('apple', 'Apple'), ('banana', 'Banana'), ('orange', 'Orange')))

would render as:

<input type="text" name="favourite_fruit" id="id_favourite_fruit" list="favourite_fruit_list" required>
<datalist id="favourite_fruit_list">
    <option label="Apple" value="apple"></option>
    <option label="Banana" value="banana"></option>
    <option label="Orange" value="orange"></option>
</datalist>

I'm not suggesting options=... would be the best syntax, as this may clash with future additions to the Django forms API - open to suggestions of a better interface.

How to put in all the types of fields in one map and also all the types of maps in one placeholder ?

First of all , a brilliant application , and thank you for all the help till now .

This is my forms.py

from django import forms
from openmaps.models import Open_Layers
from django.contrib.admin import widgets
import floppyforms as forms
class PointWidget(forms.gis.PointWidget, forms.gis.BaseGMapWidget):
pass
class MultiPointWidget(forms.gis.MultiPointWidget,forms.gis.BaseGMapWidget):
pass
class LineStringWidget(forms.gis.LineStringWidget,forms.gis.BaseGMapWidget):
pass
class PolygonWidget(forms.gis.PolygonWidget,forms.gis.BaseGMapWidget):
pass
class MultiPolygonWidget(forms.gis.MultiPolygonWidget,forms.gis.BaseGMapWidget):
pass
class GeoForm(forms.Form):
point = forms.gis.PointField()
multipoint = forms.gis.MultiPointField()
line = forms.gis.LineStringField()
poly = forms.gis.PolygonField()
multipoly= forms.gis.MultiPolygonField()

According to this , all the points , multipoints , line etc load in separate openlayers maps , but in the same page . Is it by anychance possible to put in all the geometries in one map . And also , allow to change between maps like openlayers , osm , google maps using layerswitcher .

setCenter breaks PointWidget

I'm writing a site as a project for a university course. The site should have a possibility for users to locate one or more points on a map, which would then be stored in a GeoDjango PointField or MultiPointField. I've set up a floppyforms PointWidget which works, but I've been trying to add HTML5 geolocation into the mix using a setCenter() call on the widget's map object.

My demo is live at http://loytotavarat.nytsoi.net/find/create/
If you disallow geolocation, the widget seems to work ok and you can input a point just fine. If you do allow geolocation, however, the map zooms to the correct location, but inserting a point no longer works (I'm testing on the latest stable Chrome on OS X). I assume the widget loses track of what the map is pointing at due to the geolocation moving the map. When this happens, the blue circle no longer tracks the cursor or disappears altogether and it's not possible to insert points on the map anymore. If the user zooms in or out manually, functionality is restored.

I change the map's location based on geolocation data with the following function (the list 'maps' contains the ids of all maps in the form):

function setCoords(longitude, latitude, zoom) {
            // Create point to transform it to correct map coordinates
            var point = new OpenLayers.LonLat(longitude, latitude);
            // Coordinate system is WGS 84
            var proj = new OpenLayers.Projection("EPSG:4326");

            {% for map in maps %}
                var map = map_{{ map }}.map;
                point.transform(proj, map.getProjectionObject());
                map.setCenter(point, zoom, true, true);
            {% endfor %}
        }

Is there another way to incorporate geolocation or move the map that doesn't upset the widget or is this a real issue?

Passing attributes to formfield via formconfig and template not working

I'm trying to render some formfields and pass attributes via the template, to be passed to the widget, as I understood you could from the docs. It doesn't seem to be working. For example if I create a form like

import floppyforms as forms

class TestForm(forms.Form):
    test_input = forms.CharField(required=True)
    second_input = forms.CharField(required=False)

and a template like

{% load floppyforms %}
<!doctype html>
<html>
<body>
    {% form test_form using %}
        {% formfield form.test_input with placeholder="foo" %}
        {% formconfig field with placeholder="bar" for "second_input" %}
        {% formfield form.second_input %}
    {% endform %}
</body>
</html>

I would expect each field to get a placeholder. I did this to illustrate 2 different methods of passing the attribute I read in the docs, yet neither seems to work. Am I doing it wrong?

Transformed Geometry sometimes lack spaces after commas

Hi
I encountered a bug where sometimes transformed geometries lack spaces after the commas, which causes the parsing regex to only split the first object

<textarea name="geometry" rows="10" cols="40" id="id_geometry">MULTIPOINT (16674703.623217998072505 -3134091.533951798919588,15852852.695243995636702 -3192795.171664301306009,15735445.419818997383118 -3750479.729933001101017,16097451.185711996629834 -4083133.676970499567688)</textarea>

My suggested fix is to change the parsing regex in MapWidget.js as follows:

this.regExes.justComma = /\s_,\ ?\s_/;

Which allows 0 or 1 spaces after the comma.

Platform is Centos 6, Django 1.3, PostGIS 1.5.3, Geos 3.3.2

New Search Forms? Better Range widget?

The range widget returns a specific value as opposed to a range. HTML5 did not go far enough it appears in this area.

Well, this is quite particular to my case. But I'm looking at creating a new base search form based off the model/floppy forms. In my situation I want to replace all numeric fields, with a new range field. Unlike the floppyforms range field this will return a top and bottom search range ala as in jquery. This is not HTML5 compatible, but it seems there would be great need for this type of widget. The min and max for the widget would be based on the min and max in the database for that field.

In my specific case I will probably iterate over the fields in a form and only modify the widgets for those fields that are numeric (integer, float, or Decimal). This type of search is the more common case, rather than specifying an exact value to search for in the case of numeric fields (it seems someone else has probably solved this before).

http://jqueryui.com/demos/slider/#range

local copy of openlayers.js

hello,

May be it's no relevant, but I would like to have a local copy of openlayers, and google (js and css) instead of getting them via their absolute URL.

  • how can I achieve this ? (we could have sort of settings for that, instead of modify the widget Media class of BaseGMapWidget BaseOsmWidget or BaseMetacartaWidget)
  • how interesting is it to use, for example django_compressor, to increase performance ?

thx

Allow input type to be optional

There are two reasons I can think of for making the input type="whatever" easily switched off:

  • Full backwards compatibility with Django 1.2/1.3
  • Browser support
  • Number formatting code

Much like issue #1, backwards compatibility would allow people to get the override-able templates without any other changes to their application. It makes floppyforms a drop in replacement.

Secondly, there is an issue with the default controls provided by some browsers. For instance, a web developer might wish to use floppyforms but they don't like the built in browser control for the input type="datetime" in Safari/FFox/Chrome/IE and they want to provide their own javascript control until support improves on the browsers they need to support.

Third, the type="number" widgets may not behave well with humanized text. For example a value of "1,234" will not work with the up/down buttons provided by safari. This is the case for me in Safari and is one of the things that immediately put a roadblock up for me with the html5 input types. (I actually filed it as a comment with the W3C for clarification but I think that's likely a black hole.) I'm still trying to figure out who can answer this question for me.

Anyway, I think for these reasons it would be good to have a switch to turn off the type="whatever" on a per-application as well as a per-widget basis. Do you have any thoughts on how this should be implemented?

Allow floppyforms to override default form widgets

Currently the documentation states "As for ModelForms, all the fields coming from the model still get a widget from django.forms and not from floppyforms, unless the widgets are overridden in the form’s Meta inner class." The reason for this is because Django has no officially sanctioned way for a form library to override this. The unofficial way would be to override the formfield_callback method but due to a quirk in Django's behavior, that gets lost in the inheritance chain.

There has been some discussion of how to best achieve this but no decisions have been made yet. We want to pick an implementation that is along the design path of Django itself.

Form Layouts - change row template based on field type

I'm really liking floppyforms but there's one thing I haven't figured out, even after reading the source.
I want to be able to use a generic form layout that can use different row templates for different widget types (or have type in the context for the row template to do conditionals). The use case for this is where the label's relationship to the field might be different.

e.g. a BooleanField should generate the following row code (bootstrap style)

<div class="controls">
    <label class="checkbox"><input type="checkbox"> Remember me</label>
</div>

instead of

<label class="control-label">Remember me:</label>
<div class="controls">
    <input type="checkbox">
</div>

which would otherwise be fine for a text input.

If I missed something give me a clue and I'll write up a pull request for the documentation when I've got it worked out. Otherwise I would like to make a feature request.

Default template gets fields printed multiple times with formset

https://github.com/brutasse/django-floppyforms/blob/master/floppyforms/templates/floppyforms/layouts/p.html#L9

formconfig is set on forloop.last, but that only applies to the for field loop. There's a outer loop too, and if forconfig is set, formconfig isn't reset for the next form you loop over. Simply doing:

{% if forloop.last %}
    {% formconfig row with hidden_fields=settings.hidden_fields %}
{% else %}
    {% formconfig row with hidden_fields=None %}
{% endif %}

Solves the problem.

(Also: formatting the templates like that makes these kinds of bugs very hard to find)

Widget type not used for extra fields on ModelForm

Per the issue title, specifying a widget type doesn't work when adding extra fields to a form. Example:

class TestForm(ModelForm):
    should_be_hidden = CharField()

    class Meta:
        widgets = {
                'should_be_hidden':  HiddenInput
        }

In this case, should_be_hidden appears as a normal input box regardless of what I set in the widgets dict. This is true for both additional form fields and overridden form fields.

using "only" breaks form layout use of {% formconfig %}

{% formconfig %} only works in the context of a {% form %} tag. To know whether it's in such a context, it checks for the presence of a particular context variable (_form_render).

Unfortunately, if only is set on a {% form %} tag, the _form_render variable is not passed in (because it's set as part of the outer context rather than the inner context.)

I believe the solution would be as simple as setting _form_render in get_extra_context instead of in render.

decimalfield should specify step=any

To avoid a validation error in chrome when entering decimals, the DecimalField template should specify

<input type="number" step="any" />

See: http://blog.isotoma.com/2012/03/html5-input-typenumber-and-decimalsfloats-in-chrome/

What I have done so far is this:

Added this to input.html:

{% if attrs.decimal %}step="any"{% endif %}

And created a new widget like this:

class DecimalInput(floppyforms.widgets.NumberInput):
    def __init__(self, *args, **kwargs):
        kwargs['attrs'] = {'decimal':True}
        super(DecimalWidget, self).__init__(*args, **kwargs)

bug SelectDateWidget

Hi.
Sorry for my bad english.
I found a bug :
The SelectDateWidget has not empty choice ( ----- choices).
The class has a none_value, but it isn't use.
The problem is :
the fisrt load of the page, the selectDateWideget has already value selected.
My solution :

    none_value = ('', '---')
    #none_value = (0, '---')
    def render(self, name, value, attrs=None, extra_context={}):
    try:
        year_val, month_val, day_val = value.year, value.month, value.day
    except AttributeError:
        year_val = month_val = day_val = None
        if isinstance(value, basestring):
            if settings.USE_L10N:
                try:
                    input_format = formats.get_format(
                        'DATE_INPUT_FORMATS'
                    )[0]
                    v = datetime.datetime.strptime(value, input_format)
                    year_val, month_val, day_val = v.year, v.month, v.day
                except ValueError:
                    pass
            else:
                match = RE_DATE.match(value)
                if match:
                    year_val, month_val, day_val = map(int, match.groups())

    context = self.get_context(name, value, attrs=attrs,
                               extra_context=extra_context)

    context['year_choices'] = [self.none_value]+[(i, i) for i in self.years]
    #context['year_choices'] = [(i, i) for i in self.years]
    context['year_val'] = year_val

    context['month_choices'] = [self.none_value]+MONTHS.items()
    #context['month_choices'] = MONTHS.items()
    context['month_val'] = month_val

    context['day_choices'] =[self.none_value] + [(i, i) for i in range(1, 32)]
    #context['day_choices'] = [(i, i) for i in range(1, 32)]
    context['day_val'] = day_val

    return loader.render_to_string(self.template_name, context)

Thx

Changing default widget class attribute for all widgets

Is there a way to change the default CSS class for widgets ? I am trying to use Bootstrap 3, and form widgets need a class form-control to be displayed properly. I can't seem to find a way to do it without writing lots of code...

SelectDateWidget fault during rendering

Hi there,

I discovered that the rendering of a SelectDateWidget makes a fault when rendering the value. It expects a date object or a unicode string, but it receives a normal string.
I'm using floppyforms-1.1.
The mistake appears to be made in the 'def value_from_datadict' (line 649) here the date value is returned as a normal string while the 'def render' expects a unicode string -> if isinstance(value, six.text_type): (line 607).

The steps i follow to reproduce this error:
When i update a form that contains a SelectDateWidget field and during the update a validation error occurs (on an other field than the SelectDateWidget), the SelectDateWidget doesn't render the persistent date and the view displays the default date and not the actual persistent date.

Pass dynamic param to widget

Hi,

I have tried to pass a dynamic paramater to get_context_data without success (I don't wan't to just add a static value to context like shown in the doc examples). I can't find a solution to achieve this.
I have a form with this field : forms.PolygonField(widget=PolygonWidget(foo=bar))
I have to use __init__(self, **kwargs), and I get this parameter inside init method, but can't find a solution to get in in the get_context_data method.

(Also, I don't understand where render method is used for gis fields, it doesn't seem to be called ?)

Any idea ?

Thanks

Date formatting of input type=date value attribute should always be rfc3339

Certain cases with regards to how floppyforms handles date/time types is broken. For example, this code (which is arguably wrong but works in django):

date = forms.DateField(label=_('Date'), initial=lambda: datetime.now())

Here we have a form that is a DateField but the underlying model is a DateTime. This will output an input type like:

<input type="date" name="date" value="2012-01-15 17:24:06.987060" required="" id="id_date">

.. which is different than the django output as well as immediately invalid under html5. Two issues conspire to make it difficult to resolve:

  • Most browsers have poor or broken implementations of date/time pickers and no way to enable disable them other than setting input type="text"
  • The formats allowed by the HTML specification for the value parameter are very restrictive and not compatible with localization.

I brought this up in the django-devlopers group but it affects this project as well. It is possible to have a date input type with a value that doesn't match the format (try setting the default of a Date form field that has a datetime object in the model) which will be instantly flagged as invalid by the browser.

  • Technically, localization should be ignored and output of dates should always be rfc3339 full-date types. I am not sure if this is suitable.
  • It would be nice to be able to switch certain html5 features on and off on a per-request basis.

I am not sure how much effort is going to go into this project now that django 1.4 is doing something similar but I figured I'd get it documented here.

ModelForms appear to be ignoring model field validators

I've run into a case using a ModelForm where a field's validators are not being run.

For example:

models.py

import re
from django.core.validators import RegexValidator
from django.db import models

prefix_regex = re.compile(r'^[a-z]+[a-z0-9-]{3,61}$', re.IGNORECASE)

class Business(models.Model):
    ...
    url_prefix = models.CharField(..., validators=[RegexValidator(regex=prefix_regex, message='Please enter a valid prefix')])

forms.py

import floppyforms as forms
from .models import Business

class PrefixForm(forms.ModelForm):

    class Meta:
        model = Business
        fields = ('url_prefix', )
        widgets = {'url_prefix': forms.TextInput}

Given this code, I wasn't getting any validation errors -ever-. I had to change the form to the following:

forms.py

import floppyforms as forms
from .models import Business, prefix_regex

class PrefixForm(forms.ModelForm):
    url_prefix = forms.RegexField(..., regex=prefix_regex)

    class Meta:
        model = Business
        fields = ('url_prefix', )

With this, I finally got an error of "Enter a valid value."

I couldn't find any documentation of this behaviour; only of the necessity to redefine widgets. Is there any way to get this validation to climb back up the chain, or do I need to redefine the validation for every model field using validators?

Javascript check for input type

In datepicker example you are using " var type = $('').attr('type');".

Chrome v.16 always returns "date" (as well as firefox). I'm using a "modernizr" library to check for support and it works fine.. maybe you could mention that in docs ?

There's still a mess with html5 browser support.

Thanks

Floppyforms incompatible with pgettext_lazy

In the past I've been able to add translation context with this pattern on models:

from django.utils.translation import pgettext_lazy
....

my_thing = models.CharField(
    pgettext_lazy('Context for this widget','Name'),
    blank=True,
    max_length=200)

When you try to render a model form with this I get:

{% load floppyforms %}
{% form my_form %}


...
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/debug.py" in render_node
  74.             return node.render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/floppyforms/templatetags/floppyforms.py" in render
  462.             output = nodelist.render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/base.py" in render
  140.             return self._render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/test/utils.py" in instrumented_test_render
  62.     return self.nodelist.render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/base.py" in render
  823.                 bit = self.render_node(node, context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/debug.py" in render_node
  74.             return node.render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  53.             result = self.nodelist.render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/base.py" in render
  823.                 bit = self.render_node(node, context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/debug.py" in render_node
  74.             return node.render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/defaulttags.py" in render
  185.                         nodelist.append(node.render(context))
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/defaulttags.py" in render
  476.         output = self.nodelist.render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/base.py" in render
  823.                 bit = self.render_node(node, context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/debug.py" in render_node
  74.             return node.render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  53.             result = self.nodelist.render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/base.py" in render
  823.                 bit = self.render_node(node, context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/debug.py" in render_node
  74.             return node.render(context)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/template/debug.py" in render
  87.             output = force_unicode(output)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/utils/encoding.py" in force_unicode
  71.                 s = unicode(s)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/utils/functional.py" in __unicode_cast
  121.             return func(*self.__args, **self.__kw)
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/utils/text.py" in <lambda>
  17. capfirst = lambda x: x and force_unicode(x)[0].upper() + force_unicode(x)[1:]
File "/Users/poswald/Projects/env/lib/python2.7/site-packages/django/utils/functional.py" in __wrapper__
  112.                 raise TypeError("Lazy object returned unexpected type.")

Extra attributes to hidden fields are not parsed by default

This took me by surprise while porting an existing app to use floppyforms. All of a sudden, the input type="hidden" in my ModelForm no longer had any of their extra attributes

Slightly reduced code:

class HiddenMapInput(HiddenInput):
    def __init__(self, map, maptype, *args, **kwargs):
        kwargs.setdefault("attrs", {"data-map": map, "data-maptype": maptype})
        super(HiddenMapInput, self).__init__(*args, **kwargs)

class MerchantForm(ModelForm):
    class Meta:
        widgets = {
            "latitude": HiddenMapInput("merchant_coords", "latitude"),
        }

I tracked it down to templates/floppyforms/layouts/p.html, in the formconfig line for hidden fields. We then end up here in templates/floppyforms/rows/p.html:
{% block hidden_fields %}{% for field in hidden_fields %}{{ field.as_hidden }}{% endfor %}{% endblock %}

This calls django.forms.BoundField.as_hidden(), which takes an attrs=None argument. So of course the extra attributes disappear here.

Switching to just {{ field }} fixes the issue but I'm not sure about the implications.

floppyforms/select.html multiple variable does nothing

The {% if multiple %} in select.html appears to me to do nothing. The addition of multiple="multiple" is done in attrs.html.

The existence of if multiple seems to imply the variable can be used but it can't actually. IMO it would be nice to have this variable as it may be desirable to change the select if it is multiple.

mark_safe

The as_XXX methods don't use mark_safe (opposed to the standard django as_XXX methods).
Is this intentional?

Render widget using formfield tag problem

Hello,

I have got some troubles with formfield. I tried something like:

{% form form using %}
{% formfield form.price using "foo/input.html" with custom_attr="bar" type="number" %}
{% endform %}

And, it doesn't use my template foo/input.html, neither add any/change any attributes on the widget.

I took a look at the code, and I don't understand how it works using floppyform template rendering, as this line:
https://github.com/brutasse/django-floppyforms/blob/master/floppyforms/templatetags/floppyforms.py#L636 calls the as_widget() function from django widgets.py

Cheers,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.