'How to use Httprequest object in FormView?

i was converting the below function view in class based view : but the problem was the below login code uses request object . so how to use this request in a form view .

Functional view i wanted to change to class based view :


def login(request):
    if request.method == 'GET':
        form = UserLoginForm()


    elif request.method == 'POST':
        form = UserLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('name')
            password = form.cleaned_data.get('password')
            user = User.objects.filter(name=username, password=password).first()
            if user is not None:
                request.session['user'] = username
                return redirect('index')

            else:
                messages.error(request, 'Username or password no matched')


    return render(request, 'products_app/login.html', {'form': form})

FormView/class based view of the above code i changed to that gives error :

class Login(FormView):
    template_name = 'products_app/login.html'
    form_class = UserLoginForm
    success_url = reverse_lazy('index')

    def form_valid(self, form):
            username = form.cleaned_data.get('name')
            password = form.cleaned_data.get('password')
            user = User.objects.filter(name=username, password=password).first()
            if user is not None:
                request.session['user'] = username
            else:
                messages.error(request, 'Username or password no matched')
            super().form_valid(form)

here the problem is ,request is not being received unlike in the functional view of above def login(request). so gives error:

module 'django.http.request' has no attribute 'session'


Solution 1:[1]

The problem is you are using the request module as stated in the error. What you actually want is the request instance that invoked the class. Your code should be self.request.

I've eliminated all the superfluous code to only show the parts with request.

class Login(FormView):
    ...

    def form_valid(self, form):
            ...
            if user is not None:
                self.request.session['user'] = username
            else:
                messages.error(self.request, 'Username or password no matched')
            ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Butler