- create django 1.8.3 project "mysite" and project app "myapp" (for pythonanywhere.com hosting)
open console inside target forlder. Consoledjango-admin.py startproject mysite && cd mysite
this command create the project and move into project folder
console(inside project folder, on manage.py level)
python manage.py startapp myapp
this command create the app named "myapp", with templates for model that work with database etc.
Create "_temp" folder on manage.py level, create "_db.sqlite3" copy of clean database, and place "_db.sqlite3" inside "_temp" just for case. Create "static" inside "mysite/myapp" folder, for *.css etc files for myapp.
Copy "pythoncachekiller.py" and "pythontreecompiler.py" on "manage.py" level.
- edit mysite/settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))+os.sep
TEMPLATE_DIRS = (
'/home/mysite/tmps', # for pythonanywhere.com(add manual into static files sector "WEB" tab of gui) or local linux
'C:/django/tmps/mysite', # local windows
)
# DIRS can be part of other object(TEMPLATE), with different structure
DEBUG = True # must be False in product version or site will be auto blocked !!!
TEMPLATE_DEBUG = True # must be False in product version or site will be auto blocked !!!
ALLOWED_HOSTS = ['mysite.pythonanywhere.com']
# ALLOWED_HOSTS = ['mysite.pythonanywhere.com','localhost', '127.0.0.1'] # must be commented in server version
# local host for template debug, in case of "DEBUG = False TEMPLATE_DEBUG = False" or will error
# локальный хост для проверки шаблонов и т.п. при отключенном дебаге,а то ошибку выдает
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
# 'django.contrib.messages.middleware.MessageMiddleware',
# 'django.middleware.security.SecurityMiddleware',
)
USE_TZ = False
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')+os.sep
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))+os.sep
STATICFILES_DIRS=(
os.path.join(SITE_ROOT, 'static')+os.sep,
)
- create model for using "db.sqlite3"
edit "myapp/models.py"
from django.db import models
# Create your models here.
class Myappmodel(models.Model):
u_id = models.AutoField(primary_key=True) # auto-incrementing primary key ,
if model have not at least one "model.AutoField(primary_key=True)" then
will be created django automatically as "id = models.AutoField(primary_key=True)"
u_float = models.FloatField() # десятичное с плавающей точкой
u_intbig = models.BigIntegerField() # большое целое
u_int = models.IntegerField() # целое
u_text = models.CharField(max_length=16) # текстовое поле
u_datetime = models.DateTimeField(auto_now=True) # python datetime.datetime analog,
"auto_now=True" will refresh this field value every object save(for example
"u=Myappmodel.objects.get(id=int("u_id int number string") ,u_int=int("number string"))
u.u_int=123; u.save()" )
u_bool = models.BooleanField()
edit "myapp/views.py"
from datetime import datetime,timedelta #time period calculating (if older then 30 days then delete)
from django.http import HttpResponse # just return string data, not use template.html etc
from django.shortcuts import render_to_response # full page return method
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
from myapp models import Myappmodel
def index(request,var1,var2="show"):
x=request.POST.copy() # dict with incoming data in string format
u=Myappmodel.objects.get(u_id=int(x["u_id"]))
u.u_int=int(x["u_int"])
u.save()
# delete all objects older then 30 days
Myappmodel.objects.filter(u_datetime__lte=(datetime.now()-timedelta(days=30))).delete()
# get all data
ux=Myappmodel.objects.all()
# reverse sorting from big to small use u_int model field
ux=ux.order_by("-u_int")
html="Hello, world. You're at the myapp index.\n<br>test data sorting"
for u in ux: html+="\n<br>"+str(u.u_int)
if var2=="hide": return HttpResponse(html) # return without template.html
else:
temp="index.html"
serverdate=str(datetime.now().date())
return render_to_response(temp,{"html":html,"serverdate":serverdate})
where index.html
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
{% load static from staticfiles %}
{% static "style.css" as stylecss %}
{% static "logo.svg" as logo %}
<link rel="stylesheet" href="{{stylecss|default:'0.0'}}" type="text/css">
<title>Example template index.html</title>
</head>
<body>
server date: {{serverdate}}
<br>Sorted testing data order_by
{{ html|safe }}
</body>
</html>
This simple view for myapp.
Use return render_to_response() that use templates and template variables.
Call "render_to_response()" and "HttpResponse()" inside "def index(request,var1,var2="show"):" function body. Calls from other places can create errors.
Create "mysite/myapp/urls.py" file and edit it
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index,{'var1': 'string value of var1','var2':'value'}, name='index'),
]
"{'var1': 'string value of var1','var2':'value'}" extra options дополнительные аргументы.
To connect "myapp/urls.py" to "mysite/urls.py" open and edit "mysite/urls.py"
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^myapp/', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
]
modern django versions can have "url(r'^admin/', admin.site.urls)," syntax for admin url
- prepare and test mysite myapp
Console
python manage.py makemigrations
"Enter"
python manage.py migrate
"Enter", to prepare "db.sqlite3" for using later
python manage.py runserver
then open web browser "http://localhost:8000/myapp/" to test simple view.
- deploy "mysite" project on pythonanywhere.com server
Create pythonanywhere.com account(for example with login name "mysite"), and/or log in. In "web" tab create/add new web app. Name it for example "mysite" as django project name. Choose from variants of default(predetermined) django settings. In 2017 it has python 3.4, django 1.10 versions. And this settings allow run django 1.8 project with sqlite3 etc, created and tested using python3.4.4.
upload(copy folders/files tree) project on server manually or use zipped folder without compressing (good variant in case of big number of file in project). That use zip folder method, compress the mysite project folder to zip folder(for example named "my.zip"), upload "my.zip" on server use "files" tab in web gui, then press on my.zip level "open bash console here", wait, the bash console will opened. Console
unzip my.zip
"Enter", wait while process will be done. Delete "my.zip", that clear your available server space, or keep it, just for case.
If need, for static files, add new paths inside"web" tab using "static files: - Enter URL - Enter path" gui section. For "mysite" example project above "Enter URL" /static/ , "Enter path" /home/mysite/mysite/myapp/static .
Open "mysite/settings.py" for editing on the server and edit it
DEBUG = False
TEMPLATE_DEBUG = False
ALLOWED_HOSTS = ['mysite.pythonanywhere.com'] # where "mysite" is your pythonanywhere.com log in name
Check that template dirs(one of variants) in "mysite/settings.py" will equal server adresses of templates etc.
In "web" tab press "Reload mysite.pythonanywhere.com" , wait and when process is done, can test it. Open use browser "http://mysite.pythonanywhere.com/myapp/" link for example above. If all good then will displayed page same as "python manage.py runserver" then browser "http://localhost:8000/myapp/" testing case.
Done. If something wrong, then read the docs on https://docs.djangoproject.com/en/1.8/ , or create request in pythonanywhere.com support in "help" tab, it wokred, and answers will from real people, not bots. If you want have handmaded error pages (error 404, error 500 etc), then place into server templates dirs files "404.html" , "500.html" etc.
- additional syntax
delete all subfolders include files, except "db.sqlite3" file, from pythonanywhere.com account tab "files" folder. Move into "db.sqlite3" file folder (in example above this "/home/mysite/mysite"). Press "Open Bash console here". Console
ls | grep -v db.sqlite3 | xargs rm -rfv
"Enter"
windows console move to folder and create new project
cd C:\django && django-admin.py startproject mysite
windows console move to folder and run interactive python use cmd for database checking
cd C:\django\mysite && manage.py shell
windows console move to folder and run testing server
cd C:\django\mysite && manage.py runserver
windows console change the disk letter after move into this disk folder (windows idiotism). Or can do this before moving into folder placed on other disk.
cd /D d: