004-Django 关于 templates的详细操作

Django 模版

  1. {% %} 为django模版语言标签,用于加载文件

  2. {{ }} 为django模版语言标签,用于定义显示变量

  3. for循环

    {% for user in users %}
    <tr>
      <td>{{ userinfo.username }}</td>
      <td>{{ userinfo.iphone }}</td>
    </tr>
    {% endfor %}
  4. if 判断

    {% if userinfo.username == "仙女" %}
    <h1>
      {{ userinfo.username }}是最最漂亮的仙女~
    </h1>
    {% endif %}
  5. POST请求提交表单添加csrf令牌,防止跨站请求伪造(Cross-Site Request Forgery, CSRF)漏洞

    <form method="post" action="/login/" >
      {% csrf_token %}
     姓名: <input class="texts" type="text" name="username"><br><br>
     密码: <input class="texts" type="password" name="password"><br><br>
     <br>{{ error }}<br><br>
      <input type="reset" value="取消">&nbsp
     <input type="submit" value="登录">
    </form>
  6. 加载静态文件

    1. yourprojectname/下新建文件夹static,用于存储静态文件

    2. 上传你要用的图片至该文件夹下,例home.png

    3. 配置sittings.py

      # Static files (CSS, JavaScript, Images)
      # https://docs.djangoproject.com/en/2.2/howto/static-files/
      
      STATIC_URL = '/static/'
      STATICFILES_DIRS = [
          os.path.join(BASE_DIR, 'static'),
      ]
    4. templates/***.html加载静态文件

      {% load static %}
      <a href="/home/"><img src="{% static "home.png" %}" alt="首页" title="首页"></a><br>

猜你喜欢

转载自www.cnblogs.com/feizisy/p/11914430.html