get_model_or_404
Attempt to get a model from the `AppCache` and raise `Http404` if it cannot be found.
- shortcut
- model
- db
- helper
Attempt to get a model from the `AppCache` and raise `Http404` if it cannot be found.
Given such code: class ProductImage(models.Model): fullsize = models.ImageField(upload_to= "products/%Y/%m/%d/") display = AutoImageField(upload_to= "products/%Y/%m/%d/",prepopulate_from='fullsize', size=(300, 300)) thumbnail = AutoImageField(upload_to="products/%Y/%m/%d/",null=True,default='/media/noimage.jpg')) display will be automatically resized from fullsize, and thumbnail will default to /media/noimage.jpg if no image is uploaded Note: At some point the code broke against trunk, which has now been updated to work properly
A CharField (Model) that checks that the value is a valid HTML color code (Hex triplet) like #FFEE00.
Just easier for me to use this. Put in app/management/commands and run python manage.py reset_db to start from afresh then do a sync.
Warning: This python script is designed for Django 0.96. It exports data from models quite like the `dumpdata` command, and throws the data to the standard output. It fixes glitches with unicode/ascii characters. It looked like the 0.96 handles very badly unicode characters, unless you specify an argument that is not available via the command line. The simple usage is: $ python export_models.py -a <application1> [application2, application3...] As a plus, it allows you to export only one or several models inside your application, and not all of them: $ python export_models.py application1.MyModelStuff application1.MyOtherModel Of course, you can specify the output format (serializer) with the -f (--format) option. $ python export_models.py --format=xml application1.MyModel
Custom field for using MySQL's `text` type. `text` is more compact than the `longtext` field that Django assigns for `models.TextField` (2^16 vs. 2^32, respectively)
This is useful especially during the model-creation stage, when things are in constant flux. The `freshdb` command will drop the project's database, then create a new one. A common use case: manage.py freshdb manage.py syncdb
*Incredibly useful for storing just about anything in the database (provided it is Pickle-able, of course) when there isn't a 'proper' field for the job:* A field which can store any pickleable object in the database. It is database-agnostic, and should work with any database backend you can throw at it. Pass in any object and it will be automagically converted behind the scenes, and you never have to manually pickle or unpickle anything. Also works fine when querying. **Please note that this is supposed to be two files, one fields.py and one tests.py (if you don't care about the unit tests, just use fields.py)**
Based on the UPDATE query section of `Model.save()`, this is another means of limiting the fields which are used in an UPDATE statement and bypassing the check for object existence which is made when you use `Model.save()`. Just make whatever changes you want to your model instance and call `update`, passing your instance and the names of any fields to be updated. Usage example: import datetime from forum.models import Topic from forum.utils.models import update topic = Topic.objects.get(pk=1) topic.post_count += 1 topic.last_post_at = datetime.datetime.now() update(topic, 'post_count', 'last_post_at') (Originally intended as a comment on [Snippet 479](/snippets/479/), but comments aren't working for me)
Provides the method from_related_ids, which lets you select some objects by providing a list of related ids (The huge difference to __in is that the objects have to match al of the ids, not only one) Model Example:: class Article(models.Model): text = models.TextField() tags = ManyToManyField('Tag') objects = AllInManager() Usage:: Article.objects.from_related_ids((1,2,3,4), 'tags')
This is a great way to pack extra data into a model object, where the structure is dynamic, and not relational. For instance, if you wanted to store a list of dictionaries. The data won't be classically searchable, but you can define pretty much any data construct you'd like, as long as it is JSON-serializable. It's especially useful in a JSON heavy application or one that deals with a lot of javascript. **Example** (models.py): from django.db import models from jsonfield import JSONField class Sequence(models.Model): name = models.CharField(maxlength=25) list = JSONField() **Example** (shell): fib = Sequence(name='Fibonacci') fib.list = [0, 1, 1, 2, 3, 5, 8] fib.save() fib = Sequence.objects.get(name='Fibonacci') fib.list.append(13) print fib.list [0, 1, 1, 2, 3, 5, 8, 13] fib.get_list_json() "[0, 1, 1, 2, 3, 5, 8, 13]" *Note:* You can only save JSON-serializable data. Also, dates will be converted to string-timestamps, because I don't really know what better to do with them. Finally, I'm not sure how to interact with forms yet, so that realm is a bit murky.
Inspired by http://www.djangosnippets.org/snippets/159/ This context processor provides a new variable {{ sqldebug }}, which can be used as follows: {% if sqldebug %}...{% endif %} {% if sqldebug.enabled %}...{% endif %} This checks settings.SQL_DEBUG and settings.DEBUG. Both need to be True, otherwise the above will evaluate to False and sql debugging is considered to be disabled. {{ sqldebug }} This prints basic information like total number of queries and total time. {{ sqldebug.time }}, {{ sqldebug.queries.count }} Both pieces of data can be accessed manually as well. {{ sqldebug.queries }} Lists all queries as LI elements. {% for q in sqldebug.queries %} <li>{{ q.time }}: {{ q }}</li> {% endfor %} Queries can be iterated as well. The query is automatically escaped and contains <wbr> tags to improve display of long queries. You can use {{ q.sql }} to access the unmodified, raw query string. Here's a more complex example. It the snippet from: http://www.djangosnippets.org/snippets/93/ adjusted for this context processor. {% if sqldebug %} <div id="debug"> <p> {{ sqldebug.queries.count }} Quer{{ sqldebug.queries|pluralize:"y,ies" }}, {{ sqldebug.time }} seconds {% ifnotequal sql_queries|length 0 %} (<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.display=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>) {% endifnotequal %} </p> <table id="debugQueryTable" style="display: none;"> <col width="1"></col> <col></col> <col width="1"></col> <thead> <tr> <th scope="col">#</th> <th scope="col">SQL</th> <th scope="col">Time</th> </tr> </thead> <tbody> {% for query in sqldebug.queries %}<tr class="{% cycle odd,even %}"> <td>{{ forloop.counter }}</td> <td>{{ query }}</td> <td>{{ query.time }}</td> </tr>{% endfor %} </tbody> </table> </div> {% endif %}
Ever want to call stored procedures from Django easily? How about PostgreSQL functions? That's that this manager attempts to help you with. To use, just stick this in some module and in a model do: class Article(models.Model): objects = ProcedureManager() Now you can call procedures (MySQL or PostgreSQL only) to filter for models like: Article.objects.filter_by_procedure('ProcName', request.user) This will attempt to construct a queryset of objects. To just get random values, do: Article.objects.values_from_procedure('ProcName', request.user) Which will give you a list of dictionaries.
Every now and then you need to have items in your database which have a specific order. As SQL does not save rows in any order, you need to take care about this for yourself. No - actually, you don't need to anymore. You can just use this file - it is designed as kind-of plug-in for the Django ORM. Usage is (due to use of meta-classes) quite simple. It is recommended to save this snippet into a separate file called `positional.py`. To use it, you only have to import `PositionalSortMixIn` from the `positional` module and inherit from it in your own, custom model (but *before* you inherit from `models.Model`, the order counts). Usage example: Add this to your `models.py` from positional import PositionalSortMixIn class MyModel(PositionalSortMixIn, models.Model): name = models.CharField(maxlength=200, unique=True) Now you need to create the database tables: `PositionalSortMixIn` will automatically add a `postition` field to your model. In your views you can use it simply with `MyModel.objects.all().order_by('position')` and you get the objects sorted by their position. Of course you can move the objects down and up, by using `move_up()`, `move_down()` etc. In case you feel you have seen this code somewhere - right, this snippet is a modified version of [snippet #245](/snippets/245/) which I made earlier. It is basically the same code but uses another approach to display the data in an ordered way. Instead of overriding the `Manager` it adds the `position` field to `Meta.ordering`. Of course, all of this is done automatically, you only need to use `YourItem.objects.all()` to get the items in an ordered way. Update: Now you can call your custom managers `object` as long as the default manager (the one that is defined first) still returns all objects. This Mix-in absolutely needs to be able to access all elements saved. In case you find any errors just write a comment, updated versions are published here from time to time as new bugs are found and fixed.
First off: This snippet is more or less obsoleted by [snippet #259](/snippets/259/). The way that snippet #259 uses feels cleaner and more usable. It is basically the same code but the magic works a little bit different. In case you prefer this way, I've left this snippet as-is. Maybe you know this problem: you have some objects in your database and would like to display them in some way. The problem: the Django ORM does not provide any way to sort model instances by a user-defined criterion. There was already a plug-in in SQLAlchemy called [orderinglist](http://www.sqlalchemy.org/docs/plugins.html#plugins_orderinglist), so implementing this in Django was basically not a big deal. Usage is (due to use of meta-classes) quite simple. It is recommended to save this snippet into a separate file called `positional.py`. To use it, you only have to import `PositionalSortMixIn` from the `positional` module and inherit from it in your own, custom model (but *before* you inherit from `models.Model`, the order counts).
34 snippets posted so far.