TemplateZipFile is a class for creating ZipFiles out of Django templates.
Usage example:
from zipfile import ZIP_DEFLATED
from django_zipfile import TemplateZipFile
def myview(request, object_id):
obj = get_object_or_404(MyModel, pk=object_id)
context = {
'object': obj
}
response = HttpResponse(mimetype='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename=myfile.zip'
container = TemplateZipFile(response, mode='w', compression=ZIP_DEFLATED, template_root='myapp/myzipskeleton/')
container.add_template('mimetype')
container.add_template('META-INF/container.xml')
container.add_template('chapter1.html', context=context)
container.close()
return response
Django provides a `get_or_create` helper method in the `models.Manager` class which looks up an object for the given `kwargs`, creating one if necessary. But sometime you need a method which updates the object with given `kwargs` or creates it if it's not found. This snippet provides the helper for that purpose.
Use the snippet like this:
from django.db import models
class PersonManager(models.Manager):
update_or_create = _update_or_create
class Person(models.Model):
first_name = models.CharField()
last_name = models.CharField()
city = models.CharField()
objects = PersonManager()
person, created, updated = Person.objects.update_or_create(first_name="John",
last_name="Smith", defaults=dict(city="London"))
The method returns a tuple of (`object`, `created`, `updated`), where `created` and `updated` are booleans specifying whether an `object` was created or updated respectively. Both `created` and `updated` are `false` if `object` is neither created nor updated (that is `object` has just been fetched "as is" from db). This happens if the update fails.
- model
- helper
- update
- create