newforms and ModelForm

 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. Database Schema Upgrade (deprecated) by guettli 5 years, 5 months ago
  2. isUnique validator for newforms by clamothe 5 years, 9 months ago
  3. view ModelForm by hrdcdr 1 year ago
  4. Reorder fields directly in the ModelForm by HM 5 years, 11 months ago
  5. Multiple inheritance of newforms and modelforms by simon 6 years ago

Comments

(Forgotten your password?)