path.py FilePathField
A slightly adapted FilePathField that converts path.py (http://pypi.python.org/pypi/path.py) objects into strings and back from the database.
- custom field
- filepathfield
- path.py
A slightly adapted FilePathField that converts path.py (http://pypi.python.org/pypi/path.py) objects into strings and back from the database.
You can extend the class **ModifiedModel** to set new fields, replace existing or exclude any fields from a model class without patch or change the original code. **my_app/models.py** from django.db import models class CustomerType(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Customer(models.Model): name = models.CharField(max_length=50) type = models.ForeignKey('CustomerType') is_active = models.BooleanField(default=True, blank=True) employer = models.CharField(max_length=100) def __unicode__(self): return self.name **another_app/models.py** from django.db import models from django.contrib.auth.models import User from this_snippet import ModifiedModel class City(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class HelperCustomerType(ModifiedModel): class Meta: model = 'my_app.CustomerType' description = models.TextField() class HelperCustomer(ModifiedModel): class Meta: model = 'my_app.Customer' exclude = ('employer',) type = models.CharField(max_length=50) # Replaced address = models.CharField(max_length=100) city = models.ForeignKey(City) def __unicode__(self): return '%s - %s'%(self.pk, self.name) class HelperUser(ModifiedModel): class Meta: model = User website = models.URLField(blank=True, verify_exists=False)
This function will take a model instance and return an insert statement for it. I use it for extracting a subset of my production data so that I can reproduce problems in a local environment. The quoting is for mysql, you may have to change it depending on your db backend. Also, it assumes the 'default' database.
**Warning**: I'm quite sure this is **not** a best practice, but this snippet has proven being very useful to me. Handle with care. I also wonder about the impact on performance, while I didn't notice any slowdown on a very small app of mine. Idea is to expose project settings to template request context through a context processor, and \__doc__ should be self-explanatory. Of course, if you know a better way to achieve the purpose, please tell in the comments.
This fields.py file defines a new model field type, "JsonObjectField," which is designed to allow the storage of arbitrary Python objects in Django TextFields. It is intended primarily to allow the storage of Python dictionaries or list objects. As the name implies, it converts objects to JSON for storage; this conversion happens transparently, so from your model's perspective, the field stores and retrieves the actual objects.
It is not so portable and easy as I wanted it to be because of how django forms work - they don't play well with recaptcha. To get it to work: * Add two variables to your app settings, **RECAPTCHA_PUBKEY** and **RECAPTCHA_PRIVKEY** * Derive forms you want to have a captcha from the provided `ReCaptchaForm` class (how to get it working with ModelForm? any ideas?) * * If you override the form's clean method make sure you firstly call the `ReCaptchaForm`'s clean method * * In your view, upon receiving the form data initialize the objects like this `form = YouFormClassDerivedFromReCaptchaForm(remoteip=request.META['REMOTE_ADDR'], data=request.POST)` (or request.GET of course) - this is because reCaptcha needs the user's remote ip.
This snippet in the one to improve the method described in [http://djangosnippets.org/snippets/679/](http://djangosnippets.org/snippets/679/). It uses some jquery extensions to make the task more easier: **jquery.timers.js**, **jquery.progressbar.js**, **jquery.form.js**.
This compares two objects (of the same model) and returns a tuple containing dictionaries with the changed attributes. Note that ALL attributes are run through comparison, so if you are modifying non-field attributes at runtime, these will also be included. Excluded keys is a tuple containing the names if attributes you do not want to include in the comparison loop (i.e. attributes which changes are irrelevant).
ModelPagination Designed and Coded by Cal Leeming Many thanks to Harry Roberts for giving us a heads up on how to do this properly! ---------------------------------------------------------------------------- This is a super optimized way of paginating datasets over 1 million records. It uses MAX() rather then COUNT(), because this is super faster. EXAMPLE: >>> _t = time.time(); x = Post.objects.aggregate(Max('id')); "Took %ss"%(time.time() - _t ) 'Took 0.00103402137756s' >>> _t = time.time(); x = Post.objects.aggregate(Count('id')); "Took %ss"%(time.time() - _t ) 'Took 0.92404794693s' >>> This does mean that if you go deleting things, then the IDs won't be accurate, so if you delete 50 rows, you're exact count() isn't going to match, but this is okay for pagination, because for SEO, we want items to stay on the original page they were scanned on. If you go deleting items, then the items shift backwards through the pages, so you end up with inconsistent SEO on archive pages. If this doesn't make sense, go figure it out for yourself, its 2am in the morning ffs ;p Now, the next thing we do, is use id seeking, rather then OFFSET, because again, this is a shitton faster: EXAMPLE: >>> _t = time.time(); x = map(lambda x: x, Post.objects.filter(id__gte=400000, id__lt=400500).all()); print "Took %ss"%(time.time() - _t) Took 0.0467309951782s >>> _t = time.time(); _res = map(lambda x: x, Post.objects.all()[400000:400500]); print "Took %ss"%(time.time() - _t) Took 1.05785298347s >>> By using this seeking method (which btw, can be implemented on anything, not just pagination) on a table with 5 million rows, we are saving 0.92s on row count, and 1.01s on item grabbing. This may not seem like much, but if you have 1024 concurrent users, this will make a huge difference. If you have any questions or problems, feel free to contact me on cal.leeming [at] simplicitymedialtd.co.uk
Humanized and localized version of built-in *timesince* template filter. Based on [Joey Bratton's idea](http://www.joeyb.org/blog/2009/10/08/custom-django-template-filter-for-humanized-timesince).
This slugify correctly transliterates special characters using the translitcodec package from PyPI. Make sure you've installed http://pypi.python.org/pypi/translitcodec/ before using this.
look ma, no api! a python method for [fabric](fabfile.org) script to send a message to your [campfire](campfirenow.com) chat room. not really a django script but I didn't know where else to put it. I use it to send a deployment messages to campfire when we deploy new revisions. like the comment mentions, put your api key in ~/.fabricrc. the example api key is garbage so don't waste your time.
This assumes that you have a method called **decode_signed_request** which will validate the signed_request parameter and return None if the validation check fails. A similar method can be found here - https://github.com/iplatform/pyFaceGraph/blob/70e456c79f1ac1c7eddece03af323346a00481ef/src/facegraph/canvas.py
The example of the Image inlining template tag lib which inline images in the browser instead of making an Http request. The lib is available at : [http://djangosnippets.org/snippets/2268/](http://djangosnippets.org/snippets/2268/)
Example usage: Add static var with static value to get : {% urlget 'var'='val' %} Add dynamic val (from template vars) to static variable: {% urlget 'var'=val %} Using dynamic variable names works similiar - adding dynamic varialbe (from template vars) : {% urlget var='val' %} Clearing variable from GET string : {% urlget 'var'='' %} Retrieving GET string: {% urlget %}
3110 snippets posted so far.