用户名和电子邮件字段的help_text始终在浏览器中输出

时间:2017-12-15 12:55:54

标签: django

我有这个型号:

class User(AbstractUser):
    REQUIRED_FIELDS = []
    USERNAME_FIELD = 'email'
    email = models.EmailField(
        _('email address'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters of fewer. Must be a valid email address.'),
        error_messages={
            'unique':_("A user with that email address already exists."),
        },
    )

此表单类:

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['username','email','password']

此视图类:

class UserFormView(View):
    form_class = UserForm
    template_name = 'workoutcal/register.html'

    def get(self, request):
        print("Hi again")
        form = self.form_class(None)
        return render(request, self.template_name, {'form':form})
    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():

            user = form.save(commit=False)

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()

            user = authenticate(username=username, password=password)

            if user is not None:

                if user.is_active:
                    login(request, user)
                    return redirect('workoutcal:calendar')

        return render(request, self.template_name, {'form': form})

和这个网址:

url(r'^register/$', views.UserFormView.as_view(), name='register')

所以,当我去/workoutcal/register时,我看到了这一点:

enter image description here

"帮助文字"始终显示在浏览器中。这是默认的Django行为,还是由于我犯了一些错误?

另外,如果用户在相应字段中输入错误数据,如何才显示文本?

1 个答案:

答案 0 :(得分:1)

  

如果您在模板中使用{{ form }}

它会始终自动显示help_textlabelerrorswidget

如果您不希望自己需要looping over fields

手动呈现form
<form method="post" novalidate>
    {% csrf_token %}

    {{ form.non_field_errors }}

    {% for hidden_field in form.hidden_fields %}
       {{ hidden_field.errors }}
       {{ hidden_field }}
    {% endfor %}

    {% for field in form.visible_fields %}
        <div class="fieldWrapper">
           {{ field.errors }}
           {{ field.label_tag }} {{ field }}
           {{ field.help_text }} <!-- remove this line if you don't want to show it in your html.-->
        </div>
    {% endfor %}
    <button type="submit">Submit</button>
</form>
  

有关更多阅读文档:https://docs.djangoproject.com/en/2.0/topics/forms/