Проблемы с валидаторами в моделях django

Я хочу создать страницу редактирования, где клиент может редактировать страницу профиля. У меня проблема с валидаторами, и я не знаю, как ее решить.

model.py

class UserProfile(models.Model):
CAT_G = (
        ('W', 'W'),
        ('M', 'M'),
        ('do not want to mention', 'do not want to mention'),
    )
    age = models.IntegerField(default=1, validators=[ MaxValueValidator(100), MinValueValidator(1)])
    height = models.DecimalField(max_digits=3, validators=[MinValueValidator(Decimal('0.0'))], decimal_places=2)
    gender = models.CharField(max_length=27, blank=False, null= False, choices=CAT_G)

view.py

def edit_view(request):
    context={}
    if request.method == "POST":
        form = ProfileUpForm(request.POST, instance=request.user.userprofile)
        if form.is_valid():
            form.save()
            return redirect('/profPage')
    else:
        form = ProfileUpForm(
            initial={
                "age":request.user.userprofile.age,
                "height":request.user.userprofile.height,
                "gender":request.user.userprofile.gender,
            }
        )

        context['profE_form']= form
        return render(request, 'editPage.html', context)

forms.py

class ProfileUpForm(forms.ModelForm):
    class Meta:
        model= UserProfile
        fields =('age', 'height', 'gender', )

    def clean_age(self):
        if self.is_valid():
            age=self.cleaned_data['age']
            return age
    
    def clean_height(self):
        if self.is_valid():
            height=self.cleaned_data['height']
            return height
   
    def clean_gender(self):
        if self.is_valid():
            gender=self.cleaned_data['gender']
            return gender

    

editPage.html

{% for fieldProfile in profE_form %}
            <p>
                {{fieldProfile.label_tag}}
                {{fieldProfile}}
            </p>
            {% endfor %}

Проблема в том, что на html-странице пользователь может выбрать отрицательное число, даже если я помещу этот валидатор в свою модель. enter image description here

Вам нужно передать ошибки полей, так:

{{ profE_form.non_field_errors }}
{% for fieldProfile in profE_form %}
<p>
    {{ fieldProfile.errors }}
    {{ fieldProfile.label_tag }}
    {{ fieldProfile }}
</p>
{% endfor %}

Вы также должны рендерить profE_form.non_field_errors. Для получения дополнительной информации смотрите раздел Рендеринг полей вручную в документации.

Вам не следует реализовывать методы .clean_…(), и определенно не, где вы вызываете is_valid(), поскольку Django вызывает эти .clean_…() для проверки валидности формы.

Вы можете упростить представление, передав экземпляр форме с помощью:

from django.contrib.auth.decorators import login_required

@login_required
def edit_view(request):
    if request.method == 'POST':
        form = ProfileUpForm(request.POST, request.FILES, instance=request.user.userprofile)
        if form.is_valid():
            form.save()
            return redirect('/profPage')
    else:
        form = ProfileUpForm(instance=request.user.userprofile)

    context = {'profE_form': form}
    return render(request, 'editPage.html', context)

Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

Вместо того, чтобы использовать встроенные формы django, вы должны сделать свою собственную html форму и проверить значение следующим образом

<input type="number" min="0">
Вернуться на верх