django upload files using class-based-view

I am facing this problem when I try to upload files it doesn’t work from the html page but from the admin panel it works.

my model is:

class contrat(models.Model):
        contrtID     = models.CharField(max_length=25,unique=True)
        SHRPath      = models.FileField(upload_to='contrats/')
        post_date    = models.DateTimeField(
        author       = models.ForeignKey(User,on_delete=models.CASCADE)
        def __str__(self):
            return self.contrtID
        def delete(self, *args, **kwargs):
            super().delete(*args, **kwargs)
        def get_absolute_url(self):
            return reverse('Scheduling')
        class Meta:
            ordering = ('-post_date',)

The form is:

class contrat_F(forms.ModelForm):
    contrtID     = forms.CharField(label='Code',max_length=25)
    class Meta:
        model= contrat

The is:

class Contratadd(LoginRequiredMixin, CreateView):
    model = contrat
    template_name = 'Home/Scheduling/Add_contract.html'
    form_class=  contrat_F
    def form_valid(self, form):
        form =contrat_F(request.POST, request.FILES) = self.request.user
        return super().form_valid(form)

the is:

path('Add_Contrat/', views.Contratadd.as_view(), name='Add_Contrat'),

the page html code is:

<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="border p-2 mb-3 mt-3 border-secondary">
        <div class="form-row">
            <div class="form-group col-md-12 mb-0">
                {{ form.contrtID|as_crispy_field }}
        <div class="form-row">
            <div class="form-group col-md-12 mb-0">
    <input class="btn btn-success mb-4" type="submit" value="ADD Contrat">

enter image description here

BUT IT DOESN’T UPLOAD THE FILE! where is my mistake please?
the error is:

name ‘request’ is not defined

The full error would be more helpful than just that one line, but based upon what I’m seeing here, I can make a guess or two.

One item I see is that you’re trying to recreate the form in your form_valid function. However, this is a CBV inheriting from CreateView, which means that the form you’re being passed has already been built with the POST and FILES data. Specifically, you can delete the following line:
form =contrat_F(request.POST, request.FILES)

(You can follow the logic in the code, but I tend to recommend the “Classy Class-Based View” site for understanding how these classes work.)
Basically, get_form uses the return value from get_form_kwargs - which in FormMixin returns the data and files information for a POST.

I’m also guessing that since you’re referencing request directly in that function, but it’s not being passed in as a parameter, that’s the cause of the error you’ve reported.