Skip to content
New issue

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

Django学习记录(十五):Django by example -- Blog(十一) #51

Open
PyxYuYu opened this issue Oct 14, 2016 · 0 comments
Open

Django学习记录(十五):Django by example -- Blog(十一) #51

PyxYuYu opened this issue Oct 14, 2016 · 0 comments
Labels

Comments

@PyxYuYu
Copy link
Owner

PyxYuYu commented Oct 14, 2016

First hand experience is often necessary for personal growth.

0x01 Django

  • Build a Blog Application
    • 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.to 无法显示,估计是 cdform 的区别
      • <form action="." method="post"> 这里表明了表单这个元素必须是通过 POST 方法提交
      • form.as_p 渲染表单为一系列的 p 标签,每个 p 标签包含一个字段
        • 其他的表单渲染方式:
        • form.as_ul 渲染表单为一系列的 li 标签,每个 li 标签包含一个字段,不包含 ul 标签
        • form.as_table 渲染表单为一个 HTMLtable
        • for field in form 通过迭代 form , 获取其中的所有 fieldfield 可引用的包括 {{ field.label_tag }} , {{ field }} , {{ field.errors }}
          • field.label_tag 输出为 fieldlabel 元素
          • field 输出为 fieldinput
          • field.errors 输出为 fielderrors 元素(一般在 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 }} 后面)
         <p>
             <a href="{% url "blog:post_share" post.id %}">
                 Share this post
             </a>
         </p>
      • 通过 {% url %} 标签建立了动态的 URL 地址,利用 blog:post_share 命名空间和 post ID 建立绝对路径
@PyxYuYu PyxYuYu added the Django label Oct 14, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant