Django Allauth - 如何向字段添加自定义css类?

时间:2014-01-26 20:01:07

标签: html css django django-allauth

在login.html中我有:

 <form class="login" method="POST" action="{% url 'account_login' %}">
  {% csrf_token %}

  {{form.as_p}}

我可以在世界上如何向字段添加自定义css类和其他属性?互联网上似乎没有人遇到过这个问题。我只需要添加像课一样简单的东西。如果有人回答此问题,请提前致谢我真的希望这会对其他人有所帮助。

4 个答案:

答案 0 :(得分:8)

您可以使用ACCOUNT_FORMS中的settings.py覆盖默认的LoginForm,例如:

ACCOUNT_FORMS = {'login': 'yourapp.forms.YourLoginForm'}

并相应地写一个YourLoginForm

# yourapp/forms.py

from allauth.account.forms import LoginForm

class YourLoginForm(LoginForm):
    def __init__(self, *args, **kwargs):
        super(YourLoginForm, self).__init__(*args, **kwargs)
        self.fields['login'].widget = forms.TextInput(attrs={'type': 'email', 'class': 'yourclass'})
        self.fields['password'].widget = forms.PasswordInput(attrs={'class': 'yourclass'})

答案 1 :(得分:3)

有点hacky方式 - 但它有效: 从您的控制台获取表单的html,因为它是从{{form.as_p}}生成的 把它贴在触手可及的地方。 现在建立自己的表格。输入和您需要的所有课程。 对于新的所有分类表格中的每个输入字段,请获取原始表格中的ID。 这应该使表单工作。 确保你拥有所有输入 - 包括{{form.as_p}}生成的隐藏输入(不是csrf!)

最后显示错误: 对于每个字段插入{{form.fieldname.errors}} 确保您的字段名称与原始格式相同。

全部完成。

答案 2 :(得分:2)

您正在使用HTML Django为您创建的HTML,致电form.as_p just like this example

您可能正在寻找的内容is the example right below it.您在模板中写下更多标记的位置。

It sounds like you might also be interested in this.使用以下内容创建表单并指定要添加到字段中的类:

myfield = forms.CharField(
            widget=forms.TextInput(attrs={'class':'myclass'}))

现在,在模板中调用form.myfield将创建一个输入文本字段,其中包含类myclass

答案 3 :(得分:-1)

每个人都有这个问题,但答案很简单。

如果您不想从django应用程序干预css并将CSS代码附加到.css文件中,您必须查看{{ form.as_p }}标记的输出(相信{{3}的强大功能})。并将该渲染输出的CSS写入.css文件

例如;我假设{{ form.as_p }}输出如下:

<form action="." method="POST" id="login_form" class="login">
<p>
    <label for="id_user_name">User Name:</label>
    <input id="id_user_name" type="text" name="user_name" maxlength="100" />
</p>
<p>
    <label for="id_password">Message:</label>
    <input type="text" name="message" id="id_password" />
</p>
</form>

正如您在输出中看到的那样,所有标签都有自己的id。所以你可以用它的id写出合适的css。

或者只是向id提供form tag,然后在form tag下为子标记写css。这更容易编写和记忆。此外,css可以应用于所有相同的id表单。

附录:

此外,您还需要将allauth html文件从库中复制到template文件夹,然后才需要对其进行更改。