值错误:解压缩需要多于1个值(Django)

时间:2016-01-04 16:22:55

标签: python django forms

我已经查看了类似的问题但找不到任何解决方案。我的问题是当我点击注册按钮时,信息被保存并且在django管理中可见。但是当我点击重定向网址中的注册按钮时得到这个错误。 我的forms.py是

from django import forms
from .models import SignUp
class ContactForm(forms.Form):
   full_name=forms.CharField()
   email=forms.EmailField()
   message=forms.CharField()

class SignUpForm(forms.ModelForm):
   class Meta:
      model=SignUp
      fields=['full_name','email']
   def clean_email(self):
      email=self.cleaned_data.get("email")
      mail_base,provider=email.split("@")
      domain,extension=provider.split(".")
      if not extension=="edu":
         raise forms.ValidationError("Plase enter valid email address")
      return email

和我的views.py是

from django.conf import settings
from django import forms
from django.core.mail import send_mail
from django.shortcuts import render
from .forms import ContactForm,SignUpForm

# Create your views here.
def home(request):
   title="welcome"
   form=SignUpForm(request.POST or None)
   context={
      "title":title,
      "form":form
   }
   if form.is_valid():
      instance=form.save(commit=False)
      full_name=form.cleaned_data.get("full_name")
      if not full_name:
         full_name="new"
      instance.full_name=full_name
      instance.save()
      context={
       "title":"Thank you"
       }



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


def contact(request):
  form=ContactForm(request.POST or None)
  if form.is_valid():
    email=form.cleaned_data.get("email")
    message=form.cleaned_data.get("message")
    full_name=form.cleaned_data.get("full_name")
  context={
    "form":form,
   }
  return render(request,"forms.html",context)

和models.py是

from django.db import models

# Create your models here.
class SignUp(models.Model):
   email=models.EmailField(blank=True)
   full_name=models.CharField(max_length=120,blank=False)
   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

我在forms.py中的“mail_base,provider = email.split(”@“)”收到错误。请帮帮我..

2 个答案:

答案 0 :(得分:4)

如果有人将email字段留空(由于SignUp模型email = EmailField(blank=True)而允许这样做),则self.cleaned_data.get('email')将返回''(空字符串)。在这种情况下,mail_base, provider = email.split('@')会引发该异常。

答案 1 :(得分:0)

出现这种情况的原因是,由于某种原因,您的email字符串没有' @'在它的象征。这导致email.split("@")得到长度为1的列表,而不是长度为2的列表,如您所料。

我的猜测是,您的某个地方有一封空白电子邮件,但任何email字段都没有' @'符号将导致引发此异常。