验证问题

时间:2012-09-03 05:30:05

标签: django django-forms django-views

我在验证方面存在一些问题。当我提交表单时, form.is_valid(): 始终返回 false 。 修改表单后,即从表单中删除所有验证后,仍然返回false(我的表单未提交)

html的代码

{% extends "base.html" %}
{% block extrahead %}
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js" type="text/javascript"></script>
    <script>
    $(function() {
        $( "#id_birthday" ).datepicker();
    });
    </script>
{% endblock %}
{% block content %}
<form action="" method="post">
{% csrf_token %}

<div class="register_div">

    <p><label for="username">Username:</label></p>


    <p>{{ form.username }}</p>
</div>
<div class="register_div">

    <p><label for="email">Email:</label></p>
    <p>{{ form.email }}</p>
</div>
<div class="register_div">

    <p><label for="password">Password:</label></p>
    <p>{{ form.password }}</p>
</div>
<div class="register_div">

    <p><label for="password1">Verify Password:</label></p>
    <p>{{ form.password1 }}</p>
</div>
<div class="register_div">

    <p><label for="birthday">Birthday:</label></p>
    <p>{{ form.birthday }}</p>
</div>
<div class="register_div">
    <p><label for="name">Name:</label></p>
    <p>{{ form.username }}</p>
</div>
<p><input type="submit" value="submit" alt="register"/></p>
</form>
{% endblock %}

forms.py

的代码
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from drinker.models import Drinker

class RegistrationForm(ModelForm):
       username   = forms.CharField(label=(u'User Name'))
       email      = forms.EmailField(label=(u'Email Address'))
       password   = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
       password1   = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput(render_value=False))

       class Meta:
              model=Drinker
              exclude=('user',)

       def clean_username(self):
                username=self.cleaned_data['username']
                try:
                      User.objects.get(username=username)
                except User.DoesNotExist:
                      return username
                raise forms.ValidationError("The Username is already taken, please try another.")
       def clean_password(self):
                password=self.cleaned_data['password']
                password1=self.cleaned_data['password1']
                if password1 != password:
                    raise forms.ValidationError("The Password did not match, please try again.")
                return password

class LoginForm(forms.Form):
      username  = forms.CharField(label=(u'User Name'))
      password  = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))

和views.py的代码

def DrinkerRegistration(request):
    if request.user.is_authenticated():
         return HttpResponseRedirect('/profile/')
    if request.method == 'POST':
         form = RegistrationForm(request.POST)
         #return render_to_response('register')
         if form.is_valid():
                  user=User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password = form.cleaned_data['password'])

                  user.save()
 #                 drinker=user.get_profile()
  #                drinker.name=form.cleaned_data['name']
   #               drinker.birthday=form.cleaned_data['birthday']
    #              drinker.save()
                  drinker=Drinker(user=user,name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])  
                  drinker.save()    
                  return HttpResponseRedirect('/profile/')
         else:
                  return render_to_response('register.html',{'form':form} , context_instance=RequestContext(request))  
    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))

型号代码

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class Drinker(models.Model):
       user     =models.OneToOneField(User)
       birthday =models.DateField()
       name     =models.CharField(max_length=100)

       def __unicode__(self):
             return self.name

#create our user object to attach to our drinker object

def create_drinker_user_callback(sender, instance, **kwargs):
      drinker, new=Drinker.objects.get_or_create(user=instance)
post_save.connect(create_drinker_user_callback, User)

3 个答案:

答案 0 :(得分:0)

我可以看到两个可能的原因:

  1. 您的模板包含两个username用法:一次位于顶部,一次位于底部。表单可能会失败,因为它不适合单个CharField
  2. 没有你的模型类很难说,但也许它包含你没有明确排除的字段?
  3. 如果不是选项1,您是否也可以发布Drinker模型?

答案 1 :(得分:0)

您在验证时检查了错误报告吗?

使用print form.errors并检查控制台是否有错误消息

答案 2 :(得分:0)

如果您的代码更改未在运行环境中反映出来,请查看删除* .pyc文件。这些有时可以缓存。

对于Linux OS,您可以从项目的根目录运行以下命令;

find . -iname "*.pyc" -exec rm -f {} \;