“object of type 'NoneType' has no len()” error

家住魔仙堡 提交于 2021-02-05 08:16:46

问题


Error: object of type 'NoneType' has no len() Error in Signupform validation in django

def signup(request):
    print(request)
    if request.method == "POST":
        error_msg = None
        fname = request.POST.get('fname')
        lname = request.POST.get('lname')
        email = request.POST.get('email')
        password = request.POST.get('password')
        value = {'fname': fname,
                 'lname': lname,
                 'email':email}
        customer = Signup(first_name=fname, last_name=lname,
                          email=email, password=password)

        if len(fname) < 4:
            error_msg = "First Name Must Be More Than 4 Character"
        elif len(lname) < 4:
            error_msg = "Last Name Must Be More Than 4 Character"
        elif customer.is_exist(): # describe in models.py
            error_msg = "Email is Registered"
        if not error_msg:
            customer.save()
            return redirect('index')
        else:
            context = {'error': error_msg, 'value':value}
            return render(request, 'product/signup.html', context)

    else:
        print('get request')
        return render(request, 'product/signup.html')

models.py :

class Signup(models.Model):
    first_name=models.CharField(max_length=100)
    last_name=models.CharField(max_length=100)
    email = models.EmailField()
    password = models.CharField(max_length=500)

    def __str__(self):
        return self.first_name

    def is_exist(self):
        return Signup.objects.filter(email = self.email)

GET request also pass a Value(variable) I didn't pass any variable in get request


回答1:


Your fname, lname derived from request.POST.get('fname'), request.POST.get('lname') will get a None object if the corresponding field is submitted empty, thus len(None) will raise TypeError: object of type 'NoneType' has no len()

The simplest solution could be: providing a default value that support builtin len() method

def signup(request):
    if request.method == "POST":
        # make empty string '' as default value instead of None
        fname = request.POST.get('fname', '')
        lname = request.POST.get('lname', '')

       ...


来源:https://stackoverflow.com/questions/62903936/object-of-type-nonetype-has-no-len-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!