保存化身时出现Django错误:预期的str,字节或os.PathLike对象,而不是NoneType

问题描述

cleaned_data ['avatar'](在forms.py中)存在错误:预期的str,字节或os.pathLike对象,而不是nonetype

当我使用头像头像登录时,会出现此错误

我使用的是Django-allauth,但不习惯使用...。所以我添加一个以sign_in形式显示的头像字段,但提交时出现了错误

这是我的代码:models.py

from django.db import models
from django.contrib.auth.models import AbstractUser


def get_path_name(instance,filename):
    path = 'media/avatar/'
    name = instance.user.id + "-" + instance.user.email
    path = path + name
    return path

# custom User model
class CustomUser(AbstractUser):
    avatar = models.ImageField(upload_to= get_path_name,blank=True,null=True)

我的表格:

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
from django.core.files.images import get_image_dimensions
from django import forms

class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = get_user_model()
        fields = ('email','username','avatar')

    def clean_avatar(self):
        avatar = self.cleaned_data['avatar']

        try:
            w,h = get_image_dimensions(avatar)

            # validate dimensions
            max_width = max_height = 100
            if w > max_width or h > max_height:
                raise forms.ValidationError(
                    u'Please use an image that is '
                    '%s x %s pixels or smaller.' % (max_width,max_height))

            # validate content type
            main,sub = avatar.content_type.split('/')
            if not (main == 'image' and sub in ['jpeg','pjpeg','gif','png']):
                raise forms.ValidationError(u'Please use a JPEG,'
                                            'GIF or PNG image.')

            # validate file size
            if len(avatar) > (20 * 1024):
                raise forms.ValidationError(
                    u'Avatar file size may not exceed 20k.')

        except AttributeError:
            """
            Handles case when we are updating the user profile
            and do not supply a new avatar
            """
            pass

        return avatar

class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = get_user_model()
        fields = ('email','avatar')

我的模板:

{% extends '_base.html' %}
{% load crispy_forms_tags %}

{% block title %}

{% endblock title %}

{% block content %}
    <h2>Sign Up</h2>
    <form method="post">
        {% csrf_token %}
        {{ form|crispy }}
        <button class="btn btn-success" type="submit">Sign Up</button>
    </form>
{% endblock content %}

我的设置

AUTH_USER_MODEL = 'accounts.CustomUser'

我已经检查迁移工作,因为我可以看到数据库中的字段。但是,当然要清空以前的错误

我还有一个问题是,化身字段没有出现在/ admin / change / user中,但是我将该字段放在CustomUserChangeForm(UserChangeForm)中:

这是我的admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model


from .forms import CustomUserCreationForm,CustomUserChangeForm

CustomUser = get_user_model()

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email','avatar']

admin.site.register(CustomUser,CustomUserAdmin)

错误回溯:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/signup/

Django Version: 3.1.2
Python Version: 3.7.7
Installed Applications:
['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','bootstrap4','crispy_forms','allauth','allauth.account','django.contrib.sites','accounts','home']
Installed Middleware:
['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/Users/hima/venv/lib/python3.7/site-packages/django/core/handlers/exception.py",line 47,in inner
    response = get_response(request)
  File "/hima/venv/lib/python3.7/site-packages/django/core/handlers/base.py",line 179,in _get_response
    response = wrapped_callback(request,*callback_args,**callback_kwargs)
  File "/Users//hima/venv/lib/python3.7/site-packages/django/views/generic/base.py",line 70,in view
    return self.dispatch(request,*args,**kwargs)
  File "/Users//hima/venv/lib/python3.7/site-packages/django/utils/decorators.py",line 43,in _wrapper
    return bound_method(*args,**kwargs)
  File "/Users//hima/venv/lib/python3.7/site-packages/django/views/decorators/debug.py",line 89,in sensitive_post_parameters_wrapper
    return view(request,**kwargs)
  File "/Users//hima/venv/lib/python3.7/site-packages/allauth/account/views.py",line 215,in dispatch
    return super(SignupView,self).dispatch(request,line 81,in dispatch
    **kwargs)
  File "/Users//hima/venv/lib/python3.7/site-packages/allauth/account/views.py",line 193,in dispatch
    **kwargs)
  File "/Users//hima/venv/lib/python3.7/site-packages/django/views/generic/base.py",line 98,in dispatch
    return handler(request,line 103,in post
    if form.is_valid():
  File "/Users//hima/venv/lib/python3.7/site-packages/django/forms/forms.py",line 177,in is_valid
    return self.is_bound and not self.errors
  File "/Users//hima/venv/lib/python3.7/site-packages/django/forms/forms.py",line 172,in errors
    self.full_clean()
  File "/Users//hima/venv/lib/python3.7/site-packages/django/forms/forms.py",line 374,in full_clean
    self._clean_fields()
  File "/Users/hima/venv/lib/python3.7/site-packages/django/forms/forms.py",line 395,in _clean_fields
    value = getattr(self,'clean_%s' % name)()
  File "/Users//hima/accounts/forms.py",line 15,in clean_avatar
    w,h = get_image_dimensions(avatar)
  File "/Users/hima/venv/lib/python3.7/site-packages/django/core/files/images.py",in get_image_dimensions
    file = open(file_or_path,'rb')

Exception Type: TypeError at /accounts/signup/
Exception Value: expected str,bytes or os.pathLike object,not nonetype

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)