During the use of Django, I have accumulated a lot of small tools: decorators, shortcuts, custom fields, and just utilities that wandered with me from project to project in the form of a combined handy package. In the end, I decided to share my experience, because such a code - this is a materialized experience (even better - the code can be executed), and open the most useful pieces of handy for everyone.
The package aims to reduce the required boilerplate when using the jango framework. To eliminate the need to write the same thing over and over again, make the code shorter and more expressive.
So, install the package:
pip install handy
and let's start. What do we get using handy?
')
1. Avoid messing with
HttpResponse
and
render_to_response()
using the
@render_to()
decorator:
# 'app_name/foo.html', # app_name - @render_to() def foo(request): return { 'bar': Bar.objects.all() # , HTTP , 'STATUS': 410, 'CONTENT_TYPE': 'text/plain' }
2. JSON views in a couple of lines:
@render_to_json() def posts_by_tag(request, tag=None): posts = Post.object.values().filter(tag=tag) return list(posts)
3. And even higher level wrapper for handling more complex asynchronous requests:
@ajax @ajax.login_required @ajax.catch(Post.DoesNotExist) def enable_post(request): post = Post.objects.get(pk=request.GET['id']) if post.author != request.user: # {"success": false, "error": "permission_denied"} raise ajax.error('permission_denied') post.enabled = True post.save() # {"success": true, "data": null}
4. We send the letter generated on a template in one line:
render_to_email(article.author.email, 'approved.html', {'article': article})
A letter template can contain a subject and any other headers.
5. A collection of model fields and corresponding form fields and widgets:
DAYS = zip(range(7), 'Sun Mon Tue Wed Thu Fri Sat'.split()) class Company(models.Model): phones = StringArrayField('Phone numbers', blank=True, default='{}') workdays = IntegerArrayField('Work days', choices=DAYS) company = Company(phones=['234-5016', '516-2314'], workdays=[1,2,3,4]) company.save()
In the form of
phones
will be displayed in a text field separated by commas, and
workdays
in the form of several checkboxes.
There is also a
JSONField
for storing arbitrary data and other fields.
And further:
- middleware, which cuts out unnecessary spaces from html-answers,
- shared master-slave router,
- a small wrapper to simplify logging,
- and a couple of text and debug utilities.
Share experience
I would like to hear back, or better see, your ways to simplify your life. If there are no solutions, then problems and problems or just repetitive work patterns that are encountered in your developer life are interesting.
Links:
Github ,
PyPi ,
Django Packages and
documentation in English .