ifcontains tag
Django does not have ability to write {% if "item" in list %}, so I had to write this tag. It can be used just like ifequal tag
- tag
- if
- ifcontains
- block-tag
Django does not have ability to write {% if "item" in list %}, so I had to write this tag. It can be used just like ifequal tag
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...
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.
This is a somewhat simpler alternative to [http://www.djangosnippets.org/snippets/243/](http://www.djangosnippets.org/snippets/243/) that does not return a 401 response. It's meant to be used along with the login_required decorator as an alternative way to authenticate to REST-enabled views. Usage: @http_basic_auth @login_required def my_view(request): ... If an HTTP basic auth header is provided, the request will be authenticated before the login_required check happens. Otherwise, the normal redirect to login page occurs.
**Sumary** M2M relation without creating table. Normally you should specify m2m only in *one* model, thus widgets for many-to-many relations will be displayed inline on whichever model contains the actual reference to the ManyToManyField. But if you want to be able to have widgets displayed on both form you need some tricks, for example using intermediary-models can help, but you will not get multiselect widget (and in case of inlining extra = multi). Also you can write your own form which takes care about adding widget (just 1 line) and setting default values and saving it (more than few lines of code). If you try ManyToManyField with same db_table specified, the only problem will be in syncdb (it will try to create two identical tables) and the only thing our class does is preventing creation of table for M2M, so in one model you should use ManyToManyField and in another ManyToManyField_NoSyncdb with the same db_table argument. **Example** So to have M2M widgets in both forms you can write: class User(models.Model): #... groups = ManyToManyField('Group', related_name='groups', db_table=u'USERS_TO_GROUPS') class Group(models.Model): #... users = ManyToManyField_NoSyncdb(User, related_name='users', db_table=u'USERS_TO_GROUPS')
Background ========== Edit: This snippet doesn't make a lot of sense when Malcolm's blog is down. Read on for some history, or go [here](http://www.djangosnippets.org/snippets/1955/) to see the new trick that Malcolm taught me. A year ago, Malcolm Tredinnick put up an excellent post about doing complex Django forms [here](http://www.pointy-stick.com/blog/2008/01/06/django-tip-complex-forms/). I ended up reinventing that wheel, and then some, in an attempt to create a complex formset. I'm posting my (partial) solution here, in hopes that it will be useful to others. Edit: I should have known - just as soon as I post this, Malcolm comes back with a solution to the same problem, and with slightly cleaner code. Check out his complex formset post [here](http://www.pointy-stick.com/blog/2009/01/23/advanced-formset-usage-django/). I'll use Malcolm's example code, with as few changes as possible to use a formset. The models and form don't change, and the template is almost identical. Problem ======= In order to build a formset comprised of dynamic forms, you must build the forms outside the formset, add them, and then update the management form. If any data (say from request.POST) is then passed to the form, it will try to create forms inside the formset, breaking the dynamically created form. Code ==== To use this code: * Copy `BaseDynamicFormSet` into your forms.py * Create a derived class specific to your needs (`BaseQuizDynamicFormSet` in this example). * Override `__init__`, and keep a reference to your object that you need to build your custom formset (`quiz`, in this case). * Call the parent `__init__` * Call your custom add forms logic * Call the parent `_defered_init` To write your custom add_forms logic, remember these things: * You've got to pass any bound data to your forms, and you can find it in self.data. * You've got to construct your own unique prefixes by doing an enumerate, as shown in the example above. This is the same way it is usually handled by the formset. Add a `formset_factory` call, and specify your derived dynamic formset as the base formset - we now have a `QuizFormSet` class that can instantiated in our view. The view and template code look identical to a typical formset, and all of the dynamic code is encapsulated in your custom class. Warning ======= This solution does not yet handle forms that work with files, use the ordering/delete features, or adding additional forms to the set via javascript. I don't think that any of these would be that hard, but don't assume that they'll just work out of the box.
I've got a bunch of `Models` that form a tree like structure. I'd like to duplicate them all changing one field to something else. Say for example I've got a `Website` which has `Pages` and `Links` and all kinds of other `Models`. Each one of these belong to a `User` (through a foreign key relation). I could use `duplicate` to create a copy of an entire website and give it to another `User` with something like this: class Website(Model): owner = ForeignKey('auth.User') ... class Link(Model): owner = ForeignKey('auth.User') ... class Page(Model): owner = ForeignKey('auth.User') ... ################################## website = Website.objects.get(pk=1) new_owner = User.objects.get(pk=1) duplicate(website, new_owner, 'owner') For a in depth example of the problem see: [Duplicating Model Instances @ STO](http://stackoverflow.com/questions/437166/duplicating-model-instances-and-their-related-objects-in-django-algorithm-for-r) *Note* * Not tested with anything but simple Foreign Key relations - the model ordering is _very_ naive.
While django provides the `django_admin.py cleanup` script, if sessions get out of control sometimes you have to go lower level to get everything cleaned up. If the problem gets out of hand and you hit the resource limits of the machine, it is very difficult to get anything done in the database. Attached is SQL code which was used to cleanup 27GB of expired session data in 3h. Run it like this to make sure it runs to completion: `nohup mysql --user=username --password=password --host=hostname database < delete_expired_sessions.sql` nohup causes the script to run detached from a terminal, so if your session gets disconnected it will keep running.
** Image on demand view ** I often post photos on photography fora. Most fora want you to place a link to a photo somewhere on the net, but different fora have different rules. Some fora want you to stick to a maximum of 800 pixels wide, some 700 pixel and some even strange values like 639 pixels. My own site uses 600 pixels so I end up resizing images all the time. Since I keep my originals with my gallery as well (hidden for public viewing) resizing on the fly would be a nice asset. I'm using my previous snippet to apply a slight unsharp mask for better web display of my photos. ** usage ** This snippet takes the url to my photo application which is a simple link using the pk of my photo table and adds 'width'.jpg to the end (some fora check if the link is an image based on extenstion) The view takes the width requested and creates the resized image from the original full size image or takes it from the cache for display on demand. To prevent a dozen directories I use a setting to specify which widths are allowed, providing room for several versions of the same image. Any improvements are appreciated since I'm still rather inexperienced in Python and Django.
[See the blog entry](http://sciyoshi.com/blog/2008/nov/18/rails-mvc-controllers-django/) Allows using controllers for views. This allows for nice subclassing to override behavior of views. `Controller.urls` (see below) works fine for subclasses as well. Similar to [snippet #1165](http://www.djangosnippets.org/snippets/1165/) except that it won't break reverse URL resolving and regex validation in URLs. In `views.py`: import mvc class MyController(mvc.Controller): @mvc.view('myview/$', 'myview') def my_view(self): # do something with self.request return HttpResponse('something') class Meta(mvc.Controller.Meta): url_prefix = 'mycontroller-' In `urls.py`: from . import views urlpatterns = patterns('', # ... other urls here ... *views.MyController.urls(r'prefix/') ) Then the view `MyController.my_view` will be accessible from `'prefix/myview/'` and have the name `'mycontroller-myview'`, i.e. `reverse('mycontroller-myview')` will work as expected.
This is a view that can be used to add a print button (link) in the admin change form for an individual record. Pretty simple to use. A nice enhancement to it is to be able to pull the model field name tie with the field value, something like making {{ object.as_dl }} available to the template. PS: The code is a modification from the django.views.generic.list_detail.object_detail
Seeing [snippet 1178](http://www.djangosnippets.org/snippets/1178/) reminded me that I also had a go at writing a Choices class at some point. I'm content with the result, but I doubt xgettext will discover your translation strings, which will no doubt be inconvenient. Here it is anyway, in all its overly-complicated glory :-) The following demo was pulled from the function's docstring tests. >>> simple = Choices("one", "two", "three") >>> simple Choices(one=0, two=1, three=2) >>> tuple(simple) ((0, u'ein'), (1, u'zwei'), (2, u'drei')) >>> (0, _('one')) in simple True >>> simple.ONE 0 >>> hasattr(simple, 'FOUR') False Ordering just follows the order that positional arguments were given. Keyword arguments are ordered by their value at appear after positional arguments. >>> [ key for key, val in simple ] [0, 1, 2] >>> Choices(one=1, two=2, three=3) Choices(one=1, two=2, three=3) A Mix of keyword and non-keyword arguments >>> Choices("one", two=2, three=3) Choices(one=0, two=2, three=3) Automatically generated values (for "one" below) should not clash. >>> Choices("one", none=0, three=1, four=2) Choices(one=3, none=0, three=1, four=2) Here is an example of combined usage, using different object types. >>> combined = Choices(one=1, two="two", three=None, four=False) >>> len(combined) 4 >>> (1, _('one')) in combined True >>> ('two', _('two')) in combined True >>> (None, _('three')) in combined True >>> (False, _('four')) in combined True And here is an empty choices set. Not sure why you would want this.... >>> empty = Choices() >>> empty Choices()
This is standart address model. Must match US / GB / French address and other... Specifics locales fields are notice by comments.
If you want to add an fckeditor for every vLargeTextField (the input class used by models.TextField) you can use this javascript. you can load that in all admin pages overriding templates/admin/base_site.html with this: {% extends "admin/base.html" %} {% load i18n %} {% block title %}{{ title }} | {% trans "Administrative Area" %}{% endblock %} {% block branding %} <h1 id="site-name">{% trans "Administrative Area" %}</h1> {% endblock %} {% block nav-global %}{% endblock %} {% block extrahead %}{{ block.super }} <script src="{{media_url}}js/jquery.js" type="text/javascript"></script> <script src="{{media_url}}fckeditor/fckeditor.js" type="text/javascript"></script> <script src="{{media_url}}fckeditor/custom/vTextField.js" type="text/javascript"></script> {% endblock %}
Used for showing size of the page in human readable format and time taken to generate the page on the server. To use it, in your base template, somewhere put the line: `<!-- ____SIZE_AND_DATE_PLACEHOLDER____ -->`. May be used on production.
3110 snippets posted so far.