---
tags: Python Web
---
# Тема 3. Приложение доска объявлений
https://github.com/roman-yatsenko/django-topics/tree/main/django-mb
## Начальная настройка
```shell
pipenv install Django==2.2.16
pipenv shell
django-admin startproject mb_project .
python manage.py startapp posts
```
### mb_project/settings.py
```python=33
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts'
]
```
```shell
python manage.py migrate
python manage.py runserver
```
## Создание модели базы данных
### posts/models.py
```python=
from django.db import models
class Post(models.Model):
text = models.TextField()
```
## Активация моделей
```shell
python manage.py makemigrations posts
python manage.py migrate posts
```
## Django Admin
```shell
python manage.py createsuperuser
python manage.py runserver
```
### localhost:8000/admin
### posts/admin.py
```python=
from django.contrib import admin
from .models import Post
admin.site.register(Post)
```
### Add new Post
### posts/models.py
```python=3
class Post(models.Model):
text = models.TextField()
def __str__(self):
"""Строковое отображение модели"""
return self.text[:50]
```
## URLs
### posts/views.py
```python=
from django.views.generic import ListView
from .models import Post
class HomePageView(ListView):
model = Post
template_name = 'home.html'
```
```shell
mkdir templates
touch templates/home.html
```
### mb_project\settings.py
```python=55
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...
```
### templates\home.html
```html=
<h1>Message board homepage</h1>
<ul>
{% for post in object_list %}
<li>{{ post }}</li>
{% endfor %}
</ul>
```
### mb_project\urls.py
```python=16
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('posts.urls')),
]
```
```shell
touch posts/urls.py
```
### posts\urls.py
```python=
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
]
```
```shell
python manage.py runserver
```
### Add more posts
## Tests
### posts\tests.py
```python=
from django.test import TestCase
from .models import Post
class PostModelTest(TestCase):
def setUp(self):
Post.objects.create(text='just a test')
def test_text_content(self):
post=Post.objects.get(id=1)
expected_object_name = f'{post.text}'
self.assertEqual(expected_object_name, 'just a test')
```
```shell
python manage.py test
```
### posts\tests.py
```python=2
from django.urls import reverse
```
```python=17
class HomePageViewTest(TestCase):
def setUp(self):
Post.objects.create(text='this is another test')
def test_view_url_exists_at_proper_location(self):
resp = self.client.get('/')
self.assertEqual(resp.status_code, 200)
def test_view_url_by_name(self):
resp = self.client.get(reverse('home'))
self.assertEqual(resp.status_code, 200)
def test_view_uses_correct_template(self):
resp = self.client.get(reverse('home'))
self.assertEqual(resp.status_code, 200)
self.assertTemplateUsed(resp, 'home.html')
```
```shell
python manage.py test
```
---
(c) Яценко Р.Н., 2018-2020
[Учебный центр компьютерных технологий "Кит"](http://kit.kh.ua/)
<img src="https://i.imgur.com/Kh901c1.png" style="width: 150px; position: fixed; top: 100px; right: 10px; border: 0; box-shadow: none;">