Django自定义注册表单html

时间:2021-03-13 13:08:31

标签: django django-models django-views django-forms

Django 新手,我正在尝试创建客户注册表并成功。然而,我遵循的教程向我展示了如何遍历循环,我的 registration_form 的内容从 UI 的角度来看并没有真正给我很大的灵活性,或者看起来如此。有人可以告诉我如何根据我获得的代码自定义此表单吗?

HTML:

    <h1>This is the register.html</h1>
<div class="col-md-4 offset-md-4">
    <form method="post">
        {% csrf_token %}
        {% for field in registration_form %}
            <p>
                {{field.label_tag}}
                {{field}}
                {% if field.help_text %}
                    <small style="color: grey;">{{field.help_text}}</small>
                {% endif %}
                {% for error in field.errors %}
                    <p style="color: grey;">{{error}}</p>
                {% endfor %}
            </p>
        {% endfor %}
        <button type="submit">Register</button>
    </form>
</div>

views.py

def registration_view(request):
    context = {}
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            email = form.cleaned_data.get('email')
            raw_password = form.cleaned_data.get('password1')
            account = authenticate(email=email, password=raw_password)
            login(request, account)
            return redirect('home')
        else:
            context['registration_form'] = form
    else:
        form = RegistrationForm()
        context['registration_form'] = form
        print(context)
    return render(request, 'accounts/register.html', context)

forms.py

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(max_length=100, help_text='Required. Add a valid email address')

    class Meta:
        model = Account
        fields = ('email', 'username', 'password1', 'password2', 'first_name', 'last_name')

表单呈现并在注册时工作正常,只是看起来有点蹩脚。谢谢!

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以单独渲染每个字段并利用引导程序样式。例如对于电子邮件字段,您可以使用以下内容

  <div class="form-group">
    {{ registration_form.email.label_tag }}
    {{ registration_form.email }}
  </div>

您也可以在其下方放置一个 div 以在帖子中显示其错误

<div class="errors">
  {% if registration_form.email.errors %}
      {% for error in registration_form.email.errors %}
          <strong>{{ error|escape }}</strong>
      {% endfor %}
  {% endif %}
</div>