Validating a Django form, including using session data

The use case that I am trying to solve is the requirement that the user upload the file before they are allowed to go to the next step in the form process.

To achieve this, I have a Django form to capture general user information that POSTS matches Django 'A' view. The form is displayed using a template that also includes an iFrame with a simple built-in button that links to the Django "B" view URL.

View 'B' simply sets the session variable, indicating that the download has occurred, and returns the URL of the file being downloaded, thereby causing the download.

As part of checking form “A” (main form), I need to check if a session variable is set indicating the file is loading.

My question is: is it better to do this using the “A” form verification procedure, and if so, how is this achieved?

If this is not a good approach, where should this event be tested?

+3
source share
2 answers

You can override the method __init__for your form so that it takes as an argument request.

class MyForm(forms.Form):
    def __init__(self, request, *args, **kwargs)
        self.request = request
        super(MyForm, self).__init__(*args, **kwargs)

    def clean(self):
        if not self.request.session.get('file_downloaded', False):
            raise ValidationError('File not downloaded!')

def my_view(request):
    form = MyForm(request, data=request.POST)

This saves all validation logic in a form.

+10
source

, . , , , (.. ) :

    def formX(request):
        class FormX(forms.Form):
            def clean(self):
                if not request.session.get('file_downloaded', False):
                    raise ValidationError('File not downloaded!')
        return FormX

( , clean(), - , , , )

:

    def my_view(request):
        form = formX(request)(...)
+2

Source: https://habr.com/ru/post/1766204/