1

I want to use Django to make a notice board on my website, so I made a model like this:

class notice(models.Model):
    # the title of the notice
    text = models.CharField(max_length = 50)
    date_added = models.DateTimeField(auto_now_add = True)

    def __str__(self):
        return self.text

And I wrote "views.py" like this (the main part):

def notices(request):
    # display the notice title
    notices = notice.objects.order_by("date_added")
    context = {"notice": notices}
    return render(request, "index.html", context)

But in the file "index.html", when I wrote these codes:

    <ul>
        {% for n in notices %}
        <li>{{n.text}}</li>
        {% endfor %}
    </ul>

Nothing was displayed. Does anyone know how to solve this issue? I'd be grateful if you help me.

Well...My English is really poor, and if what I said is kind of impolite... Might you just forgive me for that? Thanks!

Update:

Thanks for Biplove Lamichhane's answer! And This is what it said while running the Django Shell:

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from wl.models import *
>>> notice.objects.order_by("date_added")
<QuerySet [<notice: testing>]>

In "index.html":

    <ul>
        {% for n in notices %}
        <li>{{n}}</li>
        {% endfor %}
    </ul>

In "views.py":

def notices(request):
    # display the notice title
    notices = notice.objects.order_by("date_added")
    context = {"notices": notices}
    return render(request, "index.html", context)

Still, displayed nothing.

2 Answers2

1

You gave notice to the context variable, here: context = {"notice": notices}. But used, notices in template. So, either change the variable in views.py like:

context = {"notices": notices}

Or,

Change template like:

    <ul>
        {% for n in notice %}
        <li>{{ n.text }}</li>
        {% endfor %}
    </ul>

Update

As your notice class __str__ returns text you can simply do:

<li>{{ n }}</li>
Biplove Lamichhane
  • 3,995
  • 4
  • 14
  • 30
1

yes indeed it's a typo. make it notice in the html page, you're done.