新建myForms.py ,在myFroms.py中设置表单:

myForms.py

from django import forms

class NameForm(forms.Form):
	your_name = forms.CharField(label='Your name', max_length=100)
	your_phone = forms.CharField(max_length=100)
	message = forms.CharField(widget=forms.Textarea)
	sender = forms.EmailField()
	cc_myself = forms.BooleanField(required=False)
在views.py中显示传递表单

views.py

需要导入myForms

from templates.myForms import NameForm
def dashboard(request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            return redirect('dashboard')
    else:
        form = NameForm()

    return render(request, 'accounts/dashboard.html', {'form': form})

dashboard函数需要在urls中配置

urls.py

from django.conf.urls import url
from . import views
from django.urls import path

urlpatterns = [
    path('dashboard/',views.dashboard,name='dashboard'),
];

templates下的dashbord.html,代码非常简单

  <form method="post">
    {% csrf_token %}
    <table>{{ form.as_table }}</table>
    <button type="submit">Sign in</button>
  </form>

显示如下图所示,还是很简约的:

表格太过于简约了,用fieldWrapper美化一下

    <form action="" method="post">
    {% csrf_token %}
{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} 
        {{ field }}
        {% if field.help_text %}
        <p class="help">{{ field.help_text|safe }}</p>
        {% endif %}
    </div>
{% endfor %}
    <input type="submit" value="Submit">
  </form> 

还是不够满意,怎么用bootstrap美化表单

{{ form.non_field_errors }}
    <div class="form-group">
    <label for="yourname">your name</label>
     {{ form.your_name.errors }}
    <input type="text" class="form-control" id="yournameId" name="yourname" value="{{form.your_name.values}}">
    </div>

    <div class="form-group">
    <label for="yourphone">your name</label>
     {{ form.your_name.errors }}
    <input type="text" class="form-control" id="yourphoneId" name="yourphone" value="{{form.your_phone.values}}">
    </div>

    <div class="form-group">
    <label for="message">message</label>
     {{ form.your_name.errors }}
    <input type="text" class="form-control" id="messagesId" name="message" value="{{form.message.values}}">
    </div>

    <div class="form-group">
    <label for="{{ form.email.id_for_label }}">email</label>
     {{ form.email.errors }}
    <input type="url" class="form-control" id="emailID" name="email" value="{{form.sender.values}}">
    </div>

    <div class="form-group">
     {{ form.email.errors }}

    <label class="form-check-label" for="myselfcheck">cc_myself :</label>
    <input type="checkbox" class="form-check" id="myselfID" name="myselfcheck" >
    </div>

    <input type="submit" class="btn btn-primary" value="Submit">
  </form> 

好很多了,但是代码写的太多了,能不能简化一下。

直接使用django-crispy-forms来优化页面

1、安装crispy

pip install django-crispy-forms

2、配置settings.py的 INSTALLED_APPS

INSTALLED_APPS = [
    #add this
    'crispy_forms',
]

3、修改表单的代码

{% load crispy_forms_tags   %}
  <form method="post">
    {% csrf_token %}
    <table>{{ form|crispy }}</table>
    <button type="submit">Sign in</button>
  </form> 

表单样式如下,代码已经非常精简了:

除了对整个表单form进行渲染,也可以按照每一个字段进行渲染

      <div class="form-group col-md-6 mb-0">
        {{ form.your_name|as_crispy_field }}
      </div>

4、{{ form|crispy }}类似于as_tableas_ul and as_p ,使用{% crispy %} 更灵活

forms.py

from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column

class NameForm(forms.Form):
	your_name = forms.CharField(label='Your name', max_length=100)
	your_phone = forms.CharField(max_length=100)
	message = forms.CharField(widget=forms.Textarea)
	sender = forms.EmailField()
	cc_myself = forms.BooleanField(required=False)

	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self.helper = FormHelper()
		self.helper.layout = Layout(
            Row(
                Column('your_name', css_class='form-group col-md-6 mb-0'),
                Column('your_phone', css_class='form-group col-md-6 mb-0'),
                css_class='form-row'
            ),
            'message',

            Row(
                Column('sender', css_class='form-group col-md-6 mb-0'),

                css_class='form-row'
            ),
            'cc_myself',
            Submit('submit', 'Sign in')
        )	

dashboard.html简化为一行代码:

{% load crispy_forms_tags   %}

{% crispy form %}

表单样式如下所示:

sender这个发邮件的框有点难看,怎么自定义样式?

新建一个custom_emailbox.html

{% load crispy_forms_field %}

<div class="form-group">
  <div class="">
    {% crispy_field field 'class' 'form-control' %}
    <label for="{{ field.id_for_label }}">{{ field.label }}</label>
  </div>
</div>

在forms.py中添加自定义类

from crispy_forms.layout import Field


class CustomEmailbox(Field):
    template = 'accounts/custom_emailbox.html'

修改NameForm中的sender,改为CustomEmailbox(‘sender’),

class NameForm(forms.Form):
	your_name = forms.CharField(label='Your name', max_length=100)
	your_phone = forms.CharField(max_length=100)
	message = forms.CharField(widget=forms.Textarea)
	sender = forms.EmailField()
	cc_myself = forms.BooleanField(required=False)

	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self.helper = FormHelper()
		self.helper.layout = Layout(
            Row(
                Column('your_name', css_class='form-group col-md-6 mb-0'),
                Column('your_phone', css_class='form-group col-md-6 mb-0'),
                css_class='form-row'
            ),
            'message',

            Row(
		CustomEmailbox('sender'),#修改为自定义格式
                css_class='form-row'
            ),
            'cc_myself',
            Submit('submit', 'Sign in')
        )	

sender样式改变为如下图所示:

参考:

1.Advanced Form Rendering with Django Crispy Forms

2.django-crispy-forms


如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!



0 条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注