简体   繁体   中英

Django: Email field in form returning 'this field cannot be null/this field cannot be blank' even though there's an address in it

Before I begin I have looked through similar errors and can't seem to find the issue.

Background: I am creating a registration form using model.py in Django. I have the form running in my dev environment. Once I input data into the form, it should save it in the sqlite3 db. However at the moment, when I have completed filling in the form I see two issues. These are as follows

Issues: 1) Despite having an email address in the 'email' field, it comes up with 'this field cannot be null'. So I then add 'null=true' in my models.py file for email. Once I have completed this and try again I get: 2) another error saying 'this field cannot be blank'. I then in my models.py file add 'blank=true' for email. This results in enabling me to complete the form and register the data. However now, I am faced with issue no.3 3) When I go into the db, and click to see whose registered, it says 'none' where the email should be. When I click on 'none' I see the following error (my code is below):

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>

I have also included my code:

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)

I have so far tweaked whatever bits I can thinking they could be potential errors, this could have been a bad move and may have made things messier than they should be however I have (I hope) remembered to change none-errors back! Please provide a dumbed down explanation. I'm sure no matter how simple the error I will most likely still learn from it.

Thank you very much

You've commented out the last line of the clean_email method, where it returns the value, so it returns None instead. The return value from that method is used as the value of the field, so you really need to return the actual email value.

(Really, when you're debugging something like this and it says "email cannot be blank", you should start by investigating why the field is being reported as blank, rather than fixing the model so that it can be.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM