Django错误:确保此值最多具有10个字符(它具有321个字符)

发布于 2025-01-22 02:56:04 字数 6197 浏览 2 评论 0原文

我有页面文件,我正在更新用户的详细信息。 (学生用户) 我为学生创建领域:

id = models.charfield(max_length = 10,null = true)

,我也在Student Form中做CLEAN_ID,但是当我按正确的字符数量时 我有一个错误:

确保此值最多具有10个字符(它具有321个字符)。

您可以在这里的照片中看到这一点。 我不明白如何解决问题。

查看文件

   class DetailsStudentView(View):
      def get(self,request, student_id):
        student = Student.objects.get(pk=student_id)
        userStudent = User.objects.get(pk=student_id)
        form_student = StudentForm(request.POST or None, instance=student)
        form_user = StudentUserUpdate(None,instance=userStudent)
        return render(request, "details.html",{'form_student':form_student, 'form_user':form_user})
      
  def post(self,request,student_id):
    form_student = StudentForm(request.POST, request.FILES)
    if form_student.is_valid():
        user = User.objects.get(pk=student_id)
        email = form_student.cleaned_data['email']
        user.email = email
        user.save()
        student = Student.objects.get(pk=student_id)
        student.first_name = form_student.cleaned_data['first_name']
        student.last_name = form_student.cleaned_data['last_name']
        student.Phone = form_student.cleaned_data['Phone']
        img = request.POST.get('imag_profile')
        if img != None:
          student.imag_profile = img
        student.ID = form_student.cleaned_data['ID']
        student.save()
        return redirect('HomePage:home')
    userStudent = User.objects.get(pk=student_id)
    form_user = StudentUserUpdate(None,instance=userStudent)   
    return render(request,'details.html',{'form_student':form_student, 'form_user':form_user})  

表单文件

class StudentForm(forms.ModelForm):
    email = forms.EmailField(widget = forms.TextInput(attrs={ 'type':"text" ,'class': "bg-light form-control" }))
    class Meta():
      model = Student
      fields = ('first_name','last_name','Phone','imag_profile','ID')
      widgets = {
        'first_name': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }),
        'last_name': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }),
        'Phone': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }),
        'ID': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }),
      }

    def clean_ID(self):
      ID = self.cleaned_data.get('ID')
      if not ID.isdecimal():
        raise forms.ValidationError("ID must to contain only digits.")
      elif len(ID) != 9:
        raise forms.ValidationError("ID must to contain 9 digits.")
      return self.cleaned_data
        

html文件

{% block content %}
<form method="post" enctype="multipart/form-data">
    <div class="wrapper bg-white mt-sm-5">
        <h4 class="pb-4 border-bottom">Account settings</h4>
        <div class="d-flex align-items-start py-3 border-bottom"> 
            {% csrf_token %}
            <img src="https://images.pexels.com/photos/1037995/pexels-photo-1037995.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" class="img" alt="">
            <div class="pl-sm-4 pl-2" id="img-section"> 
                <label for="imag_profile"><b>Profile Photo</b></label>
                <p>Accepted file type .png. Less than 1MB</p> 
                {{form_student.imag_profile}}
            </div>
        </div>
        <div class="py-2">
            <div class="row py-2">
                <div class="col-md-6"> 
                    <label for="first_name">שם פרטי</label> 
                    {{form_student.first_name}} 
                </div>
                <div class="col-md-6 pt-md-0 pt-3"> 
                    <label for="last_name">שם משפחה</label>
                    {{form_student.last_name}}
                </div>
            </div>
            <div class="row py-2">
                <div class="col-md-6"> 
                    <label for="email">מייל המכללה</label> 
                    {{form_user.email}}
                </div>
                <div class="col-md-6 pt-md-0 pt-3"> 
                    <label for="Phone">מספר פלאפון</label>  
                    {{form_student.Phone}}
                </div>
            </div>
            <div class="row py-2">
                <div class="col-md-6"> 
                    <label for="ID">תעודת זהות</label> 
                    {{form_student.ID}}
                    {% if form_student.errors %}
                    <div class="alert alert-danger" role="alert">
                        {{form_student.ID.errors}}
                      </div>
                    {% endif %}
                </div>
            </div>
    </form>

            <div class="py-3 pb-4 border-bottom"> 
                <button class="btn btn-primary mr-3">Save Changes</button> 
                <a href="{% url 'HomePage:home'%}" class="btn border button">Cancel</a>
                <a href="{% url 'Details:ch-pass' request.user.id %}" class="changePass">שינוי סיסמא</a>
            </div>
            <div class="d-sm-flex align-items-center pt-3" id="deactivate">
                <div> 
                    <b>Deactivate your account</b>
                    <p>Details about your company account and password</p>
                </div>
                <div class="ml-auto"> 
                   <a href="{% url 'Details:delete-user' request.user.id %}" class="btn danger">Delete User</a>
                </div>
            </div>
        </div>
        </div>
{% endblock %}

”在此处输入图像描述”

我也删除了DB并制作 makemigrations 和 迁移,

但钢我遇到了这个问题。

i have page file that i am update the details of the user. (Student User)
and i create field for student:

ID = models.CharField(max_length=10, null=True)

and i also do clean_ID in StudentForm, but when i press the correct amount of characters
i got the this error:

Ensure this value has at most 10 characters (it has 321).

you can see this in the photo down here.
i don't understand how to fix the problem.

VIEWS FILE

   class DetailsStudentView(View):
      def get(self,request, student_id):
        student = Student.objects.get(pk=student_id)
        userStudent = User.objects.get(pk=student_id)
        form_student = StudentForm(request.POST or None, instance=student)
        form_user = StudentUserUpdate(None,instance=userStudent)
        return render(request, "details.html",{'form_student':form_student, 'form_user':form_user})
      
  def post(self,request,student_id):
    form_student = StudentForm(request.POST, request.FILES)
    if form_student.is_valid():
        user = User.objects.get(pk=student_id)
        email = form_student.cleaned_data['email']
        user.email = email
        user.save()
        student = Student.objects.get(pk=student_id)
        student.first_name = form_student.cleaned_data['first_name']
        student.last_name = form_student.cleaned_data['last_name']
        student.Phone = form_student.cleaned_data['Phone']
        img = request.POST.get('imag_profile')
        if img != None:
          student.imag_profile = img
        student.ID = form_student.cleaned_data['ID']
        student.save()
        return redirect('HomePage:home')
    userStudent = User.objects.get(pk=student_id)
    form_user = StudentUserUpdate(None,instance=userStudent)   
    return render(request,'details.html',{'form_student':form_student, 'form_user':form_user})  

Form FILE

class StudentForm(forms.ModelForm):
    email = forms.EmailField(widget = forms.TextInput(attrs={ 'type':"text" ,'class': "bg-light form-control" }))
    class Meta():
      model = Student
      fields = ('first_name','last_name','Phone','imag_profile','ID')
      widgets = {
        'first_name': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }),
        'last_name': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }),
        'Phone': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }),
        'ID': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }),
      }

    def clean_ID(self):
      ID = self.cleaned_data.get('ID')
      if not ID.isdecimal():
        raise forms.ValidationError("ID must to contain only digits.")
      elif len(ID) != 9:
        raise forms.ValidationError("ID must to contain 9 digits.")
      return self.cleaned_data
        

HTML FILE

{% block content %}
<form method="post" enctype="multipart/form-data">
    <div class="wrapper bg-white mt-sm-5">
        <h4 class="pb-4 border-bottom">Account settings</h4>
        <div class="d-flex align-items-start py-3 border-bottom"> 
            {% csrf_token %}
            <img src="https://images.pexels.com/photos/1037995/pexels-photo-1037995.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" class="img" alt="">
            <div class="pl-sm-4 pl-2" id="img-section"> 
                <label for="imag_profile"><b>Profile Photo</b></label>
                <p>Accepted file type .png. Less than 1MB</p> 
                {{form_student.imag_profile}}
            </div>
        </div>
        <div class="py-2">
            <div class="row py-2">
                <div class="col-md-6"> 
                    <label for="first_name">שם פרטי</label> 
                    {{form_student.first_name}} 
                </div>
                <div class="col-md-6 pt-md-0 pt-3"> 
                    <label for="last_name">שם משפחה</label>
                    {{form_student.last_name}}
                </div>
            </div>
            <div class="row py-2">
                <div class="col-md-6"> 
                    <label for="email">מייל המכללה</label> 
                    {{form_user.email}}
                </div>
                <div class="col-md-6 pt-md-0 pt-3"> 
                    <label for="Phone">מספר פלאפון</label>  
                    {{form_student.Phone}}
                </div>
            </div>
            <div class="row py-2">
                <div class="col-md-6"> 
                    <label for="ID">תעודת זהות</label> 
                    {{form_student.ID}}
                    {% if form_student.errors %}
                    <div class="alert alert-danger" role="alert">
                        {{form_student.ID.errors}}
                      </div>
                    {% endif %}
                </div>
            </div>
    </form>

            <div class="py-3 pb-4 border-bottom"> 
                <button class="btn btn-primary mr-3">Save Changes</button> 
                <a href="{% url 'HomePage:home'%}" class="btn border button">Cancel</a>
                <a href="{% url 'Details:ch-pass' request.user.id %}" class="changePass">שינוי סיסמא</a>
            </div>
            <div class="d-sm-flex align-items-center pt-3" id="deactivate">
                <div> 
                    <b>Deactivate your account</b>
                    <p>Details about your company account and password</p>
                </div>
                <div class="ml-auto"> 
                   <a href="{% url 'Details:delete-user' request.user.id %}" class="btn danger">Delete User</a>
                </div>
            </div>
        </div>
        </div>
{% endblock %}

enter image description here

i am also delete the db and make
makemigrations
and
migrate

but steel i got this problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

厌味 2025-01-29 02:56:04

per

始终返回一个值以用作新的清洁数据,即使
方法没有更改。此方法的返回值替换了CleanEd_Data中的现有值,因此它必须是cleaned_data的字段值(即使此方法未更改它)或新的清洁值。

因此,对于您的情况,您可能想修改clean_id以返回值,而不是全部cleaned_data

def clean_ID(self):
  ID = self.cleaned_data.get('ID')
  if not ID.isdecimal():
    raise forms.ValidationError("ID must to contain only digits.")
  elif len(ID) != 9:
    raise forms.ValidationError("ID must to contain 9 digits.")
  # return self.cleaned_data   # <--- DON'T DO THIS
  return ID

Per the documentation

Always return a value to use as the new cleaned data, even if this
method didn't change it. The return value of this method replaces the existing value in cleaned_data, so it must be the field’s value from cleaned_data (even if this method didn’t change it) or a new cleaned value.

So for your case, you probably want to amend clean_id to the following to return the value, not all of cleaned_data:

def clean_ID(self):
  ID = self.cleaned_data.get('ID')
  if not ID.isdecimal():
    raise forms.ValidationError("ID must to contain only digits.")
  elif len(ID) != 9:
    raise forms.ValidationError("ID must to contain 9 digits.")
  # return self.cleaned_data   # <--- DON'T DO THIS
  return ID
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文