Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Adding custom CSS in UpdateView

I'm trying to find a method of adding custom css to the form that is generated. What would be an appropriate way of adding custom css to those fields?

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>
like image 403
ghjwztcowsfoovxizs Avatar asked Oct 25 '25 07:10

ghjwztcowsfoovxizs


1 Answers

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

Next we can "inject" that form in the class-based view:

# 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
like image 89
Willem Van Onsem Avatar answered Oct 27 '25 04:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!