Django:在UpdateView中添加自定义CSS

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

views.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

models.py

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

profileUpdate.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>
评论
小梨涡
小梨涡

请执行下列操作:

class CommentForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
    url = forms.URLField()
    comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))

或对于ModelForms使用此:

class CommentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'class': 'special'})
        self.fields['comment'].widget.attrs.update(size='40')

Please see the source from the django docs: https://docs.djangoproject.com/en/3.0/ref/forms/widgets/#styling-widget-instances

点赞
评论
闹心*
闹心*

You can define a ModelForm, with the css attribute, for example:

# 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'})
        }

接下来,我们可以在基于类的视图中“注入”该表单:

# 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
点赞
评论