Skip to content

Instantly share code, notes, and snippets.

@bentappin
Last active August 29, 2015 14:21
Show Gist options
  • Save bentappin/e6a4d824fca84a2daac7 to your computer and use it in GitHub Desktop.
Save bentappin/e6a4d824fca84a2daac7 to your computer and use it in GitHub Desktop.
A reusable confirm field update pattern for Django
Copied from https://github.com/code-kitchen/django-utensils/ and licensed under the MIT license.
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseRedirect
class SetModelFieldMixin(object):
"""
Mixin that can be used to set a value on a detail view (i.e. the view must
have a self.get_object() function) on POST.
"""
success_url = None
def get_success_url(self):
if self.success_url:
return self.success_url
else:
raise ImproperlyConfigured(
"No URL to redirect to. Provide a success_url.")
def get_field(self):
try:
return getattr(self, 'field')
except AttributeError:
raise ImproperlyConfigured("No field provided.")
def get_value(self):
try:
return getattr(self, 'value')
except AttributeError:
raise ImproperlyConfigured("No value provided.")
def set_value(self, *args, **kwargs):
self.object = self.get_object()
setattr(self.object, self.get_field(), self.get_value())
self.object.save()
return HttpResponseRedirect(self.get_success_url())
def post(self, *args, **kwargs):
return self.set_value(*args, **kwargs)
from django.views.generic.detail import BaseDetailView, SingleObjectTemplateResponseMixin
from .viewmixins import SetModelFieldMixin
class BaseSetModelFieldView(SetModelFieldMixin, BaseDetailView):
"""
Base view for setting a single value on a model instance.
Using this base class requires subclassing to provide a response mixin.
"""
class SetModelFieldView(BaseSetModelFieldView, SingleObjectTemplateResponseMixin):
"""
View for setting a single value on an object on POST. GET should be used for
a confirmation view.
Required class settings:
* `field` or `get_field()` - string containing the field name to alter
* `value` or `get_value()` - the value to set the field to
"""
from .models import Blog
from .views import SetModelFieldView
class PublishBlogPostView(SetModelFieldView):
model = Blog
field = 'is_published'
value = True # Alternatively override `get_value()` if business logic is required.
template_name = 'publish_blog.html'
<html>
<head>
<title>Publish blog post?</title>
</head>
<body>
<h1>Are you sure you want to publish the blog post '{{ object }}'?</h1>
<form action="" method="post">
{% csrf_token %}
<button type="submit">Yes</button>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment