Commit e79da441 authored by Georgios Xonikis's avatar Georgios Xonikis

Initial setup and Blog app created

parents
.idea
__pycache__
*.pyc
.DS_Store
\ No newline at end of file
FROM continuumio/miniconda3:4.5.12
ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
RUN apt-get update && apt-get install -y wget bzip2
COPY ./app/requirements.yml /app/requirements.yml
RUN conda env update -f /app/requirements.yml
COPY ./app /app
COPY ./scripts/* /scripts/
RUN chmod +x /scripts/*
WORKDIR /app
\ No newline at end of file
from django.contrib import admin
# Register your models here.
from .models import Post
admin.site.register(Post)
from django.apps import AppConfig
class BlogConfig(AppConfig):
name = 'blog'
# Generated by Django 2.2.2 on 2019-06-12 09:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('body', models.TextField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
\ No newline at end of file
from django.test import TestCase
# Create your tests here.
from django.shortcuts import render
# Create your views here.
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
"""
Django settings for project project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'rr&p+a#_!wy*zt0*@yi!1u6g8g-qw)g^ukbejyw9doq1@2$vxd'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'PORT': 5432,
'HOST': 'postgres',
'PASSWORD': 'postgres',
'USER': 'postgres'
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
"""project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
"""
WSGI config for project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
application = get_wsgi_application()
name: base
dependencies:
- python=3.6
- psycopg2=2.7.4
- pip:
- django==2.2.2
- flake8
version: '3'
services:
app:
image: django-project-motion:latest
ports:
- 8000:8000
volumes:
- ./app:/app
depends_on:
- postgres
postgres:
image: postgres:latest
ports:
- 5432:5432
volumes:
- django-project:/var/lib/postgresql/data
volumes:
django-project:
\ No newline at end of file
Create Django Project in Docker
1. Basic Setup
- Create your project on gitlab
- Create a folder for the repo on local
- Clone the project --> git clone <project path>
- Open it in PyCharm
- Create a .gitignore file and exclude what you need to from git -->
.idea
__pycache__
*.pyc
.DS_Store
2.1 Create the requirements.yml file to update the environment of the container -->
name: base
dependencies:
- python=3.6
- psycopg2=2.7.4
- pip:
- django==2.2.2
- flake8
2.2 Create Dockerfile
- Go to docker hub and find the miniconda3 image
- Create a Dockerfile -->
FROM continuumio/miniconda3:4.5.12
ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
RUN apt-get update && apt-get install -y wget bzip2
COPY ./app/requirements.yml /app/requirements.yml
RUN conda env update -f /app/requirements.yml
COPY ./app /app
COPY ./scripts/* /scripts/
RUN chmod +x /scripts/*
WORKDIR /app
3. Create a docker-compose.yml -->
version: '3'
services:
app:
image: django-project:latest
ports:
ports:
- 8000:8000
volumes:
- ./app:/app
4. Build the image -->
docker build -t <image name>:latest .
# to remove an image --> docker rm <image name>
or --> docker rmi -f <image name>
5. Create a directory scripts ans a script -->
run.sh
6. Create a directory <app> in the main project directory
tree -->
django-project
- app
-.gitignore
- docker-compose.yml
- Dockerfile
7. Run the image to spin-up a new container -->
version: '3'
services:
app:
image: django-project:latest
ports:
- 8000:8000
volumes:
- ./app:/app
depends_on:
- postgres
postgres:
image: postgres:latest
ports:
- 5432:5432
volumes:
- django-project:/var/lib/postgresql/data
volumes:
django-project:
docker-compose run --service-ports app bash
# If dependencies not in Dockerfile
8. Install django on container -->
pip install django
9. Start django project
- Inside the app folder
- start the project --> django-admin startproject project .
- Go to settings.py and change the database -->
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'PORT': 5432,
'HOST': 'postgres',
'PASSWORD': 'postgres',
'USER': 'postgres'
}
}
# Reset or start a new database
- to create the database --> python manage.py migrate
- create superuser to access admin --> python manage.py createsuperuser
- to run the server --> python manage.py runserver 0.0.0.0:8000
- check the server visit --> http://localhost:8000
- check the admin page --> http://localhost:8000/admin
10. Connect to postgres from Pycharm
View - Tools window - Databases - Postgres -->
localhost: postgres
user: postgres
password: postgres
port: 5432
11. Create an app -->
python manage.py startapp <app name>
ex: python manage.py startapp blog
12. Add the app to the settings.py -->
INSTALLED_APPS = [
.....
'<app name>',
]
ex:
INSTALLED_APPS = [
.....
'blog',
]
13. Create a model at <app name> / models -->
example:
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
14. Save the changes to the database -->
python manage.py makemigrations
python manage.py migrate
15. Check that the table has created -->
table name = <app name>_<model class name in lowercase>
ex: blog_post
16. Add it to the admin
Go to app directory / admin.py -->
admin.site.register(<model class name>)
ex: admin.site.register(Post)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment