Login

create_update for newforms (ModelForm)

Author:
Rozza
Posted:
March 10, 2008
Language:
Python
Version:
.96
Tags:
newforms forms generic-views modelform
Score:
0 (after 2 ratings)

Based on danjak's snippet but updated to use ModelForms - so can easily handle generic CRUD operations.

A replacement create_update.py for use with ModelForm

create_object and update_project modified to handle newforms (including FileFields) with ModelForm - it also had delete_object as well for completeness.

In addition, it has some extras:

  • extra_fields - this is a dict or callable that contains additional fields to be passed to the form, for example stuff that is in the session.
  • on_success - callback called if form is valid and object created/updated, if this is not set the default behaviour is to send a redirect
  • on_failure - callback called if form is invalid, the default is to redisplay the form.

Note that once newforms are finally done these functions are likely to be redundant, as generic views will be updated to use the newforms API, so use with caution!

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
from django.core.xheaders import populate_xheaders
from django.template import loader
from django.contrib.auth.views import redirect_to_login
from django.template import RequestContext
from django.db.models import FileField
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.utils.translation import gettext
from django import newforms as forms

        
"""
Rewrites of create_object and update_object generic views, modified to use newforms.
Some other changes:
- extra_fields : this can be a dict, or callable returning a dict:
    def extra_fields(request, object = None) (object passed to callable in update_object)
  This allows passing in of non-form fields, for example the current user id, e.g.
  extra_fields = { "author" : request.user }
- model_form - a ModelForm instance.
- on_success - callback called after successful save:
    def on_success(request, form, object)
  If on_success is not set, a redirect is returned
- on_failure - callback called if form is invalid:
    def on_failure(request, form, object = None) (object passed to callable in update_object)
  If on_failure is not set, form template is displayed with errors.

Example:

class Project(models.Model):
    name = models.CharField(maxlength = 50)
    description = models.TextField()
    owner = models.ForeignKey(User, editable = False)

def add_project(request):

    return create_object(request, Project, on_success = on_create_project,
        extra_fields = {"owner" : request.user})
        
def on_create_project(request, form, project):

    request.session["flash"] = "Project %s created!" %project.name
    return HttpResponseRedirect("/")
    
"""

def save_file_fields(new_data, object):

    for f in object._meta.fields:
        if f.name in new_data and isinstance(f, FileField):
            upload_data = new_data.get(f.name, False)
            if upload_data:
                func = getattr(object, 'save_%s_file' % f.name)
                func(upload_data["filename"],upload_data["content"], False)
         
def create_object(request, model, template_name=None,
        model_form = None, extra_fields = None,
        template_loader=loader, extra_context=None, post_save_redirect=None,
        login_required=False, context_processors=None, 
        on_success = None, on_failure=None):
    
    """
    Generic object-creation function.

    Templates: ``<app_label>/<model_name>_form.html``
    Context:
        form
            the form wrapper for the object
    """
    if extra_context is None: extra_context = {}
    if login_required and not request.user.is_authenticated():
        return redirect_to_login(request.path)

    if model_form is None: 
      class ModelFormClass(ModelForm): 
          class Meta: 
              model = model_ 
      model_form = ModelFormClass

    if request.POST or request.FILES:
        # If data was POSTed, we're trying to create a new object
        new_data = request.POST.copy()

        if request.FILES:
            new_data.update(request.FILES)

        form = model_form(new_data)
        
        if form.is_valid():
            
            # No errors -- this means we can save the data!
            if callable(extra_fields) : extra_fields = extra_fields(request)
            
            if extra_fields is None : extra_fields = {}
                                
            if extra_fields or request.FILES:
                new_object = form.save(commit = False)
                for k, v in extra_fields.items():
                    setattr(new_object, k, v)
                save_file_fields(new_data, new_object)
                new_object.save()
            else:
                new_object = form.save(commit = True)
                
            if callable(on_success):
                return on_success(request, form, new_object)
            else:   

                if request.user.is_authenticated():
                    request.user.message_set.create(message=gettext("The %(verbose_name)s was created successfully.") % {"verbose_name": model._meta.verbose_name})

                # Redirect to the new object: first by trying post_save_redirect,
                # then by obj.get_absolute_url; fail if neither works.
                if post_save_redirect:
                    return HttpResponseRedirect(post_save_redirect % new_object.__dict__)
                elif hasattr(new_object, 'get_absolute_url'):
                    return HttpResponseRedirect(new_object.get_absolute_url())
                else:
                    raise ImproperlyConfigured("No URL to redirect to from generic create view.")
        else:
        
            if callable(on_failure): return on_failure(request, form)
    else:
        # No POST, so we want a brand new form without any data or errors
        form = model_form()
    
    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower())
    t = template_loader.get_template(template_name)
    c = RequestContext(request, {
        'form': form,
    }, context_processors)
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    return HttpResponse(t.render(c))

def update_object(request, model, object_id=None, slug=None,
        slug_field=None, template_name=None, template_loader=loader,
        extra_context=None, post_save_redirect=None, extra_fields = None,
        login_required=False, context_processors=None,
        model_form = None, on_success = None, on_failure = None,
        template_object_name='object'):
    """
    Generic object-update function.

    Templates: ``<app_label>/<model_name>_form.html``
    Context:
        form
            the form wrapper for the object
        object
            the original object being edited
    """
    if extra_context is None: extra_context = {}
    if login_required and not request.user.is_authenticated():
        return redirect_to_login(request.path)

    # Look up the object to be edited
    lookup_kwargs = {}
    if object_id:
        lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id
    elif slug and slug_field:
        lookup_kwargs['%s__exact' % slug_field] = slug
    else:
        raise AttributeError("Generic edit view must be called with either an object_id or a slug/slug_field")
    try:
        object = model.objects.get(**lookup_kwargs)
    except ObjectDoesNotExist:
        raise Http404, "No %s found for %s" % (model._meta.verbose_name, lookup_kwargs)

    if model_form is None: 
      class ModelFormClass(ModelForm): 
          class Meta: 
              model = model_ 
      model_form = ModelFormClass
  
    if request.POST or request.FILES:
        # If data was POSTed, we're trying to create a new object
        new_data = request.POST.copy()

        if request.FILES:
            new_data.update(request.FILES)
        form = model_form(new_data, instance=object)
    
        if form.is_valid():
            # No errors -- this means we can save the data!
            if callable(extra_fields) : extra_fields = extra_fields(request, object)
            
            if extra_fields or request.FILES:
                form.save(commit = False)
                for k, v in extra_fields.items():
                    setattr(object, k, v)
                save_file_fields(new_data, object)
                object.save()
            else:
                form.save(commit = True)

            if callable(on_success):

                return on_success(request, form, object)

            else:   

                if request.user.is_authenticated():
                    request.user.message_set.create(message=gettext("The %(verbose_name)s was updated successfully.") % {"verbose_name": model._meta.verbose_name})

                # Do a post-after-redirect so that reload works, etc.
                if post_save_redirect:
                    return HttpResponseRedirect(post_save_redirect % object.__dict__)
                elif hasattr(object, 'get_absolute_url'):
                    return HttpResponseRedirect(object.get_absolute_url())
                else:
                    raise ImproperlyConfigured("No URL to redirect to from generic create view.")

    else:
    
        form = model_form(instance=object) 
        if callable(on_failure) : return on_failure(request, form, object)
        
    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower())
    t = template_loader.get_template(template_name)
    c = RequestContext(request, {
        'form': form,
        template_object_name: object,
    }, context_processors)
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, model, getattr(object, object._meta.pk.attname))
    return response

def delete_object(request, model, post_delete_redirect,
        object_id=None, slug=None, slug_field='slug', template_name=None,
        template_loader=loader, extra_context=None,
        login_required=False, context_processors=None, template_object_name='object'):
    """
    Generic object-delete function.

    The given template will be used to confirm deletetion if this view is
    fetched using GET; for safty, deletion will only be performed if this
    view is POSTed.

    Templates: ``<app_label>/<model_name>_confirm_delete.html``
    Context:
        object
            the original object being deleted
    """
    if extra_context is None: extra_context = {}
    if login_required and not request.user.is_authenticated():
        return redirect_to_login(request.path)

    # Look up the object to be edited
    lookup_kwargs = {}
    if object_id:
        lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id
    elif slug and slug_field:
        lookup_kwargs['%s__exact' % slug_field] = slug
    else:
        raise AttributeError("Generic delete view must be called with either an object_id or a slug/slug_field")
    try:
        object = model._default_manager.get(**lookup_kwargs)
    except ObjectDoesNotExist:
        raise Http404, "No %s found for %s" % (model._meta.app_label, lookup_kwargs)

    if request.method == 'POST':
        object.delete()
        if request.user.is_authenticated():
            request.user.message_set.create(message=ugettext("The %(verbose_name)s was deleted.") % {"verbose_name": model._meta.verbose_name})
        return HttpResponseRedirect(post_delete_redirect)
    else:
        if not template_name:
            template_name = "%s/%s_confirm_delete.html" % (model._meta.app_label, model._meta.object_name.lower())
        t = template_loader.get_template(template_name)
        c = RequestContext(request, {
            template_object_name: object,
        }, context_processors)
        for key, value in extra_context.items():
            if callable(value):
                c[key] = value()
            else:
                c[key] = value
        response = HttpResponse(t.render(c))
        populate_xheaders(request, response, model, getattr(object, object._meta.pk.attname))
        return response

More like this

  1. create_object and update_object for newforms by danjak 8 years, 2 months ago
  2. ModelForm-based create_update generic views by carljm 6 years, 10 months ago
  3. Complex Formsets by smagala 6 years, 4 months ago
  4. RecaptchaForm by oggy 6 years, 11 months ago
  5. Add a CSS class to every field indicating what kind of field it is by ramen 4 years, 10 months ago

Comments

Please login first before commenting.