1 | from django.core.exceptions import ImproperlyConfigured
|
---|
2 | from django.http import HttpResponseRedirect
|
---|
3 | from django.views.generic.detail import SingleObjectTemplateResponseMixin
|
---|
4 | from django.views.generic.edit import ModelFormMixin, ProcessFormView
|
---|
5 |
|
---|
6 | class SafeModelFormMixin(ModelFormMixin):
|
---|
7 | def create_new(self):
|
---|
8 | pk = self.kwargs.get('pk', None)
|
---|
9 | slug = self.kwargs.get('slug', None)
|
---|
10 | return not (pk or slug)
|
---|
11 |
|
---|
12 | def get_object(self, *args, **kwargs):
|
---|
13 | if self.create_new():
|
---|
14 | return None
|
---|
15 | else:
|
---|
16 | return super(SafeModelFormMixin, self).get_object(*args, **kwargs)
|
---|
17 |
|
---|
18 | class BaseModelFormView(SafeModelFormMixin, ProcessFormView):
|
---|
19 | """
|
---|
20 | Base view for an object instance.
|
---|
21 |
|
---|
22 | Using this base class requires subclassing to provide a response mixin.
|
---|
23 | """
|
---|
24 |
|
---|
25 | action_name = 'action'
|
---|
26 |
|
---|
27 | def get(self, request, *args, **kwargs):
|
---|
28 | self.object = self.get_object()
|
---|
29 | return super(BaseModelFormView, self).get(request, *args, **kwargs)
|
---|
30 |
|
---|
31 | def post(self, request, *args, **kwargs):
|
---|
32 | if self.action_name and request.POST.has_key(self.action_name):
|
---|
33 | if request.POST[self.action_name].lower() == 'delete':
|
---|
34 | return self.delete(request, *args, **kwargs)
|
---|
35 | self.object = self.get_object()
|
---|
36 | return super(BaseModelFormView, self).post(request, *args, **kwargs)
|
---|
37 |
|
---|
38 | # PUT is a valid HTTP verb for creating (with a known URL) or editing an
|
---|
39 | # object, note that browsers only support POST for now.
|
---|
40 | def put(self, *args, **kwargs):
|
---|
41 | return self.post(*args, **kwargs)
|
---|
42 |
|
---|
43 | def delete(self, request, *args, **kwargs):
|
---|
44 | self.object = self.get_object()
|
---|
45 | self.object.delete()
|
---|
46 | return HttpResponseRedirect(self.get_success_url())
|
---|
47 |
|
---|
48 | def get_success_url(self):
|
---|
49 | if self.success_url:
|
---|
50 | return self.success_url
|
---|
51 | else:
|
---|
52 | raise ImproperlyConfigured(
|
---|
53 | "No URL to redirect to. Provide a success_url.")
|
---|
54 |
|
---|
55 | class ModelFormView(SingleObjectTemplateResponseMixin, BaseModelFormView):
|
---|
56 | """
|
---|
57 | View for creating an new object instance,
|
---|
58 | with a response rendered by template.
|
---|
59 | """
|
---|
60 | template_name_suffix = '_form'
|
---|