Commit da111005 authored by John Kirkwood's avatar John Kirkwood

Set CSRF token in forms.

Need to store request in threadlocals using middleware.
parent ba70fe53
from django.middleware.csrf import get_token
from ..components import Input
from ..pyreact import ce, cp, get_prop
from ..pyreact import cp
def Csrf(props=[], children=[]):
"""Return the CSRF token.
Not possible as the request is not available at this point.
Need to store the request in threading.local() as we don't have a access
to template context processor variables.
django-threadlocals is only updated to Django <1.10 on PyPI.
django-tools has many features that are not needed.
Adapted django-tools CSRF middleware feature in chp.django.threadlocals.
"""
from .threadlocals import get_current_request
request = get_current_request()
if request is None: # avoid fails in unittests
csrf_token = "REQUESTnotAVAILABLEinCONTEXT"
else:
csrf_token = get_token(request)
props.extend([
cp("type", "hidden"),
cp("name", "csrfmiddlewaretoken"),
cp("value", "REQUEST NOT AVAILABLE IN CONTEXT"),
# cp("value", get_token(request)),
cp("value", csrf_token),
])
return Input(props, children)
......@@ -22,9 +22,9 @@ class PostForm(forms.ModelForm):
model = Post
fields = "__all__"
labels = {
'checkbox': _("This is my checkbox"),
'text': _("Input Label"),
'date': _("Type = date"),
"checkbox": _("This is my checkbox"),
"text": _("Input Label"),
"date": _("Type = date"),
}
def FormSchema(self, *args, **kwargs):
......@@ -36,7 +36,8 @@ class PostForm(forms.ModelForm):
Row([], [
Cell([], [
Form([
cp('id', "form-chp"),
cp("id", "form-chp"),
cp("method", "POST"),
],
[
Csrf(),
......
......@@ -5,7 +5,7 @@
<script type="text/javascript" src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
</head>
<body>
<form id="form-django" method="post">
<form id="form-django" method="POST">
{% csrf_token %}
{{ form }}
......@@ -17,7 +17,7 @@
{{ form.render }}
<form id="form-mdc" method="post">
<form id="form-mdc" method="POST">
{% csrf_token %}
<div class="mdc_layout_grid__cell">
......
......@@ -32,35 +32,35 @@ def test_render(postform):
"""Regression test."""
regex = """
<div class="mdc-layout-grid" chp-id="[0-9]+">
<div class="mdc-layout-grid__inner" chp-id="[0-9]+">
<div class="mdc-layout-grid__cell--span-12" chp-id="[0-9]+">
<form id="form-chp" chp-id="[0-9]+">
<input type="hidden" name="csrfmiddlewaretoken" value="REQUEST NOT AVAILABLE IN CONTEXT" chp-id="[0-9]+" />
<div style="display: flex;" chp-id="[0-9]+">
<div class="mdc-form-field mdc-form-field--align-end" data-mdc-auto-init="MDCFormField" chp-id="[0-9]+">
<div class="mdc-checkbox" data-mdc-auto-init="MDCCheckbox" chp-id="[0-9]+"><input name="checkbox" id="id_checkbox" checked class="mdc-checkbox__native-control" type="checkbox" chp-id="[0-9]+" />
<div class="mdc-checkbox__background" chp-id="[0-9]+"></div></div><label for="id_checkbox" chp-id="[0-9]+">This is my checkbox:</label></div>
<div class="mdc-text-field" data-mdc-auto-init="MDCTextField" chp-id="[0-9]+"><input name="text" value="Initial value" maxlength="[0-9]+" required id="id_text" class="mdc-text-field__input" type="text" chp-id="[0-9]+" />
<label for="id_text" class="mdc-floating-label" chp-id="[0-9]+">Input Label:</label>
<div class="mdc-line-ripple" chp-id="[0-9]+"></div></div>
<div class="mdc-text-field" data-mdc-auto-init="MDCTextField" chp-id="[0-9]+"><input name="date" value="2018-10-03" required id="id_date" class="mdc-text-field__input" type="date" chp-id="[0-9]+" />
<label for="id_date" class="mdc-floating-label" chp-id="[0-9]+">Type = date:</label>
<div class="mdc-line-ripple" chp-id="[0-9]+"></div></div>
<div class="mdc-select" data-mdc-auto-init="MDCSelect" chp-id="[0-9]+">
<select name="media" required id="id_media" class="mdc-select__native-control" chp-id="[0-9]+">
<option value="" disabled chp-id="[0-9]+"></option><optgroup label="Audio" chp-id="[0-9]+"><option value="vinyl" selected chp-id="[0-9]+">Vinyl</option><option value="cd" chp-id="[0-9]+">CD</option><option value="mp3" chp-id="[0-9]+">MP3</option></optgroup><optgroup label="Video" chp-id="[0-9]+"><option value="vhs" chp-id="[0-9]+">VHS tape</option><option value="dvd" chp-id="[0-9]+">DVD</option><option value="blu-ray" chp-id="[0-9]+">Blu-ray</option></optgroup>
<div class="mdc-layout-grid" chp-id="\d+">
<div class="mdc-layout-grid__inner" chp-id="\d+">
<div class="mdc-layout-grid__cell--span-12" chp-id="\d+">
<form id="form-chp" method="POST" chp-id="\d+">
<input type="hidden" name="csrfmiddlewaretoken" value="\w+" chp-id="\d+" />
<div style="display: flex;" chp-id="\d+">
<div class="mdc-form-field mdc-form-field--align-end" data-mdc-auto-init="MDCFormField" chp-id="\d+">
<div class="mdc-checkbox" data-mdc-auto-init="MDCCheckbox" chp-id="\d+"><input name="checkbox" id="id_checkbox" checked class="mdc-checkbox__native-control" type="checkbox" chp-id="\d+" />
<div class="mdc-checkbox__background" chp-id="\d+"></div></div><label for="id_checkbox" chp-id="\d+">This is my checkbox:</label></div>
<div class="mdc-text-field" data-mdc-auto-init="MDCTextField" chp-id="\d+"><input name="text" value="Initial value" maxlength="\d+" required id="id_text" class="mdc-text-field__input" type="text" chp-id="\d+" />
<label for="id_text" class="mdc-floating-label" chp-id="\d+">Input Label:</label>
<div class="mdc-line-ripple" chp-id="\d+"></div></div>
<div class="mdc-text-field" data-mdc-auto-init="MDCTextField" chp-id="\d+"><input name="date" value="2018-10-03" required id="id_date" class="mdc-text-field__input" type="date" chp-id="\d+" />
<label for="id_date" class="mdc-floating-label" chp-id="\d+">Type = date:</label>
<div class="mdc-line-ripple" chp-id="\d+"></div></div>
<div class="mdc-select" data-mdc-auto-init="MDCSelect" chp-id="\d+">
<select name="media" required id="id_media" class="mdc-select__native-control" chp-id="\d+">
<option value="" disabled chp-id="\d+"></option><optgroup label="Audio" chp-id="\d+"><option value="vinyl" selected chp-id="\d+">Vinyl</option><option value="cd" chp-id="\d+">CD</option><option value="mp3" chp-id="\d+">MP3</option></optgroup><optgroup label="Video" chp-id="\d+"><option value="vhs" chp-id="\d+">VHS tape</option><option value="dvd" chp-id="\d+">DVD</option><option value="blu-ray" chp-id="\d+">Blu-ray</option></optgroup>
</select>
<label for="id_media" class="mdc-floating-label" chp-id="[0-9]+">Media:</label>
<div class="mdc-line-ripple" chp-id="[0-9]+"></div></div>
<div class="mdc-select" data-mdc-auto-init="MDCSelect" chp-id="[0-9]+">
<select name="foreignkey" required id="id_foreignkey" class="mdc-select__native-control" chp-id="[0-9]+">
<option value="" selected disabled chp-id="[0-9]+"></option>
<label for="id_media" class="mdc-floating-label" chp-id="\d+">Media:</label>
<div class="mdc-line-ripple" chp-id="\d+"></div></div>
<div class="mdc-select" data-mdc-auto-init="MDCSelect" chp-id="\d+">
<select name="foreignkey" required id="id_foreignkey" class="mdc-select__native-control" chp-id="\d+">
<option value="" selected disabled chp-id="\d+"></option>
</select>
<label for="id_foreignkey" class="mdc-floating-label" chp-id="[0-9]+">Foreignkey:</label>
<div class="mdc-line-ripple" chp-id="[0-9]+"></div></div></div>
<div style="display: grid;" chp-id="[0-9]+">
<div class="mdc-button" data-mdc-auto-init="None" chp-id="[0-9]+"><button form="form-chp" type="submit" chp-id="[0-9]+">Submit</button></div></div>
<label for="id_foreignkey" class="mdc-floating-label" chp-id="\d+">Foreignkey:</label>
<div class="mdc-line-ripple" chp-id="\d+"></div></div></div>
<div style="display: grid;" chp-id="\d+">
<div class="mdc-button" data-mdc-auto-init="None" chp-id="\d+"><button form="form-chp" type="submit" chp-id="\d+">Submit</button></div></div>
</form></div></div></div>
"""
regex = regex.replace("\n", "")
......
......@@ -17,7 +17,7 @@ INSTALLED_APPS = [
'chp.django.example.todos',
'crudlfap',
]
ALLOWED_HOSTS = ['localhost', 'vm-mdc']
STATIC_URL = '/static/'
BASE_DIR = os.path.dirname(__file__)
STATICFILES_DIRS = [
......@@ -38,6 +38,7 @@ MIDDLEWARE = [
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'chp.django.threadlocals.ThreadLocalMiddleware',
]
TEMPLATES = [
{
......
# coding: utf-8
"""
Code adapted from django-tools==0.42.4 (to avoid including all tools).
threadlocals middleware
~~~~~~~~~~~~~~~~~~~~~~~
make the request object everywhere available (e.g. in model instance).
based on: http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser
Put this into your settings:
--------------------------------------------------------------------------
MIDDLEWARE_CLASSES = (
...
'django_tools.middlewares.ThreadLocal.ThreadLocalMiddleware',
...
)
--------------------------------------------------------------------------
Usage:
--------------------------------------------------------------------------
from django_tools.middlewares import ThreadLocal
# Get the current request object:
request = ThreadLocal.get_current_request()
# You can get the current user directly with:
user = ThreadLocal.get_current_user()
--------------------------------------------------------------------------
:copyleft: 2009-2017 by the django-tools team, see AUTHORS for more
details.
:license: GNU GPL v3 or above, see LICENSE for more details.
# LICENSE
All rights reserved.
django-tools is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 3 or later as
published by the Free Software Foundation.
complete GNU General Public License version 3:
http://www.gnu.org/licenses/gpl-3.0.txt
German translation:
http://www.gnu.de/documents/gpl.de.html
# AUTHORS
PRIMARY AUTHORS are and/or have been (alphabetic order):
* Diemer, Jens
Main Developer since the first code line.
ohloh.net profile: <http://www.ohloh.net/accounts/4179/>
Homepage: <http://www.jensdiemer.de/>
CONTRIBUTORS are and/or have been (alphabetic order):
- Ben Konrath <https://github.com/benkonrath>
- Don Naegely <https://github.com/naegelyd>middleware
- Lucas Wiman <https://github.com/lucaswiman>
"""
from __future__ import absolute_import, division, print_function
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object # fallback for Django < 1.10
_thread_locals = local()
def get_current_request():
""" returns the request object for this thread """
return getattr(_thread_locals, "request", None)
def get_current_user():
""" returns the current user, if exist, otherwise returns None """
request = get_current_request()
if request:
return getattr(request, "user", None)
class ThreadLocalMiddleware(MiddlewareMixin):
""" Simple middleware that adds the request object in thread local storage.
"""
def process_request(self, request):
_thread_locals.request = request
def process_response(self, request, response):
if hasattr(_thread_locals, 'request'):
del _thread_locals.request
return response
def process_exception(self, request, exception):
if hasattr(_thread_locals, 'request'):
del _thread_locals.request
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment