Code Monkey home page Code Monkey logo

django-crispy-forms's Introduction

django-crispy-forms

http://codecov.io/github/django-crispy-forms/django-crispy-forms/coverage.svg?branch=main

The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered HTML without writing HTML in templates. All this without breaking the standard way of doing things in Django, so it plays nice with any other form application.

django-crispy-forms supports Django 4.2+ with Python 3.8+.

Looking for Bootstrap 5 support? See the crispy-bootstrap5 package.

The application mainly provides:

  • A filter named |crispy that will render elegant div based forms. Think of it as the built-in methods: as_table, as_ul and as_p. You cannot tune up the output, but it is easy to start using it.
  • A tag named {% crispy %} that will render a form based on your configuration and specific layout setup. This gives you amazing power without much hassle, helping you save tons of time.

Django-crispy-forms supports several frontend frameworks, such as Twitter Bootstrap (versions 2, 3, and 4), tailwind, Bulma and Foundation. You can also easily adapt your custom company's one, creating your own, see the docs for more information. You can easily switch among them using CRISPY_TEMPLATE_PACK setting variable.

Authors

django-crispy-forms is the new django-uni-form. django-uni-form was an application created by Daniel Greenfeld that I led since version 0.8.0. The name change tries to better explain the purpose of the application, which changed in a significant way since its birth.

If you are upgrading from django-uni-form, we have instructions for helping you.

Example

This is a teaser of what you can do with latest django-crispy-forms. Find here the gist for generating this form:

http://i.imgur.com/LSREg.png

Documentation

For extensive documentation see the docs folder or read it on readthedocs

Special thanks

  • To Daniel Feldroy (@pydanny) for his support, time and the opportunity given to me to do this.
  • The name of the project was suggested by the fantastic Audrey Feldroy (@audreyfeldroy)
  • To Kenneth Love (@kennethlove) for creating django-uni-form-contrib from which bootstrap template pack was started.

django-crispy-forms's People

Contributors

agentk avatar amishbni avatar beezz avatar bmihelac avatar bryan-brancotte avatar carltongibson avatar ckrybus avatar cpina avatar davidszotten avatar dbinit avatar fin avatar graystevens avatar illia-v avatar j0hnsmith avatar jamesmfriedman avatar jcomeauictx avatar kavdev avatar laplacesdemon avatar maraujop avatar meshy avatar michael-k avatar mrkre avatar pydanny avatar simonpanay avatar smithdc1 avatar staaas avatar theromis avatar tomyam1-personal avatar treyhunner avatar zoidyzoidzoid 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  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

django-crispy-forms's Issues

Suggestion: autocomplete

With my app I need to disable form autocomplete. Rather than have to add my own form tags it would be nice if it were possible to do this:

self.helper.form_autocomplete = 'on' (or off)

Which would then add 'autocomplete="on"' to the form tag.

How to disable/readonly all fields?

(notice i have posted the same question to django.users)

I have a model that i would like to create/read/update and delete
(CRUD); i'm using generic views (create_update) to do that. Also i'm
using crispy forms to do the form (layout) styling icw twitter-
bootstrap styling. Now the thing i'm not sure about is how to do the
'read' function. I prefer to show a similar page as the update
function but then without a button and with all fields set to readonly
mode (or disabled). How could i do that with crispy forms?

The solution i have now:

  • I created a form class that has the FormHelper
  • From the urlconf i first route to my own view function to retrieve
    the object (to read)
  • Then i call object_detail (from generic views) with extra_context
    that has the form initialized with the object to read: extra_context =
    {'form': ReadForm(instance = object)},
  • Then in the template i simply invoke crispy forms to display the
    'form'
  • to replace the <input ...> with <span class-"uneditable-input">... i subclassed the crispy-tag and then post-process the html using re's. Offcourse this will only work as long as the raw html is compatible with the re's.... which is the reason i don't like it.

A better solution is probably to create custom templates for the field but i'm missing complete and working examples to do that. And also since the crispy (field) template invoke tags again that render other templates (and so on...) it's difficult to reach the same quality level.

The BEST approach would offcourse be to have support from the crispy-forms module, using an attribute of some kind.

Paul

class CrispyUneditable(UniFormNode):
'''subclass the crispy tag to modify the tags output: each input
field shall be uneditable using bootstraps uneditable styling'''
def render(self, context):
import re
value = super(CrispyUneditable, self).render(context)
return re.sub(
r'<input (.?) value="([^"]?)" class="([^"])" (.?)>',
r'\2', value)

{% crispy-uneditable %} tag

@register.tag(name="crispy-uneditable")
def do_crispy_uneditable_form(parser, token):
token = token.split_contents()
form = token.pop(1)

try: 
    helper = token.pop(1) 
except IndexError: 
    helper = None 


return CrispyUneditable(form, helper)

Insert something at the end of ModelForm

When using forms.ModelForm, this code

helper = FormHelper()
helper.form_class = 'form-horizontal'
helper.layout = Layout(
    FormActions(
        Submit('save_changes', 'Save', css_class='btn-primary'),
        Submit('cancel', 'Cancel'),
    )
)

would first produce the buttons (FormActions), and only then the fields based on model. Obviously I'd want FormActions to appear in the end of the form and not the beginning.

How can I do that without mentioning the fields in Layout()?

Thank you!

How to use django crispy forms with django inline formsets?? (Solved)

Hello,

I was wondering if it is possible to use django crispy forms with django inline formsets, and if so how can that be accomplished?

I have two models related via a foreign key. I am using an inlineformset_factory for processing models inside a django view and for displaying (rendering in a template) I would like to use advantages of crispy forms.

I tried following in my template:

< form method="post" action="" >
       
   {% load crispy_forms_tags %}
   {% crispy form %}
   {% crispy formset %}

   <input class="submit" type="submit" value="Submit data">

</form>

There are a few problems with this:

  1. There are two forms (form and formset) rendered inside another form which I don't like at all :-), like this:
<form>
    <form name=โ€crispy_formโ€>โ€dataโ€</form>
    <form name=โ€crispy_formsetโ€>โ€dataโ€</form>
    <input class="submit" type="submit" value="Submit data">
</form>
  1. ManagementForm data is not rendered (form-TOTAL_FORMS, form-INITIAL_FORMS and form-MAX_NUM_FORMS).

  2. Submit button posts no data to server for processing because the outer form doesn't have any data. This problem can be resolved using javascript code to submit both forms but this is not the django way :-).

If necessary I could post a full example with models, forms, view, url and html template.
I am using django-crispy-forms version 1.1.2-0

Thank You

Append and Prepend simultaneously

Hello,

Great app, thw for sharing.
Here I propose you a append-prepend-text for bootstrap :

in bootstrap.py

class AppendedPrependedText(Field):
    template = "bootstrap/layout/appended_prepended_text.html"

    def __init__(self, field, prepended_text, appended_text, *args, **kwargs):
        self.appended_text = appended_text
        self.prepended_text = prepended_text
        if 'active' in kwargs:
            self.active = kwargs.pop('active')

        super(AppendedPrependedText, self).__init__(field, *args, **kwargs)

    def render(self, form, form_style, context):
        context.update({'crispy_appended_text': self.appended_text, 
                        'crispy_prepended_text': self.prepended_text,
                        'active': getattr(self, "active", False)})
        return render_field(self.field, form, form_style, context, template=self.template, attrs=self.attrs)

and custom template

{% load crispy_forms_field %}

<div id="div_{{ field.auto_id }}" class="clearfix control-group{% if field.errors %} error{% endif %} {% if field.field.widget.attrs.class %} {{ field.field.widget.attrs.class }}{% endif %}">

    {% if field.label %}
        <label for="{{ field.id_for_label }}" class="control-label {% if field.field.required %}requiredField{% endif %}">
            {{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
        </label>
    {% endif %}

    <div class="controls">
        <div class="input-prepend">
            <span class="add-on {% if active %}active{% endif %}">{{ crispy_prepended_text|safe }}</span>
            {% crispy_field field %}
            <span class="add-on {% if active %}active{% endif %}">{{ crispy_appended_text|safe }}</span>
            {% include 'bootstrap/layout/field_errors.html' %}
        </div>
        {% include 'bootstrap/layout/help_text.html' %}
    </div>
</div>

RadioSelect widget doesn't work correctly

I'm trying to make my crispy forms work with formwizard and bootstrap. I noticed that the form wasn't working with a ChoiceField that had a RadioSelect widget.

I tracked it down to the fact that the crispy forms templates render most fields as {% crispy_field field %}, but the RadioSelect uses an {% include %} tag that uses the radioselect.html template. This template appears to work, but puts the wrong value in name="" for the input.

I'm not sure what the "right" answer to this problem is. For now, I have changed my radioselect.html template to use {{ field.html_name }} instead of field.name, which makes things work. But the bigger question in my mind is: Is this the right way to do things? I.e., should we still be using radioselect.html to render a RadioSelect widget, or should we be using the widgets normal as_widget function, like the others? Of course the problem with doing that is that it wraps the 's in a <ul>, which is undesirable.

Looking forward to discussion on this.

-PT

Table-based formset rendering

Hello.

I'm currently rendering a formset, where every row of a table is a form from the formset. I'm not using Div as a layout object because, in this case, a table is the semantically the right way of doing it.

It looks like this: http://d.pr/i/Mgwa

I tackled the problem creating a TR and TD Layout object and a custom template (because I don't render formset errors inline), but before that, I tried using {{ field | as_crispy_field}} and {% crispy_field field %} (this was a longshot) over every form in the formset, but these doesn't work with formsets.

Using the layout objects worked. What do you think of it? Would it be better if as_crispy_field supported formsets?

Helper attribute form_action allow arguments to url template tag?

Does the helper attribute form_action allow for arguments to the url template tag?

For example, I have an html

tag looks like:

I tried setting the form _action helper attribute like this:

self.helper.form_action = 'event_resource event.id'

and it did not work. It got translated to: ../event_resource%20event.id

Thanks,
Jim

Removal of whitespace in generated HTML

This might sound a bit anal - bit would it be possible to remove the huge amounts of whitespace in the generated HTML?

I've no problem doing this myself and generating a pull request - but don't want to waste my time if there's some valid reason for it.

Layout files doing untyped comparison

For example here: https://github.com/maraujop/django-crispy-forms/blob/dev/crispy_forms/templates/bootstrap/layout/radioselect.html#L6

The problem with this is that choice.0 and field.value may not be of the same type as field.value has already been cast to a string. This is particularly problematic with fields where choices are used to represent integers or booleans. Similar problems exist in checkboxselectmultiple.html

I have a fix for it, but it's really quite unpleasant, and is doing type casts in the template which seems pretty wrong to me.

Feature request: per-form CRISPY_TEMPLATE_PACK setting

Hi, thanks for a very nice lib.

While implementing the site, I've met up with the following issue:

As the public pages of my site do not use bootstrap, I'm using uni-form template pack.
The admin (non-django part) uses bootstrap.

Currently, as far as I know, it's impossible to use different template packs within a single django instance.

I've come up with using monkeypatch decorators for the forms, which patch global values in your code, while rendering the form. The other solution I saw, was splitting the admin, and the public part into different django sites, but that was not a solution that I'd be comfortable with.

Doing this seems like a lot of work, but I think it's reasonable. How do you think, maraujop, is it possible?

Thanks.

Hidden fields

Hello

I require to be able to create a hidden field in a layout of a model form.

I had expected to be able to use this:

Hidden ('sample', '{{ sample }}')

However, the value of the hidden field is not translated by the template and therefore is represented by value="{{ security_hash }}"

Am I missing something from the documentation, or was this not it's intended use?

Thank you

Ascii/Unicode error

I have a model with:

tags = ManyToManyField(Tag, null=True)

Tag is a simple model with a CharField. The tags field is included in my form without modification (in a Fieldset, no custom widget). I have recently added a non-ascii tag, eg "Tรฉstiรฑg". This causes a UnicodeEncodeError when displaying {% crispy form %}.

Django, my filesystem (OS X) and my database (Postgres) are all Unicode-aware, so I believe this is an issue with Crispy. Unicode issues can be tricky to diagnose, so please let me know if you'd like to know more about any part of my environment or configuration.

No CrispyFormMixin

Some of us love when there is a bit more magic.

I use a mixin class in all of my projects witch use uni_form or crispy_forms.

My MixIn class just add a simple property, here it is:

@property
def helper(self):
    helper = helpers.FormHelper()

    if hasattr(self, "parent_url"):
        back = helpers.Button('back', 'Retour')
        back.field_classes += ' primaryAction'
        helper.add_input(back)

    reset = helpers.Reset('reset', 'Dรฉfaire')
    reset.field_classes += ' primaryAction'
    helper.add_input(reset)

    submit = helpers.Submit('submit', 'Valider')
    submit.field_classes += ' primaryAction'
    helper.add_input(submit)

    helper.form_method = getattr(self, "form_method", 'POST')

    if hasattr(self, "action_url"):
        helper.form_action = self.action_url

    if hasattr(self, "form_style"):
        helper.form_style = self.form_style
        if not hasattr(self, "form_layout"):
            helper.add_layout(helpers.Layout(helpers.Fieldset("",*self.fields.keys())))
    if hasattr(self, "form_layout"):
        fs=[]
        for name, fields in self.form_layout.iteritems():
            fs.append(helpers.Fieldset(name, *fields))
        helper.add_layout(helpers.Layout(*fs))

    return helper

You want Fancy Formsets?

Hi

I just shared an extension to crispy-forms at https://github.com/runekaagaard/django-crispy-forms-fancy-formsets, that basically makes it easy to render multiple dynamic inline formsets on a page. It's very young, and the API needs a lot of factoring. I was wondering if it would be interesting to merge this functionality into crispy-forms or it should stay a standalone extension? This decision would help me make the API go in the right direction.

There is a screenshot here: https://github.com/runekaagaard/django-crispy-forms-fancy-formsets/blob/master/screenshots/fancy_formsets.png.

Thanks for your time!
Rune Kaagaard

Problems with load date field in a EditForm with crispy-forms

Hello everybody!
I am using crispy-forms with bootstrap datepicker, I can save the form, but in edit page the date is not showing in template.

This is the code:

in editForm

def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        Div('date_end', id="date_end", template='project/util/datepicker_end.html'),    

the datepicker_end.html

<div class="input-append date" id="date_end" data-date="{% now 'd-m-Y' %}" data-date-format="dd-mm-yyyy">
<label for="id_date_end">Date end:</label>
<input type="text" name="date_end" id="id_date_end" readonly="readonly" class="input-small"><span id="datepicker-icon" class="add-on"><i class="icon-calendar"></i></span>
</div>

The output of print form(the date is comming in form, but is not rendered):

  <tr><th><label for="id_date_end" class="required">Date end: *</label></th><td><input type="text" name="date_end" value="31-05-2012" id="id_date_end" /></td></tr>

This result in a empty field:
http://postimage.org/image/r9wqfyrvf/

Is a bug?
Regards!

Django-crispy-forms and django-uni-form-contrib : twitter-bootstrap templates

Hello,
maybe and surely it's and update needed for django-uni-form-contrib.

Of course the {% load uni_form_field %} raise an error at django startup when only crispy is installed.

What is the way to modify django-uni-form-contrib twitter-bootstrap templates to have them running with crispy ?

If you can provide informations for that I'll do it (I know it's maybe only an rpl job under Linux).

Thanks for the job to all contributors.

regards

Alain

Fieldset and Multifield should not accept non basestring objects

While it may sound against Python's duck typing philosophy, this can lead to annoying bugs. If you pass it a layout object as the first item, it's converted to unicode and put in the template. Since it is done immediately after instantiation, there is no advantage over requiring it to be done outside.

django-crispy-forms and django-sekizai and django-jinja2

Hey,

using the above combination of modules results in an error (looks like a circular import on find_template_loader):

(djangocms)cmstest@dev:~/djangocms/project/subproject/toxavis$ python manage.py runserver 0.0.0.0:8000 --settings=settings_panni
Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    execute_manager(settings)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/devserver/management/commands/runserver.py", line 70, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/core/management/base.py", line 209, in execute
    translation.activate('en-us')
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/utils/translation/__init__.py", line 100, in activate
    return _trans.activate(language)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 202, in activate
    _active.value = translation(language)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 185, in translation
    default_translation = _fetch(settings.LANGUAGE_CODE)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 162, in _fetch
    app = import_module(appname)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/cms/__init__.py", line 9, in <module>
    patch_settings()
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/cms/conf/__init__.py", line 32, in patch_settings
    post_patch_check()
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/cms/conf/patch.py", line 56, in post_patch_check
    if not validate_template(template[0], ['js', 'css']):
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django_sekizai-0.5-py2.6.egg/sekizai/helpers.py", line 86, in validate_template
    found = get_namespaces(template)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django_sekizai-0.5-py2.6.egg/sekizai/helpers.py", line 76, in get_namespaces
    compiled_template = get_template(template)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/template/loader.py", line 157, in get_template
    template, origin = find_template(template_name)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/template/loader.py", line 128, in find_template
    loader = find_template_loader(loader_name)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/template/loader.py", line 95, in find_template_loader
    mod = import_module(module)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django_jinja/loaders.py", line 7, in <module>
    from django_jinja.base import env
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django_jinja/base.py", line 173, in <module>
    env = Environment(**initial_params)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django_jinja/base.py", line 94, in __init__
    filemod = import_module(file_mod_path)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/crispy_forms/templatetags/crispy_forms_filters.py", line 8, in <module>
    from crispy_forms.helper import FormHelper
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/crispy_forms/helper.py", line 4, in <module>
    from utils import render_field
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/crispy_forms/utils.py", line 14, in <module>
    default_field_template = get_template("%s/field.html" % TEMPLATE_PACK)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/template/loader.py", line 157, in get_template
    template, origin = find_template(template_name)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/template/loader.py", line 128, in find_template
    loader = find_template_loader(loader_name)
  File "/home/cmstest/djangocms/lib/python2.6/site-packages/django/template/loader.py", line 101, in find_template_loader
    raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
django.core.exceptions.ImproperlyConfigured: Error importing template source loader django_jinja.loaders.FileSystemLoader: "'module' object has no attribute 'FileSystemLoader'"

TEMPLATE_LOADERS is

(
    'django_jinja.loaders.FileSystemLoader',
    'django_jinja.loaders.AppLoader',
)

baseinput.html template should not slugify or modify the input field name

The "uni_form/layout/baseinput.html" contains a line to slugify the input field name, however this should be conditional or disabled when the Layout is defined.

Example:

hidden = Hidden('callbackURL', 'http://www.google.com')

renders the following HTML:

<input type="hidden" name="callbackurl" value="http://www.google.com">

This is incorrect, as the camel-casing should be preserved. The correct rendered HTML should be instead:

<input type="hidden" name="callbackURL" value="http://www.google.com">

Missing baseinput.html template for Bootstrap

It seems 1.1 was released with a missing template: .../bootstrap/layout/baseinput.html. This shows up as an include in .../bootstrap/whole_uni_form.html:

{% include "bootstrap/layout/baseinput.html" %}

Alas, no such file exists for the Bootstrap templates. I tried adding it to my project-specific templates, but for some reason it doesn't load properly and I still get: TemplateDoesNotExist: bootstrap/layout/baseinput.html.

bootstrap button of type submit

I am currently using a FormActions layout inside my Helper

    f1 = Div('username', css_class='form-block')
    f2 = Div('password', css_class='form-block last')
    f3 = FormActions(Submit('submit', 'Submit', css_class='btn-primary'))
    helper.add_layout(Fieldset(_(u'Sign In To Your Account'), f1, f2, f3))

The markup I get from this gives me a

<input type="submit" />

If I use

   f3 = FormActions(Button('submit', 'Submit', css_class='btn-primary'))

The markup I get from this gives me

 <input type="button"/>

How do i get

<button type="submit"/>

Do i need to write my own layout template?

Error using deepcopy after update (to commit b00c0e12bccb03f69027df2d0617305bc8d69f8a)

Not sure whether opening an issue for this is the right thing to do, pls close it when its not needed.

I created a fork and cloned it, then added a link from my existing application towards the clone. Reload page: error 500!

My unittests show a problem with deepcopy; which indeed is added with this newer version (not sure since when though).

Appears to be a problem with some string somewhere in the context; how to debug this? how to solve it?

Paul


Traceback (most recent call last):
File "/home/p/d/site/project/apps/accounts/tests/test_website.py", line 12, in testLoginRequired
self.assertRedirects(response, reverse('auth_login') + '?next=' + reverse(url))
File "/home/p/d/site/local/lib/python2.7/site-packages/django/test/testcases.py", line 582, in assertRedirects
redirect_response = response.client.get(path, QueryDict(query))
File "/home/p/d/site/local/lib/python2.7/site-packages/django/test/client.py", line 439, in get
response = super(Client, self).get(path, data=data, **extra)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/test/client.py", line 244, in get
return self.request(**r)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 136, in get_response
response = response.render()
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/response.py", line 104, in render
self._set_content(self.rendered_content)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/response.py", line 81, in rendered_content
content = template.render(context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/base.py", line 140, in render
return self._render(context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/test/utils.py", line 62, in instrumented_test_render
return self.nodelist.render(context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/base.py", line 823, in render
bit = self.render_node(node, context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/debug.py", line 74, in render_node
return node.render(context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 123, in render
return compiled_parent._render(context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/test/utils.py", line 62, in instrumented_test_render
return self.nodelist.render(context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/base.py", line 823, in render
bit = self.render_node(node, context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/debug.py", line 74, in render_node
return node.render(context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/base.py", line 823, in render
bit = self.render_node(node, context)
File "/home/p/d/site/local/lib/python2.7/site-packages/django/template/debug.py", line 74, in render_node
return node.render(context)
File "/home/p/d/site/local/lib/python2.7/site-packages/crispy_forms/templatetags/crispy_forms_tags.py", line 173, in render
c = self.get_render(context)
File "/home/p/d/site/local/lib/python2.7/site-packages/crispy_forms/templatetags/crispy_forms_tags.py", line 108, in get_render
node_context = deepcopy(context)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 230, in _deepcopy_list
y.append(deepcopy(a, memo))
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 329, in _reconstruct
y = callable(*args)
File "/home/p/d/site/lib/python2.7/copy_reg.py", line 93, in newobj
return cls.new(cls, *args)
TypeError: object.new(cStringIO.StringI) is not safe, use cStringIO.StringI.new()

Layout doesn't exclude fields

According to the docs: "By default django-crispy-forms renders the layout specified if it exists strictly, which means it only renders what the layout mentions, unless your form has Meta.fields and Meta.exclude defined, in that case it uses them."

I've set helpers.layout, which renders my specified fieldsets correctly. However, following those fields, all other fields are also displayed. Are the docs correct?

Code snippet:

class FooForm(ModelForm):
    class Meta:
        model = Foo
        widgets = {
            [...]
        }

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Fieldset(
                [...]
            ),
        )
        super(FooForm, self).__init__(*args, **kwargs)

Problem viewing docs

Any time I try viewing the docs I'm seeing this alert saying "For security reasons, framing is not allowed." which redirects to a github 404 page.

AppendedText ignores form_show_errors flag

Unfortunately the great form_show_error flag is ignored by the AppendedText layout template (templates/bootstrap/layout/appended_text.html ). I guess, it should be changed from

... {% if field.errors %} error{% endif %}...

to:

... {% if form_show_errors and field.errors %} error{% endif %} ...

The same goes for the templates/bootstrap/layout/prepended_text.html template.

HTML5 tag attributes containing -, raises Exception

Whenever we use an attribute containing the minus sign it gives an exception, since Python understands as a subtraction. Maybe I'm unaware of a work-around of it, but yeah, maybe there's no work-around.

Great work guys! Great django app!

Enable errors by default for |crispy filter

When using the |as_crispy filter, errors are currently not shown at all (they should be shown by default and ideally it would be configurable). I presume this is due to the fact that the template checks for form_show_errors, which isn't present when using the filter.

Template issue

Hi Miguel,

the template field.strict.html of bootstrap pack doesn't correspond to the Bootstrap guidelines. I think it's the same as the uni_form. BTW, setting the attribute form_style of the Helper class to 'inline', should render this template with bootstrap template pack.

What do you think?

Templates for LayoutObjects

Hi @maraujop

I noticed two things (in the dev branch):

  1. Many classes inheriting from LayoutObject in crispy_forms.layout do not use settings.TEMPLATE_PACK at all, but some do (BaseInput, FIeld. Is there a reason for this? Currently I'm using settings.TEMPLATE_PACK and overwriting the template attribute in settings.py using
from crispy_forms.layout import MultiField;
MultiField.template = 'template-name/layout/multifield.html'

So while it might be an issue, there's still a workaround, however this isn't sufficient in my case, see the next thing
2. MultiField actually uses two templates: uni_form/layout/multifield.html and uni_form/multifield.html. However, you can only override one of them. I actually want to override uni_form/multifield.html (the template used for render_field). Why? I want to add css classes to the div.ctrlHolder wrapping the fields inside. If there's another way I'm missing, please let me know.

Error alerts

Miguel,

I've been working with error alerts and Bootstrap provides a JS plugin for a close icon. See here.

I was about to add it to a pull request, but thought it might need to be a configuration option. Any thoughts on how to implement? Especially since the same thing isn't available on uni-form.

For now I've just overridden the template with my own:

{% if form.non_field_errors %}
    <div class="alert alert-block alert-error fade in">
        <a class="close" data-dismiss="alert" href="#">&times;</a>
        {% if form_error_title %}<h4 class="alert-heading">{{ form_error_title }}</h4>{% endif %}
        <ul class="unstyled">
            {{ form.non_field_errors|unordered_list }}
        </ul>
    </div>
{% endif %}

I also changed the

    to
      because I think it looks nicer.

      It's obviously quite easy to just override the template, so that might be the best option.

Django datetime fields

Hi

Is there a recommended route to take when rendering django datetime fields? Currently they are rendered (for me) in one textbox such as 2012-03-16 12:03:29.

It would be very helpful to either split those like the django admin does.

Thank you for your efforts on this project. So far, it's a joy to work with.

Redisplaying form / ajax

Hello

Is it possible to redisplay a form by constructing the crispy form through a django view? I am trying to process a form, submit it through ajax, and then have the form regenerate and overwrite a div.

I was hoping to pass this through as a json.dumps(form) using HttpResponse.

Thank you

autocomplete from a model on a text_input field

Hello,

been using crispy for a few months and its worked everytime, keep up the good work, i have been asked to create a autocomplete field on a text_input field, data from either a list in the form or from a model, had a look around and tried to do this my self, but not having any luck.

My question is, is this possible todo with crispy and if so would there be any examples i could look at or any tips

Cheers

Rich

Inject a generic inline formset into a form with crispy-forms

Sorry for the issues, this time I need to inject an generic inline formset inside a form.
So, my form with the inline formset:

<form action="{% url 'add_cliente' %}" method="POST">{% csrf_token %}

<div class="well">
{{form}}
</div>

<div class="well">
{{ formset.management_form }}
{{ formset.non_form_errors }}
{{ formset }}
</div>

<div class="form-actions">
<input class="btn" type="submit" value="Cadastrar" />
</div>

</form>

How can I make a form with the cliente form and a endereco formset using the crispy-forms?
Regards!

Tiny cosmetic issue: space between buttons in FormActions (Bootstrap)

This code, when using the Bootstrap template

FormActions(
    Submit('save_changes', 'Save', css_class='btn-primary'),
    Submit('cancel', 'Cancel'),
)

generates the following

As you can see the buttons are aligned contiguously because there is no space between <input> tags, while all Bootstrap examples include the space.

A workaround would be to include HTML('&zwnj;') between Submits (and &nbsp; wouldn't do because for some reason it generates two spaces), but I think it should be fixed somewhere in templates. Here's how they should look:

Thanks for attention to my super tiny issue :)

Invalid HTML output

Moving this ticket from the old tracker: pydanny/django-uni-form#124 (comment)

Warning, I did not try the latest version of django crispy form, I'm still using django-uni-form. This may not be applicable anymore.

I have a gigantic layout, and part of it is:

   layout = Layout(
        super(ThisForm, self).get_layout(),
        MultiField(
            u'<h3>Section J</h3>',
            Div(*(
                ThisForm.get_section_j_fields() +
                [HTML("<a href='#' class='button button-next'>Next</a>")]
            )),
            css_id = "step9",
            css_class = "form-step"
        ),
       [...]

It produces the following HTML:

<p class="blockLabel"/><h3>Section J</h3><p/>

Notice that the first 'p' tag is self closed.

bootstrap single choice checkbox (django form booleanfield) has no a label tag

I have a form with a booleanfield in Django. The generated checkbox input under bootstrap form-horizontal template has no outter label tag, which causes the checkbox is not lining up with field label on the left.

Here is on the bootstrap documentation.

"Up to v1.4, Bootstrap required extra markup around checkboxes and radios to stack them. Now, it's a simple matter of repeating the <label class="checkbox"> that wraps the <input type="checkbox">."

Overriding ModelChoiceField

Hello

I have a modelform. One of the fields is modelchoicefield made up of users (using Django's built in Auth).

I need to override this so the first_name and last_name of the user are displayed instead of their username.

So I created a class:

class UserModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "%s (%s)" % (obj.get_full_name(), obj.username)

How can I override the field in Crispy Forms? or should I be using a custom template here?

    self.helper.layout = Layout(
        Div(
            Fieldset(
                'Key Information',
                'person',
                ),
            ),
        )

Thank you for any assistance

Passing initial null value?

I have a field which can take a null value (null=True). I'd like to pass null as the initial value to the form. I've tried the following:

widgets = { 'my_field': HiddenInput(attrs={'value': ''}) }

and

widgets = { 'my_field': HiddenInput(attrs={'value': None}) }

Neither one of these works. How can I initialize this field to a null value?

Integer choices on MultipleChoiceField with CheckboxSelectMultiple

When an integer is used as the value for a choice in MultipleChoiceFIeld with a CheckboxSelectMultipleWidget, initial values do not function.

form_field = forms.MultipleChoiceField(
    choices={
        (0, 'choice 0'),
        (1, 'choice 1'),
    ),
    initial=0,
    widget=forms.CheckboxSelectMultiple,
)

(Same behavior when re-rendering form with initial data from a previous POST/GET).

This is due to the "{% for x in y %}" functionality used in checkboxselectmultiple.html (and the radio box template). I'm filing a pull request that fixes this issue and contains more details.

Invalid block tag: 'crispy'

I've just upgraded to 1.1.0 (installed with pip, not dev branch) and am getting the following 'Invalid block tag' error when rendering a form that was working without issue before the upgrade.

snippet from template

{% block activation_content %}
    <div class="page-header">
        <h1>Add New Customer</h1>
    </div>
    {% crispy form form.helper %}
{% endblock %}

results in

Invalid block tag: 'crispy', expected 'endblock' or 'endblock activation_content'

To be sure i didn't have an unclosed tag somewhere i created the simplest possible template without any inheritance

{% load crispy_forms_tags %}
<html>
<head>
    <title>Test</title>
</head>
<body>
    <h1>Test Form</h1>
    {% crispy form form.helper %}
</body>
</html>

This results in

Invalid block tag: 'crispy'

Any ideas??

Thanks
Roger.

Fieldset labels are not translatable

Fieldset labels are currently converted to unicode in Fieldset constructor.
This makes it impossible to properly pass translatable strings to it since the translatable proxy string is immediately evaluated.

Consider this example:

class VenueForm(...):
    helper = FormHelper()
    helper.layout = Layout(
        Fieldset(_('Address'),
            'address_country',
            # ...

It will not work properly with multiple languages since _('Address') is evaluated to whichever language is active during the first request to the server when the VenueForm class is constructed.
Workaround is to move the helper construction into the form's constructor, but this is somewhat tedious, especially for smaller forms where you might otherwise not need the constructor. Plus it took me quite a while to discover what's wrong when I first ran into it.

The fix would be to either move the evalutation to unicode to the render method or to avoid it entirely and pass the translatable proxy string to the Django template used to render the fieldset.

The same problem is also present in MultiField and might be related to #56

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.