无法引发 ValidationError django 验证器

can't raise ValidationError django validators

我需要知道如何在 django 中引发验证器的 ValidationError。

首先,我在简单的页面和表单中尝试了表单上的方法,并且效果很好。

但是当我在使用 pk

的页面中使用模态淡入淡出 class 时出现问题

例如(127.0.0.1:8000/wsheets/AMA2/).

消息是 (视图 Home.views.wellsets 没有 return HttpResponse 对象。它 return 编辑了 None。)

而 mt views.wellsets 是

def wellsets(request, WeelN):
    serchedWl = WellSheets.objects.filter(WellID__exact=WeelN)
    form= WelshetForm()
    context ={
        'title': 'SearchWS',
        'Wellslistsh':serchedWl,
        'WeelN':WeelN,
        'form':form,
    }
    if request.method == 'POST':
        form =WelshetForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.author = request.user
            form.save()
            return redirect('WellSheetg', WeelN)
    else:
        return render(request,'Home/WELLINFO/W_TchD/wellshts.html', context)

我的表单 + 验证器是:

from django.core.exceptions import ValidationError
class WelshetForm(forms.ModelForm):
    WellID   = forms.CharField(label='Well Name',max_length=15)
    FileNm   = forms.CharField(label='File Name',max_length=15)
    def clean_SHRPath(self):
        SHRPath = self.cleaned_data.get('SHRPath')
        size= SHRPath._size
        if SHRPath._size > 1024*1024*10:
            raise forms.ValidationError('Size is bigger than allowed')           
        return SHRPath

最后这是我的 html 表格

<button type="button" class="btn button1 btn-outline-success mb-2 btn-block"  data-toggle="modal" data-target="#myModal" >
<p class="thicker">Add new Well-Sheet</p></button>

<div class="modal fade" id="myModal" role="dialog" >
  <div class="modal-dialog ">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title"><p class="thicker">Upload Well-sheet</p></h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

<div class="modal-body">
  <p class="thicker">Check your file before uploading ({{WeelN}})</p>
<div class="w3-panel w3-light-grey w3-round-large solid"">
  <form method="POST" id="formOne" enctype= multipart/form-data>
    {% csrf_token %}

      <div class="form-row">    
        <div class="form-group col-md-6 mb-0">
          {{ form.WellID|as_crispy_field }}  </div></div>      

      <div class="form-row">    
        <div class="form-group col-md-8 mb-0">
        {{ form.SHRPath }}</div></div>
        <p style="color:red;">Maximum upload size is 10Mb</p>
        <br>
      <input class="btn btn-success mb-6" name="form_uplod" type="submit" value="AddSheet">     
  </form>
</div>
    </div>
  </div>
    <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div>
</div>
</div>

Modal form

正如@IainShelvington 所说,您需要删除 else 块才能获得响应。你可以这样尝试:

def wellsets(request, WeelN):
    serchedWl = WellSheets.objects.filter(WellID__exact=WeelN)
    form= WelshetForm()
    if request.method == 'POST':
        form =WelshetForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.author = request.user
            form.save()
            return redirect('WellSheetg', WeelN)
    context ={
        'title': 'SearchWS',
        'Wellslistsh':serchedWl,
        'WeelN':WeelN,
        'form':form,
    }
    return render(request,'Home/WELLINFO/W_TchD/wellshts.html', context)

因此,即使验证失败,您也会收到包含错误数据的表单的响应。要在模板中显示表单错误,请尝试这样:

<div class="form-group col-md-8 mb-0">
{{ form.SHRPath }}</div>
{% if form.SHRPath.errors|length > 0 %}
    <p style="color:red;">{{ form.SHRPath.errors.0 }}</p>
    <br>
{% endfor %}

可以在 documenation 中找到更多信息。

你好其实我是通过其他方式做到的 提交时 bootstrap 模式中没有出现错误消息,但它工作正常。 在我的 views.py 中,我创建了一个新表单 (form_error):

def wellsets(request, WeelN):
    serchedWl = WellSheets.objects.filter(WellID__exact=WeelN)
    form= WelshetForm()
    form_error = False
    if request.method == 'POST':
        form =WelshetForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.author = request.user
            form.save()
            return redirect('WellSheetg', WeelN)
        else:
            form_error = 'Check your file Name, type and size <10Mb'
            
    context ={
        'title': 'SearchWS',
        'Wellslistsh':serchedWl,
        'WeelN':WeelN,
        'form':form,
        'form_error': form_error,
    }
    return render(request,'Home/WELLINFO/W_TchD/wellshts.html', context)

在我的 Html 中:

      {% if form %}
<div class="w3-panel w3-light-grey w3-round-large solid"">
  <form method="POST" id="formOne" enctype= multipart/form-data>
    {% csrf_token %}
      <div class="form-row">    
        <div class="form-group col-md-6 mb-0">
          {{ form.WellID|as_crispy_field }}</div></div>
          {% if form_error %}
            <li style="color:red;"><strong>Check the Well if it does exist</strong></li>
          {% endif %}
     
      <div class="form-row">    
        <div class="form-group col-md-6 mb-0">
        {{ form.FileNm|as_crispy_field }}</div></div>
      <div class="form-row">    
        <div class="form-group col-md-6 mb-0">
        {{ form.Folio|as_crispy_field }}</div></div>
      
      <div class="form-row">    
        <div class="form-group col-md-8 mb-0">
        {{ form.SHRPath }}</div></div>
        {% if form_error %}
            <li style="color:red;"><strong>{{form_error}}</strong></li>
            <li style="color:red;"><strong>File type (pdf, jpg ,xls..) only accepted</strong></li>
        {% endif %}
        <p style="color:red;">Maximum upload size is 10Mb</p>
        <br>
      <input class="btn btn-success mb-6" data-target="#myModal" name="form_uplod" type="submit" value="AddSheet"> 

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>    
  </form>
  {% endif %}

我创建了一个 validators.py 并在其中:

    def validate_file_size(value):
    filesize= value.size
    print('very nice',filesize/(1024*1024))
    if filesize > 1024*1024*10:
        raise ValidationError(_("The maximum file size that can be uploaded is 10MB"), code='invalid')
    return value


def validate_text(value):
    from Home.models import Wellinfo
    WELDATA= Wellinfo.objects.filter(WellID=value)
    print(value, WELDATA)
    if Wellinfo.objects.filter(WellID=value).exists():
        return value
    raise ValidationError("The Well does't exists!")

最后在 model.py 中,我将装饰器称为;

class WellSheets(models.Model):
    WellID      = models.CharField(max_length=15, validators= [validate_text])
    FileNm      = models.CharField(max_length=15)
    Folio       = models.PositiveIntegerField(blank=True, null=True)
    SHRPath     = models.FileField(upload_to='Well_sheets/', validators= [validate_file_size])

最后文件不会添加或上传,当我 cambak 到我的模态时 window 我看到了 Description of modal window