We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
First hand experience is often necessary for personal growth.
Rendering forms in templates
blog/templates/blog/post/
share.html
{% extends "blog/base.html" %} {% block title %}Share a post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully sent</h1> <p> "{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}. </p> {% else %} <h1>Share "{{ post.title }}" by e-mail</h1> <form action="." method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Send e-mail"> </form> {% endif %} {% endblock %}
form.cleaned_data.to
cd.to
cd
form
<form action="." method="post">
POST
form.as_p
p
form.as_ul
li
ul
form.as_table
HTML
table
for field in form
field
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
field.label_tag
label
input
field.errors
errors
form.fieldname
form.title
title
csrf_token
token
CSRF
Django
CSRF token
blog/post/detail.html
{{ post.body|linebreaks }}
<p> <a href="{% url "blog:post_share" post.id %}"> Share this post </a> </p>
{% url %}
URL
blog:post_share
post ID
The text was updated successfully, but these errors were encountered:
No branches or pull requests
0x01 Django
Rendering forms in templates
blog/templates/blog/post/
文件夹下创建一个share.html
文件form.cleaned_data.to
代替了cd.to
,因为cd.to
无法显示,估计是cd
和form
的区别<form action="." method="post">
这里表明了表单这个元素必须是通过POST
方法提交form.as_p
渲染表单为一系列的p
标签,每个p
标签包含一个字段form.as_ul
渲染表单为一系列的li
标签,每个li
标签包含一个字段,不包含ul
标签form.as_table
渲染表单为一个HTML
的table
for field in form
通过迭代form
, 获取其中的所有field
,field
可引用的包括{{ field.label_tag }}
,{{ field }}
,{{ field.errors }}
field.label_tag
输出为field
的label
元素field
输出为field
的input
field.errors
输出为field
的errors
元素(一般在form
验证出错的时候显示)form.fieldname
直接将form
作为一个字典,比如form.title
引用了form
中的title
这个field
csrf_token
自动生成一个token
来避免CSRF
攻击,默认的情况下,Django
会检查所有POST
请求中的CSRF token
,所以所有通过POST
提交的表单都需要包含csrf_token
blog/post/detail.html
中添加:({{ post.body|linebreaks }}
后面){% url %}
标签建立了动态的URL
地址,利用blog:post_share
命名空间和post ID
建立绝对路径The text was updated successfully, but these errors were encountered: