Displaying html form in Django

Displaying html form in Django

В the previous article on Django we created an application, a database model and mirrored the created database in the admin application. In today’s article, we are following the pattern MVC – (model, controller, template), include in the file views.py apps blog, our model from models.py, and create functions for accessing data, and displaying them in html template.

Creating a controller.

Model layer in file models.py serves to create and display database fields. The next layer is stored in the folder views.py, he is responsible for what will be displayed in response to requests for the blog page. The layer accepts the request request and returns the response in the form html page template. That is, the template will be generated dynamically depending on the data in our database, and the data itself will be formatted with the appropriate tags!


      
from django.shortcuts import render
from django.http import HttpResponse
# импорт модели
from .models import Post

def show(request):
    
    #обращение к модели и вывод значений из нее
    posts = Post.objects.all()[:10]

    context = {
        'title':'Post',
        'posts': posts
    }
    # возврат  шаблона с подставленными значениями
    return render(request, "blog/detail.html", context)

The next step is to create a folder inside the application directory template, with the following structure template / blog / file.html… Subfolder blog is present here to avoid name conflicts in the project. Further, in the internal folder blog create a file index.htmlcontaining the basic markup.
And in the same place we will create detail.html


# index.html

    
    
         

Posts

    

        

 class="container center-align"> rel="stylesheet" href="https:> name="viewport" content="width=device-width, initial-scale=1.0"> charset="utf-8"> lang="en">

    

    

        {% block content %}
        # здесь окажется код с дочерних файлов
        {% endblock %}
        

 class="container">

        Polls app
        Admin Login
    

# detail.html 

{% extends 'blog/index.html' %}

{% block content %}

{{title}}

 class="center-align blue lighten-2">

        {% for post in posts %}
        

  • {{post.title}}
  •  class="collection-item">

 class="collection">

    {% endfor %}

{% endblock %}

As you can see, both files have a common construction {% block content%} – {% endblock%}. And in detail.html present {% extends ‘blog / index.html’%}. That’s what it is template engine with its own language. Now, when requesting the application file url.py, the module function will be called views.pywhich will return the data page.


from django.urls import path 
from . import views
from django.conf.urls import url

urlpatterns = [
      url(r'^details/(?Pd+)/$', views.details, name = 'details'),
     ]
    

Thus, splitting the code into separate components reduces their interdependence, and Django templating engine minimizes the writing of monotonous code.

Previous article Next article

Copying of materials is allowed only with the indication of the author (Mikhail Rusakov) and an indexed direct link to the site (http://myrusakov.ru)!

Add to my friends VK: http://vk.com/myrusakov.
If you want to rate me and my work, then write it in my group: http://vk.com/rusakovmy.

If you do not want to miss new materials on the site,
then you can subscribe to updates: Subscribe to updates

If you still have any questions, or you have a desire to comment on this article, then you can leave your comment at the bottom of the page.

Recommend this article to your friends:

If you liked the site, then post a link to it (on your site, on the forum, in contact):

  1. Button:

    It looks like this: How to create your website

  2. Text link:

    It looks like this: How to create your website

  3. BB-code of the link for forums (for example, you can put it in the signature):

Related Posts

Property Management in Dubai: Effective Rental Strategies and Choosing a Management Company

“Property Management in Dubai: Effective Rental Strategies and Choosing a Management Company” In Dubai, one of the most dynamically developing regions in the world, the real estate…

In Poland, an 18-year-old Ukrainian ran away from the police and died in an accident, – media

The guy crashed into a roadside pole at high speed. In Poland, an 18-year-old Ukrainian ran away from the police and died in an accident / illustrative…

NATO saw no signs that the Russian Federation was planning an attack on one of the Alliance countries

Bauer recalled that according to Article 3 of the NATO treaty, every country must be able to defend itself. Rob Bauer commented on concerns that Russia is…

The Russian Federation has modernized the Kh-101 missile, doubling its warhead, analysts

The installation of an additional warhead in addition to the conventional high-explosive fragmentation one occurred due to a reduction in the size of the fuel tank. The…

Four people killed by storm in European holiday destinations

The deaths come amid warnings of high winds and rain thanks to Storm Nelson. Rescuers discovered bodies in two separate incidents / photo ua.depositphotos.com Four people, including…

Egg baba: a centuries-old recipe of 24 yolks for Catholic Easter

They like to put it in the Easter basket in Poland. However, many countries have their own variations of “bab”. The woman’s original recipe is associated with…

Leave a Reply

Your email address will not be published. Required fields are marked *