Login

Snippets by marinho

Snippet List

RangeField and RangeWidget

These field and widget are util for to those fields where you can put a star and end values. It supports most of field types and widgets (tested with IntegerField, CharField and DateField / TextInput and a customized DateInput). **Example of use:** class FormSearch(forms.Form): q = forms.CharField(max_length=50, label=_('Search for')) price_range = RangeField(forms.IntegerField, required=False) **Example of use (with forced widget):** class FormSearch(forms.Form): q = forms.CharField(max_length=50, label=_('Search for')) price_range = RangeField(forms.IntegerField, widget=MyWidget)

  • forms
  • field
  • widget
  • range
Read More

Replacing pattern groups by values

This function takes a pattern with groups and replaces them with the given args and/or kwargs. Example: IMPORTANT: this code is NOT to use replacing Django's reverse function. The example below is just to illustrate how it works. For a given pattern '/docs/(\d+)/rev/(\w+)/', args=(123,'abc') and kwargs={}, returns '/docs/123/rev/abc/'. For '/docs/(?P<id>\d+)/rev/(?P<rev>\w+)/', args=() and kwargs={'rev':'abc', 'id':123}, returns '/docs/123/rev/abc/' as well. When both args and kwargs are given, raises a ValueError.

  • regex
  • reverse
Read More

DropDownMultiple widget

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)

  • newforms
  • multiple
  • forms
  • jquery
  • select
  • widget
Read More

Class ModelInfo for show object info

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.

  • forms
  • model
  • display
  • modelforms
  • info
  • values
Read More

Date/time util template filters

**Explanations:** - the series "is_*_of" was created 'cos it's easier write: `{% if 10|is_day_of:date and user %}` than write: `{% ifequal date.day 10 %}{% if user %}...` - the series "inc/dec" is not complete, but can the extended to day, hour, minute, etc as you needs. It's util to inc 10 months since 05/31/2006 by example and get a 2007's date :) **Setup:** Insert the snippet into an_app/templatetags/datetimeutils.py. **Use in template:** `{% load datetimeutils %}` and use filters as following: - `{{ 30|is_day_of:a_date_time_variable }}` - `{{ 11|is_month_of:a_date_time_variable }}` - `{{ 2006|is_year_of:a_date_time_variable }}` - `{{ 58|is_minute_of:a_date_time_variable }}` - `{{ 23|is_hour_of:a_date_time_variable }}` - `{{ a_date_time_variable|dec_year:2 }}` - `{{ a_date_time_variable|dec_month:2 }}` - `{{ a_date_time_variable|inc_year:2 }}` - `{{ a_date_time_variable|inc_month:2 }}`

  • date
  • time
  • template-filters
Read More

Template filters utils

**Explanation:** That template filters is util for combine boolean-return conditions using template tag `{% if %}`. **Setup:** Insert the snippet into an_app/templatetags/myutils.py. **Use in template:** {% load myutils %} and use filters as following: - `{% if 10|is_multiple_of:5 %}` - `{% if 10|in_list:a_list_variable %}` - `{% if user.username|is_equal:a_variable %}` - `{% if user.username|is_not_equal:a_variable %}` - `{% if a_variable_|is_lt:5 %}` - `{% if a_variable_|is_lte:5 %}` - `{% if a_variable_|is_gt:5 %}` - `{% if a_variable_|is_gte:5 %}`

  • template-filters
Read More

Template Filter attr

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" }}

  • template
  • filter
  • newforms
  • forms
  • form
  • field
  • attr
Read More

User post_save signal to auto create 'admin' profile

**How to use:** 1. puts this code at the end of the `models.py` file who haves the User Profile class declared; 2. verify if your User Profile class has the name 'UserProfile'. If not, change the code to the right name. **About:** this snippet makes the ORM create a profile each time an user is created (or updated, if the user profile lost), including 'admin' user.

  • admin
  • user
  • userprofile
Read More

SectionedForm

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)

  • newforms
  • forms
  • form
  • formset
Read More

Clear FileField/ImageField files in the Admin

The widget for FileField and ImageField has a problem: it doesn't supports clear its value and it doesn't delete the old file when you replace it for a new one. This is a solution for this. It is just for Admin, but you can make changes to be compatible with common forms. The jQuery code will put an **<input type="checkbox">** tag next to every **<input type="file">** and user can check it to clear the field value. When a user just replace the current file for a new one, the old file will be deleted.

  • admin
  • jquery
  • imagefield
  • filefield
Read More

Real shuffle function

This function solve the issue of random.shuffle that is based only on randomized shuffling (that's not a real shuffling, because many times items returned aren't shuffled enough). This function make a randomized shuffle and after this loops long the list resorting to avoid two items with a same value in a given attribute. When shuffling is over and there are duplicates, they are leftover to the end (and you can remove them if you set 'remove_duplicates' to True) Run it in a separated file to see it in action.

  • shuffle
Read More

PermanentRedirectMiddleware

This is a simple middleware that redirects the exactly URL requested with the correct domain. It is useful when you have more than one domain (most of cases with "www." or IP) to access a website. To make it works, download the snippet file as the name "permanent_redirect.py" and add its path as the first item in MIDDLEWARE_CLASSES setting in settings.py. Later you must inform a setting called `HTTP_HOST_DOMAIN` with the correct domain.

  • middleware
  • redirect
  • permanent
  • seo
Read More

render_to_json

**Explanation:** I think this shortcut can be util for who uses JSON many times and does not want to write same code everytime. **Setup:** Saves the snippet as `myproject/utils.py` or add the code to some place in your project with same ends. **Use in a view:** from myproject.utils import render_to_json from django.contrib.admin.models import User def json_view(request): admin_user = User.objects.get(username='admin') return render_to_json( 'json/example.json', locals(), ) **Update:** This code can be used as complement to [http://www.djangosnippets.org/snippets/154/](JsonResponse snippet) too.

  • template
  • json
Read More

Little middleware that create a facebook user

**How to use**: 1. Install [**PyFacebook** package](http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial). 2. After make all steps in tutorial above, put this code in your app's models.py module (you maybe prefer split it and put the middleware class in some other file). 3. Put the FacebookUserMiddleware python-path in the MIDDLEWARE_CLASSES in your settings.py (after facebook.djangofb.FacebookMiddleware). You probably will add some fields to FacebookUser model class :)

  • middleware
  • user
  • facebook
Read More