Help us understand the problem. What is going on with this article?

DjangoのFormにKnockout.jsのdata-bind属性を書く際に勝手にエスケープされるケースの回避方法

More than 5 years have passed since last update.

こう書くと、HTML上ではvalueUpdate: 'afterkeydown'がエスケープされてvalueUpdate: 'afterkeydown'となり、afterkeydownが効かない。

form_exapmle1.py
from django import forms


class ExampleForm(forms.Form):
    address = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'data-bind': 'value: address, valueUpdate: \'afterkeydown\''
            }
        )
    )

エスケープされないようにするには、mark_safeを使う。

form_exapmle2.py
from django import forms
from django.utils.safestring import mark_safe


class ExampleForm(forms.Form):
    address = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'data-bind': mark_safe('value: address, valueUpdate: \'afterkeydown\'')
            }
        )
    )

data-bind属性の中にユーザーが入力した値を埋め込む仕様であればXSS脆弱性になるので、ユーザーの入力値は手動でエスケープする必要がある。(そもそも、そういう設計は避けた方がいいとは思うけど…)

参考
http://stackoverflow.com/questions/777458/django-form-values-without-html-escape

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away