Search code examples
pythonhtmldjangoformsstyles

How can I style a django form with css?


I tried looking for the answer earlier but couldn't seem to figure out a few things. I'm creating my form in a form.py file so its a python file.

Here is my forms.py file :

class UploadForm(ModelForm):
    name = forms.TextInput(attrs={'class': 'myfieldclass'})
    details = forms.TextInput()
    littype = forms.TextInput()
    image = forms.ImageField()
    class Meta:
        model = info
        fields = ["name", "details", "littype", "image"]

Here is my views.py function for it if it helps find the solution :

def uploadform(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        print(request.FILES)
        if form.is_valid():
            form.save()
        redirect(home)
    return render(request, 'uploadform.html', {'form': UploadForm})

To style it I thought I could do something like this which I found in another question :

class MyForm(forms.Form):
myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass'}))

Except I have no idea how to link a css page to that python file. This is what I tried writing but i think it doesnt work because its meant for html but its in a python file :

<link type="text/css" rel="stylesheet" href="templates/form.css">

And so I'm just not sure how to style my form. Thanks for any answers!


Solution

  • Within your template you have to just import the css file in the head tag, but do ensure you load static first.

    html file:

    {% load static %}
    
    <!doctype html>
    <html lang="en">
         <head>
              # import the css file here
              <link rel="stylesheet" href="{% static 'path to css file' %}">
         </head>
         ...
    </html>
    

    Within the css file:

    # Styling the class 
    .myfieldclass{
         width: 30% !important;
         height: 100px !important;
         ...
    }
    

    But please note that you don't have to import a css file since you can add the style tag in the head tag as well. For example:

    <!doctype html>
    <html lang="en">
         <head>
              <style type="text/css">
                   .myfieldclass{
                        width: 30% !important;
                        height: 100px !important;
                        ...
                   }
              </style>
         </head>
         ...
    </html>
    

    You could apply css from the python file itself as well.

    Approach from the python file.

    # Custom way to set css styling on a form field in python code
    def field_style():
         styles_string = ' '
    
         # List of what you want to add to style the field
         styles_list = [
              'width: 30% !important;',
              'height: 100px !important;',
         ]
    
         # Converting the list to a string 
         styles_string = styles_string.join(styles_list)
         # or
         # styles_string = ' '.join(styles_list)
    return styles_string
    
    class MyForm(forms.Form):
         myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass', 'style': field_style()}))
         # 'style': field_style() .... field_style() will return in this case 'width: 30% !important; height: 100px !important;'
    

    Any of those should work, but I recommend styling from the html or css file instead.