簡體   English   中英

Django 模板中的表單自定義

[英]Form customization in Django template

我想在下面的表單中添加樣式(主要目標是更改占位符的文本顏色,因為我的表單是深色的,並且占位符由於其默認的灰色而不可見)我相信一定有某種方法可以實現這僅在模板中。

來自 CSS 的片段

 ::placeholder {
      color: aquamarine;
      opacity: 1;
    }

來自模板的片段

<form action="{% url 'register' %}" class="box" method="POST">
  <input type="text" name="username" placeholder="{{form.username.label}}" id=""/>
  <input type="text" name="firstname" placeholder="{{form.first_name.label}}" id="" />
  <input type="text" name="lastname" placeholder="{{form.last_name.label}}" id=""/>
  <input type="text" name="email"placeholder="{{form.email.label}}"id="" />
  <input type="text" name="password1" placeholder="{{form.password1.label}}" id=""/>
  <input type="text" name="password2" placeholder="{{form.password2.label}}" id=""/>
  <input type="submit" value="Submit" />
</form>

這是我創建的用於添加新用戶的表單(django.contrib.auth.models 用戶)。 我不確定如何在現有表單中使用{{form.username}} 如果我只是將{{form.username}}放在表單中,它會創建一個沒有應用任何樣式的新字段。

也許我誤解了您想要實現的目標,但是您可以通過<style></style>標簽簡單地設置自定義 CSS。 如果您想要更復雜的解決方案,您可以在表單小部件屬性中定義 CSS 類或將自定義樣式附加到表單

 <style> ::placeholder { color: aquamarine; opacity: 1; } </style> <form action="{% url 'register' %}" class="box" method="POST"> <input type="text" name="username" placeholder="{{form.username.label}}" id=""/> <input type="text" name="firstname" placeholder="{{form.first_name.label}}" id="" /> <input type="text" name="lastname" placeholder="{{form.last_name.label}}" id=""/> <input type="text" name="email"placeholder="{{form.email.label}}"id="" /> <input type="text" name="password1" placeholder="{{form.password1.label}}" id=""/> <input type="text" name="password2" placeholder="{{form.password2.label}}" id=""/> <input type="submit" value="Submit" /> </form>

我為這個問題找到了一個骯臟的解決辦法。 我第一次輸入的表格如下 -

<form action="{% url 'register' %}" class="box" method="POST">
{{form.username}}
{{form.first_name}}
...
</form>

然后我檢查了渲染的模板並竊取了與上述代碼等效的 HTML。 我在輸入標簽中添加了所有必需的屬性。 它看起來像下面的片段 -

      {% csrf_token%}
      <input
        type="text"
        name="username"
        maxlength="150"
        **placeholder="Username"**
        autofocus=""
        required=""
        id="id_username"
      />

      <input
        type="text"
        name="first_name"
        maxlength="30"
        **placeholder="First Name"**
        id="id_first_name"
      />
...

我知道這可能不是一個完美的解決方案,必須有一種更優雅的方式來處理這種情況。 但是,我暫時繼續采用這種方法,因為它可以達到目的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM