Django:在 UpdateView 中添加自定义 CSS

标签 django django-models django-views

我正在尝试找到一种将自定义 css 添加到生成的表单的方法。将自定义 css 添加到这些字段的合适方法是什么?

View .py

class ProfileUpdateView(UpdateView):
    template_name = "users/profileUpdate.html"
    model = models.User
    fields = (
        "first_name",
        "last_name",
        "about",
        "displayImg",
    )

    def get_object(self, queryset=None):
        return self.request.user

模型.py
class User(AbstractUser):
    about = models.TextField(default="")
    displayImg = models.ImageField(blank=True, upload_to="users")

配置文件更新.html
    <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button
            class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline w-full">Update</button>
    </form>

最佳答案

您可以定义一个 ModelForm , 带有 css 属性,例如:

# app/forms.py

from django import forms

class ProfileForm(forms.ModelForm):
    class Meta:
        model = models.User
        fields = (
            'first_name',
            'last_name',
            'about',
            'displayImg',
        )
        widgets = {
            'first_name': forms.TextInput(attrs={'class': 'myclass'})
        }

接下来,我们可以在基于类的 View 中“注入(inject)”该表单:
# app/views.py

from app.forms import ProfileForm

class ProfileUpdateView(UpdateView):
    template_name = "users/profileUpdate.html"
    model = models.User
    form_class = ProfileForm

    def get_object(self, queryset=None):
        return self.request.user

关于Django:在 UpdateView 中添加自定义 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61860145/

相关文章:

python - Django : SyntaxError 'unexpected EOF' while saving a Form

django - 我无法在 Osx 中安装 'pip install pil'

python - Django 从字符字段迁移到整数字段?

django - 如何强制Django Admin使用select_related?

Django 优化查询

python - 带有 token 参数的 Django 电子邮件验证 URL

python - 删除前编辑记录。 Django 删除 View

python - 使用 Python Social-auth 如何从自定义管道检索存储在 session 中的字段

django - 使用 django.shortcuts.redirect 添加 request.GET 变量

python - Django Admin - 批量编辑数据?