Django allauth:删除表单标签?

Django allauth: Remove form label?

问题

我正在使用 Django 和 allauth 构建一个注册页面。我正在尝试从电子邮件字段中删除 'E-mail' 标签。

我试过的

我已经从 First NameLast Name 中删除了标签,方法是将 label='' 添加到它们的字段 (as was recommended in similar questions)。出于某种原因,这不适用于电子邮件字段。

我的forms.py:

class CustomSignupForm(SignupForm): 
    first_name = forms.CharField(max_length=30, label="", widget=forms.TextInput(attrs={'placeholder': 'First Name'})) 
    last_name = forms.CharField(max_length=30, label="", widget=forms.TextInput(attrs={'placeholder': 'Last Name'})) 
    email = forms.EmailField(label='', widget=forms.TextInput(attrs={'placeholder': 'Email'}))  

    def signup(self, request, user): 
        user.first_name = self.cleaned_data['first_name'] 
        user.last_name = self.cleaned_data['last_name'] 
        user.email = self.cleaned_data['email'] 
        user.save() 
        return user 

我也试过:

email = forms.EmailField(label='', widget=forms.TextInput(attrs={'type': 'email', 'placeholder': 'E-mail address'}))

下面是表单继承自的授权 forms.py:

class BaseSignupForm(_base_signup_form_class()):
    username = forms.CharField(label=_("Username"),
                               min_length=app_settings.USERNAME_MIN_LENGTH,
                               widget=forms.TextInput(
                                   attrs={'placeholder':
                                          _('Username'),
                                          'autofocus': 'autofocus'}))
    email = forms.EmailField(widget=forms.TextInput(
        attrs={'type': 'email',
               'placeholder': _('E-mail address')}))

    def __init__(self, *args, **kwargs):
        email_required = kwargs.pop('email_required',
                                    app_settings.EMAIL_REQUIRED)
        self.username_required = kwargs.pop('username_required',
                                            app_settings.USERNAME_REQUIRED)
        super(BaseSignupForm, self).__init__(*args, **kwargs)
        username_field = self.fields['username']
        username_field.max_length = get_username_max_length()
        username_field.validators.append(
            validators.MaxLengthValidator(username_field.max_length))
        username_field.widget.attrs['maxlength'] = str(
            username_field.max_length)

        default_field_order = [
            'email',
            'email2',  # ignored when not present
            'username',
            'password1',
            'password2'  # ignored when not present
        ]
        if app_settings.SIGNUP_EMAIL_ENTER_TWICE:
            self.fields["email2"] = forms.EmailField(
                label=_("E-mail (again)"),
                widget=forms.TextInput(
                    attrs={
                        'type': 'email',
                        'placeholder': _('E-mail address confirmation')
                    }
                )
            )
        if email_required:
            self.fields['email'].label = gettext("E-mail")
            self.fields['email'].required = True
        else:
            self.fields['email'].label = gettext("E-mail (optional)")
            self.fields['email'].required = False
            self.fields['email'].widget.is_required = False
            if self.username_required:
                default_field_order = [
                    'username',
                    'email',
                    'email2',  # ignored when not present
                    'password1',
                    'password2'  # ignored when not present
                ]

        if not self.username_required:
            del self.fields["username"]

        set_form_field_order(
            self,
            getattr(self, 'field_order', None) or default_field_order)

    def clean_username(self):
        value = self.cleaned_data["username"]
        value = get_adapter().clean_username(value)
        return value

    def clean_email(self):
        value = self.cleaned_data['email']
        value = get_adapter().clean_email(value)
        if value and app_settings.UNIQUE_EMAIL:
            value = self.validate_unique_email(value)
        return value

    def validate_unique_email(self, value):
        return get_adapter().validate_unique_email(value)

    def clean(self):
        cleaned_data = super(BaseSignupForm, self).clean()
        if app_settings.SIGNUP_EMAIL_ENTER_TWICE:
            email = cleaned_data.get('email')
            email2 = cleaned_data.get('email2')
            if (email and email2) and email != email2:
                self.add_error(
                    'email2', _("You must type the same email each time.")
                )
        return cleaned_data

    def custom_signup(self, request, user):
        custom_form = super(BaseSignupForm, self)
        if hasattr(custom_form, 'signup') and callable(custom_form.signup):
            custom_form.signup(request, user)
        else:
            warnings.warn("The custom signup form must offer"
                          " a `def signup(self, request, user)` method",
                          DeprecationWarning)
            # Historically, it was called .save, but this is confusing
            # in case of ModelForm
            custom_form.save(user)


class SignupForm(BaseSignupForm):
    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)
        self.fields['password1'] = PasswordField(label=_("Password"))
        if app_settings.SIGNUP_PASSWORD_ENTER_TWICE:
            self.fields['password2'] = PasswordField(
                label=_("Password (again)"))

        if hasattr(self, 'field_order'):
            set_form_field_order(self, self.field_order)

    def clean(self):
        super(SignupForm, self).clean()

        # `password` cannot be of type `SetPasswordField`, as we don't
        # have a `User` yet. So, let's populate a dummy user to be used
        # for password validaton.
        dummy_user = get_user_model()
        user_username(dummy_user, self.cleaned_data.get("username"))
        user_email(dummy_user, self.cleaned_data.get("email"))
        password = self.cleaned_data.get('password1')
        if password:
            try:
                get_adapter().clean_password(
                    password,
                    user=dummy_user)
            except forms.ValidationError as e:
                self.add_error('password1', e)

        if app_settings.SIGNUP_PASSWORD_ENTER_TWICE \
                and "password1" in self.cleaned_data \
                and "password2" in self.cleaned_data:
            if self.cleaned_data["password1"] \
                    != self.cleaned_data["password2"]:
                self.add_error(
                    'password2',
                    _("You must type the same password each time."))
        return self.cleaned_data

    def save(self, request):
        adapter = get_adapter(request)
        user = adapter.new_user(request)
        adapter.save_user(request, user, self)
        self.custom_signup(request, user)
        # TODO: Move into adapter `save_user` ?
        setup_user_email(request, user, [])
        return user

我的 signup.html 模板。它是 allauth 附带的原始 signup.py 模板的略微修改版本:

{% extends 'coreapp/base.html' %} {% load staticfiles %} {% block content %}{% load i18n %}

<div class="col-lg-8 offset-lg-2 accounts-page">
  <div class="custom-card">
    <h1>{% trans "Please register to recieve your results by email" %}</h1>


    <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
      {% csrf_token %}
      {{ form.as_p }}
      {% if redirect_field_value %}
      <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
      {% endif %}
      <button class="accounts-register-button" type="submit">{% trans "REGISTER" %}</button>
    </form>

  </div>
</div>
<div>
  {% include "socialaccount/snippets/provider_list.html" with process="login" %}

</div>
<p>{% blocktrans %}Already have an account? <a href="{{ login_url }}">Sign in</a>.{% endblocktrans %}</p>
</div>
{% endblock %}

问题

有没有人知道如何删除此电子邮件标签?

这个:

{{ form.as_p }}

加载您不想要的字段标签,所以改为这样做:

{% for field in form %}
  {{ field }} # this will only load the field 
{% endfor %}

对于其他想知道的人。在您的其中一个应用程序中创建一个 forms.py,并添加以下内容('signin' 页面示例):

from django import forms
from allauth.account.forms import LoginForm, PasswordField


class SelfLoginForm(LoginForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields["login"].label = ""
        self.fields["password"].label = ""

然后在您的 settings.py 中添加以下内容:

# Forms
# https://django-allauth.readthedocs.io/en/latest/forms.html?highlight=ACCOUNT_FORMS#account-forms
# Overwrites AllAuth forms to change their style.
ACCOUNT_FORMS = {
    "login": "authentication.forms.SelfLoginForm", # Notice modification to LOGIN form. 
    "signup": "allauth.account.forms.SignupForm",
    "add_email": "allauth.account.forms.AddEmailForm",
    "change_password": "allauth.account.forms.ChangePasswordForm",
    "set_password": "allauth.account.forms.SetPasswordForm",
    "reset_password": "allauth.account.forms.ResetPasswordForm",
    "reset_password_from_key": "allauth.account.forms.ResetPasswordKeyForm",
    "disconnect": "allauth.socialaccount.forms.DisconnectForm",
}

将这行代码插入您的 css 文件

label {
display: none;
}