Search code examples
djangovalidationdjango-formsvalidationerrorraiserror

can't raise ValidationError django validators


I need to know how I raise ValidationError of a validators in django.

First I tried the methode on form in simple page and forms and it works perfectly.

but the problems appear when I use modal fade class in a page works with pk

for example(127.0.0.1:8000/wsheets/AMA2/).

the message is (The view Home.views.wellsets didn't return an HttpResponse object. It returned None instead.)

and mt views.wellsets is

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)

and my form + validator is:

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

and at last this is my html form

<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


Solution

  • Hi In fact I did it by other way no error message appear in the bootstrap modal at the moment of submitting but it works fine. in my views.py I created a new form (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)
    

    and in my 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 %}
    

    and I creted a validators.py and in it:

        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!")
    

    and at last in the model.py i called the decorator as;

    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])
    

    at the end the file will not added or uploaded and when I cambak to my modal window I see that Description of modal window