[PYTHON] Build a bulletin board app from scratch with Django. (Part 3)

Part 2 https://qiita.com/TuruMaru/items/8b55d1e134f29b8a8dcd

Just a little CSS

$mkdir static
$touch base.css

Create a static directory directly under the project and create a css file in it. static means static, so it seems to store static files.

mysite/setting.py


STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

Add this to your config file.

templates/base.html


{% load staticfiles %}← Add this
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
↓ Add this
    <link rel="stylesheet" href="{% static 'base.css' %}">
    <title>{% block page_title %}{% endblock %}</title>

</head>

Now you can use css. It's a little annoying.

Before creating the function to display the post, I will write the HTML and CSS of the base.

templates/base.html


{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="{% static 'base.css' %}">
    <title>{% block page_title %}{% endblock %}</title>

</head>
<body>
<nav>
    <p class="site-name">Blog</p>
    <ul>
        <li><a href="{% url 'posts:index' %}">Top</a></li>
        <li><a href="{% url 'posts:write' %}">Write</a></li>
    </ul>
</nav>

<div class="title">
    <h1>{% block title %}{% endblock %}</h1>
</div>

<hr>

<div class="content">
    {% block content%}{% endblock %}
</div>

<hr>

</body>
</html>

static/base.css


html, body{
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

body, h1, hr {
    margin: 0px;
}

a{
    color: #e8e8e8;
}

nav p{
    margin: 0px;
    font-size: 30px;
}

nav{
    padding: 10px 10px;
    color: #e8e8e8;
    background-color: #41a888;
}

nav .site-name{
    display: inline-block;
}

nav ul{
    margin: 0px;
    padding: 0px;
    float: right;
}

nav ul li{
    padding: 10px;
    display: inline-block;
}

.title{
    margin: 21px 50px;
}

.content{
    margin: 20px 50px;
}

Add a screen (write) to write posts to view.py and ʻurls.py`.

posts/views.py


class WriteView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'posts/write.html')


write = WriteView.as_view()

posts/urls.py


app_name = 'posts'
urlpatterns = [
    path('', views.index, name='index'),
    path('write/', views.write, name='write'),← Add this
]
スクリーンショット 2019-11-05 11.24.22.png

Then it will look like this.

I was wondering which of the post list screen (post) and the post writing screen (write) should be done first, but I will do it from the post writing screen (write).

Post creation screen

Create an input form and save your input in the database.

flow

  1. Create form.py
  2. Create views.py
  3. Create html

First only the form

$cd posts
$touch form.py

posts/form.py


from django import forms
from .models import Posts


class WriteForm(forms.ModelForm):
    class Meta:
        #Specify model
        model = Posts
        #Specify the column you want to display as a form
        fields = ('text',)

posts/views.py


from django.shortcuts import render

# Create your views here.
from django.views.generic import View
#form.Import form from py
from .form import WriteForm


class IndexView(View):
    def get(self,request, *args, **kwargs):
        return render(request, 'posts/post.html')


index = IndexView.as_view()


class WriteView(View):
    def get(self, request, *args, **kwargs):
        #Jump to html file with value
        return render(request, 'posts/write.html', {'form': WriteForm})


write = WriteView.as_view()

templates/posts/write.html


{% extends "base.html" %}

{% block page_title %}Write{% endblock %}
{% block title %}Write{% endblock %}

{% block content %}
    <form method="post" action="{% url 'posts:write' %}">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="button">Post</button>
    </form>
{% endblock %}

This is the screen you can do. スクリーンショット 2019-11-05 16.24.03.png

I don't write that much. I really have more to write HTML. The code less here is form.py. At first I didn't know why I had to create such a file, but it's obviously more efficient if I create a lot of forms. Also, it seems to be convenient when saving to the database.

Save to database

If nothing is done, an error will occur when the "Post" button is pressed. So, let's write the process when the method is post, that is, the process to save in the database in views.py.

posts/views.py


class WriteView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'posts/write.html', {'form': WriteForm})

    def post(self, request, *args, **kwargs):
        #Store the contents written in the form
        form = WriteForm(request.POST)
        #Take out before saving
        post = form.save(commit=False)
        #Save
        post.save()
        #Go to view of index
        return redirect(to='posts:index')


write = WriteView.as_view()

You can now save it to the database. Next, the saved posts will be displayed in the post list.

Post list screen

flow

  1. Create views.py
  2. Create html

views.py


class IndexView(View):
    def get(self, request, *args, **kwargs):
        #Get all the data in the Posts table
        queryset = Posts.objects.all().order_by('-created_at')
        #Post with price.Jump to html
        return render(request, 'posts/post.html', {'posts': queryset})


index = IndexView.as_view()

By the way, data is acquired in descending order by prefixing '-created_at' and "-" with "-". Quite important.

templates/posts/post.html


{% extends "base.html" %}
{% block page_title %}post{% endblock %}
{% block title %}Posts{% endblock %}
{% block content %}
    {% for post in posts %}← Use the array of posts stored posts as post
        <div class="post">
            <p class="text">{{ post.text }}</p>
            {{ post.created_at }}
            <hr>
        </div>
    {% endfor %}
{% endblock %}

If you look at the list screen with this スクリーンショット 2019-11-06 2.40.40.png

Finally completed ~ (^ ○ ^) It's a very simple code, but I tried it all. There is still room for expansion, so please try expanding it.

Recommended Posts

Build a bulletin board app from scratch with Django. (Part 2)
Build a bulletin board app from scratch with Django. (Part 3)
Django starting from scratch (part: 2)
Django starting from scratch (part: 1)
Build a web application with Django
Create a Todo app with Django ① Build an environment with Docker
How to develop a cart app with Django
Create a game UI from scratch with pygame2!
[Python] Build a Django development environment with Docker
Build a Django environment with Vagrant in 5 minutes
Create a bulletin board with Heroku, Flask, SQLAlchemy
Build a Django development environment with Doker Toolbox
Quickly build a Python Django environment with IntelliJ
Let's make a nervous breakdown app with Vue.js and Django-Rest-Framework [Part 1] ~ Django setup ~
Django memo # 1 from scratch
Create a Todo app with Django REST Framework + Angular
Create a Todo app with the Django REST framework
Steps from installing Python 3 to creating a Django app
Create a Todo app with Django ③ Create a task list page
Deploy a Django app made with PTVS on Azure
Create a Todo app with Django ⑤ Create a task editing function
Build a development environment with Poetry Django Docker Pycharm
Build a Django environment for Win10 (with virtual space)
Create a machine learning environment from scratch with Winsows 10
Build a Django development environment with Docker! (Docker-compose / Django / postgreSQL / nginx)
[Memo] Build a development environment for Django + Nuxt.js with Docker
[Django] Build a Django container (Docker) development environment quickly with PyCharm
Deploy Django + React from scratch to GKE (3) Create a GCP project
# 3 Build a Python (Django) environment on AWS EC2 instance (ubuntu18.04) part2
Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)
Make a scraping app with Python + Django + AWS and change jobs
[DynamoDB] [Docker] Build a development environment for DynamoDB and Django with docker-compose
Test Driven Development with Django Part 3
Test Driven Development with Django Part 4
Play with a turtle with turtle graphics (Part 1)
Test Driven Development with Django Part 6
Django: Import a class from a string
Build a deb file with Docker
Deploy a Django application with Docker
Test Driven Development with Django Part 2
Django Tips-Create a ranking site with Django-
Implement a Django app on Hy
App installed from Windows10 32-bit scratch
Creating a simple app with flask
Make a filter with a django template
Test Driven Development with Django Part 1
Post bulletin board creation with flask
Test Driven Development with Django Part 5
Create a file uploader with Django
How to authenticate with Django Part 2
How to authenticate with Django Part 3
Throw GQL with a numeric ID from the App Engine management screen
Web App Development Practice: Create a Shift Creation Page with Django! (Introduction)
I tried to send a registration completion email from Gmail with django.
Create a Todo app with Django ④ Implement folder and task creation functions
Build a "Deep learning from scratch" learning environment on Cloud9 (jupyter miniconda python3)
I made a webAPI! Build environment from Django Rest Framework 1 on EC2
Steps to build a Django environment with Win10 WSL Ubuntu18.04 + Anaconda + Apache2
A simple RSS reader made with Django
Easily build a development environment with Laragon
Build a blockchain with Python ① Create a class