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

Posted

技术标签:

【中文标题】Django:表单中的电子邮件字段返回“此字段不能为空/此字段不能为空”,即使其中有地址【英文标题】:Django: Email field in form returning 'this field cannot be null/this field cannot be blank' even though there's an address in it 【发布时间】:2015-12-25 04:15:55 【问题描述】:

在开始之前,我查看了类似的错误,但似乎找不到问题所在。

背景:我正在 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)

到目前为止,我已经调整了我认为可能是潜在错误的所有位,这可能是一个糟糕的举动,并且可能使事情变得比应有的更混乱,但是我(我希望)记得将无错误改回!请提供一个愚蠢的解释。我敢肯定,无论错误多么简单,我很可能仍会从中吸取教训。

非常感谢

【问题讨论】:

一篇非常长的帖子,但您遗漏了最重要的信息 TypeError ...... 【参考方案1】:

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

(实际上,当您在调试类似这样的内容并显示“电子邮件不能为空白”时,您应该首先调查为什么该字段被报告为空白,而不是修复模型以使其成为空白。)

【讨论】:

谢谢。我现在可以看到了。是的,我试图了解为什么该字段报告为空白,但我自己却无法看到这一点。已经编码了大约 7 个小时,所以当我了解某事的含义时,有时我会忘记,因为有这么多!非常感谢您的帮助。

以上是关于Django:表单中的电子邮件字段返回“此字段不能为空/此字段不能为空”,即使其中有地址的主要内容,如果未能解决你的问题,请参考以下文章

将Django Choices表单字段的详细名称传递给查看上下文

使用注册表单添加到自定义用户字段(django)

如何将表单控件添加到 Django 表单?

检查表单输入值到 Django 中的现有值

如何使 Django 表单字段唯一?

Django:表单验证:一个字段接受多个值