FileField with file extension whitelist
A simple FileField with a addition file extension whitelist. Raised ValidationError("Not allowed filetype!") if a filename contains a extension witch is not in the whitelist.
- forms
- filefield
A simple FileField with a addition file extension whitelist. Raised ValidationError("Not allowed filetype!") if a filename contains a extension witch is not in the whitelist.
Here is a class decorator that allows not to bother with stripping leading and trailing white space from user input provided via forms. This could be a temporary solution for an issue addressed in the ticket [#6362](http://code.djangoproject.com/ticket/6362). The documentation is provided in the form of doctest. The decorator works with `ModelForm`'s just as well as with ordinary forms. Note however that this is not a 100% panacea. Your models still could become malformed if theirs data is obtained from another source, not forms.
The original USPhoneNumberField only validates xxx-xxx-xxxx values. This field validates... > (xxx) xxx xxxx > xxx-xxx-xxxx > (xxx)-xxx-xxxx > many others. **Explanation of the regular expression:** 1. Accepts either (xxx) or xxx at the start of the value. 2. Allows for any amount of dashes and spaces (including none) before the next set of digits. 3. Accepts 3 digits 4. Allows for any amount of dashes and spaces (including none) before the next set of digits. 5. Accepts 4 digits, finishing the value. This field saves in the same format that the original USPhoneNumberField does (xxx-xxx-xxxx). Enjoy!
Django administration provides three buttons for submitting the currently edited object. Each of them has a unique name and depending on the name that is sent to the server, the specific action is performed. I see this as an ugly solution and prefer to have a choice field in the form which would render as submit buttons with different values. Then the values would be checked instead of the names. Therefore, I created the `MultipleSubmitButton` widget. When `<input type="submit" value="Go" />` is used, the value sent to the server always matches the text on the button, but if `<button type="submit" value="go">Go</button>`, the value and the human representation might differ. To use the `MultipleSubmitButton` widget, pass it to the widget parameter of a `ChoiceField` like this: SUBMIT_CHOICES = ( ('save', _("Save")), ('save-add', _("Save and Add Another")), ) class TestForm(forms.Form): do = forms.ChoiceField( widget=MultipleSubmitButton, choices=SUBMIT_CHOICES, ) When you print `{{ form.do }}` in the template, the following HTML will be rendered: <ul> <li><button type="submit" name="do" value="save">Save</button></li> <li><button type="submit" name="do" value="save-add">Save and Add Another</button></li> </ul> When you submit this form and check the validity of it, `form.cleaned_data['do']` will return "save" or "save-add" depending on the submit button clicked.
I will change a model form widget attribute without define the complete field. Because many "meta" information are defined in the model (e.g. the help_text) and i don't want to repeat this. I found a solution: Add/change the widget attribute in the __init__, see example code.
Please delete the snippet.
This class works in compatibility with a ModelForm, but instead of show a form, it shows the field values. The Meta class attributes can be used to customize fields to show, to be excluded, to divide by sections, to urlize text fields, etc. **Example 1:** class InfoSingleCertificate(ModelInfo): class Meta: model = SingleCertificate sections = ( (None, ('vessel','description','document','comments','status',)), ('Issue', ('issue_date','issue_authority','issue_location',)), ) **Example 2:** class InfoSingleCertificate(ModelInfo): class Meta: model = SingleCertificate fields = ('vessel','description','document','comments','status', 'issue_date','issue_authority','issue_location',) **How to use:** Just save this snippet as a file in your project, import to your views.py module (or a new module named "info.py") and create classes following seemed sytax you use for ModelForms.
Sometimes we need divide forms in fieldsets, but this make us declare all fields in HTML template manually. This class is to help you to do this by a easy way. **How to use** First, download this file as name "sectioned_form.py" Later, turn your form inherited from the class **SectionedForm**, override method "_html_output" and declare fieldsets and fieldset_template attribute, like below: from sectioned_form import SectionedForm class MyForm(forms.ModelForm, SectionedForm): fieldsets = ( (None, ('name','age','date')), (_('Documents'), ('number','doc_id')), ) fieldset_template = "<h2>%s</h2>" def _html_output(self, *args, **kwargs): return SectionedForm._html_output(self, *args, **kwargs)
Creating new field to handle checkbox validation in situations where the checkbox must be checked, as in check to agree to terms and such. Thanks to Daniel Pope for the [suggestion](http://code.djangoproject.com/ticket/5957#comment:7) on Django Trac Ticket #[5957](http://code.djangoproject.com/ticket/5957)
Observation: depends on jQuery to works! This widget works like other multiple select widgets, but it shows a drop down field for each choice user does, and aways let a blank choice at the end where the user can choose a new, etc. Example using it: class MyForm(forms.ModelForm): categories = forms.Field(widget=DropDownMultiple) def __init__(self, *args, **kwargs): self.base_fields['categories'].widget.choices = Category.objects.values_list('id', 'name') super(MyForm, self).__init__(*args, **kwargs)
You can add this code to a file named "field_attrs.py" in a templatetags folder inside an application. To use it, remember to load the file with the following template tag: {% load field_attrs %} And for each field you want to change the widget's attr: {{ form.phone|attr:"style=width:143px;background-color:yellow"|attr:"size=30" }}
This template tag build a Form splitted in fieldsets. The fieldsets are configured with a second parameter, that is a tuple like the one used in the Admin class in models in the attribute "fields". You pass to the template the form and the tuple and than use them as parameters for the templatetag. You can take a look at the source and modify It to build forms the way you like. It is very useful If you do not like the way Django build forms with the methods as_p, as_ul or as_table and also do not like to write html by hand.
**The problem** ModelChoiceField always uses __unicode__ or __str__ to fill the labels. I needed to dynamically select which field to use for the labels. **The solution** My approach copies a lot from [this blog](http://oebfare.com/blog/2008/feb/23/overriding-modelchoicefield-labels/) with some modifications to make it more dynamic. There are some proposals to fix on this [Ticket #4620]( http://code.djangoproject.com/ticket/4620) **How to use** Include the code on your forms.py (or whatever you are using) and use the CustomChoiceField with the extra argument label_field instead of ModelChoiceField. Hope it helps someone.
Based on [danjak's](http://www.djangosnippets.org/users/danjak/) [snippet](http://www.djangosnippets.org/snippets/99/) but updated to use ModelForms - so can easily handle generic CRUD operations. A replacement create_update.py for use with ModelForm create_object and update_project modified to handle newforms (including FileFields) with ModelForm - it also had delete_object as well for completeness. In addition, it has some extras: * extra_fields - this is a dict or callable that contains additional fields to be passed to the form, for example stuff that is in the session. * on_success - callback called if form is valid and object created/updated, if this is not set the default behaviour is to send a redirect * on_failure - callback called if form is invalid, the default is to redisplay the form. Note that once newforms are finally done these functions are likely to be redundant, as generic views will be updated to use the newforms API, so use with caution!
The class LocationField renders a form field with map (from google maps) and a mark. It allows the user to drag the mark to point at some particular location, whose value (lat, lng) is saved in a hidden field. It requires jquery and google maps.
141 snippets posted so far.