无法在html模板中填充django生成的表单

时间:2014-05-08 04:55:19

标签: python django forms

我正在尝试使用django的表单模块来创建和显示表单。我执行的以下代码没有错误,但未填充HTML表单。 我已经确定我正在加载正确的模板。我也确定当我转到某个URL时会触发正确的视图。我在下面从视图,模型,表单和模板文件中发布了一些相关代码。我通过反复试验进行了相当多的调试,但无法找到问题的根源。

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from app.forms import RegistrationForm

def registration(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/profile/')
    if request.method == 'POST':
        pass
    else:
        ''' user is not submitting the form, show them a blank registration form '''
        form = RegistrationForm()
        context = {'form': form}
        return render_to_response('register.html', context, context_instance=RequestContext(request))

register.html

{% extends "base.html" %}
{% block content %}


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


{% endblock %}

form.py

from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from app.models import Agent

class RegistrationForm(ModelForm):
    username = forms.CharField( label=(u'User Name'), required=True )
    first_name = forms.CharField( label=(u'First Name'), required=True )
    last_name = forms.CharField( label=(u'Last Name'), required=True )
    birthday = forms.DateField( label=(u'Date of birth'), required=True )
    email = forms.EmailField( label=(u'Email Address'), required=True )
    password = forms.CharField( label=(u'Password'), widget=forms.PasswordInput(render_value=False), required=True )
    password_confirm = forms.CharField( label=(u'Confirm Password'), widget=forms.PasswordInput(render_value=False), required=True )

    class Meta:
        model = Agent
        #exclude = ['username',]

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError("That username is already taken, please select another.")

    def clean(self):
        if self.cleaned_data['password'] != self.cleaned_data['password_confirm']:
            raise forms.ValidationError("The passwords did not match.  Please try again.")
        return self.cleaned_data       

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class Agent(models.Model):
    username = models.OneToOneField(User)
    birthday = models.DateField()
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField()

    def __unicode__(self):
        return self.last_name + ", " + self.first_name

1 个答案:

答案 0 :(得分:0)

必须在base.html中添加内容块引用

{% block content %}
{% endblock %}