Generic Views for newforms

 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
# Generic views for newforms library

def nf_update_object(request, model, object_id=None, fields=[], template_name=None, extra_context={}, post_save_redirect="../", context_instance=None, my_callback=None):
    
    object = get_object_or_404(model, pk=object_id)
    ObjectForm = newforms.form_for_instance(object, fields=fields, formfield_callback=my_callback )

    if request.POST:
        form = ObjectForm(request.POST)
        if form.is_valid():
            object_updated = form.save()
            log.change_object(object_updated, request.user.username)
            return HttpResponseRedirect(post_save_redirect)
    else:
        form = ObjectForm()
    
    context = {'form':form, 'object':object, 'add':False}
    context.update(extra_context)

    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower())

    if context_instance:
        return render_to_response(template_name, context, context_instance=context_instance)
    else:
        return render_to_response(template_name, context, context_instance=RequestContext(request))

def nf_create_object(request, model, fields=[], template_name=None, extra_context={}, post_save_redirect="../", context_instance=None, my_callback=None):
    
    ObjectForm = newforms.form_for_model(model, fields=fields, formfield_callback=my_callback )

    if request.POST:
        form = ObjectForm(request.POST)
        if form.is_valid():
            object_created = form.save()
            log.add_object(object_created, request.user.username)
            return HttpResponseRedirect(post_save_redirect)
    else:
        form = ObjectForm()
    
    context = {'form':form, 'object':object, 'add':True}
    context.update(extra_context)
    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower())

    if context_instance:
        return render_to_response(template_name, context, context_instance=context_instance)
    else:
        return render_to_response(template_name, context, context_instance=RequestContext(request))
        

More like this

  1. ModelForm-based create_update generic views by carljm 5 years, 9 months ago
  2. login_required for a generic view in URLconf by pgugged 5 years, 9 months ago
  3. create_object and update_object for newforms by danjak 7 years, 1 month ago
  4. Generic view 'redirect_to' that supports QUERY_STRING by marinho 4 years, 6 months ago
  5. create_update for newforms (ModelForm) by Rozza 6 years, 1 month ago

Comments

david_bgk (on February 4, 2008):

form_for_* are now deprecated, you should use ModelForm instead.

#

(Forgotten your password?)