T
T
tonyjasta2016-04-28 11:56:19
Django
tonyjasta, 2016-04-28 11:56:19

Question about outputting Django content to HTML?

There is an expanded page. However, everything that is displayed in it is specified in HTML (pictures, text, etc.)
How to output content from the database?
https://codeshare.io/ZwwR8 here is an attempt to do this, but it did not work out. :(

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2016-04-28
@tonyjasta

Well, pass data to the context in views, and actually display this data in templates.
In views.py, you pass some data to the context:

from django.http import Http404
from django.shortcuts import render
from models import КакаяТоМодель

def my_view(request, какой_то_id):
    try:
        my_obj = КакаяТоМодель.objects.get(pk=какой_то_id)
    except КакаяТоМодель.DoesNotExist:
        raise Http404(u"Объект КакаяТоМодель с id={id} отсутствует в базе".format(id=какой_то_id))

    какая_то_переменная = ФункцияДляПолучениЧегоТоИзБазы()
    return render(request, 'какой_то_темплейт.html', {'my_obj': my_obj, 'my_var': какая_то_переменная})

and in the template you get what was passed to the context
...
{{ my_obj.какое_то_поле }}
{{ my_obj.какое_то_поле }}
....
{{ my_var }}
....

In general, here it is:
class BannerView(View):
model = Banner
template_name = 'home.html'
def get_queryset(self):
return Banner.objects.all()

should be replaced with this:
class BannerView(ListView):
    model = Banner
    template_name = 'home.html'

then in the template a list of all your objects will be passed in the form of an object_list, through which you can run something like this:
....
{% for obj in object_list %}
     {{ obj.какое_то поле }}
{% endfor %}
....

here
class HomePage(TemplateView):
template_name = 'home.html'

context can be passed like this:
class HomePage(TemplateView):
    template_name = 'home.html'

def get_context_data(self, *args, **kwargs):
    context = super(HomePage, self).get_context_data(*args, **kwargs)
    context['имя_какой_то_переменной_для_темплейта'] = ФункцияДляПолученияКакихТоДанных()
    return context

then in the template it will be available as:
....
{{ имя_какой_то_переменной_для_темплейта }}
....

In general - go through at least some Django tutorial where this is explained in detail ...

V
Vadim Shandrinov, 2016-04-28
@suguby

How do you start the server? what version of junga?
Did you put the statics in the right directories?
You need to understand that static and media files are different things. Static is css + js + icon - what is always displayed on the site, it is usually stored on the file system and is given to the web server (nginx or apache)
in the production - also on the file system.
More details - djbook.ru/rel1.9/howto/static-files/index.html and djbook.ru/rel1.9/topics/files.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question