Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

python - Django Form validation including the use of session data

The use case I am try to address is a requirement for a user to have downloaded a file before being permitted to proceed to the next stage in a form process.

In order to achieve this, I have a Django Form to capture the user's general information which POSTS to Django view 'A'. The Form is displayed using a template which also includes an iFrame with a simple embedded button which links to the URL of Django view 'B'.

View 'B' simply sets a session variable to indicate that the download has occurred, and returns the URL of the file for download, thereby triggering the download.

As part of the validation of Form 'A' (the main Form), I need to check whether the session variable indicating file download is set.

My question is, is this best done using Form 'A' validation process, and if so, how is this best achieved?

If this is not a good approach, where should validation of this event take place?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could override the __init__ method for your form so that it takes request as an argument.

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 keeps all the validation logic in the form.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...