Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add css in django Updateview or Create view form

I am working on a project, and my designer gave me the design, so I want to mimic the input forms which are in the design, to do that I need to add css in my form object.

If in the case of django function based view, It is easy to addcss by creating forms.py files and add css as follows. adding css class in django forms

I also tried to inject css class using jquery, but I couldn't succed. Injecting css class in html forms element using jquery

myapp/forms.py

But how do I add custom css in the form field, when using class based view.

class ItemUpdateView(UpdateView):
    model = Item
    fields = ('name','tag', 'category', 'company', 'price',)

How do I add the custom class to name, tag, category field.

like image 784
shining Avatar asked Oct 27 '25 06:10

shining


2 Answers

You can define form_class attribute on your update view and add css to that form.

class ItemUpdateView(UpdateView):
    form_class = ItemForm

ItemForm can be a ModelForm and you can customize it as described here: https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#overriding-the-default-fields

like image 65
ozren1983 Avatar answered Oct 28 '25 21:10

ozren1983


When django generates html from form fields, it automatically add it as "id_fieldName". So you can add css with javascript on frontend.

<script>
    document.getElementById("id_company").classList.add("class name");
</script>
like image 22
Turabek Holmirzaev Avatar answered Oct 28 '25 20:10

Turabek Holmirzaev



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!