diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..776b2dd --- /dev/null +++ b/.coveragerc @@ -0,0 +1,5 @@ +[run] +include = petycja_norweskie/* +omit = *migrations*, *tests* +plugins = + django_coverage_plugin diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..2f395ac --- /dev/null +++ b/.editorconfig @@ -0,0 +1,33 @@ +# http://editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{py,rst,ini}] +indent_style = space +indent_size = 4 + +[*.py] +line_length=120 +known_first_party=petycja_norweskie +multi_line_output=3 +default_section=THIRDPARTY + +[*.{html,css,scss,json,yml}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[Makefile] +indent_style = tab + +[nginx.conf] +indent_style = space +indent_size = 2 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..176a458 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..16e8b35 --- /dev/null +++ b/.gitignore @@ -0,0 +1,75 @@ +### OSX ### +.DS_Store +.AppleDouble +.LSOverride + +### SublimeText ### +# cache files for sublime text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# workspace files are user-specific +*.sublime-workspace + +# project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using SublimeText +# *.sublime-project + +# sftp configuration file +sftp-config.json + +# Basics +*.py[cod] +__pycache__ + +# Logs +logs +*.log +pip-log.txt +npm-debug.log* + +# Unit test / coverage reports +.coverage +.tox +nosetests.xml +htmlcov + +# Translations +*.mo +*.pot + +# Pycharm +.idea/* + +# Provided default Pycharm Run/Debug Configurations should be tracked by git +# In case of local modifications made by Pycharm, use update-index command +# for each changed file, like this: +# git update-index --assume-unchanged .idea/petycja_norweskie.iml +!.idea/runConfigurations/ +!.idea/petycja_norweskie.iml +!.idea/vcs.xml +!.idea/webResources.xml + + +# Vim + +*~ +*.swp +*.swo + +# npm +node_modules/ + +# Compass +.sass-cache + +# virtual environments +.env + +# User-uploaded media +petycja_norweskie/media/ + + + +staticfiles/ diff --git a/.idea/petycja_norweskie.iml b/.idea/petycja_norweskie.iml new file mode 100644 index 0000000..34d7caa --- /dev/null +++ b/.idea/petycja_norweskie.iml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/Docker__migrate.xml b/.idea/runConfigurations/Docker__migrate.xml new file mode 100644 index 0000000..86a6d65 --- /dev/null +++ b/.idea/runConfigurations/Docker__migrate.xml @@ -0,0 +1,32 @@ + + + + diff --git a/.idea/runConfigurations/Docker__runserver.xml b/.idea/runConfigurations/Docker__runserver.xml new file mode 100644 index 0000000..05ac4eb --- /dev/null +++ b/.idea/runConfigurations/Docker__runserver.xml @@ -0,0 +1,33 @@ + + + + diff --git a/.idea/runConfigurations/Docker__runserver_plus.xml b/.idea/runConfigurations/Docker__runserver_plus.xml new file mode 100644 index 0000000..6b173a9 --- /dev/null +++ b/.idea/runConfigurations/Docker__runserver_plus.xml @@ -0,0 +1,33 @@ + + + + diff --git a/.idea/runConfigurations/Docker__tests___all.xml b/.idea/runConfigurations/Docker__tests___all.xml new file mode 100644 index 0000000..2c9af34 --- /dev/null +++ b/.idea/runConfigurations/Docker__tests___all.xml @@ -0,0 +1,30 @@ + + + + diff --git a/.idea/runConfigurations/Docker__tests___class__TestUser.xml b/.idea/runConfigurations/Docker__tests___class__TestUser.xml new file mode 100644 index 0000000..a3a662b --- /dev/null +++ b/.idea/runConfigurations/Docker__tests___class__TestUser.xml @@ -0,0 +1,30 @@ + + + + diff --git a/.idea/runConfigurations/Docker__tests___file__test_models.xml b/.idea/runConfigurations/Docker__tests___file__test_models.xml new file mode 100644 index 0000000..526e925 --- /dev/null +++ b/.idea/runConfigurations/Docker__tests___file__test_models.xml @@ -0,0 +1,30 @@ + + + + diff --git a/.idea/runConfigurations/Docker__tests___module__users.xml b/.idea/runConfigurations/Docker__tests___module__users.xml new file mode 100644 index 0000000..f857595 --- /dev/null +++ b/.idea/runConfigurations/Docker__tests___module__users.xml @@ -0,0 +1,30 @@ + + + + diff --git a/.idea/runConfigurations/Docker__tests___specific__test_get_absolute_url.xml b/.idea/runConfigurations/Docker__tests___specific__test_get_absolute_url.xml new file mode 100644 index 0000000..3486bb6 --- /dev/null +++ b/.idea/runConfigurations/Docker__tests___specific__test_get_absolute_url.xml @@ -0,0 +1,30 @@ + + + + diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/webResources.xml b/.idea/webResources.xml new file mode 100644 index 0000000..5e27f36 --- /dev/null +++ b/.idea/webResources.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..feecc1b --- /dev/null +++ b/.pylintrc @@ -0,0 +1,14 @@ +[MASTER] +load-plugins=pylint_common, pylint_django + +[FORMAT] +max-line-length=120 + +[MESSAGES CONTROL] +disable=missing-docstring,invalid-name + +[DESIGN] +max-parents=13 + +[TYPECHECK] +generated-members=REQUEST,acl_users,aq_parent,"[a-zA-Z]+_set{1,2}",save,delete diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..493667b --- /dev/null +++ b/.travis.yml @@ -0,0 +1,12 @@ +sudo: true +before_install: + - sudo apt-get update -qq + - sudo apt-get install -qq build-essential gettext python-dev zlib1g-dev libpq-dev xvfb + - sudo apt-get install -qq libtiff4-dev libjpeg8-dev libfreetype6-dev liblcms1-dev libwebp-dev + - sudo apt-get install -qq graphviz-dev python-setuptools python3-dev python-virtualenv python-pip + - sudo apt-get install -qq firefox automake libtool libreadline6 libreadline6-dev libreadline-dev + - sudo apt-get install -qq libsqlite3-dev libxml2 libxml2-dev libssl-dev libbz2-dev wget curl llvm +language: python +python: +- "3.5" + diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt new file mode 100644 index 0000000..7a4e883 --- /dev/null +++ b/CONTRIBUTORS.txt @@ -0,0 +1 @@ +Adam Dobrawy diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..24feb5b --- /dev/null +++ b/LICENSE @@ -0,0 +1,10 @@ + +The MIT License (MIT) +Copyright (c) 2017, Adam Dobrawy + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..d6d1e01 --- /dev/null +++ b/README.rst @@ -0,0 +1,77 @@ +petycja-norweskie +================= + +Strona ankcji w sprawie Fundusz Norweskich sfinansowana przez Fundacje Akademia Organizacji Pozarządowych + +.. image:: https://img.shields.io/badge/built%20with-Cookiecutter%20Django-ff69b4.svg + :target: https://github.com/pydanny/cookiecutter-django/ + :alt: Built with Cookiecutter Django + + +:License: MIT + + +Settings +-------- + +Moved to settings_. + +.. _settings: http://cookiecutter-django.readthedocs.io/en/latest/settings.html + +Basic Commands +-------------- + +Setting Up Your Users +^^^^^^^^^^^^^^^^^^^^^ + +* To create a **normal user account**, just go to Sign Up and fill out the form. Once you submit it, you'll see a "Verify Your E-mail Address" page. Go to your console to see a simulated email verification message. Copy the link into your browser. Now the user's email should be verified and ready to go. + +* To create an **superuser account**, use this command:: + + $ python manage.py createsuperuser + +For convenience, you can keep your normal user logged in on Chrome and your superuser logged in on Firefox (or similar), so that you can see how the site behaves for both kinds of users. + +Test coverage +^^^^^^^^^^^^^ + +To run the tests, check your test coverage, and generate an HTML coverage report:: + + $ coverage run manage.py test + $ coverage html + $ open htmlcov/index.html + +Running tests with py.test +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:: + + $ py.test + +Live reloading and Sass CSS compilation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Moved to `Live reloading and SASS compilation`_. + +.. _`Live reloading and SASS compilation`: http://cookiecutter-django.readthedocs.io/en/latest/live-reloading-and-sass-compilation.html + + + + + +Sentry +^^^^^^ + +Sentry is an error logging aggregator service. You can sign up for a free account at https://sentry.io/signup/?code=cookiecutter or download and host it yourself. +The system is setup with reasonable defaults, including 404 logging and integration with the WSGI application. + +You must set the DSN url in production. + + +Deployment +---------- + +The following details how to deploy this application. + + + diff --git a/config/__init__.py b/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config/settings/__init__.py b/config/settings/__init__.py new file mode 100644 index 0000000..40a96af --- /dev/null +++ b/config/settings/__init__.py @@ -0,0 +1 @@ +# -*- coding: utf-8 -*- diff --git a/config/settings/base.py b/config/settings/base.py new file mode 100644 index 0000000..e7eb65d --- /dev/null +++ b/config/settings/base.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +""" +Django settings for petycja-norweskie project. + +For more information on this file, see +https://docs.djangoproject.com/en/dev/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/dev/ref/settings/ +""" +from __future__ import absolute_import, unicode_literals + +import environ + +ROOT_DIR = environ.Path(__file__) - 3 # (petycja_norweskie/config/settings/base.py - 3 = petycja_norweskie/) +APPS_DIR = ROOT_DIR.path('petycja_norweskie') + +# Load operating system environment variables and then prepare to use them +env = environ.Env() + +# .env file, should load only in development environment +READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False) + +if READ_DOT_ENV_FILE: + # Operating System Environment variables have precedence over variables defined in the .env file, + # that is to say variables from the .env files will only be used if not defined + # as environment variables. + env_file = str(ROOT_DIR.path('.env')) + print('Loading : {}'.format(env_file)) + env.read_env(env_file) + print('The .env file has been loaded. See base.py for more information') + +# APP CONFIGURATION +# ------------------------------------------------------------------------------ +DJANGO_APPS = [ + # Default Django apps: + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + # Useful template tags: + # 'django.contrib.humanize', + + # Admin + 'django.contrib.admin', +] +THIRD_PARTY_APPS = [ + 'crispy_forms', # Form layouts + 'allauth', # registration + 'allauth.account', # registration + 'allauth.socialaccount', # registration +] + +# Apps specific for this project go here. +LOCAL_APPS = [ + # custom users app + 'petycja_norweskie.users.apps.UsersConfig', + # Your stuff: custom apps go here +] + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps +INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS + +# MIDDLEWARE CONFIGURATION +# ------------------------------------------------------------------------------ +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', +] + +# MIGRATIONS CONFIGURATION +# ------------------------------------------------------------------------------ +MIGRATION_MODULES = { + 'sites': 'petycja_norweskie.contrib.sites.migrations' +} + +# DEBUG +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug +DEBUG = env.bool('DJANGO_DEBUG', False) + +# FIXTURE CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS +FIXTURE_DIRS = ( + str(APPS_DIR.path('fixtures')), +) + +# EMAIL CONFIGURATION +# ------------------------------------------------------------------------------ +EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend') + +# MANAGER CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins +ADMINS = [ + ("""Adam Dobrawy""", 'naczelnik@jawnosc.tk'), +] + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers +MANAGERS = ADMINS + +# DATABASE CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases +DATABASES = { + 'default': env.db('DATABASE_URL', default='postgres:///petycja_norweskie'), +} +DATABASES['default']['ATOMIC_REQUESTS'] = True + + +# GENERAL CONFIGURATION +# ------------------------------------------------------------------------------ +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# In a Windows environment this must be set to your system time zone. +TIME_ZONE = 'UTC' + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code +LANGUAGE_CODE = 'en-us' + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id +SITE_ID = 1 + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n +USE_I18N = True + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n +USE_L10N = True + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz +USE_TZ = True + +# TEMPLATE CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#templates +TEMPLATES = [ + { + # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs + 'DIRS': [ + str(APPS_DIR.path('templates')), + ], + 'OPTIONS': { + # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug + 'debug': DEBUG, + # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders + # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types + 'loaders': [ + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', + ], + # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.template.context_processors.i18n', + 'django.template.context_processors.media', + 'django.template.context_processors.static', + 'django.template.context_processors.tz', + 'django.contrib.messages.context_processors.messages', + # Your stuff: custom template context processors go here + ], + }, + }, +] + +# See: http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs +CRISPY_TEMPLATE_PACK = 'bootstrap4' + +# STATIC FILE CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root +STATIC_ROOT = str(ROOT_DIR('staticfiles')) + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url +STATIC_URL = '/static/' + +# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS +STATICFILES_DIRS = [ + str(APPS_DIR.path('static')), +] + +# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders +STATICFILES_FINDERS = [ + 'django.contrib.staticfiles.finders.FileSystemFinder', + 'django.contrib.staticfiles.finders.AppDirectoriesFinder', +] + +# MEDIA CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root +MEDIA_ROOT = str(APPS_DIR('media')) + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url +MEDIA_URL = '/media/' + +# URL Configuration +# ------------------------------------------------------------------------------ +ROOT_URLCONF = 'config.urls' + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application +WSGI_APPLICATION = 'config.wsgi.application' + +# PASSWORD STORAGE SETTINGS +# ------------------------------------------------------------------------------ +# See https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django +PASSWORD_HASHERS = [ + 'django.contrib.auth.hashers.Argon2PasswordHasher', + 'django.contrib.auth.hashers.PBKDF2PasswordHasher', + 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', + 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', + 'django.contrib.auth.hashers.BCryptPasswordHasher', +] + +# PASSWORD VALIDATION +# https://docs.djangoproject.com/en/dev/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', + }, +] + +# AUTHENTICATION CONFIGURATION +# ------------------------------------------------------------------------------ +AUTHENTICATION_BACKENDS = [ + 'django.contrib.auth.backends.ModelBackend', + 'allauth.account.auth_backends.AuthenticationBackend', +] + +# Some really nice defaults +ACCOUNT_AUTHENTICATION_METHOD = 'username' +ACCOUNT_EMAIL_REQUIRED = True +ACCOUNT_EMAIL_VERIFICATION = 'mandatory' + +ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True) +ACCOUNT_ADAPTER = 'petycja_norweskie.users.adapters.AccountAdapter' +SOCIALACCOUNT_ADAPTER = 'petycja_norweskie.users.adapters.SocialAccountAdapter' + +# Custom user app defaults +# Select the correct user model +AUTH_USER_MODEL = 'users.User' +LOGIN_REDIRECT_URL = 'users:redirect' +LOGIN_URL = 'account_login' + +# SLUGLIFIER +AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify' + + +# Location of root django.contrib.admin URL, use {% url 'admin:index' %} +ADMIN_URL = r'^admin/' + +# Your common stuff: Below this line define 3rd party library settings +# ------------------------------------------------------------------------------ diff --git a/config/settings/local.py b/config/settings/local.py new file mode 100644 index 0000000..7254e68 --- /dev/null +++ b/config/settings/local.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +""" +Local settings + +- Run in Debug mode + +- Use console backend for emails + +- Add Django Debug Toolbar +- Add django-extensions as app +""" + +import socket +import os +from .base import * # noqa + +# DEBUG +# ------------------------------------------------------------------------------ +DEBUG = env.bool('DJANGO_DEBUG', default=True) +TEMPLATES[0]['OPTIONS']['debug'] = DEBUG + +# SECRET CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +# Note: This key only used for development and testing. +SECRET_KEY = env('DJANGO_SECRET_KEY', default='26*g<@E(h+#th/abORs~rAS]fQ^79)eA}lp?O#_*z^~/ox,Z@s') + +# Mail settings +# ------------------------------------------------------------------------------ + +EMAIL_PORT = 1025 + +EMAIL_HOST = 'localhost' +EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', + default='django.core.mail.backends.console.EmailBackend') + + +# CACHING +# ------------------------------------------------------------------------------ +CACHES = { + 'default': { + 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', + 'LOCATION': '' + } +} + +# django-debug-toolbar +# ------------------------------------------------------------------------------ +MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ] +INSTALLED_APPS += ['debug_toolbar', ] + +INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ] +# tricks to have debug toolbar when developing with docker +if os.environ.get('USE_DOCKER') == 'yes': + ip = socket.gethostbyname(socket.gethostname()) + INTERNAL_IPS += [ip[:-1] + '1'] + +DEBUG_TOOLBAR_CONFIG = { + 'DISABLE_PANELS': [ + 'debug_toolbar.panels.redirects.RedirectsPanel', + ], + 'SHOW_TEMPLATE_CONTEXT': True, +} + +# django-extensions +# ------------------------------------------------------------------------------ +INSTALLED_APPS += ['django_extensions', ] + +# TESTING +# ------------------------------------------------------------------------------ +TEST_RUNNER = 'django.test.runner.DiscoverRunner' + +# Your local stuff: Below this line define 3rd party library settings +# ------------------------------------------------------------------------------ diff --git a/config/settings/production.py b/config/settings/production.py new file mode 100644 index 0000000..deffe5c --- /dev/null +++ b/config/settings/production.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +""" +Production Configurations + +- Use Amazon's S3 for storing static files and uploaded media +- Use mailgun to send emails +- Use Redis for cache + +- Use sentry for error logging + + +""" +from __future__ import absolute_import, unicode_literals + +from boto.s3.connection import OrdinaryCallingFormat +from django.utils import six + +import logging + + +from .base import * # noqa + +# SECRET CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ +SECRET_KEY = env('DJANGO_SECRET_KEY') + + +# This ensures that Django will be able to detect a secure connection +# properly on Heroku. +SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') +# raven sentry client +# See https://docs.sentry.io/clients/python/integrations/django/ +INSTALLED_APPS += ['raven.contrib.django.raven_compat', ] +RAVEN_MIDDLEWARE = ['raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware'] +MIDDLEWARE = RAVEN_MIDDLEWARE + MIDDLEWARE + + +# SECURITY CONFIGURATION +# ------------------------------------------------------------------------------ +# See https://docs.djangoproject.com/en/dev/ref/middleware/#module-django.middleware.security +# and https://docs.djangoproject.com/en/dev/howto/deployment/checklist/#run-manage-py-check-deploy + +# set this to 60 seconds and then to 518400 when you can prove it works +SECURE_HSTS_SECONDS = 60 +SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( + 'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True) +SECURE_CONTENT_TYPE_NOSNIFF = env.bool( + 'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True) +SECURE_BROWSER_XSS_FILTER = True +SESSION_COOKIE_SECURE = True +SESSION_COOKIE_HTTPONLY = True +SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True) +CSRF_COOKIE_SECURE = True +CSRF_COOKIE_HTTPONLY = True +X_FRAME_OPTIONS = 'DENY' + +# SITE CONFIGURATION +# ------------------------------------------------------------------------------ +# Hosts/domain names that are valid for this site +# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts +ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['norweskie.org', ]) +# END SITE CONFIGURATION + +INSTALLED_APPS += ['gunicorn', ] + + +# STORAGE CONFIGURATION +# ------------------------------------------------------------------------------ +# Uploaded Media Files +# ------------------------ +# See: http://django-storages.readthedocs.io/en/latest/index.html +INSTALLED_APPS += ['storages', ] + +AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') +AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') +AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') +AWS_AUTO_CREATE_BUCKET = True +AWS_QUERYSTRING_AUTH = False +AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat() + +# AWS cache settings, don't change unless you know what you're doing: +AWS_EXPIRY = 60 * 60 * 24 * 7 + +# TODO See: https://github.com/jschneier/django-storages/issues/47 +# Revert the following and use str after the above-mentioned bug is fixed in +# either django-storage-redux or boto +AWS_HEADERS = { + 'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % ( + AWS_EXPIRY, AWS_EXPIRY)) +} + +# URL that handles the media served from MEDIA_ROOT, used for managing +# stored files. + +# See:http://stackoverflow.com/questions/10390244/ +from storages.backends.s3boto import S3BotoStorage +StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static') +MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media') +DEFAULT_FILE_STORAGE = 'config.settings.production.MediaRootS3BotoStorage' + +MEDIA_URL = 'https://s3.amazonaws.com/%s/media/' % AWS_STORAGE_BUCKET_NAME + +# Static Assets +# ------------------------ + +STATIC_URL = 'https://s3.amazonaws.com/%s/static/' % AWS_STORAGE_BUCKET_NAME +STATICFILES_STORAGE = 'config.settings.production.StaticRootS3BotoStorage' +# See: https://github.com/antonagestam/collectfast +# For Django 1.7+, 'collectfast' should come before +# 'django.contrib.staticfiles' +AWS_PRELOAD_METADATA = True +INSTALLED_APPS = ['collectfast', ] + INSTALLED_APPS + +# EMAIL +# ------------------------------------------------------------------------------ +DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL', + default='petycja-norweskie ') +EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[petycja-norweskie]') +SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL) + +# Anymail with Mailgun +INSTALLED_APPS += ['anymail', ] +ANYMAIL = { + 'MAILGUN_API_KEY': env('DJANGO_MAILGUN_API_KEY'), + 'MAILGUN_SENDER_DOMAIN': env('MAILGUN_SENDER_DOMAIN') +} +EMAIL_BACKEND = 'anymail.backends.mailgun.MailgunBackend' + +# TEMPLATE CONFIGURATION +# ------------------------------------------------------------------------------ +# See: +# https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader +TEMPLATES[0]['OPTIONS']['loaders'] = [ + ('django.template.loaders.cached.Loader', [ + 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), +] + +# DATABASE CONFIGURATION +# ------------------------------------------------------------------------------ + +# Use the Heroku-style specification +# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ +DATABASES['default'] = env.db('DATABASE_URL') + +# CACHING +# ------------------------------------------------------------------------------ + +REDIS_LOCATION = '{0}/{1}'.format(env('REDIS_URL', default='redis://127.0.0.1:6379'), 0) +# Heroku URL does not pass the DB number, so we parse it in +CACHES = { + 'default': { + 'BACKEND': 'django_redis.cache.RedisCache', + 'LOCATION': REDIS_LOCATION, + 'OPTIONS': { + 'CLIENT_CLASS': 'django_redis.client.DefaultClient', + 'IGNORE_EXCEPTIONS': True, # mimics memcache behavior. + # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior + } + } +} + + +# Sentry Configuration +SENTRY_DSN = env('DJANGO_SENTRY_DSN') +SENTRY_CLIENT = env('DJANGO_SENTRY_CLIENT', default='raven.contrib.django.raven_compat.DjangoClient') +LOGGING = { + 'version': 1, + 'disable_existing_loggers': True, + 'root': { + 'level': 'WARNING', + 'handlers': ['sentry', ], + }, + 'formatters': { + 'verbose': { + 'format': '%(levelname)s %(asctime)s %(module)s ' + '%(process)d %(thread)d %(message)s' + }, + }, + 'handlers': { + 'sentry': { + 'level': 'ERROR', + 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', + }, + 'console': { + 'level': 'DEBUG', + 'class': 'logging.StreamHandler', + 'formatter': 'verbose' + } + }, + 'loggers': { + 'django.db.backends': { + 'level': 'ERROR', + 'handlers': ['console', ], + 'propagate': False, + }, + 'raven': { + 'level': 'DEBUG', + 'handlers': ['console', ], + 'propagate': False, + }, + 'sentry.errors': { + 'level': 'DEBUG', + 'handlers': ['console', ], + 'propagate': False, + }, + 'django.security.DisallowedHost': { + 'level': 'ERROR', + 'handlers': ['console', 'sentry', ], + 'propagate': False, + }, + }, +} +SENTRY_CELERY_LOGLEVEL = env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO) +RAVEN_CONFIG = { + 'CELERY_LOGLEVEL': env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO), + 'DSN': SENTRY_DSN +} + +# Custom Admin URL, use {% url 'admin:index' %} +ADMIN_URL = env('DJANGO_ADMIN_URL') + +# Your production stuff: Below this line define 3rd party library settings +# ------------------------------------------------------------------------------ diff --git a/config/settings/test.py b/config/settings/test.py new file mode 100644 index 0000000..4f061f7 --- /dev/null +++ b/config/settings/test.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +''' +Test settings + +- Used to run tests fast on the continuous integration server and locally +''' + +from .base import * # noqa + + +# DEBUG +# ------------------------------------------------------------------------------ +# Turn debug off so tests run faster +DEBUG = False +TEMPLATES[0]['OPTIONS']['debug'] = False + +# SECRET CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +# Note: This key only used for development and testing. +SECRET_KEY = env('DJANGO_SECRET_KEY', default='CHANGEME!!!') + +# Mail settings +# ------------------------------------------------------------------------------ +EMAIL_HOST = 'localhost' +EMAIL_PORT = 1025 + +# In-memory email backend stores messages in django.core.mail.outbox +# for unit testing purposes +EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' + +# CACHING +# ------------------------------------------------------------------------------ +# Speed advantages of in-memory caching without having to run Memcached +CACHES = { + 'default': { + 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', + 'LOCATION': '' + } +} + +# TESTING +# ------------------------------------------------------------------------------ +TEST_RUNNER = 'django.test.runner.DiscoverRunner' + + +# PASSWORD HASHING +# ------------------------------------------------------------------------------ +# Use fast password hasher so tests run faster +PASSWORD_HASHERS = [ + 'django.contrib.auth.hashers.MD5PasswordHasher', +] + +# TEMPLATE LOADERS +# ------------------------------------------------------------------------------ +# Keep templates in memory so tests run faster +TEMPLATES[0]['OPTIONS']['loaders'] = [ + ['django.template.loaders.cached.Loader', [ + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', + ], ], +] diff --git a/config/urls.py b/config/urls.py new file mode 100644 index 0000000..62bfd58 --- /dev/null +++ b/config/urls.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.conf import settings +from django.conf.urls import include, url +from django.conf.urls.static import static +from django.contrib import admin +from django.views.generic import TemplateView +from django.views import defaults as default_views + +urlpatterns = [ + url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), + url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'), + + # Django Admin, use {% url 'admin:index' %} + url(settings.ADMIN_URL, admin.site.urls), + + # User management + url(r'^users/', include('petycja_norweskie.users.urls', namespace='users')), + url(r'^accounts/', include('allauth.urls')), + + # Your stuff: custom urls includes go here + + +] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + +if settings.DEBUG: + # This allows the error pages to be debugged during development, just visit + # these url in browser to see how these error pages look like. + urlpatterns += [ + url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}), + url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}), + url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}), + url(r'^500/$', default_views.server_error), + ] + if 'debug_toolbar' in settings.INSTALLED_APPS: + import debug_toolbar + + urlpatterns += [ + url(r'^__debug__/', include(debug_toolbar.urls)), + ] diff --git a/config/wsgi.py b/config/wsgi.py new file mode 100644 index 0000000..4eed0b7 --- /dev/null +++ b/config/wsgi.py @@ -0,0 +1,36 @@ +""" +WSGI config for petycja-norweskie project. + +This module contains the WSGI application used by Django's development server +and any production WSGI deployments. It should expose a module-level variable +named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover +this application via the ``WSGI_APPLICATION`` setting. + +Usually you will have the standard Django WSGI application here, but it also +might make sense to replace the whole Django WSGI application with a custom one +that later delegates to the Django one. For example, you could introduce WSGI +middleware here, or combine a Django application with an application of another +framework. + +""" +import os + +from django.core.wsgi import get_wsgi_application +if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': + from raven.contrib.django.raven_compat.middleware.wsgi import Sentry + +# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks +# if running multiple sites in the same mod_wsgi process. To fix this, use +# mod_wsgi daemon mode with each site in its own daemon process, or use +# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") + +# This application object is used by any WSGI server configured to use this +# file. This includes Django's development server, if the WSGI_APPLICATION +# setting points here. +application = get_wsgi_application() +if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': + application = Sentry(application) +# Apply WSGI middleware here. +# from helloworld.wsgi import HelloWorldApplication +# application = HelloWorldApplication(application) diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..21c9c21 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/petycja_norweskie.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/petycja_norweskie.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/petycja_norweskie" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/petycja_norweskie" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/__init__.py b/docs/__init__.py new file mode 100644 index 0000000..8772c82 --- /dev/null +++ b/docs/__init__.py @@ -0,0 +1 @@ +# Included so that Django's startproject comment runs against the docs directory diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..1e03522 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,247 @@ +# -*- coding: utf-8 -*- +# +# petycja-norweskie documentation build configuration file, created by +# sphinx-quickstart. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +from __future__ import unicode_literals + +import os +import sys + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'petycja-norweskie' +copyright = """2017, Adam Dobrawy""" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.1' +# The full version, including alpha/beta/rc tags. +release = '0.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'petycja_norweskiedoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # 'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', + 'petycja_norweskie.tex', + 'petycja-norweskie Documentation', + """Adam Dobrawy""", 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'petycja_norweskie', 'petycja-norweskie Documentation', + ["""Adam Dobrawy"""], 1) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'petycja_norweskie', 'petycja-norweskie Documentation', + """Adam Dobrawy""", 'petycja-norweskie', + """Strona ankcji w sprawie Fundusz Norweskich sfinansowana przez Fundacje Akademia Organizacji Pozarządowych""", 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' diff --git a/docs/deploy.rst b/docs/deploy.rst new file mode 100644 index 0000000..1e642c7 --- /dev/null +++ b/docs/deploy.rst @@ -0,0 +1,4 @@ +Deploy +======== + +This is where you describe how the project is deployed in production. diff --git a/docs/docker_ec2.rst b/docs/docker_ec2.rst new file mode 100644 index 0000000..1c015b9 --- /dev/null +++ b/docs/docker_ec2.rst @@ -0,0 +1,186 @@ +Developing with Docker +====================== + +You can develop your application in a `Docker`_ container for simpler deployment onto bare Linux machines later. This instruction assumes an `Amazon Web Services`_ EC2 instance, but it should work on any machine with Docker > 1.3 and `Docker compose`_ installed. + +.. _Docker: https://www.docker.com/ +.. _Amazon Web Services: http://aws.amazon.com/ +.. _Docker compose: https://docs.docker.com/compose/ + +Setting up +^^^^^^^^^^ + +Docker encourages running one container for each process. This might mean one container for your web server, one for Django application and a third for your database. Once you're happy composing containers in this way you can easily add more, such as a `Redis`_ cache. + +.. _Redis: http://redis.io/ + +The Docker compose tool (previously known as `fig`_) makes linking these containers easy. An example set up for your Cookiecutter Django project might look like this: + +.. _fig: http://www.fig.sh/ + +:: + + webapp/ # Your cookiecutter project would be in here + Dockerfile + ... + database/ + Dockerfile + ... + webserver/ + Dockerfile + ... + docker-compose.yml + +Each component of your application would get its own `Dockerfile`_. The rest of this example assumes you are using the `base postgres image`_ for your database. Your database settings in `config/base.py` might then look something like: + +.. _Dockerfile: https://docs.docker.com/reference/builder/ +.. _base postgres image: https://registry.hub.docker.com/_/postgres/ + +.. code-block:: python + + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': 'postgres', + 'USER': 'postgres', + 'HOST': 'database', + 'PORT': 5432, + } + } + +The `Docker compose documentation`_ explains in detail what you can accomplish in the `docker-compose.yml` file, but an example configuration might look like this: + +.. _Docker compose documentation: https://docs.docker.com/compose/#compose-documentation + +.. code-block:: yaml + + database: + build: database + webapp: + build: webapp: + command: /usr/bin/python3.4 manage.py runserver 0.0.0.0:8000 # dev setting + # command: gunicorn -b 0.0.0.0:8000 wsgi:application # production setting + volumes: + - webapp/your_project_name:/path/to/container/workdir/ + links: + - database + webserver: + build: webserver + ports: + - "80:80" + - "443:443" + links: + - webapp + +We'll ignore the webserver for now (you'll want to comment that part out while we do). A working Dockerfile to run your cookiecutter application might look like this: + +:: + + FROM ubuntu:14.04 + ENV REFRESHED_AT 2015-01-13 + + # update packages and prepare to build software + RUN ["apt-get", "update"] + RUN ["apt-get", "-y", "install", "build-essential", "vim", "git", "curl"] + RUN ["locale-gen", "en_GB.UTF-8"] + + # install latest python + RUN ["apt-get", "-y", "build-dep", "python3-dev", "python3-imaging"] + RUN ["apt-get", "-y", "install", "python3-dev", "python3-imaging", "python3-pip"] + + # prepare postgreSQL support + RUN ["apt-get", "-y", "build-dep", "python3-psycopg2"] + + # move into our working directory + # ADD must be after chown see http://stackoverflow.com/a/26145444/1281947 + RUN ["groupadd", "python"] + RUN ["useradd", "python", "-s", "/bin/bash", "-m", "-g", "python", "-G", "python"] + ENV HOME /home/python + WORKDIR /home/python + RUN ["chown", "-R", "python:python", "/home/python"] + ADD ./ /home/python + + # manage requirements + ENV REQUIREMENTS_REFRESHED_AT 2015-02-25 + RUN ["pip3", "install", "-r", "requirements.txt"] + + # uncomment the line below to use container as a non-root user + USER python:python + +Running `sudo docker-compose build` will follow the instructions in your `docker-compose.yml` file and build the database container, then your webapp, before mounting your cookiecutter project files as a volume in the webapp container and linking to the database. Our example yaml file runs in development mode but changing it to production mode is as simple as commenting out the line using `runserver` and uncommenting the line using `gunicorn`. + +Both are set to run on port `0.0.0.0:8000`, which is where the Docker daemon will discover it. You can now run `sudo docker-compose up` and browse to `localhost:8000` to see your application running. + +Deployment +^^^^^^^^^^ + +You'll need a webserver container for deployment. An example setup for `Nginx`_ might look like this: + +.. _Nginx: http://wiki.nginx.org/Main + +:: + + FROM ubuntu:14.04 + ENV REFRESHED_AT 2015-02-11 + + # get the nginx package and set it up + RUN ["apt-get", "update"] + RUN ["apt-get", "-y", "install", "nginx"] + + # forward request and error logs to docker log collector + RUN ln -sf /dev/stdout /var/log/nginx/access.log + RUN ln -sf /dev/stderr /var/log/nginx/error.log + VOLUME ["/var/cache/nginx"] + EXPOSE 80 443 + + # load nginx conf + ADD ./site.conf /etc/nginx/sites-available/your_cookiecutter_project + RUN ["ln", "-s", "/etc/nginx/sites-available/your_cookiecutter_project", "/etc/nginx/sites-enabled/your_cookiecutter_project"] + RUN ["rm", "-rf", "/etc/nginx/sites-available/default"] + + #start the server + CMD ["nginx", "-g", "daemon off;"] + +That Dockerfile assumes you have an Nginx conf file named `site.conf` in the same directory as the webserver Dockerfile. A very basic example, which forwards traffic onto the development server or gunicorn for processing, would look like this: + +:: + + # see http://serverfault.com/questions/577370/how-can-i-use-environment-variables-in-nginx-conf#comment730384_577370 + upstream localhost { + server webapp_1:8000; + } + server { + location / { + proxy_pass http://localhost; + } + } + +Running `sudo docker-compose build webserver` will build your server container. Running `sudo docker-compose up` will now expose your application directly on `localhost` (no need to specify the port number). + +Building and running your app on EC2 +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +All you now need to do to run your app in production is: + +* Create an empty EC2 Linux instance (any Linux machine should do). + +* Install your preferred source control solution, Docker and Docker compose on the news instance. + +* Pull in your code from source control. The root directory should be the one with your `docker-compose.yml` file in it. + +* Run `sudo docker-compose build` and `sudo docker-compose up`. + +* Assign an `Elastic IP address`_ to your new machine. + +.. _Elastic IP address: https://aws.amazon.com/articles/1346 + +* Point your domain name to the elastic IP. + +**Be careful with Elastic IPs** because, on the AWS free tier, if you assign one and then stop the machine you will incur charges while the machine is down (presumably because you're preventing them allocating the IP to someone else). + +Security advisory +^^^^^^^^^^^^^^^^^ + +The setup described in this instruction will get you up-and-running but it hasn't been audited for security. If you are running your own setup like this it is always advisable to, at a minimum, examine your application with a tool like `OWASP ZAP`_ to see what security holes you might be leaving open. + +.. _OWASP ZAP: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..f12604b --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,26 @@ +.. petycja-norweskie documentation master file, created by + sphinx-quickstart. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to petycja-norweskie's documentation! +==================================================================== + +Contents: + +.. toctree:: + :maxdepth: 2 + + install + deploy + docker_ec2 + tests + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/install.rst b/docs/install.rst new file mode 100644 index 0000000..1bc0333 --- /dev/null +++ b/docs/install.rst @@ -0,0 +1,4 @@ +Install +========= + +This is where you write how to get a new laptop to run this project. diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..9953c6c --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,190 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\petycja_norweskie.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\petycja_norweskie.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +:end diff --git a/docs/pycharm/configuration.rst b/docs/pycharm/configuration.rst new file mode 100644 index 0000000..bbf94e2 --- /dev/null +++ b/docs/pycharm/configuration.rst @@ -0,0 +1,72 @@ +Docker Remote Debugging +======================= + +To connect to python remote interpreter inside docker, you have to make sure first, that Pycharm is aware of your docker. + +Go to *Settings > Build, Execution, Deployment > Docker*. If you are on linux, you can use docker directly using its socket `unix:///var/run/docker.sock`, if you are on Windows or Mac, make sure that you have docker-machine installed, then you can simply *Import credentials from Docker Machine*. + +.. image:: images/1.png + +Configure Remote Python Interpreter +----------------------------------- + +This repository comes with already prepared "Run/Debug Configurations" for docker. + +.. image:: images/2.png + +But as you can see, at the beggining there is something wrong with them. They have red X on django icon, and they cannot be used, without configuring remote python interpteter. To do that, you have to go to *Settings > Build, Execution, Deployment* first. + + +Next, you have to add new remote python interpreter, based on already tested deployment settings. Go to *Settings > Project > Project Interpreter*. Click on the cog icon, and click *Add Remote*. + +.. image:: images/3.png + +Switch to *Docker Compose* and select `dev.yml` file from directory of your project, next set *Service name* to `django` + +.. image:: images/4.png + +Because Pycharm restarts container every time you use Configuration Run, to not have server restarted during running tests, we defined second service in `dev.yml` file called pycharm. To use it, you have to add interpreter of second service as well. + +.. image:: images/5.png + +The final result should be: + +.. image:: images/6.png + +Having that, click *OK*. Close *Settings* panel, and wait few seconds... + +.. image:: images/7.png + +After few seconds, all *Run/Debug Configurations* should be ready to use. + +.. image:: images/8.png + +**Things you can do with provided configuration**: + +* run and debug python code +.. image:: images/f1.png +* run and debug tests +.. image:: images/f2.png +.. image:: images/f3.png +* run and debug migrations or different django management commands +.. image:: images/f4.png +* and many others.. + +Known issues +------------ + +* Pycharm hangs on "Connecting to Debugger" + +.. image:: images/issue1.png + +This might be fault of your firewall. Take a look on this ticket - https://youtrack.jetbrains.com/issue/PY-18913 + +* Modified files in `.idea` directory + +Most of the files from `.idea/` were added to `.gitignore` with a few exceptions, which were made, to provide "ready to go" configuration. After adding remote interpreter some of these files are altered by PyCharm: + +.. image:: images/issue2.png + +In theory you can remove them from repository, but then, other people will lose a ability to initialize a project from provided configurations as you did. To get rid of this annoying state, you can run command:: + + $ git update-index --assume-unchanged petycja_norweskie.iml diff --git a/docs/pycharm/images/1.png b/docs/pycharm/images/1.png new file mode 100644 index 0000000..06908a1 Binary files /dev/null and b/docs/pycharm/images/1.png differ diff --git a/docs/pycharm/images/2.png b/docs/pycharm/images/2.png new file mode 100644 index 0000000..1fb8cf1 Binary files /dev/null and b/docs/pycharm/images/2.png differ diff --git a/docs/pycharm/images/3.png b/docs/pycharm/images/3.png new file mode 100644 index 0000000..32c9335 Binary files /dev/null and b/docs/pycharm/images/3.png differ diff --git a/docs/pycharm/images/4.png b/docs/pycharm/images/4.png new file mode 100644 index 0000000..cf07f9d Binary files /dev/null and b/docs/pycharm/images/4.png differ diff --git a/docs/pycharm/images/5.png b/docs/pycharm/images/5.png new file mode 100644 index 0000000..39fac95 Binary files /dev/null and b/docs/pycharm/images/5.png differ diff --git a/docs/pycharm/images/6.png b/docs/pycharm/images/6.png new file mode 100644 index 0000000..0cd70d2 Binary files /dev/null and b/docs/pycharm/images/6.png differ diff --git a/docs/pycharm/images/7.png b/docs/pycharm/images/7.png new file mode 100644 index 0000000..4f8807e Binary files /dev/null and b/docs/pycharm/images/7.png differ diff --git a/docs/pycharm/images/8.png b/docs/pycharm/images/8.png new file mode 100644 index 0000000..05946f2 Binary files /dev/null and b/docs/pycharm/images/8.png differ diff --git a/docs/pycharm/images/f1.png b/docs/pycharm/images/f1.png new file mode 100644 index 0000000..2d8c4b6 Binary files /dev/null and b/docs/pycharm/images/f1.png differ diff --git a/docs/pycharm/images/f2.png b/docs/pycharm/images/f2.png new file mode 100644 index 0000000..b123a47 Binary files /dev/null and b/docs/pycharm/images/f2.png differ diff --git a/docs/pycharm/images/f3.png b/docs/pycharm/images/f3.png new file mode 100644 index 0000000..713ab54 Binary files /dev/null and b/docs/pycharm/images/f3.png differ diff --git a/docs/pycharm/images/f4.png b/docs/pycharm/images/f4.png new file mode 100644 index 0000000..11668ec Binary files /dev/null and b/docs/pycharm/images/f4.png differ diff --git a/docs/pycharm/images/issue1.png b/docs/pycharm/images/issue1.png new file mode 100644 index 0000000..1bb68ee Binary files /dev/null and b/docs/pycharm/images/issue1.png differ diff --git a/docs/pycharm/images/issue2.png b/docs/pycharm/images/issue2.png new file mode 100644 index 0000000..174f6fd Binary files /dev/null and b/docs/pycharm/images/issue2.png differ diff --git a/env.example b/env.example new file mode 100644 index 0000000..92b508d --- /dev/null +++ b/env.example @@ -0,0 +1,32 @@ + +# PostgreSQL +POSTGRES_PASSWORD=mysecretpass +POSTGRES_USER=postgresuser + +# General settings +# DJANGO_READ_DOT_ENV_FILE=True +DJANGO_ADMIN_URL= +DJANGO_SETTINGS_MODULE=config.settings.production +DJANGO_SECRET_KEY=a%ng7Vs@W:_2f=Ipb^<$`MA>kU:x-Cj8&xTgForbidden (403) + +

CSRF verification failed. Request aborted.

+{% endblock content %} diff --git a/petycja_norweskie/templates/404.html b/petycja_norweskie/templates/404.html new file mode 100644 index 0000000..98327cd --- /dev/null +++ b/petycja_norweskie/templates/404.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} + +{% block title %}Page not found{% endblock %} + +{% block content %} +

Page not found

+ +

This is not the page you were looking for.

+{% endblock content %} diff --git a/petycja_norweskie/templates/500.html b/petycja_norweskie/templates/500.html new file mode 100644 index 0000000..21df606 --- /dev/null +++ b/petycja_norweskie/templates/500.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% block title %}Server Error{% endblock %} + +{% block content %} +

Ooops!!! 500

+ +

Looks like something went wrong!

+ +

We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing.

+{% endblock content %} + + diff --git a/petycja_norweskie/templates/account/account_inactive.html b/petycja_norweskie/templates/account/account_inactive.html new file mode 100644 index 0000000..17c2157 --- /dev/null +++ b/petycja_norweskie/templates/account/account_inactive.html @@ -0,0 +1,12 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Account Inactive" %}{% endblock %} + +{% block inner %} +

{% trans "Account Inactive" %}

+ +

{% trans "This account is inactive." %}

+{% endblock %} + diff --git a/petycja_norweskie/templates/account/base.html b/petycja_norweskie/templates/account/base.html new file mode 100644 index 0000000..8e1f260 --- /dev/null +++ b/petycja_norweskie/templates/account/base.html @@ -0,0 +1,10 @@ +{% extends "base.html" %} +{% block title %}{% block head_title %}{% endblock head_title %}{% endblock title %} + +{% block content %} +
+
+ {% block inner %}{% endblock %} +
+
+{% endblock %} diff --git a/petycja_norweskie/templates/account/email.html b/petycja_norweskie/templates/account/email.html new file mode 100644 index 0000000..0dc8d14 --- /dev/null +++ b/petycja_norweskie/templates/account/email.html @@ -0,0 +1,80 @@ + +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Account" %}{% endblock %} + +{% block inner %} +

{% trans "E-mail Addresses" %}

+ +{% if user.emailaddress_set.all %} +

{% trans 'The following e-mail addresses are associated with your account:' %}

+ + + +{% else %} +

{% trans 'Warning:'%} {% trans "You currently do not have any e-mail address set up. You should really add an e-mail address so you can receive notifications, reset your password, etc." %}

+ +{% endif %} + + +

{% trans "Add E-mail Address" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+ +{% endblock %} + + +{% block javascript %} +{{ block.super }} + +{% endblock %} + diff --git a/petycja_norweskie/templates/account/email_confirm.html b/petycja_norweskie/templates/account/email_confirm.html new file mode 100644 index 0000000..46c7812 --- /dev/null +++ b/petycja_norweskie/templates/account/email_confirm.html @@ -0,0 +1,32 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} + +{% block head_title %}{% trans "Confirm E-mail Address" %}{% endblock %} + + +{% block inner %} +

{% trans "Confirm E-mail Address" %}

+ +{% if confirmation %} + +{% user_display confirmation.email_address.user as user_display %} + +

{% blocktrans with confirmation.email_address.email as email %}Please confirm that {{ email }} is an e-mail address for user {{ user_display }}.{% endblocktrans %}

+ +
+{% csrf_token %} + +
+ +{% else %} + +{% url 'account_email' as email_url %} + +

{% blocktrans %}This e-mail confirmation link expired or is invalid. Please issue a new e-mail confirmation request.{% endblocktrans %}

+ +{% endif %} + +{% endblock %} + diff --git a/petycja_norweskie/templates/account/login.html b/petycja_norweskie/templates/account/login.html new file mode 100644 index 0000000..2cadea6 --- /dev/null +++ b/petycja_norweskie/templates/account/login.html @@ -0,0 +1,48 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account socialaccount %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Sign In" %}{% endblock %} + +{% block inner %} + +

{% trans "Sign In" %}

+ +{% get_providers as socialaccount_providers %} + +{% if socialaccount_providers %} +

{% blocktrans with site.name as site_name %}Please sign in with one +of your existing third party accounts. Or, sign up +for a {{ site_name }} account and sign in below:{% endblocktrans %}

+ +
+ +
    + {% include "socialaccount/snippets/provider_list.html" with process="login" %} +
+ + + +
+ +{% include "socialaccount/snippets/login_extra.html" %} + +{% else %} +

{% blocktrans %}If you have not created an account yet, then please +sign up first.{% endblocktrans %}

+{% endif %} + + + +{% endblock %} + diff --git a/petycja_norweskie/templates/account/logout.html b/petycja_norweskie/templates/account/logout.html new file mode 100644 index 0000000..8e2e675 --- /dev/null +++ b/petycja_norweskie/templates/account/logout.html @@ -0,0 +1,22 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Sign Out" %}{% endblock %} + +{% block inner %} +

{% trans "Sign Out" %}

+ +

{% trans 'Are you sure you want to sign out?' %}

+ +
+ {% csrf_token %} + {% if redirect_field_value %} + + {% endif %} + +
+ + +{% endblock %} + diff --git a/petycja_norweskie/templates/account/password_change.html b/petycja_norweskie/templates/account/password_change.html new file mode 100644 index 0000000..b72ca06 --- /dev/null +++ b/petycja_norweskie/templates/account/password_change.html @@ -0,0 +1,17 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Change Password" %}{% endblock %} + +{% block inner %} +

{% trans "Change Password" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+{% endblock %} + diff --git a/petycja_norweskie/templates/account/password_reset.html b/petycja_norweskie/templates/account/password_reset.html new file mode 100644 index 0000000..845bbda --- /dev/null +++ b/petycja_norweskie/templates/account/password_reset.html @@ -0,0 +1,26 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Password Reset" %}{% endblock %} + +{% block inner %} + +

{% trans "Password Reset" %}

+ {% if user.is_authenticated %} + {% include "account/snippets/already_logged_in.html" %} + {% endif %} + +

{% trans "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+ +

{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}

+{% endblock %} + diff --git a/petycja_norweskie/templates/account/password_reset_done.html b/petycja_norweskie/templates/account/password_reset_done.html new file mode 100644 index 0000000..c59534a --- /dev/null +++ b/petycja_norweskie/templates/account/password_reset_done.html @@ -0,0 +1,17 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} + +{% block head_title %}{% trans "Password Reset" %}{% endblock %} + +{% block inner %} +

{% trans "Password Reset" %}

+ + {% if user.is_authenticated %} + {% include "account/snippets/already_logged_in.html" %} + {% endif %} + +

{% blocktrans %}We have sent you an e-mail. Please contact us if you do not receive it within a few minutes.{% endblocktrans %}

+{% endblock %} + diff --git a/petycja_norweskie/templates/account/password_reset_from_key.html b/petycja_norweskie/templates/account/password_reset_from_key.html new file mode 100644 index 0000000..0bd60d6 --- /dev/null +++ b/petycja_norweskie/templates/account/password_reset_from_key.html @@ -0,0 +1,25 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} +{% block head_title %}{% trans "Change Password" %}{% endblock %} + +{% block inner %} +

{% if token_fail %}{% trans "Bad Token" %}{% else %}{% trans "Change Password" %}{% endif %}

+ + {% if token_fail %} + {% url 'account_reset_password' as passwd_reset_url %} +

{% blocktrans %}The password reset link was invalid, possibly because it has already been used. Please request a new password reset.{% endblocktrans %}

+ {% else %} + {% if form %} +
+ {% csrf_token %} + {{ form|crispy }} + +
+ {% else %} +

{% trans 'Your password is now changed.' %}

+ {% endif %} + {% endif %} +{% endblock %} + diff --git a/petycja_norweskie/templates/account/password_reset_from_key_done.html b/petycja_norweskie/templates/account/password_reset_from_key_done.html new file mode 100644 index 0000000..89be086 --- /dev/null +++ b/petycja_norweskie/templates/account/password_reset_from_key_done.html @@ -0,0 +1,10 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% block head_title %}{% trans "Change Password" %}{% endblock %} + +{% block inner %} +

{% trans "Change Password" %}

+

{% trans 'Your password is now changed.' %}

+{% endblock %} + diff --git a/petycja_norweskie/templates/account/password_set.html b/petycja_norweskie/templates/account/password_set.html new file mode 100644 index 0000000..7786e9e --- /dev/null +++ b/petycja_norweskie/templates/account/password_set.html @@ -0,0 +1,17 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Set Password" %}{% endblock %} + +{% block inner %} +

{% trans "Set Password" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+{% endblock %} + diff --git a/petycja_norweskie/templates/account/signup.html b/petycja_norweskie/templates/account/signup.html new file mode 100644 index 0000000..6a2954e --- /dev/null +++ b/petycja_norweskie/templates/account/signup.html @@ -0,0 +1,23 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Signup" %}{% endblock %} + +{% block inner %} +

{% trans "Sign Up" %}

+ +

{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}

+ + + +{% endblock %} + diff --git a/petycja_norweskie/templates/account/signup_closed.html b/petycja_norweskie/templates/account/signup_closed.html new file mode 100644 index 0000000..2322f17 --- /dev/null +++ b/petycja_norweskie/templates/account/signup_closed.html @@ -0,0 +1,12 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Sign Up Closed" %}{% endblock %} + +{% block inner %} +

{% trans "Sign Up Closed" %}

+ +

{% trans "We are sorry, but the sign up is currently closed." %}

+{% endblock %} + diff --git a/petycja_norweskie/templates/account/verification_sent.html b/petycja_norweskie/templates/account/verification_sent.html new file mode 100644 index 0000000..ad093fd --- /dev/null +++ b/petycja_norweskie/templates/account/verification_sent.html @@ -0,0 +1,13 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Verify Your E-mail Address" %}{% endblock %} + +{% block inner %} +

{% trans "Verify Your E-mail Address" %}

+ +

{% blocktrans %}We have sent an e-mail to you for verification. Follow the link provided to finalize the signup process. Please contact us if you do not receive it within a few minutes.{% endblocktrans %}

+ +{% endblock %} + diff --git a/petycja_norweskie/templates/account/verified_email_required.html b/petycja_norweskie/templates/account/verified_email_required.html new file mode 100644 index 0000000..09d4fde --- /dev/null +++ b/petycja_norweskie/templates/account/verified_email_required.html @@ -0,0 +1,24 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Verify Your E-mail Address" %}{% endblock %} + +{% block inner %} +

{% trans "Verify Your E-mail Address" %}

+ +{% url 'account_email' as email_url %} + +

{% blocktrans %}This part of the site requires us to verify that +you are who you claim to be. For this purpose, we require that you +verify ownership of your e-mail address. {% endblocktrans %}

+ +

{% blocktrans %}We have sent an e-mail to you for +verification. Please click on the link inside this e-mail. Please +contact us if you do not receive it within a few minutes.{% endblocktrans %}

+ +

{% blocktrans %}Note: you can still change your e-mail address.{% endblocktrans %}

+ + +{% endblock %} + diff --git a/petycja_norweskie/templates/base.html b/petycja_norweskie/templates/base.html new file mode 100644 index 0000000..f605e0e --- /dev/null +++ b/petycja_norweskie/templates/base.html @@ -0,0 +1,107 @@ +{% load staticfiles i18n %} + + + + + {% block title %}petycja-norweskie{% endblock title %} + + + + + + + + {% block css %} + + + + + + + + + {% endblock %} + + + + + +
+ +
+ +
+ + {% if messages %} + {% for message in messages %} +
{{ message }}
+ {% endfor %} + {% endif %} + + {% block content %} +

Use this document as a way to quick start any new project.

+ {% endblock content %} + +
+ + {% block modal %}{% endblock modal %} + + + + {% block javascript %} + + + + + + + + + + + + + {% endblock javascript %} + + + diff --git a/petycja_norweskie/templates/bootstrap4/field.html b/petycja_norweskie/templates/bootstrap4/field.html new file mode 100644 index 0000000..d08f5c6 --- /dev/null +++ b/petycja_norweskie/templates/bootstrap4/field.html @@ -0,0 +1,49 @@ + +{% load crispy_forms_field %} + +{% if field.is_hidden %} + {{ field }} +{% else %} + {% if field|is_checkbox %} +
+ {% if label_class %} +
+ {% endif %} + {% endif %} + <{% if tag %}{{ tag }}{% else %}div{% endif %} id="div_{{ field.auto_id }}" {% if not field|is_checkbox %}class="form-group{% if using_grid_layout %} row{% endif %}{% else %}class="checkbox{% endif %}{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if form_show_errors%}{% if field.errors %} has-danger{% endif %}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}"> + {% if field.label and not field|is_checkbox and form_show_labels %} + + {% endif %} + + {% if field|is_checkboxselectmultiple %} + {% include 'bootstrap4/layout/checkboxselectmultiple.html' %} + {% endif %} + + {% if field|is_radioselect %} + {% include 'bootstrap4/layout/radioselect.html' %} + {% endif %} + + {% if not field|is_checkboxselectmultiple and not field|is_radioselect %} + {% if field|is_checkbox and form_show_labels %} + + {% else %} +
+ {% crispy_field field %} +
+ {% include 'bootstrap4/layout/help_text_and_errors.html' %} + {% endif %} + {% endif %} + + {% if field|is_checkbox %} + {% if label_class %} +
+ {% endif %} +
+ {% endif %} +{% endif %} diff --git a/petycja_norweskie/templates/bootstrap4/layout/field_errors_block.html b/petycja_norweskie/templates/bootstrap4/layout/field_errors_block.html new file mode 100644 index 0000000..e06e5f2 --- /dev/null +++ b/petycja_norweskie/templates/bootstrap4/layout/field_errors_block.html @@ -0,0 +1,7 @@ + +{% if form_show_errors and field.errors %} + {% for error in field.errors %} +

{{ error }}

+ {% endfor %} +{% endif %} + diff --git a/petycja_norweskie/templates/pages/about.html b/petycja_norweskie/templates/pages/about.html new file mode 100644 index 0000000..63913c1 --- /dev/null +++ b/petycja_norweskie/templates/pages/about.html @@ -0,0 +1 @@ +{% extends "base.html" %} \ No newline at end of file diff --git a/petycja_norweskie/templates/pages/home.html b/petycja_norweskie/templates/pages/home.html new file mode 100644 index 0000000..63913c1 --- /dev/null +++ b/petycja_norweskie/templates/pages/home.html @@ -0,0 +1 @@ +{% extends "base.html" %} \ No newline at end of file diff --git a/petycja_norweskie/templates/users/user_detail.html b/petycja_norweskie/templates/users/user_detail.html new file mode 100644 index 0000000..e86eda1 --- /dev/null +++ b/petycja_norweskie/templates/users/user_detail.html @@ -0,0 +1,36 @@ +{% extends "base.html" %} +{% load static %} + +{% block title %}User: {{ object.username }}{% endblock %} + +{% block content %} +
+ +
+
+ +

{{ object.username }}

+ {% if object.name %} +

{{ object.name }}

+ {% endif %} +
+
+ +{% if object == request.user %} + +
+ +
+ My Info + E-Mail + +
+ +
+ +{% endif %} + + +
+{% endblock content %} + diff --git a/petycja_norweskie/templates/users/user_form.html b/petycja_norweskie/templates/users/user_form.html new file mode 100644 index 0000000..a054047 --- /dev/null +++ b/petycja_norweskie/templates/users/user_form.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} +{% load crispy_forms_tags %} + +{% block title %}{{ user.username }}{% endblock %} + +{% block content %} +

{{ user.username }}

+
+ {% csrf_token %} + {{ form|crispy }} +
+
+ +
+
+
+{% endblock %} diff --git a/petycja_norweskie/templates/users/user_list.html b/petycja_norweskie/templates/users/user_list.html new file mode 100644 index 0000000..47d3f85 --- /dev/null +++ b/petycja_norweskie/templates/users/user_list.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} +{% load static i18n %} +{% block title %}Members{% endblock %} + +{% block content %} +
+

Users

+ +
+ {% for user in user_list %} + +

{{ user.username }}

+
+ {% endfor %} +
+
+{% endblock content %} diff --git a/petycja_norweskie/users/__init__.py b/petycja_norweskie/users/__init__.py new file mode 100644 index 0000000..40a96af --- /dev/null +++ b/petycja_norweskie/users/__init__.py @@ -0,0 +1 @@ +# -*- coding: utf-8 -*- diff --git a/petycja_norweskie/users/adapters.py b/petycja_norweskie/users/adapters.py new file mode 100644 index 0000000..ce8a159 --- /dev/null +++ b/petycja_norweskie/users/adapters.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- +from django.conf import settings +from allauth.account.adapter import DefaultAccountAdapter +from allauth.socialaccount.adapter import DefaultSocialAccountAdapter + + +class AccountAdapter(DefaultAccountAdapter): + def is_open_for_signup(self, request): + return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True) + + +class SocialAccountAdapter(DefaultSocialAccountAdapter): + def is_open_for_signup(self, request, sociallogin): + return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True) diff --git a/petycja_norweskie/users/admin.py b/petycja_norweskie/users/admin.py new file mode 100644 index 0000000..ce6d8e1 --- /dev/null +++ b/petycja_norweskie/users/admin.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, unicode_literals + +from django import forms +from django.contrib import admin +from django.contrib.auth.admin import UserAdmin as AuthUserAdmin +from django.contrib.auth.forms import UserChangeForm, UserCreationForm +from .models import User + + +class MyUserChangeForm(UserChangeForm): + class Meta(UserChangeForm.Meta): + model = User + + +class MyUserCreationForm(UserCreationForm): + + error_message = UserCreationForm.error_messages.update({ + 'duplicate_username': 'This username has already been taken.' + }) + + class Meta(UserCreationForm.Meta): + model = User + + def clean_username(self): + username = self.cleaned_data["username"] + try: + User.objects.get(username=username) + except User.DoesNotExist: + return username + raise forms.ValidationError(self.error_messages['duplicate_username']) + + +@admin.register(User) +class MyUserAdmin(AuthUserAdmin): + form = MyUserChangeForm + add_form = MyUserCreationForm + fieldsets = ( + ('User Profile', {'fields': ('name',)}), + ) + AuthUserAdmin.fieldsets + list_display = ('username', 'name', 'is_superuser') + search_fields = ['name'] diff --git a/petycja_norweskie/users/apps.py b/petycja_norweskie/users/apps.py new file mode 100644 index 0000000..870642f --- /dev/null +++ b/petycja_norweskie/users/apps.py @@ -0,0 +1,13 @@ +from django.apps import AppConfig + + +class UsersConfig(AppConfig): + name = 'petycja_norweskie.users' + verbose_name = "Users" + + def ready(self): + """Override this to put in: + Users system checks + Users signal registration + """ + pass diff --git a/petycja_norweskie/users/migrations/0001_initial.py b/petycja_norweskie/users/migrations/0001_initial.py new file mode 100644 index 0000000..e76c333 --- /dev/null +++ b/petycja_norweskie/users/migrations/0001_initial.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.1 on 2016-09-23 04:36 +from __future__ import unicode_literals + +import django.contrib.auth.models +import django.contrib.auth.validators +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0008_alter_user_username_max_length'), + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), + ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), + ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')), + ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), + ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), + ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), + ('name', models.CharField(blank=True, max_length=255, verbose_name='Name of User')), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), + ], + options={ + 'verbose_name_plural': 'users', + 'verbose_name': 'user', + 'abstract': False, + }, + managers=[ + ('objects', django.contrib.auth.models.UserManager()), + ], + ), + ] diff --git a/petycja_norweskie/users/migrations/__init__.py b/petycja_norweskie/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/petycja_norweskie/users/models.py b/petycja_norweskie/users/models.py new file mode 100644 index 0000000..0beebfb --- /dev/null +++ b/petycja_norweskie/users/models.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals, absolute_import + +from django.contrib.auth.models import AbstractUser +from django.core.urlresolvers import reverse +from django.db import models +from django.utils.encoding import python_2_unicode_compatible +from django.utils.translation import ugettext_lazy as _ + + +@python_2_unicode_compatible +class User(AbstractUser): + + # First Name and Last Name do not cover name patterns + # around the globe. + name = models.CharField(_('Name of User'), blank=True, max_length=255) + + def __str__(self): + return self.username + + def get_absolute_url(self): + return reverse('users:detail', kwargs={'username': self.username}) diff --git a/petycja_norweskie/users/tests/__init__.py b/petycja_norweskie/users/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/petycja_norweskie/users/tests/factories.py b/petycja_norweskie/users/tests/factories.py new file mode 100644 index 0000000..e2c967d --- /dev/null +++ b/petycja_norweskie/users/tests/factories.py @@ -0,0 +1,11 @@ +import factory + + +class UserFactory(factory.django.DjangoModelFactory): + username = factory.Sequence(lambda n: 'user-{0}'.format(n)) + email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) + password = factory.PostGenerationMethodCall('set_password', 'password') + + class Meta: + model = 'users.User' + django_get_or_create = ('username', ) diff --git a/petycja_norweskie/users/tests/test_admin.py b/petycja_norweskie/users/tests/test_admin.py new file mode 100644 index 0000000..a1ff0b8 --- /dev/null +++ b/petycja_norweskie/users/tests/test_admin.py @@ -0,0 +1,40 @@ +from test_plus.test import TestCase + +from ..admin import MyUserCreationForm + + +class TestMyUserCreationForm(TestCase): + + def setUp(self): + self.user = self.make_user('notalamode', 'notalamodespassword') + + def test_clean_username_success(self): + # Instantiate the form with a new username + form = MyUserCreationForm({ + 'username': 'alamode', + 'password1': '7jefB#f@Cc7YJB]2v', + 'password2': '7jefB#f@Cc7YJB]2v', + }) + # Run is_valid() to trigger the validation + valid = form.is_valid() + self.assertTrue(valid) + + # Run the actual clean_username method + username = form.clean_username() + self.assertEqual('alamode', username) + + def test_clean_username_false(self): + # Instantiate the form with the same username as self.user + form = MyUserCreationForm({ + 'username': self.user.username, + 'password1': 'notalamodespassword', + 'password2': 'notalamodespassword', + }) + # Run is_valid() to trigger the validation, which is going to fail + # because the username is already taken + valid = form.is_valid() + self.assertFalse(valid) + + # The form.errors dict should contain a single error called 'username' + self.assertTrue(len(form.errors) == 1) + self.assertTrue('username' in form.errors) diff --git a/petycja_norweskie/users/tests/test_models.py b/petycja_norweskie/users/tests/test_models.py new file mode 100644 index 0000000..894ed18 --- /dev/null +++ b/petycja_norweskie/users/tests/test_models.py @@ -0,0 +1,19 @@ +from test_plus.test import TestCase + + +class TestUser(TestCase): + + def setUp(self): + self.user = self.make_user() + + def test__str__(self): + self.assertEqual( + self.user.__str__(), + 'testuser' # This is the default username for self.make_user() + ) + + def test_get_absolute_url(self): + self.assertEqual( + self.user.get_absolute_url(), + '/users/testuser/' + ) diff --git a/petycja_norweskie/users/tests/test_urls.py b/petycja_norweskie/users/tests/test_urls.py new file mode 100644 index 0000000..6e181cc --- /dev/null +++ b/petycja_norweskie/users/tests/test_urls.py @@ -0,0 +1,51 @@ +from django.core.urlresolvers import reverse, resolve + +from test_plus.test import TestCase + + +class TestUserURLs(TestCase): + """Test URL patterns for users app.""" + + def setUp(self): + self.user = self.make_user() + + def test_list_reverse(self): + """users:list should reverse to /users/.""" + self.assertEqual(reverse('users:list'), '/users/') + + def test_list_resolve(self): + """/users/ should resolve to users:list.""" + self.assertEqual(resolve('/users/').view_name, 'users:list') + + def test_redirect_reverse(self): + """users:redirect should reverse to /users/~redirect/.""" + self.assertEqual(reverse('users:redirect'), '/users/~redirect/') + + def test_redirect_resolve(self): + """/users/~redirect/ should resolve to users:redirect.""" + self.assertEqual( + resolve('/users/~redirect/').view_name, + 'users:redirect' + ) + + def test_detail_reverse(self): + """users:detail should reverse to /users/testuser/.""" + self.assertEqual( + reverse('users:detail', kwargs={'username': 'testuser'}), + '/users/testuser/' + ) + + def test_detail_resolve(self): + """/users/testuser/ should resolve to users:detail.""" + self.assertEqual(resolve('/users/testuser/').view_name, 'users:detail') + + def test_update_reverse(self): + """users:update should reverse to /users/~update/.""" + self.assertEqual(reverse('users:update'), '/users/~update/') + + def test_update_resolve(self): + """/users/~update/ should resolve to users:update.""" + self.assertEqual( + resolve('/users/~update/').view_name, + 'users:update' + ) diff --git a/petycja_norweskie/users/tests/test_views.py b/petycja_norweskie/users/tests/test_views.py new file mode 100644 index 0000000..23f30f0 --- /dev/null +++ b/petycja_norweskie/users/tests/test_views.py @@ -0,0 +1,64 @@ +from django.test import RequestFactory + +from test_plus.test import TestCase + +from ..views import ( + UserRedirectView, + UserUpdateView +) + + +class BaseUserTestCase(TestCase): + + def setUp(self): + self.user = self.make_user() + self.factory = RequestFactory() + + +class TestUserRedirectView(BaseUserTestCase): + + def test_get_redirect_url(self): + # Instantiate the view directly. Never do this outside a test! + view = UserRedirectView() + # Generate a fake request + request = self.factory.get('/fake-url') + # Attach the user to the request + request.user = self.user + # Attach the request to the view + view.request = request + # Expect: '/users/testuser/', as that is the default username for + # self.make_user() + self.assertEqual( + view.get_redirect_url(), + '/users/testuser/' + ) + + +class TestUserUpdateView(BaseUserTestCase): + + def setUp(self): + # call BaseUserTestCase.setUp() + super(TestUserUpdateView, self).setUp() + # Instantiate the view directly. Never do this outside a test! + self.view = UserUpdateView() + # Generate a fake request + request = self.factory.get('/fake-url') + # Attach the user to the request + request.user = self.user + # Attach the request to the view + self.view.request = request + + def test_get_success_url(self): + # Expect: '/users/testuser/', as that is the default username for + # self.make_user() + self.assertEqual( + self.view.get_success_url(), + '/users/testuser/' + ) + + def test_get_object(self): + # Expect: self.user, as that is the request's user object + self.assertEqual( + self.view.get_object(), + self.user + ) diff --git a/petycja_norweskie/users/urls.py b/petycja_norweskie/users/urls.py new file mode 100644 index 0000000..6ae4b6f --- /dev/null +++ b/petycja_norweskie/users/urls.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, unicode_literals + +from django.conf.urls import url + +from . import views + +urlpatterns = [ + url( + regex=r'^$', + view=views.UserListView.as_view(), + name='list' + ), + url( + regex=r'^~redirect/$', + view=views.UserRedirectView.as_view(), + name='redirect' + ), + url( + regex=r'^(?P[\w.@+-]+)/$', + view=views.UserDetailView.as_view(), + name='detail' + ), + url( + regex=r'^~update/$', + view=views.UserUpdateView.as_view(), + name='update' + ), +] diff --git a/petycja_norweskie/users/views.py b/petycja_norweskie/users/views.py new file mode 100644 index 0000000..4cfe64a --- /dev/null +++ b/petycja_norweskie/users/views.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, unicode_literals + +from django.core.urlresolvers import reverse +from django.views.generic import DetailView, ListView, RedirectView, UpdateView + +from django.contrib.auth.mixins import LoginRequiredMixin + +from .models import User + + +class UserDetailView(LoginRequiredMixin, DetailView): + model = User + # These next two lines tell the view to index lookups by username + slug_field = 'username' + slug_url_kwarg = 'username' + + +class UserRedirectView(LoginRequiredMixin, RedirectView): + permanent = False + + def get_redirect_url(self): + return reverse('users:detail', + kwargs={'username': self.request.user.username}) + + +class UserUpdateView(LoginRequiredMixin, UpdateView): + + fields = ['name', ] + + # we already imported User in the view code above, remember? + model = User + + # send the user back to their own page after a successful update + def get_success_url(self): + return reverse('users:detail', + kwargs={'username': self.request.user.username}) + + def get_object(self): + # Only get the User record for the user making the request + return User.objects.get(username=self.request.user.username) + + +class UserListView(LoginRequiredMixin, ListView): + model = User + # These next two lines tell the view to index lookups by username + slug_field = 'username' + slug_url_kwarg = 'username' diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..5b4369b --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +DJANGO_SETTINGS_MODULE=config.settings.test diff --git a/requirements/base.txt b/requirements/base.txt new file mode 100644 index 0000000..3eed5cc --- /dev/null +++ b/requirements/base.txt @@ -0,0 +1,50 @@ +# Wheel 0.25+ needed to install certain packages on CPython 3.5+ +# like Pillow and psycopg2 +# See http://bitly.com/wheel-building-fails-CPython-35 +# Verified bug on Python 3.5.1 +wheel==0.29.0 + +# Bleeding edge Django +django==1.10.7 # pyup: >=1.10,<1.11 + +# Configuration +django-environ==0.4.1 + + + +# Forms +django-braces==1.11.0 +django-crispy-forms==1.6.1 + +# Models +django-model-utils==2.6.1 + +# Images +Pillow==4.0.0 + +# Password storage +argon2-cffi==16.3.0 + +# For user registration, either via email or social +# Well-built with regular release cycles! +django-allauth==0.31.0 + + +# Python-PostgreSQL Database Adapter +psycopg2==2.7.1 + +# Unicode slugification +awesome-slugify==1.6.5 + +# Time zones support +pytz==2017.2 + +# Redis support +django-redis==4.7.0 +redis>=2.10.5 + + + + + +# Your custom requirements go here diff --git a/requirements/local.txt b/requirements/local.txt new file mode 100644 index 0000000..6723349 --- /dev/null +++ b/requirements/local.txt @@ -0,0 +1,19 @@ +# Local development dependencies go here +-r base.txt + +coverage==4.3.4 +django-coverage-plugin==1.5.0 + +Sphinx==1.5.3 +django-extensions==1.7.8 +Werkzeug==0.12.1 +django-test-plus==1.0.17 +factory-boy==2.8.1 + +django-debug-toolbar==1.7 + +# improved REPL +ipdb==0.10.2 + +pytest-django==3.1.2 +pytest-sugar==0.8.0 diff --git a/requirements/production.txt b/requirements/production.txt new file mode 100644 index 0000000..5943a88 --- /dev/null +++ b/requirements/production.txt @@ -0,0 +1,26 @@ +# Pro-tip: Try not to put anything here. Avoid dependencies in +# production that aren't in development. +-r base.txt + + + +# WSGI Handler +# ------------------------------------------------ +gevent==1.2.1 +gunicorn==19.7.1 + +# Static and Media Storage +# ------------------------------------------------ +boto==2.46.1 +django-storages-redux==1.3.2 +Collectfast==0.5.2 + +# Email backends for Mailgun, Postmark, SendGrid and more +# ------------------------------------------------------- +django-anymail==0.8 + +# Raven is the Sentry client +# -------------------------- +raven==6.0.0 + + diff --git a/requirements/test.txt b/requirements/test.txt new file mode 100644 index 0000000..76f7840 --- /dev/null +++ b/requirements/test.txt @@ -0,0 +1,13 @@ +# Test dependencies go here. +-r base.txt + + + +coverage==4.3.4 +flake8==3.3.0 # pyup: != 2.6.0 +django-test-plus==1.0.17 +factory-boy==2.8.1 + +# pytest +pytest-django==3.1.2 +pytest-sugar==0.8.0 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..c18b80d --- /dev/null +++ b/setup.cfg @@ -0,0 +1,7 @@ +[flake8] +max-line-length = 120 +exclude = .tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules + +[pep8] +max-line-length = 120 +exclude=.tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules diff --git a/utility/install_os_dependencies.sh b/utility/install_os_dependencies.sh new file mode 100755 index 0000000..ec9372f --- /dev/null +++ b/utility/install_os_dependencies.sh @@ -0,0 +1,96 @@ +#!/bin/bash + +WORK_DIR="$(dirname "$0")" +DISTRO_NAME=$(lsb_release -sc) +OS_REQUIREMENTS_FILENAME="requirements-$DISTRO_NAME.apt" + +cd $WORK_DIR + +# Check if a requirements file exist for the current distribution. +if [ ! -r "$OS_REQUIREMENTS_FILENAME" ]; then + cat <<-EOF >&2 + There is no requirements file for your distribution. + You can see one of the files listed below to help search the equivalent package in your system: + $(find ./ -name "requirements-*.apt" -printf " - %f\n") + EOF + exit 1; +fi + +# Handle call with wrong command +function wrong_command() +{ + echo "${0##*/} - unknown command: '${1}'" >&2 + usage_message +} + +# Print help / script usage +function usage_message() +{ + cat <<-EOF + Usage: $WORK_DIR/${0##*/} + Available commands are: + list Print a list of all packages defined on ${OS_REQUIREMENTS_FILENAME} file + help Print this help + + Commands that require superuser permission: + install Install packages defined on ${OS_REQUIREMENTS_FILENAME} file. Note: This + does not upgrade the packages already installed for new versions, even if + new version is available in the repository. + upgrade Same that install, but upgrade the already installed packages, if new + version is available. + EOF +} + +# Read the requirements.apt file, and remove comments and blank lines +function list_packages(){ + grep -v "#" "${OS_REQUIREMENTS_FILENAME}" | grep -v "^$"; +} + +function install_packages() +{ + list_packages | xargs apt-get --no-upgrade install -y; +} + +function upgrade_packages() +{ + list_packages | xargs apt-get install -y; +} + +function install_or_upgrade() +{ + P=${1} + PARAN=${P:-"install"} + + if [[ $EUID -ne 0 ]]; then + cat <<-EOF >&2 + You must run this script with root privilege + Please do: + sudo $WORK_DIR/${0##*/} $PARAN + EOF + exit 1 + else + + apt-get update + + # Install the basic compilation dependencies and other required libraries of this project + if [ "$PARAN" == "install" ]; then + install_packages; + else + upgrade_packages; + fi + + # cleaning downloaded packages from apt-get cache + apt-get clean + + exit 0 + fi +} + +# Handle command argument +case "$1" in + install) install_or_upgrade;; + upgrade) install_or_upgrade "upgrade";; + list) list_packages;; + help|"") usage_message;; + *) wrong_command "$1";; +esac diff --git a/utility/install_python_dependencies.sh b/utility/install_python_dependencies.sh new file mode 100755 index 0000000..45f4396 --- /dev/null +++ b/utility/install_python_dependencies.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +WORK_DIR="$(dirname "$0")" +PROJECT_DIR="$(dirname "$WORK_DIR")" + +pip --version >/dev/null 2>&1 || { + echo >&2 -e "\npip is required but it's not installed." + echo >&2 -e "You can install it by running the following command:\n" +echo >&2 "wget https://bootstrap.pypa.io/get-pip.py --output-document=get-pip.py; chmod +x get-pip.py; sudo -H python3 get-pip.py" + + echo >&2 -e "\n" + echo >&2 -e "\nFor more information, see pip documentation: https://pip.pypa.io/en/latest/" + exit 1; +} + +virtualenv --version >/dev/null 2>&1 || { + echo >&2 -e "\nvirtualenv is required but it's not installed." + echo >&2 -e "You can install it by running the following command:\n" +echo >&2 "sudo -H pip3 install virtualenv" + + echo >&2 -e "\n" + echo >&2 -e "\nFor more information, see virtualenv documentation: https://virtualenv.pypa.io/en/latest/" + exit 1; +} + +if [ -z "$VIRTUAL_ENV" ]; then + echo >&2 -e "\nYou need activate a virtualenv first" + echo >&2 -e 'If you do not have a virtualenv created, run the following command to create and automatically activate a new virtualenv named "venv" on current folder:\n' +echo >&2 -e "virtualenv venv --python=\`which python3\`" + + echo >&2 -e "\nTo leave/disable the currently active virtualenv, run the following command:\n" + echo >&2 "deactivate" + echo >&2 -e "\nTo activate the virtualenv again, run the following command:\n" + echo >&2 "source venv/bin/activate" + echo >&2 -e "\nFor more information, see virtualenv documentation: https://virtualenv.pypa.io/en/latest/" + echo >&2 -e "\n" + exit 1; +else + + pip install -r $PROJECT_DIR/requirements/local.txt + pip install -r $PROJECT_DIR/requirements/test.txt + +fi + diff --git a/utility/requirements-jessie.apt b/utility/requirements-jessie.apt new file mode 100644 index 0000000..f602262 --- /dev/null +++ b/utility/requirements-jessie.apt @@ -0,0 +1,24 @@ +##basic build dependencies of various Django apps for Debian Jessie 8.x +#build-essential metapackage install: make, gcc, g++, +build-essential +#required to translate +gettext +python3-dev + + +##shared dependencies of: +##Pillow, pylibmc +zlib1g-dev + +##Postgresql and psycopg2 dependencies +libpq-dev + +##Pillow dependencies +libtiff5-dev +libjpeg62-turbo-dev +libfreetype6-dev +liblcms2-dev +libwebp-dev + +##django-extensions +graphviz-dev diff --git a/utility/requirements-trusty.apt b/utility/requirements-trusty.apt new file mode 100644 index 0000000..db3f01f --- /dev/null +++ b/utility/requirements-trusty.apt @@ -0,0 +1,25 @@ +##basic build dependencies of various Django apps for Ubuntu Trusty 14.04 +#build-essential metapackage install: make, gcc, g++, +build-essential +#required to translate +gettext +python3-dev + + +##shared dependencies of: +##Pillow, pylibmc +zlib1g-dev + +##Postgresql and psycopg2 dependencies +libpq-dev + +##Pillow dependencies +libtiff4-dev +libjpeg8-dev +libfreetype6-dev +liblcms1-dev +libwebp-dev + +##django-extensions +graphviz-dev + diff --git a/utility/requirements-xenial.apt b/utility/requirements-xenial.apt new file mode 100644 index 0000000..00c3720 --- /dev/null +++ b/utility/requirements-xenial.apt @@ -0,0 +1,25 @@ +##basic build dependencies of various Django apps for Ubuntu Xenial 16.04 +#build-essential metapackage install: make, gcc, g++, +build-essential +#required to translate +gettext +python3-dev + + +##shared dependencies of: +##Pillow, pylibmc +zlib1g-dev + +##Postgresql and psycopg2 dependencies +libpq-dev + +##Pillow dependencies +libtiff5-dev +libjpeg8-dev +libfreetype6-dev +liblcms2-dev +libwebp-dev + +##django-extensions +graphviz-dev +