Login

Tag "custom"

Snippet List

Reusable form template with generic view

If you require lots of forms in your project and do not want to be creating an extended template for each one I propose this solution. Classes in the html correspond to bootstrap, you can work without them if you do not use bootstrap.

  • template
  • django
  • dynamic
  • fields
  • forms
  • generic
  • generic-views
  • html
  • form
  • bootstrap
  • reusable
  • custom
  • modelform
  • crud
  • dynamic-form
Read More

ByteSplitterField

When you want to save integers to the db, you usually have the choice between 16-, 32- and 64-bit Integers (also 8- and 24-bit for MySQL). If that doesn't fit your needs and you want to use your db-memory more efficient, this field might be handy to you. Imagine you have 3 numbers, but need only 10 bit to encode each (i.e. from 0 to 1000). Instead of creating 3 smallint-fields (48 bit), you can create one 'ByteSplitterField' which implements 3 'subfields' and automatically encodes them inside a 32 bit integer. You don't have to take care how each 10-bit chunk is encoded into the 32-bit integer, it's all handled by the field (see also field's description). Additionally, the Field offers opportunity to use decimal_places for each of your subfields. These are 'binary decimal places', meaning the integer-content is automatically divided by 2, 4, 8, etc. when you fetch the value from the field. You can also specify how values are rounded ('round' parameter) and what happens when you try to save a value out of range ('overflow' parameter) Not implemented (maybe in the future if I should need it sometime): * signed values. All values are positive right now! * real (10-based) decimal places (actually you could probably directly use DecimalFields here) * further space optimization, i.e. saving into CharField that's length can be chosen byte-wise

  • model
  • db
  • database
  • field
  • custom
  • custom-model-field
  • IntegerField
  • multibit-field
  • model-field
Read More

template filter to check login status

In templates sometimes you need to display some menu by checking whether the user is logged in or not. So use the above filter as shown below {% with request|check_login as logout %} {% if logout%} display something.... {% endif %} {% endwith %}

  • template
  • filters
  • custom
Read More

Copy media files to central location for easier sharing

I was in need to have pluggable components that all have more or less some media files. I didn't want to pollute my config with dozens of media paths so I wrote this custom command that copies contents `<appdir>/app_media` to your `MEDIA_ROOT/<appname>` path. In template you will refer your media files like `{{MEDIA_URL}}/appname/<path to media>`

  • media
  • static
  • custom
  • command
Read More

Tuned IPAddressField with IPv4 & IPv6 support using Postgres Network Field type

I wanted to store ipv4 and ipv6 ip's in django but I wanted to use the postgresql inet network field type: http://www.postgresql.org/docs/8.3/static/datatype-net-types.html and I wanted to use IPy.py IP objects in python. I followed these very helpful examples along with the django documentation: http://vaig.be/2009/03/numeric-ip-field-for-django.html http://www.djangosnippets.org/snippets/1381/ It took me awhile to figure out how this works (not that I completely understand it now..) and figured I would share it. If anyone finds problems with this or can make it better I will definitely use it.

  • model
  • field
  • ip
  • custom
  • ip-address
  • ip-addresses
  • ipv4
  • ipv6
  • ipy
  • postgresql-network-field
Read More

keywords arguments parser for custom template tags

returns a list of (argname, value) tuples (NB: keeps ordering and is easily turned into a dict). Params: * tagname : the name of calling tag (for error messages) * bits : sequence of tokens to parse as kw args * args_spec : (optional) dict of argname=>validator for kwargs, cf below * restrict : if True, only argnames in args_specs will be accepted If restrict=False and args_spec is None (default), this will just try to parse a sequence of key=val strings. About args_spec validators : * A validator can be either a callable, a regular expression or None. * If it's a callable, the callable must take the value as argument and return a (possibly different) value, which will become the final value for the argument. Any exception raised by the validator will be considered a rejection. * If it's a regexp, the value will be matched against it. A failure will be considered as a rejection. * Using None as validator only makes sense with the restrict flag set to True. This is useful when the only validation is on the argument name being expected.

  • template
  • tag
  • custom
  • template_tags
Read More

CountryField (UN Country List, 3 Char Codes)

**Adapted from** [CountryField](http://www.djangosnippets.org/snippets/494/) - **Initial thanks to marinho** Uses the UN country list listed in the source - this provides the 3 character ISO country code. Ordered by display value and not country code. Just place anywhere you like and import CountryField to use. `country = CountryField(verbose_name="Country", help_text="The registrant's country of residence.")`

  • forms
  • form
  • field
  • list
  • country
  • countries
  • custom
  • custom-field
  • countryfield
  • countrys
Read More
Author: djm
  • 1
  • 1

Overriding Third-party Admin

With the advent of newforms-admin it's now possible to override admin interfaces without having to change any code in third-party modules. This example shows how to enable a rich-text editor for `django.contrib.flatpages` without touching Django's code at all. (Actual embedding of the editor via Javascript left as an exercise for the reader – plenty of examples of that elsewhere.)

  • admin
  • newforms-admin
  • custom
  • contrib.admin
  • override
  • rich-text
Read More

CustomQueryManager

A `models.Manager` subclass that helps to remove some of the boilerplate involved in creating managers from certain queries. Usually, a manager would be created by doing this: class MyManager(models.Manager): def get_query_set(self): return super(MyManager, self).get_query_set().filter(query=blah) Other managers may return other query sets, but this is especially useful as one may define queries on a table which would be used a lot. Since the only part that ever changes is the `query=blah` set of keyword arguments, I decided to abstract that into a class which, besides taking the repetition out of manager definition, allows them to be and'd and or'd in a manner similar to the `Q` objects used for complex database queries. `CustomQueryManager` instances may be defined in one of two ways. The first, more laborious but reusable manner, is to subclass it, like so: class MyManager(CustomQueryManager): query = Q(some=query) Then, `MyManager` is instantiated with no arguments on a model, like normal managers. This allows a query to be reused without extra typing and copying, and keeps code DRY. Another way to do this is to pass a `Q` object to the `__init__` method of the `CustomQueryManager` class itself, on the model. This would be done like so: class MyModel(models.Model): field1 = models.CharField(maxlength=100) field2 = models.PositiveIntegerField() my_mgr = CustomQueryManager(Q(field1='Hello, World')) This should mainly be used when a query is only used once, on a particular model. Either way, the definition of `__and__` and `__or__` methods on the `CustomQueryManager` class allow the use of the `&` and `|` operators on instances of the manager and on queries. For example: class Booking(models.Model): start_date = models.DateField() end_date = models.DateField() public = models.BooleanField() confirmed = models.BooleanField() public_bookings = CustomQueryManager(Q(public=True)) private_bookings = public_bookings.not_() confirmed_bookings = CustomQueryManager(Q(confirmed=True)) public_confirmed = public_bookings & confirmed_bookings public_unconfirmed = public_bookings & confirmed_bookings.not_() public_or_confirmed = public_bookings | confirmed_bookings public_past = public_bookings & Q(end_date__lt=models.LazyDate()) public_present = public_bookings & Q(start_date__lte=models.LazyDate(), end_date__gte=models.LazyDate()) public_future = public_bookings & Q(start_date__gt=models.LazyDate()) As you can see, `CustomQueryManager` instances can be manipulated much like `Q` objects, including combination, via `&` (and) and `|` (or), with other managers (currently only other `CustomQueryManager` instances) and even `Q` objects. This makes it easy to define a set of prepared queries on the set of data represented by a model, and removes a lot of the boilerplate of usual manager definition.

  • models
  • q
  • manager
  • query
  • custom
Read More

exception handling middleware

<code> is_loaded = False if not is_loaded: is_loaded = True #... ExceptionHandlingMiddleware as EHM import views EHM.append(views.AuthFailError, views.auth_fail) # when AuthFailError thrown it redirects to `auth_fail` view function. </code>

  • middleware
  • error
  • exception
  • custom
  • handling
Read More

13 snippets posted so far.