0

I am trying to create a ModelForm that updates a record in my database, but for some reason it isn't working. It turns out blank. What am I doing wrong here?

this is my forms.py:

class PageForm(ModelForm):
    class Meta:
        model = Page

this is my views.py:

def detail(request, page_id):
    p = get_object_or_404(Page, pk=id)
    if request.method == 'POST':
        form = PageForm(request.POST, instance=p)
        if form.is_valid():
           form.save()
           messages.success(request, "Detail updated successfully.")
           return HttpResponseRedirect('/thanks/')
    return render(request, 'pages/pageform.html', {
    'form': PageForm(instance=p),
})

this is my model.py:

class Page(models.Model):
    pub_date = models.DateTimeField('date published')
    title = models.CharField(max_length=255)
    keywords = models.CharField(max_length=255)
    description = models.CharField(max_length=255)
    content = models.TextField()
    def __unicode__(self):
        return self.title

this is my pageform.html

<form action="/detail/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

this is my urls.py

urlpatterns = patterns('',
    url(r'^page/(?P<id>\d+)/$', 'detail', name='detail'),
)

2 Answers2

0

You need to create form for get request as well.

Update your view as

def detail(request, page_id):
    if request.method == 'POST':
    ....
    else:
        p = Page.objects.get(pk=page_id)
        form = PageForm(instance=p)
    ....

Also, do not create new form when form is not valid as it will not show any errors.

Rohan
  • 52,392
  • 12
  • 90
  • 87
  • I tried doing what you said too, but the form still appears blank, and only the submit button appears. I edited my question to include my template. – user972356 Jan 26 '13 at 13:07
0

Thank you Cathy and Rohan! This worked for me:

views.py

def detail(request, page_id):
    p = get_object_or_404(Page, pk=page_id)
    if request.method == 'POST':
        form = PageForm(request.POST or None, instance=p)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/thanks/')
    else:
        form = PageForm(instance=p)
    return render_to_response('pages/detail.html', {'page': p, 'form': form}, context_instance=RequestContext(request))

urls.py:

urlpatterns = patterns('',
    url(r'^page/(?P<page_id>\d+)/$', 'pages.views.detail'),
)