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
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 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
4 snippets posted so far.