Django:表单中的电子邮件字段返回'此字段不能为空/此字段不能为空',即使其中有地址

时间:2015-09-28 00:26:07

标签: python django database forms sqlite

在开始之前,我已经查看了类似的错误,似乎无法找到问题。

背景:我正在使用Django中的model.py创建一个注册表单。我的表单在我的开发环境中运行。一旦我将数据输入表单,它应该将其保存在sqlite3 db中。但是目前,当我填写表格时,我看到了两个问题。这些如下

问题: 1)尽管在“电子邮件”字段中有一个电子邮件地址,但它出现'此字段不能为空'。所以我在models.py文件中添加'null = true'来发送电子邮件。一旦我完成了这个并再试一次,我得到: 2)另一个错误说“此字段不能为空”。然后我在models.py文件中为电子邮件添加'blank = true'。 这使我能够完成表单并注册数据。但是现在,我面临第3号问题 3)当我进入数据库,然后点击查看已注册的人时,它会在电子邮件中显示“无”。当我点击'none'时,我看到以下错误(我的代码在下面):

TypeError at .............
coercing to Unicode: need string or buffer, NoneType found
Request Method: GET
Request URL:    ......
Django Version: 1.8.2
Exception Type: TypeError
Exception Value:    
coercing to Unicode: need string or buffer, NoneType found
Exception Location: /Library/Python/2.7/site-packages/Django-1.8.2-py2.7.egg/django/utils/encoding.py in force_text, line 92
Python Executable:  /usr/bin/python
Python Version: 2.7.6
Python Path:    
['/Users/Desktop/Website/booksrc',
 '/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg',
 '/Library/Python/2.7/site-packages/Django-1.8.2-py2.7.egg',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
 '/Library/Python/2.7/site-packages']
Server time:    Mon, 28 Sep 2015 00:19:11 +0000
Error during template rendering

In template /Library/Python/2.7/site-packages/Django-1.8.2-py2.7.egg/django/contrib/admin/templates/admin/change_form.html, error at line 21
coercing to Unicode: need string or buffer, NoneType found
11  {% block coltype %}colM{% endblock %}
12  
13  {% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} change-form{% endblock %}
14  
15  {% if not is_popup %}
16  {% block breadcrumbs %}
17  <div class="breadcrumbs">
18  <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a>
19  &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a>
20  &rsaquo; {% if has_change_permission %}<a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst }}</a>{% else %}{{ opts.verbose_name_plural|capfirst }}{% endif %}
21  
      &rsaquo; {% if add %}{% trans 'Add' %} {{ opts.verbose_name }}{% else %}
      {{ original|truncatewords:"18" }}
      {% endif %}

22  </div>
23  {% endblock %}
24  {% endif %}
25  
26  {% block content %}<div id="content-main">
27  {% block object-tools %}
28  {% if change %}{% if not is_popup %}
29    <ul class="object-tools">
30      {% block object-tools-items %}
31      <li>

我还包含了我的代码:

models.py:

from django.db import models

# Create your models here.
class Register(models.Model):

    Profession = models.CharField(max_length=120)
    first_name = models.CharField(max_length=120)
    last_name = models.CharField(max_length=120)
    email = models.EmailField(max_length = 120, null=True, unique=True, blank=True)
    phone_number = models.CharField(max_length=120)
    instgram_ID = models.CharField(max_length=120, blank=True, null=True)
    facebook_ID = models.CharField(max_length=120, blank=True, null=True)
    twitter_ID = models.CharField(max_length=120, blank=True, null=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return self.email

views.py:

from django.shortcuts import render

from .forms import RegisterForm
# Create your views here.
def home(request):
    title = 'Welcome'
    form = RegisterForm(request.POST or None)
    context = {
        "title": title, 
        "form": form 
    }


    if form.is_valid():
        #form.save()
        instance = form.save(commit=False)

        first_name = form.cleaned_data.get("first_name")
        if not first_name:
            first_name = "New first name"
        instance.first_name = first_name
        #if not instance.full_name:
        #   instance.full_name = "Justin"
        instance.save()
        context = {
            "title": "Thank you"
        }

    return render(request, "home.html", context)

forms.py

from django import forms

from .models import Register

class RegisterForm(forms.ModelForm):
    class Meta: 
        model = Register
        fields = ['first_name', 'last_name', 'email', 'phone_number', 'instgram_ID', 'facebook_ID', 'twitter_ID']

    def clean_email(self):
        email = self.cleaned_data.get('email')
        email_base, provider = email.split("@")
        domain, extension = provider.split('.')
        #if not domain = 'USC':
        #   raise forms.ValidationError("Please make sure you use your USC email.")
        #if not extension == "edu":
        #   raise forms.ValidationError("Please use a valid .EDU email address")
        #return email

    def clean_full_name(self):
        full_name = self.cleaned_data.get('full_name')
        #write validation code.
        return full_name

admin.py

from django.contrib import admin

# Register your models here.

from .forms import RegisterForm
from .models import Register

class RegisterAdmin(admin.ModelAdmin):
    list_display = ["__unicode__", "timestamp", "updated"]
    form = RegisterForm
    #class Meta:
    #   model = Register


admin.site.register(Register, RegisterAdmin)

到目前为止,我已经调整了任何可以认为它们可能是潜在错误的内容,这可能是一个糟糕的举动,并且可能使事情变得比应有的更糟糕但是我(我希望)记得改变无错误!请提供一个愚蠢的解释。我敢肯定,无论我多么简单,我很可能还会从中学到错误。

非常感谢

1 个答案:

答案 0 :(得分:2)

您已注释掉clean_email方法的最后一行,它返回值,因此它返回None。该方法的返回值用作字段的值,因此您确实需要返回实际的电子邮件值。

(实际上,当你正在调试这样的事情并且它说'#34;电子邮件不能为空白&#34;时,你应该首先调查为什么字段被报告为空白,而不是修复模型所以它可以。)