首页 > 编程问答 >字段已填满,但我仍然收到 ValidationError

字段已填满,但我仍然收到 ValidationError

时间:2024-07-28 09:53:23浏览次数:7  
标签:python django

我想使用 User.objects.create_user 和表单 Utilisateurs 的字段来创建用户。图像和用户名字段也用于填充模型 UserProfile .

views.py:

def sign_in(request):
    form=Utilisateur(request.GET)
    if request.method=="POST":
        form=Utilisateur(request.POST)
        if form.is_valid():
            User.objects.create_user(username=form.cleaned_data["username"],
                                     password=form.cleaned_data["password"],
                                     first_name=form.cleaned_data["first_name"],
                                     last_name=form.cleaned_data["last_name"],
                                     email=form.cleaned_data["email"]
                                     )
            UserProfile.objects.create(username=form.cleaned_data["username"],profile_img=form.cleaned_data["profile_img"])
            return redirect("home")
        else:
            print(form.errors.as_data())
    context={"form":form}
    return render(request,'signin.html',context)

models.py:

class UserProfile(models.Model):
    username=models.CharField(max_length=50)
    profile_img=models.ImageField(default="images/logo.png", upload_to="images/",blank=True, null=True)
    date = models.DateField(default=django.utils.timezone.now())

forms.py:

class Utilisateur(forms.Form):
    first_name=forms.CharField(min_length=4,max_length=15,label="Nom",widget=(forms.TextInput(attrs={"class":"userclass"})))
    last_name = forms.CharField(min_length=4, max_length=15,label="Prenom",widget=(forms.TextInput(attrs={"class":"userclass"})))
    username=forms.CharField(min_length=4, max_length=15,label="Nom d'uttilisateur",widget=(forms.TextInput(attrs={"class":"userclass"})))
    email=forms.EmailField(label="Email",widget=(forms.EmailInput(attrs={"class":"userclass"})))
    password=forms.CharField(label="Mot de passe",widget=(forms.PasswordInput(attrs={"class":"userclass"})))
    profile_img = forms.ImageField(label="Image de Profile")
class ProfileForm(forms.Form):
    profile_img = forms.ImageField(label="Image de Profile", required=False)

错误:

{'profile_img': [ValidationError (['此字段为必填项。'])]}

sign-in.html:

{% load static %}

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Log_in</title>
    <link rel="stylesheet" href="{% static 'styles.css' %}" >
</head>
<body>
    <br><br>
    <h2 style="background-color: black; color: beige; padding: 5px; width:fit-content;">INSCRIVEZ-VOUS</h2>
    <form action="" method="POST" enctype="multipart/form-data">

        {% csrf_token %}

        {{ form.as_p }}

        <input type="submit" value="Log-in">
    </form>
</body>
</html>

你的问题在于你对 profile_img 字段的处理方式。你在 UserProfile 模型和 Utilisateur 表单中都定义了 profile_img 字段,并且在表单中它是必需的。当提交表单时,它会验证 profile_img 字段是否已填充,即使你没有在 User.objects.create_user 中使用它。

以下是如何解决这个问题的方法:

1. 从 Utilisateur 表单中移除 profile_img 字段:

由于你只在创建 UserProfile 时需要 profile_img ,因此不需要在 Utilisateur 表单中包含它。

修改后的 forms.py

class Utilisateur(forms.Form):
    first_name=forms.CharField(min_length=4,max_length=15,label="Nom",widget=(forms.TextInput(attrs={"class":"userclass"})))
    last_name = forms.CharField(min_length=4, max_length=15,label="Prenom",widget=(forms.TextInput(attrs={"class":"userclass"})))
    username=forms.CharField(min_length=4, max_length=15,label="Nom d'uttilisateur",widget=(forms.TextInput(attrs={"class":"userclass"})))
    email=forms.EmailField(label="Email",widget=(forms.EmailInput(attrs={"class":"userclass"})))
    password=forms.CharField(label="Mot de passe",widget=(forms.PasswordInput(attrs={"class":"userclass"})))

# 删除 profile_img 字段

class ProfileForm(forms.Form):
    profile_img = forms.ImageField(label="Image de Profile", required=False)

2. 在视图中处理 profile_img

在你的 sign_in 视图中,你可以直接从 request.FILES 中获取上传的图片。

修改后的 views.py

def sign_in(request):
    if request.method == "POST":
        form = Utilisateur(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data["username"],
                password=form.cleaned_data["password"],
                first_name=form.cleaned_data["first_name"],
                last_name=form.cleaned_data["last_name"],
                email=form.cleaned_data["email"]
            )
            # 获取上传的图片
            profile_img = request.FILES.get('profile_img')

            # 创建 UserProfile,如果提供了图片则使用
            UserProfile.objects.create(
                username=form.cleaned_data["username"],
                profile_img=profile_img 
            )
            return redirect("home")
        else:
            print(form.errors.as_data())
    else:
        form = Utilisateur()
    context = {"form": form}
    return render(request, 'signin.html', context)

3. 更新你的模板以包含 profile_img 字段:

你需要在 signin.html 模板中添加一个文件上传字段,以便用户可以选择图片。

修改后的 signin.html

{% load static %}

&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt; Log_in&lt;/title&gt;
    &lt;link rel="stylesheet" href="{% static 'styles.css' %}" &gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;br&gt;&lt;br&gt;
    &lt;h2 style="background-color: black; color: beige; padding: 5px; width:fit-content;"&gt;INSCRIVEZ-VOUS&lt;/h2&gt;
    &lt;form action="" method="POST" enctype="multipart/form-data"&gt; 
        {% csrf_token %}

        {{ form.as_p }}

        &lt;label for="id_profile_img"&gt;Image de Profile:&lt;/label&gt;
        &lt;input type="file" name="profile_img" accept="image/*" id="id_profile_img"&gt; &lt;br&gt;

        &lt;input type="submit" value="Log-in"&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

通过这些更改,你就可以在创建用户时处理 profile_img 字段,并且不会再遇到 ValidationError

标签:python,django
From: 78794351

相关文章

  • 使用 cx_freeze 时 python 库 speedtest/speedtes-cli 和 tkinter 的问题
    我编写了一个脚本来使用python/tkinter和speedtest库(speedtest/speedtest-cli)执行许多宽带速度测试。当作为普通python脚本运行时,该程序按预期工作。我可以使用cx_freeze创建一个exe文件,它会正常创建所有内容。当我运行exe文件时,我得到以下回溯...Traceback(m......
  • Codeforces Round 962 (Div. 3) A - D详细题解(思路加代码Python,C++(垃圾灰名小白想
             吐槽一下,这次比赛不知道怎么的,可能是div3参加的人比较多吗,代码题解上去后全是inqueue,比赛的过程中我还看了提交的,80多页几千个提交全是inqueue,我的代码等了**半个多小时才运行,然后发现timelimit真的有点搞心态,思路在下一题我还要反过来去优化上一题,不过......
  • python2
    第三方IDE(集成开发工具)   pycharm安装教程    ......
  • 基于python+flask+mysql徐州市天气信息可视化分析系统04600-计算机毕业设计项目选题推
    摘 要信息化社会内需要与之针对性的信息获取途径,但是途径的扩展基本上为人们所努力的方向,由于站在的角度存在偏差,人们经常能够获得不同类型信息,这也是技术最为难以攻克的课题。针对天气信息等问题,对天气信息进行研究分析,然后开发设计出天气信息可视化分析系统以解决问题。......
  • 【免费领源码】Java/Mysql数据库+SSM校园兼职网站 25557,计算机毕业设计项目推荐上万套
    摘 要当今人类社会已经进入信息全球化和全球信息化、网络化的高速发展阶段。丰富的网络信息已经成为人们工作、生活、学习中不可缺少的一部分。人们正在逐步适应和习惯于网上贸易、网上购物、网上支付、网上服务和网上娱乐等活动,人类的许多社会活动正在向网络化发展。兼职......
  • 【免费领源码】Java/Mysql数据库+springboot驾校预约管理系统 25540,计算机毕业设计项
    摘 要随着科学技术的飞速发展,各行各业都在努力与现代先进技术接轨,通过科技手段提高自身的优势;对于驾校预约管理系统当然也不能排除在外,随着网络技术的不断成熟,带动了驾校预约管理系统,它彻底改变了过去传统的管理方式,不仅使服务管理难度变低了,还提升了管理的灵活性。这种......
  • Python Beautiful Soup 不加载表值
    我是美丽汤的新手,不确定如何从该网站为每个州(新南威尔士州、维多利亚州、昆士兰州、南澳大利亚州)添加“解决”栏:https://www.asxenergy.com.au/futures_au似乎没有显示数值数据。我的起始代码是:frombs4importBeautifulSoupfromurllib.requestimportur......
  • c语言模拟Python的命名参数
    最近在书里看到的,让c语言去模拟其他语言里有的命名函数参数。觉得比较有意思所以记录一下。目标众所周知c语言里是没有命名函数参数这种东西的,形式参数虽然有自己的名字,但传递的时候并不能通过这个名字来指定参数的值。而支持命名参数的语言,比如python里,我们能让代码达到这种效......
  • 乌尔都语 Tts 可与 python 一起使用
    我想为乌尔都语创建TTS有什么帮助吗?我发现很少有模特拥抱着脸TheUpperCaseGuy/Guy-Urdu-TTSpocketmonkey/speecht5_tts_urduTalha185/speecht5_finetuned_urdu_TTS但我无法从文本创建或生成高质量的语音任何人都可以帮忙吗???importtorchfromtransformersimp......
  • Windows下使用Apache和mod_wsgi部署django项目
    一、安装Python确定好所需要的python版本。二、安装Apacheapache下载地址:http://httpd.apache.org/docs/current/platform/windows.html#down下载完成后做如下操作将apache解压后直接复制到你想安装的路径下1、更改httpd.conf文件,找到如下代码并更改路径DefineSRVROOT"E:......