Snippet List
**CancelMixin**
A simple mixin to use with ```generic.CreateView``` and ```generic.UpdateView``` view form templates to effortlessly implement a "Cancel" button.
This smart mixin will add a URL to your context, ```{{ cancel_url }}```, that can be used as a cancel link in your form template. If no referrer URL is provided, the cancel button will link to ```default_cancel_url```, which can be overridden by view.
** **
- template
- django
- mixin
- update
- create
- cbv
Use this class to partially update one or more fields of a model. Only the fields that are bound to the form via the "data" parameter in the constructor get updated. All automatically generated fields have their "required" attribute set to False.
Example 1:
from django.contrib.auth.models import User
class PatchUserForm(PatchModelForm):
class Meta:
model = User
user = User.objects.get(username='old_username')
form = PatchUserForm(data={'username':'new_username'}, instance=user)
form.is_valid()
form.save()
Example 2:
from django.contrib.auth.models import User
class PatchUserForm(PatchModelForm):
class Meta:
model = User
user = User.objects.get(pk=35)
form = PatchUserForm(data={'last_name':'Smith', 'is_staff': True}, instance=user)
form.is_valid()
form.save()
- models
- rest
- update
- patch
- partial-update
This snippet is based on 928.
I've added the support to update a custom folder, using shell arguments.
It requires the argparse module.
You can install it with:
pip install argparse
Usage:
# Updates repositories in the specified <folder path>
# The default is the ./ folder
update_repos --path <folder path>
# List available options
update_repos -h
Alessandro Molari
- update
- applications
- svn
- git
- baazar
- mercurial
- repositories
Some times I want to change the `owner` of an object to another user - problem is the object often has a lot of other objects pointing to them - I also want to update those fields.
This is a generic snippet for doing just that!
For instance:
change_owner(obj, new_owner_id):
return update_related_field(obj, new_owner_id, field="user")
This is the (revamped) bash script I use to keep my git branches up-to-date with SVN to make my life a lot easier, just save it in a text file and read the instructions at the top!
Hope it's useful to somebody else than me ;)
- bash
- merge
- update
- svn
- git
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
Here's an example of writing generic views in an object-oriented style, which allows for very fine-grained customization via subclassing. The snippet includes generic create and update views which are backwards compatible with Django's versions.
To use one of these generic views, it should be wrapped in a function that creates a new instance of the view object and calls it:
def create_object(request, *args, **kwargs):
return CreateObjectView()(request, *args, **kwargs)
If an instance of one of these views is placed directly in the URLconf without such a wrapper, it will not be thread-safe.
- views
- generic
- object
- update
- create
This snippet is based on [#844](http://www.djangosnippets.org/snippets/844/ "#844") and [#892](http://www.djangosnippets.org/snippets/892/ "#892") and updates all apps in the current directory using hg, svn, git or bzr. Including subdirectories not under version control (subfolders to keep your stuff organized).
For example:
python/lib/
django-trunk/
django-0.96/
pydelicious/
(...)
django-apps/
django-tagging/
django-pagination/
django-registration/
django-threadedcomments/
django-mptt/
(...)
The script will iterate through all of your apps (in the current dir and also recursively in subdirs NOT under version control) and update them to the latest version.
To run, simply execute:
python update_apps.py
in the desired parent folder.
Just in case it could be useful: In my case I'm using MAC OS X. I have a folder full of miscellaneous scripts under my HOMEDIR, with this content:
/Users/Dedaluz/bin/update_apps.py
/Users/Dedaluz/bin/update_apps (this is a bash script)
The update_apps script contains simply:
#!/bin/bash
python /Users/Dedaluz/bin/update_apps.py
Then I put this folder in my path, so in my /HOMEDIR/.bash_profile I add this line
export PATH=$PATH:$HOME/bin
And I just can update from any parent folder just going there and typing: update_apps
- script
- update
- svn
- git
- hg
- bzr
This snippet is based on [#844](http://www.djangosnippets.org/snippets/844/) and updates all apps in the current directory using hg, svn, git or bzr.
This is a ModelForms-based rewrite of the create_object and update_object generic views, with a few added features. The views now accept a "form_class" argument optionally in place of the "model" argument, so you can create and tweak your own ModelForm to pass in. They also accept a "pre_save" callback that can make any additional changes to the created or updated instance (based on request.user, for instance) before it is saved to the DB.
Usage: just save the code in a file anywhere on the PythonPath and use the create_object and update_object functions as views in your urls.py.
- newforms
- views
- generic
- update
- modelforms
- create
A simple script that I have put in my Django applications directory to fetch the latest application code from git and svn.
For example, your directory structure might look like so:
django-apps/
django-tagging/
django-pagination/
django-registration/
django-threadedcomments/
django-mptt/
update_apps.py
Where update_apps.py is the source of this snippet.
To run, simply execute:
# python update_apps.py
And the script will iterate through all of your apps and update them to the latest version.
- script
- update
- apps
- project
- svn
- git
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)
Watch out! Previous versions of this snippet (without the values list) were vulnerable to SQL injection attacks. The "correct" solution is probably to wait until [ticket 4102](http://code.djangoproject.com/ticket/4102) hits the trunk. But here's my temporary fix while we wait for that happy day.
Django's model.save() method is a PITA:
1. It does a SELECT first to see if the instance is already in the database.
2. It has additional database performance overhead because it writes all fields, not just the ones that have been changed.
3. It overwrites other model fields with data that may be out of date. This is a real problem in concurrent applications, like almost all web apps.
If you just want to update a field or two on a model instance which is already in the database, try this:
update_fields(user,
email='[email protected]',
is_staff=True,
last_login=datetime.now())
Or you can add it to your models (see below) and then do this:
user.update_fields(
email='[email protected]',
is_staff=True,
last_login=datetime.now())
To add it to your model, put it in a module called granular_update, then write this in your models.py:
import granular_update
class User(models.Model):
email = models.EmailField()
is_staff = models.BooleanField()
last_login = models.DateTimeField()
update_fields = granular_update.update_fields
- fields
- model
- save
- performance
- field
- update
- integrity
- consistency
13 snippets posted so far.