Django : What is the difference in the return output from the post method and form_valid method?

60 Views Asked by At

I have a form to upload a file. This file is stored in a azure blob storage without using media folders.

In the html, the form send the request to a specific FormView :

<form action="{% url 'intervenant_upload' id_intervenant %}" 
        method="post" 
        enctype="multipart/form-data" 
        id="form-file-upload">
    {% csrf_token %} 
    {{ form|crispy }} 
    <div class="row">
      <button
        type="submit"
        class="btn btn-primary btn-block"
        id="submitupload"
      >
        Charger
        <i class="bi bi-upload" style="font-size: 17px"></i>
      </button>
    </div>
  </form>

The view (in Class Base View) works well, it fills the database and upload the file to the blob storage. However I have a problem when I do the return to end the process. I got this error :

didn't return an HttpResponse object. It returned None instead.

I do not understand why because I have the impression to respect the structure of the FormView according thie website https://ccbv.co.uk/

Here is the my FormView that does not work :

class IntervenantFormUpload(FormView) :
    model       = FilesIntervenants
    form_class  = FilesIntervenantForm
    
    def get_success_url(self) :
        return reverse('intervenants_image_upload', kwargs={'pk': self.id_intervenant})
    
    def setup(self, request, *args, **kwargs) :
        self.id_intervenant = kwargs['pk']
        self.user = request.session.get('user')
        return super().setup(request, *args, **kwargs)
    
    def post(self, request, *args, **kwargs) :
        form = self.form_class(request.POST, request.FILES)
        
        if form.is_valid() :
            self.form_valid(form)
        else :
            self.form_invalid(form)
    
    def form_valid(self, form) :

        BLABLA-BLABLA-BLABLA
        return super(IntervenantFormUpload, self).form_valid(form)
   

    def form_invalid(self, request, form):
        context = self.get_context_data()
        context['form'] = form

        return render(request, 'upload/upload.html', context)

However, when I do just a post method that return a redirect, it works. Here is the code that works :

class IntervenantFormUpload(FormView) :
    model       = FilesIntervenants
    form_class  = FilesIntervenantForm
     
    def post(self, request, *args, **kwargs) :
        form = self.form_class(request.POST, request.FILES)
        files_selected = self.request.FILES.getlist('Filename')
        
        if form.is_valid():                                   
            return  redirect(reverse('intervenants_image_upload', kwargs={  'pk': self.id_intervenant})) 

So what is the difference ?

Thank you

0

There are 0 best solutions below