简体   繁体   中英

Problem loading a static css file with django

I'm trying to load a static css file but to no avail:

home.html:

{% extends 'base.html' %}

{% block body%}
{% load static %}
<link rel="stylesheet" href="{% static 'home/style.css' %}"     type="text/css">
<div class="container">
    <br/>
    <form method="post">
        {% csrf_token %}
        {{ form.post }}
        <br />
        <button type="submit">Submit</button>
</form>
<h2>{{ text }}</h2>
{% for post in posts %}
    <h1>{{ post.post }}</h1>
    <p>Posted </b> on {{ post.created }}</p>
 {% endfor %}
</div>
{% endblock %}

style.css:

.HomeForm {
size:20;
}

forms.py:

class HomeForm(forms.ModelForm):
post = forms.CharField(widget=forms.TextInput(
    attrs={
        'class': 'form-control',
        'placeholder': 'How are you feeling?',
        'size': '20',

    }
))

I have a feeling I'm loading the static file in the wrong place, whats the solution? Thanks in advance.

You are loading the css file correctly. But that is not how you apply css classes to django forms.

Firstly, You are already giving bootstrap attributes to your field in your forms.py . Now to apply the css classes change the following.

style.css
doesnt matter what you name your classes. No need to name them same as your Form name.

.home-post { 
size:30; // Increase this to see difference
}

Now in your home.html add the class to your form. (Look for the comment). So now all the elements inside this container have size attribute too.

{% extends 'base.html' %} {% block body%} {% load static %}
<link rel="stylesheet" href="{% static 'home/style.css' %}" type="text/css">
<div class="container home-post"> <!--This is how you need to apply-->
    <br/>
    <form method="post"> 
        {% csrf_token %} {{ form.post }}
        <br />
        <button type="submit">Submit</button>
    </form>
    <h2>{{ text }}</h2> {% for post in posts %}
    <h1>{{ post.post }}</h1>
    <p>Posted on {{ post.created }}</p>
    {% endfor %}
</div>
{% endblock %}

EDIT: Looks like you're using bootstrap but don't seem to load it. Add bootstrap if you didn't already add it in your base.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM