Login

All snippets

Snippet List

Reusable field forms using crispy-forms

If you need to use some source to construct your form (maybe some database info or some user input), or you use the same fields with the same functionality in various forms and need to write the same piece of code for each of them, then you are looking in the right place. With this snippet you won't have those issues any more. :P This snippet present a way to wean the fields from the form. The code is made using crispy-forms, but the same idea can be applied without using it. Best luck!

  • forms
  • filters
  • reuse
  • reusable
  • form-field
  • crispy-forms
Read More

Django filter for shrinking [big] numbers

Simple filter that shrinks [big] numbers sufixing "M" for numbers bigger than million, or "K" for numbers bigger than thousand. It does a division over the number before converting to string so rounding is properly done. Examples: `{{ 123456|shrink_num }} >> 123.6K` `{{ 1234567|shrink_num }} >> 1.2M`

  • filter
  • numbers
  • kilo
  • mega
Read More

Datetime adjuster for Django Templates

The filter is **specific to datetime objects** and no allowance has been made to convert strings or epoch times. Also **no type checking** is performed so misuse will result in an error. To use include the above snippet in a file called templatetags/customfilters.py or append to existing filters file then load: `{% load customfilters %}` in your template, then to use it: `{{ dateobject|adjust:"months=1"|date:"Y/m/d" }}` To push the dateobject forward by a month, or: `{{ dateobject|adjust:"weeks=-1"|date:"Y/m/d" }}` To push the dateobject back a week, or: `{{ dateobject|adjust:"years=1, months=2"|date:"Y/m/d" }}` To push the dateobject forward by a year and 2 months

  • template
  • filter
  • datetime
  • calculation
  • adjust
  • relativedelta
Read More

Remove a clause from a queryset

I want to create Mixins for QuerySet objects that will by default filter out certain records (e.g. filter out "deleted" records, or filter out "unapproved" records, etc). I'd like those to be separate independent mixins. So in each of those, I override all() to filter out deleted or unapproved, etc. But, I also want to offer a method in the queryset to remove those filters or remove some part of those filters. That's where this code comes in. After some examination of how QuerySets work, this seemed like the simplest method for "undoing" some filter in a queryset

  • hack
  • orm
  • manager
  • mixin
  • queryset
Read More

ReadOnlyFieldsMixin to Form, ModelForm and Views (helper function)

### Usage: class Foo(models.Model): description = models.TextField() number = models.IntegerField() class FooOnlyDescriptionIsReadOnly(ReadOnlyFieldsMixin, forms.ModelForm): readonly_fields = ('description', ) class Meta: model = Foo fields = '__all__' class FooAllFieldsIsReadOnly(ReadOnlyFieldsMixin, forms.ModelForm): class Meta: model = Foo fields = '__all__' ### or use the function class FooForm(forms.ModelForm): class Meta: model = Foo fields = '__all__' ReadOnlyFooForm = new_readonly_form_class(FooForm, readonly_fields=('description', ))

  • readonly-form
  • ReadOnlyFieldsMixin
Read More

better localsettings import

Most people simply wrap "from localsettings import *" in a try/except ImportError block. That's what I've done for years, but recently came up with this better way. The problem this snippet solves is that if your localsettings.py itself causes an ImportError somehow, that error will be silently swallowed and your intended localsettings will be ignored. Instead, we use `imp` to first check if the module exists, then unconditionally try to import it.

  • development
  • staging
  • production
  • localsettings
Read More

Compare objects list and get a list of object to inserted or updated

**Problem** You have an input `json` with which you will create a list of objects, you have to validate that the object will be created if it not exists, if exists determine whether to upgrade or discard depending of they have not undergone any changes. Solution 1) With the input `json` will be created the list of objects of the class that we insert or updatee 2) Read all fields in the database, using one of the fields as key to creating a dictionary with the objects in the database 3) Compare the objects and determine if it will be updated, inserted or discarded Django problem: by default only compares the level objects using the primary key (id). Compare field by field is the solution to determine if the object has changed. hints: The _state field is present in every object, and it will produce a random memory location, You can find cache fields so you need to remove these begins with underscore `_`. The fields excluded can be fk, and these fields produce field_id, so you will needs to exclude it class Country(models.Model): # country code 'MX' -> Mexico code = models.CharField(max_length=2) name = models.CharField(max_length=15) class Client(models.Model): # id=1, name=pedro, country.code=MX, rfc=12345 name = models.CharField(max_length=100) country = models.ForeignKey(Country) rfc = models.CharField(max_length=13) Country.objects.create(**{'code': 'MX', 'name': 'Mexico'}) # creating the country Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':12345}) # creating the client obj_db = Client.objects.get(id=1) country = Country.objects.get(code='MX') obj_no_db = Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':12345}) obj_db == obj_no_db # True obj_no_db = Client(**{'id':1, 'name':'pedro', 'country': country, 'rfc':1}) obj_db == obj_no_db # True # but isn't True because the rfc has change, how can compare field by field obj_db.rfc == obj_no_db.rfc # False, I was expected this result when compare obj_db == obj_no_db because they are not equal **Solution to compare field by field** _obj_1 = [(k,v) for k,v in obj_db.__dict__.items() if k != '_state'] _obj_2 = [(k,v) for k,v in obj_no_db.__dict__.items() if k != '_state'] _obj_1 == _obj_2 # False This is only for one object, and you can include in `__eq__` method in your model, but what happen if you need compare a list of object to bulk for insert or update with `django-bulk-update`. Well my snipped pretends solve that. so **How can use it.** obj_list = [<Object Client>, <Object Client>, <Object Client>, <Object Client>] get_insert_update(Client, 'id', obj_list) exclude_fields = ['country'] get_insert_update(Client, 'id', obj_list, exclude_fields=exclude_fields)

  • models
  • bulk
Read More

@group_required decorator

Use : `@group_required(('toto', 'titi'))` `def my_view(request):` `...` `@group_required('toto')` `def my_view(request):` `...` Note that group_required() also takes an optional login_url parameter `@group_required('toto', login_url='/loginpage/')` `def my_view(request):` `...` As in the login_required() decorator, login_url defaults to settings.LOGIN_URL. If the raise_exception parameter is given, the decorator will raise PermissionDenied, prompting the 403 (HTTP Forbidden) view instead of redirecting to the login page. Such as https://docs.djangoproject.com/en/1.8/topics/auth/default/#the-permission-required-decorator **Inspired by** : https://github.com/django/django/blob/stable/1.8.x/django/contrib/auth/decorators.py

  • decorator
  • login
  • auth
  • decorators
  • group_required
  • @group_required
Read More

Make fixtures and follow relationships.

Inspired and based on https://djangosnippets.org/snippets/918/ Improvements: - Supports natural keys - Uses Django's Collector so hopefully follows reverse relationships - Fixes problem when you don't specify a slice - PEP8 etc.

  • fixtures
  • command
Read More

Inject request into functions

Long story short: * Django lets you call functions in templates, but you can't pass any parameters. * Sometimes you need to use the request object to perform certain tasks, such as determining whether the current user has permission to do something. * The recommended approach is to call functions that require parameters in the view, and then pass the results as variables in the context. This sometimes feels a bit overkill. * Creating a templatetag to call any function with any parameter will definitely break the intention for not letting functions to be called with parameters in templates. * So, what if we could tell django to inject the request into certain functions? That's what this decorator is for. For instance, suppose you have a model: class SomeModel(models.Model): ... def current_user_can_do_something(self, request): ...some logic here using request... You could use the decorator like this: class SomeModel(models.Model): ... @inject_request def current_user_can_do_something(self, request=None): ...some logic here using request... And in the template go straight to: {{ somemodel_instance.current_user_can_do_something }} So that the decorator would perform some operations to find the request in the frame tree and inject it if found. The assertions are intented to make sure things will work even if the request cannot be found, so that the coder may program defensively.

  • templates
  • request
  • decorators
Read More

3109 snippets posted so far.