Login

newforms and ModelForm

Author:
danfairs
Posted:
January 1, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

I noticed that form_for_* in newforms now carry deprecation warnings. This code is a minimal demonstration of how to use ModelForm as a replacement.

Full information can be found on Stereoplex. Hope this helps you.

 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
# models.py

class Project(models.Model):
    title = models.CharField(max_length=50)
    created_on = models.DateTimeField(auto_now_add=True)
    description = models.TextField(max_length=5000)

    def __unicode__(self):
        return self.title

    class Admin:
        pass

# forms.py

from pm.models import Project
from django import newforms as forms

class ProjectForm(forms.ModelForm):
        
    class Meta:
        model=Project

# views.py
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from pm.forms import ProjectForm

@permission_required('pm.add_project')
def project_add(request):
    project = Project()
    if request.POST:
        form = ProjectForm(data=request.POST, instance=project)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse(project_detail, args=(project.id,)))
        else:
            request.user.message_set.create(message='Please check your data.')
    else:
        form = ProjectForm(instance=project)

    context = section(request, 'projects')
    context['form'] = form
    return render_to_response('templates/pm/project_add.html', RequestContext(request, context))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.