I wrote the following middleware that displays the form and asks the user for a username and password. Middleware should apply to the entire website:
class InviteLoginForWebsiteMiddleware(object):
def process_request(self, request):
if request.session.get('has_invite') == True:
return None
form = WebsiteLoginForm()
extra_context = dict()
extra_context['form'] = form
template_name = 'websiteLogin.html'
if request.method == "POST":
form = WebsiteLoginForm(request.POST)
if form.is_valid():
login = form.cleaned_data['login']
password = form.cleaned_data['password']
if login == "mylogin" and password == "mypassword":
request.session['has_inv'] = True
return None
return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
The problem with this solution is that when creating the form inside process_request, the csrf token is not on the displayed page. I searched the answer and found that the developers recommend creating the form and processing it inside process_view
After moving all the code to process_view, for example:
def process_view(self, request, view_func, view_args, view_kwargs):
if request.session.get('has_inv') == True:
return None
form = WebsiteLoginForm()
extra_context = dict()
extra_context['form'] = form
template_name = 'websiteLogin.html'
if request.method == "POST":
form = WebsiteLoginForm(request.POST)
if form.is_valid():
login = form.cleaned_data['login']
password = form.cleaned_data['password']
if login == "mylogin" and password == "mypassword":
request.session['has_inv'] = True
return None
return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
the code started working, the csrf token was opened, and I was able to submit the form with login and password.
, , , www.mysite.com/notworkingurl/. process_view , 404 , , -. , , , .
:
- process_request,
-, csrf . csrf .
- process_view . , 404 URL- . , .
- ?
:
@knbk csrf_protect. , :
class ExtraContextTemplateViewCsrfProtect(TemplateView):
extra_context = None
@method_decorator(csrf_protect)
def dispatch(self, request, *args, **kwargs):
return super(ExtraContextTemplateViewCsrfProtect, self).dispatch(request, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
context = super(ExtraContextTemplateViewCsrfProtect, self).get_context_data(*args, **kwargs)
if self.extra_context:
context.update(self.extra_context)
return context
post = TemplateView.get