Django fields assign to html fields

扶醉桌前 提交于 2019-12-25 06:38:16

问题


How to assign Django fields to html fields. Without adding {{form}} in html?

The actual problem that I want my fields to look like this:

But if I use this {{form}}, what I can get is

I've created a custom form, can I assign my input fields from HTML to form class fields in Django?


回答1:


simple answer You can have your own form not use {{ form }} just give the input tag.

<input type="text" name="<your name">

Please note given name must match the your database field.

yes of course you can create the custom form

class YourForm(forms.ModelForm):
    class Meta:
        model = YourModel
        widgets = {
            'your_field': forms.TextInput(attrs={'class': 'yourFieldClass'}),
        }



回答2:


How I solved this problem (it was very simple)

  1. I installed django-widget-tweaks 1.4.1

    pip install django-widget-tweaks

  2. My code started to look like this

{% load widget_tweaks %}
{% csrf_token %}
<div class="input-group">
  <span class="input-group-addon" id="basic-addon1">
    <i class="fa fa-user" aria-hidden="true"></i>
  </span>
  {{ form.username | add_class:'form-control' | attr:"placeholder:Username"}}
</div>

Note: form.username - username is name of your field in forms.py



来源:https://stackoverflow.com/questions/38496439/django-fields-assign-to-html-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!