【问题标题】:IntegrityError + djangoIntegrityError + Django
【发布时间】:2011-08-02 22:17:09
【问题描述】:

我创建了一个 django 应用程序。该应用程序有一个注册表。我为生日选择器插入了一个 jQuery 插件。但是现在当我填写注册表并保存时会抛出此错误“IntegrityError at /registrationForm/
(1048, "Column 'birthday' cannot be null") "
. 我会把我的代码贴在这里。

registrationForm.html

<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<script type="text/javascript" src="http://10.1.0.90:8080/static/jquery.js"></script>
<script type="text/javascript" src="http://10.1.0.90:8080/static/jquery-ui.min.js"></script>
<link href="http://10.1.0.90:8080/static/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://10.1.0.90:8080/static/bday-picker.js"></script>



<script type="text/javascript">
      $(document).ready (function() {
        //$( "#datepicker" ).datepicker();
        $("#picker1").birthdaypicker({});
    });
   //Created / Generates the captcha function    
    function DrawCaptcha()
    {
    var a = Math.ceil(Math.random() * 10)+ '';
    var b = Math.ceil(Math.random() * 10)+ '';       
    var c = Math.ceil(Math.random() * 10)+ '';  
    var d = Math.ceil(Math.random() * 10)+ '';  
    var e = Math.ceil(Math.random() * 10)+ '';  
    var f = Math.ceil(Math.random() * 10)+ '';  
    var g = Math.ceil(Math.random() * 10)+ '';  
    var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
    document.getElementById("txtCaptcha").value = code
    }

    // Validate the Entered input aganist the generated security code function   
    function ValidCaptcha(){
        var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
        var str2 = removeSpaces(document.getElementById('txtInput').value);
        if (str1 == str2) return true;        
        return false;

    }

    // Remove the spaces from the entered and generated code
    function removeSpaces(string)
    {
        return string.split(' ').join('');
    }

    </script>
</head>
<title>Login/Registration Page</title>
<body bgcolor="#736F6E" onLoad="DrawCaptcha();">
<div align="center">
<form name="userInputForm" method="POST" id="myFormid" action="http://10.1.0.90:8080/login/">
  <div style="float:left;width:100%;">
    <p style="float:left;margin-right:10px;width:auto;">
      <label style="float:left;">Email id</label>
      <br/>
      <input type="text" name="username" size="25" />
    </p>
    <p style="float:left;margin-right:10px;width:auto;">
      <label style="float:left;">Password</label>
      <br/>
      <input type="password" name="password" size="25" />
      {% if invalid %}
      Mismatch in your email/password. 
      {% endif %} </p>
  </div>

  <p style="clear:both;float:left;">
    <input type="submit" value="Log in" style="float:left;margin-right:4px;"/>&nbsp;
    {% load facebookconnect %}
    {% facebook_connect_login_button %}
    {% facebook_connect_script %}

    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a HREF="http://10.1.0.90:8080/forgotPassword/">Forgotten your password?</a></p>
  </div>
</form>
<br>

<br>
<br>

<script type="text/javascript">
function userCheck(){
    /*document.getElementById('myFormid').action = "http://10.1.0.90:8080/login/";
    if ((document.userInputForm.username.value.length==0)) */
}
</script>
<form name ="myform"  method="POST" id='FormID'>
<table>
  <tr>
    <td>First name</td>
    <td><input type="text" name="firstName" value=""  maxlength="100" />
      <b id="firstNameID" style="font-family:Times New Roman;color:#B4045F;font-size:14px;"> </td>
  </tr>
  <tr>
    <td>Last name</td>
    <td><input type="text" name="lastName" value="" maxlength="100" />
    </td>
  </tr>
  <tr>
    <td>E-mail</td>
    <td><input type="text" name="email" value="" maxlength="100" />
    </td>
  </tr>
  <tr>
    <td>Password</td>
    <td><input type="password" name="password" value="" maxlength="100"  />
      <b id="passwordID" style="font-family:Times New Roman;color:#B4045F;font-size:14px;"> </td>
  </tr>
  <tr>
    <td>Re-Type Password</td>
    <td><input type="password" name="password1" value="" maxlength="100"  />
      <b id="passwordID1" style="font-family:Times New Roman;color:#B4045F;font-size:14px;"> </td>
  </tr>
  <tr>
    <td>Gender:</td>
    <td><input type="radio" name="sex" value="male" />
      Male
      <input type="radio" name="sex" value="female" />
      Female </td>
  </tr>
  <tr>
    <td>Birthday</td>
    <td><!--<input type="text" name="datepicker" id="datepicker" value="" maxlength="100" />-->
<div class="picker" id="picker1" name="birthday" value=""></div>

    </td>
  </tr>
  <tr>

  <td width="150">Captcha</td>
    <td><input type="text" id="txtCaptcha" 
            style="background-image:url(1.jpg); text-align:center; border:1px;
            font-weight:bold; font-family:Modern" />
      <input type="button" id="btnrefresh" value="Refresh" onClick="DrawCaptcha();" />
    </td>
    </tr>
    <tr>
        <td>Enter above text</td>
        <td style="float:left;"><input type="text" id="txtInput" value="" maxlength="100" />
      <b id="textcaptcha" style="font-family:Times New Roman;color:#B4045F;font-size:14px;"> </td>
    </tr>



</table>


</form>



<div style="width:200; float:left; margin:20px 0 0 155px;">
  <input type="button" value="Sign Up" onClick="isEmpty();"/>
</div>
<script type="text/javascript">
function isEmpty(){
    if  ((document.myform.firstName.value.length==0)) 
        {
        document.getElementById('firstNameID').innerHTML = 'Please fill this field';
        return true;
        }
    else if ((document.myform.password.value.length==0)) 
        {
        document.getElementById('passwordID').innerHTML = 'Please fill this field';
        return true;
        }
    else if (document.myform.password.value != document.myform.password1.value)
        {
        document.getElementById('passwordID1').innerHTML = 'Password mismatch';
        return true;
        }
    else if (! ValidCaptcha())
        {
            document.getElementById('textcaptcha').innerHTML = 'Please fill the captcha correctly';
        }

    else 
        { 
        document.getElementById('FormID').action = "http://10.1.0.90:8080/registrationForm/";
        document.getElementById('FormID').submit();
        return false; 
        }
}
</script><br><br>
</body>
</html>

观看次数

def registrationForm(request):
    if request.method == "POST":  
        firstName = request.POST.get("firstName")
        lastName = request.POST.get("lastName")
        email = request.POST.get("email")
        password = request.POST.get("password")
        sex = request.POST.get("sex")
        birthday = request.POST.get("birthday")
        UniversityDetails(firstName=firstName,lastName=lastName,email=email,password=password,sex=sex,birthday=birthday).save()

        send_mail('Email Verification', 'You have registered successfully', 'rv@gmail.com',
    [email], fail_silently=False)

        return render_to_response('login.html')

    return render_to_response("registrationForm.html")

【问题讨论】:

    标签: jquery python django django-models django-templates


    【解决方案1】:

    birthday 字段必须有一个输入才能与表单一起提交。

    所以要么使用:

    <td>Birthday</td>
    <td><input type="text" id="picker1" name="birthday" value="" 
               maxlength="100" class="picker" />
    

    或为birthday 使用隐藏输入,并在提交时用javascript 填充。

    另外,您没有在保存之前验证视图中的模型,这很糟糕。

    尝试使用django forms,它们在模板和视图中都非常方便。

    更新:

    我检查了birthdaypicker 插件,它有一个有趣的选项hiddenDate,它可以为您创建一个名为birthdate 的隐藏输入。您可以执行以下操作:

    恢复使用div 作为birthdaypicker

    <td>Birthday</td>
    <td><!--<input type="text" name="datepicker" id="datepicker"
                            value="" maxlength="100" />-->
        <div class="picker" id="picker1" name="birthday" value=""></div>
    

    在创建birthdaypicker 时传递hiddendate 选项:

      $(document).ready (function() {
        //$( "#datepicker" ).datepicker();
        $("#picker1").birthdaypicker({hiddenDate: true});
    });
    

    django 视图中,使用birthdate 而不是birthday

    birthday = request.POST.get("birthdate")
    

    【讨论】:

    • 感谢 manji..这修复了我的错误..但是生日值没有保存在我的数据库中..你能告诉我为什么它没有保存在数据库中吗?
    • 您在代码中看到了什么值?你为什么不使用 Django 表单?这比自己跟踪每件事要好得多,它会为你做验证?
    • 我想保存在数据库中输入的生日。现在正在提交表单,但是当我使用 django 管理员检查数据库时,生日字段保持空白。我是 django 的新手,所以当我开始做这个应用程序时不知道 django 表单
    • 你能在save 指令之前检查birthday 的值吗? (print birthday 将在服务器控制台中回显该值)
    • 我检查了birthdaypicker 插件,它正在为日/月/年构建 3 个选择,这就是为什么你什么都没有得到。它有一个有趣的选项hiddenDate,它会在表单中为您创建一个名为birthdate 的隐藏输入,您可以使用它,请参阅我的编辑。
    【解决方案2】:

    问题出在这行:

    <div class="picker" id="picker1" name="birthday" value=""></div>
    

    这不会与您的表单一起提交。您需要放置一个隐藏输入来存储生日值,以便它可以与 POST 数据一起传递。

    <input type="hidden" name="birthday" value="" />
    <div class="picker" id="picker1"></div>
    

    然后,当您从日期选择器中选择日期时,添加挂钩以更新此隐藏输入的值。

    编辑

    我还建议像这样重写您的 Django 视图,使其更易于管理,并挂钩到 Django 的内置表单验证:

    from django import forms
    
    class DetailsForm(forms.ModelForm):
      class Meta:
        model = UniversityDetails
    
    def registrationForm(request):
      form = DetailsForm()
    
      if request.method == 'POST':
        form = DetailsForm(request.POST)
    
        if form.is_valid():
          send_mail('Email Verification', 'You have registered successfully', 'rv@gmail.com', [email], fail_silently=False)
          form.save()
    
          return render_to_response('login.html')
    
      return render_to_response("registrationForm.html")
    

    【讨论】:

    • 谢谢加里..这解决了我的错误。但是该值没有保存在数据库中。你能告诉我如何解决它吗?
    • 当您从日期选择器中选择日期时,您确定设置隐藏输入的值吗?
    • 感谢 Gary 的编辑,但我的申请几乎完成了。你能帮我用我的原始代码做到这一点吗?我明白你的方法更简单直接:),但是更改我的代码需要一些时间让我理解并且对整个应用程序进行相同的更改。
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 2017-03-17
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多