Pagination which preserves additional GET parameters
Using this snippet you can easily create Pagination that preserves any additional GET paremters you may be using (for example for search module)
- pagination
Using this snippet you can easily create Pagination that preserves any additional GET paremters you may be using (for example for search module)
Middleware that ensures clients always have CSRF tokens and session ids. Useful for some fat-client apps.
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.
**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)
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
ModelAdmin for readonly in django admin panel
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.
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.
Django Template Filter that parse a tweet in plain text and turn it with working Urls Ceck it on [GitHub](https://github.com/VincentLoy/tweetparser-django-template-filter) # tweetParser Django Template Filter this is a port of [tweetParser.js](https://github.com/VincentLoy/tweetParser.js) to work as a Django template filter ## How does it work ? Once installed, just : ``` <p>{{ your_tweet|tweetparser }}</p> ``` ## Installation Take a look at the [Django Documentation](https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/) #### You can change the classes given to each anchor tags ``` USER_CLASS = 'tweet_user' URL_CLASS = 'tweet_url' HASHTAG_CLASS = 'hashtag' ```
By combining the CreateView and UpdateView, you can significantly reduce repetition when processing complex forms (for example, with multiple inline formsets), by only writing the get_context_data and form_valid functions once. This class can be used just like a normal CreateView or UpdateView. Note that if you're trying to use it as an UpdateView but it cannot find the requested object, it will behave as a CreateView, rather than showing a 404 page.
Render a given instance of collections.Counter into a 2 column html table. Optionally accepts `column_title` keyword argument which sets the table key column header. Usage: {% counter_table event_counter column_title='event type' %} The above will render the a table from the `event_counter` variable with the first (key) column set to "event type". See below for an example template (i.e `counter_table.html`) {% load i18n %} <table> <thead> <tr> <th>{{column_title|capfirst}}</th> <th>{% trans "count"|capfirst %}</th> </tr> </thead> <tbody> {% for key, count in most_common %} <tr> <td>{{key}}</td> <td>{{count}}</td> </tr> {% endfor %} </tbody> <tfoot> <tr> <td>{% trans "total"|capfirst %}</td> <td>{{total_count}}</td> </tr> </tfoot> </table>
Use post_migrate to load bulk permissions to grant groups full access to certain apps using the group name and the app name only.
This snippets generate the sum of the field values, for use in summary reports. More info in https://github.com/thomazs/django_templates_plus
It's an update of snippet [https://djangosnippets.org/snippets/1376/](https://djangosnippets.org/snippets/1376/) to work with Django 1.8. With this piece of code, you can override admin templates without copy or symlink files. Just write your template and extend the target.
**CancelMixin** A simple mixin to use with ```generic.CreateView``` and ```generic.UpdateView``` view form templates to effortlessly implement a "Cancel" button. This smart mixin will add a URL to your context, ```{{ cancel_url }}```, that can be used as a cancel link in your form template. If no referrer URL is provided, the cancel button will link to ```default_cancel_url```, which can be overridden by view. ** **
2955 snippets posted so far.