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.
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'
```
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>
Requires [line_profiler](https://pypi.python.org/pypi/line_profiler)
pip install line_profiler
Will print profile info into console
@line_profiler
def my_view(request):
context = some_quick_func()
return some_heavy_func(context)
It does not work good when nested, so don't wrap `some_heavy_func`. If you want to profile also some nested call - use `extra_view` parameter:
@line_profiler(extra_view=[some_heavy_func])
def my_view(request):
context = some_quick_func()
return some_heavy_func(context)
It will profile `my_view` and `some_heavy_func`
Update to https://djangosnippets.org/snippets/1907/ to be a bit more flexible, and code cleaned up a tiny bit.
To use, add this snippet as a file in a templatetags folder in an app or in a project. Then include and call the tag with
{% obfuscate_email 'email' %}
or
{% obfuscate_email 'email' 'link_text' %}
if 'link_text' is provided, it will be used as the text in the body of the <a> tag. If not, then the email will be used.
I wanted to be able to restyle the inputs, which required having access to each of the select widgets. When used in a form, you can simply iterate over the field to access each element.
Example:
{% for form_field in form.date %}
<div class="select-wrap">
{{ form_field }}
</div>
{% endfor %}
This class lets me have a model choice field that includes optgroups . Django has built-in support for optgroups if you explicitly set all the choices in a ChoiceField, but that doesn't help with ModelChoiceFields. Optgroups let you have nice-looking subscategories in huge dropdowns. They're even more useful if you're using something like selectize.js, because you have a ton of options.
If you inherit from GroupedModelChoiceField and override the optgroup_from_instance function, as in SampleChoiceField, you'll get a dropdown with your models with the expected optgroup tags in the html. Be sure to have your queryset first order by whatever you're displaying in optgroup.
This is a quite simple snippet to integrate postgresql trgm search in django 1.6.10
This snippet is easy to adapt to other special operators by changing the trgm_search function. This example uses the operator `%%` but you could use `ts_vector(fieldname) @@ to_tsquery(%s)`
Instead of the default Django User the Auth Model is 'customer' from the usercp App.
User's can use username as a display to the public, without disclosing their login information. This way they can use a forum with their username, which is seen by everyone.
The login credentials, however are more privat, since it is the e-mail address. Allowing the user to not disclose any information.
The recipe uses deferred constraint validation to create circular references across database tables. The example requires Postgres (MySQL doesn't support deferred constraints).
To achieve this, the following is required:
* Insertions must be performed in a transaction. Foreign key constraints will be validated at the end of the transactions, allowing for insertion of rows with FKs pointing to rows that don't exist yet.
* Primary keys need to be generated before insertion. That's what `prefetch_id` does by pulling the next value from the `*_id_seq` sequence.
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.