Inspired by [http://www.djangosnippets.org/snippets/712/](YUI Loader as Django middleware)
This loads in css and javascript files where you want them (usually in the head) - but allows you to put them anywhere in your code - i.e. in a TemplateTag.
so your head code will look like this:
`
<head>
...
<!-- HEAD_init -->
...
</head>
`
then somewhere in your templates you can load in javascript or css files like so:
`
<!-- HEAD_include myfile.js myotherfile.css -->
`
It automatically checks if you've already included the files, and only puts them in once.
It automatically figures out if its a javascript or css file by the file name -
If you have an irregular filename (i.e. a google maps api script url) you can force it by using either of the following tags:
`
<!-- HEAD_include_js [my javascript file] -->
<!-- HEAD_include_css [my css file] -->
`
Or you can write inline code to get rendered in the head:
`
<!-- HEAD_render
<script>
someJavascriptCall();
</script>
-->
`
Todo: make it compress the js into one file...
This allows you to host your own URL shortening service for your site's internal urls. By adding this class as a Mixin to your models, any model with a get_absolute_url method will have a get_short_url method also, which either returns an existing redirect or creates a new one and returns that.
**Usage:**
Import the class above, add the mixin to your model declaration, and ensure you have declared a get_absolute_url method.
`class MyModel = (models.Model, ShortURL):`
**Pre-requisites:**
You must have the django.contrib.redirects app installed, and you must be using the RedirectFallbackMiddleware as a middleware class.
**Settings:**
Change the settings in the code above or set them in your settings.py file
SHORTURL_CHARS: the characters to use when creating a shorturl
SHORTURL_CHAR_NO = the number of characters to use in a shorturl
SHORTURL_APPEND_SLASH = whether to append a slash to the end of the shorturl redirect
**Notes:**
The default settings will give you about 17 million different unique short URLs, reducing the number of characters used to 4 will give you 600,000 or so. That's enough that collisions will be quite rare for sites of a few thousand pages (collisions just result in a urls being generated until an unused combination is found) but if you've got a big site you'll probably want to explore a more robust solution with a proper hash function.
[http://matt.geek.nz/blog/text/generating-short-urls-django-site-urls/](http://matt.geek.nz/blog/text/generating-short-urls-django-site-urls/)
create an instance of this class: `rpcserver = XMLRPC()` then define handlers on it with the register decorator:
@rpcserver.register("pingback.ping")
def handle_pingback(sourceURI, targetURI)
# ...
de-serialization of the arguments and serialization of the return values is handled by the XMLRPC object, so just expect python built-in types as your arguments and use them as your return values. you can also raise instances of xmlrpclib.Fault from within your handlers and a proper xmlrpc fault will be sent out as the response.
then you can use `rpcserver.view` in your urlconf to offer up your XML-RPC service at a URL:
urlpatterns = patterns('',
url(r'^$', rpcserver.view, name="xmlrpc"),
# ...
)
I often use it so I hope it helps!
Usage:
urlpatterns = patterns('',
url(r'^nav/$', redirect('/navigation/')),
url(r'^search/(?P<category_name>\w+)/$',
redirect('/documents/%(category_name)s/')),
and so on...
)
It keeps GET arguments too.
My problem was that I needed user names with fullstops in them (eg dodgy.ville), but the slugfield on the admin form was rejecting them. This small snippet overrides the validation field on the admin form,
To use it: place it in your admin.py
This test runner is invoked with its own command:
./manage.py quicktest {usual test args follow}
this creates a test database if it needs to and then DOES NOT delete it. subsequent uses of it start with the same database. this is for rapid test/development cycles usually running a single test. a single test can run in less than a second.
when you need to alter the schema simply use the normal ./manage.py test which will delete the old test database and create a fresh one.
it does not replace your normal test runner. it could probably be altered to even use your custom test runner.
there are improvements to be done, and it will be included with a small testy app soon.
This is my first snipplet. With this, you can manage your models in console using ncurses Dialog or Whiptail or XDialog. Models are auto-discovered. You can browse, edit, add and delete models. Bugreports very welcome.
Simple debug middleware that uses [pycallgraph](http://pycallgraph.slowchop.com) to get a visual representation of the call graph, including number of calls and execution times.
Usage:
1. Replace *myapp* in the snippet with the name of your application and or adjust include and exclude according to your needs
2. Add CallgraphMiddleware to your middlewares in settings.py
3. Append ?prof to any URL in your application to trigger the callgraph creation
Each callgraph cerated will be named callgraph-*timestamp*.png. This is because multiple callgraphs will be created when a re-direction occurs for example.
A test runner for Django unittests which profiles the tests run, and saves the result. Very useful for diagnosing your apps. Place the top portion of the code into a file called `profiling.py` someplace in your python path. Update your `settings.py` file with the bottom two lines of the code. Now you are ready, so just run `python manage.py test [appnames...]` to test any apps listed with profiling. By default this will just print a nice report after the unittests. If you change the value of `TEST_PROFILE` to a file, the profile will be saved to that file. The latter is recommended because these profiling reports have a lot of info in them, so it is best to tear through them with the `pstats` module.
**NOTE**: Further development of this snippet will take place in the [django-form-utils](http://launchpad.net/django-form-utils) project.
This snippet provides BetterForm and BetterModelForm classes which are subclasses of django.forms.Form and django.forms.ModelForm, respectively. BetterForm and BetterModelForm allow subdivision of forms into fieldsets which are iterable from a template, and also allow definition of row_attrs which can be accessed from the template to apply attributes to the surrounding container of a specific form field.
It's frequently said that a generic form layout template is a pipe dream and in "real usage" it's necessary to manually layout forms, but in my experience the addition of fieldsets and row_attrs, plus a competent CSS designer, make it possible to create a generic template that can render useful production form markup in 95+% of cases.
Usage:
class MyForm(BetterForm):
one = forms.CharField()
two = forms.CharField()
three = forms.CharField()
class Meta:
fieldsets = (('main', {'fields': ('two',), 'legend': ''}),
('Advanced', {'fields': ('three', 'one'),
'description': 'advanced stuff'}))
row_attrs = {'one': {'style': 'display: none'}}
Then in the template:
{% if form.non_field_errors %}{{ form.non_field_errors }}{% endif %}
{% for fieldset in form.fieldsets %}
<fieldset class="fieldset_{{ fieldset.name }}">
{% if fieldset.legend %}
<legend>{{ fieldset.legend }}</legend>
{% endif %}
{% if fieldset.description %}
<p class="description">{{ fieldset.description }}</p>
{% endif %}
<ul>
{% for field in fieldset %}
{% if field.is_hidden %}
{{ field }}
{% else %}
<li{{ field.row_attrs }}>
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
</li>
{% endif %}
{% endfor %}
</ul>
</fieldset>
{% endfor %}
This is an extension of the snippet http://www.djangosnippets.org/snippets/1302/ to make it a bit more flexible and been able pass more than one parameter to our "Partial Template". To use it you can
{% partial_template template_name param1:variable1 param2:variable2 ... %}
or:
{% partial_template partials/mini_template.html item:data1 var2:"False" var3:"2*2" %}
This snippet is a replacement views.py for [SOAP views with on-demand WSDL generation](http://www.djangosnippets.org/snippets/979/)
It iterates over your installed apps looking for web_service.py in each one, any methods decorated with @soapmethod within web_service.py will automatically be imported into the local namespace making them visible in the WSDL.
It will blindly override local objects of the same name so it's not very safe (could do with some more error checks) but it works very well.
This small app can display messages to users after they login and before they get to the normal landing page. This can be useful for displaying maintenance notices, information on new features, or a one-day-sale on shoes.
To redirect to the MOTD view after login, change:
`<input type="hidden" name="next" value="{{ next }}" />`
to:
`<input type="hidden" name="next" value="{% url django_motd.views.motd %}?next={{ next }}" />`
in your login.html template.