Commit 726590fc authored by Andreas Berger's avatar Andreas Berger
Browse files

Initial commit

parents
# Static files
static/uploads/
agreelance/staticfiles/*
!agreelance/staticfiles/.gitkeep
# DB
db.sqlite3
# Mac
.DS_Store
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
# Pycharm
.idea/
# Visual Studio Code
.vscode/
image: python:3
test:
script:
# this configures Django application to use attached postgres database that is run on `postgres` host
- apt-get update -qy
- pip install -r requirements.txt
- python manage.py test
staging:
type: deploy
image: ruby
script:
- apt-get update -qy
- apt-get install -y ruby-dev
- gem install dpl
- dpl --provider=heroku --app=agreelance --api-key=$HEROKU_STAGING_API_KEY
only:
- master
#https://docs.gitlab.com/ee/ci/examples/test-and-deploy-python-application-to-heroku.html
web: python manage.py runserver 0.0.0.0:$PORT
# Agreelance
The best way to agree on the price of your freelancing jobs!
## Code and structure
.gitlab-ci.yml - gitlab ci
Procfile - heroku kjører serveren
- **agreelance/** django project folder containing the project modules
- **core/** contains all the project templates
- **index.html** One of the project templates that uses a template language to insert if, loops and variables into html.
- **home/** user profile - overview over user projects
- **static/** - contains static files like js and images
- **templatetags/** folder containing [template tags](https://docs.djangoproject.com/en/2.1/ref/templates/builtins/). Methods you import into your templates. Can be used in combination with views.
- **admins.py** - file contaning definitions to connect models to the django admin panel
- **urls.py** - contains mapping between urls and views
- **models.py** - contains data models
- **tests/** - contains tests for the module. [View Testing in Django](https://docs.djangoproject.com/en/2.1/topics/testing/) for more.
- **views.py** - Controller in MVC. Methods for rendering and accepting user data
- **forms.py** - defenition of forms. Used to render html forms and verify user input
- **payment/** - module handling payment
- **projects/** - The largest module of the project containing code for creating project and tasks. Upload files, view files, adding roles and user to roles.
- **agreelance/** - The projects main module contaning settings.
- **static/** - common static files
- **user/** - module extending django's user model with a profile contaning more information about the user.
- **manage.py** - entry point for running the project.
- **seed.json** - contains seed data for the project to get it up and running quickly
## Get started
It's reccomended to have a look at: https://www.djangoproject.com/start/
Basic tutorial that walks trough what the different files do.
https://docs.djangoproject.com/en/2.0/intro/tutorial01/
Create a virtualenv https://docs.python-guide.org/dev/virtualenvs/
## Local setup
### Installation with examples for ubuntu. Windows and OSX is mostly the same
Fork the project and clone it to your machine.
#### Setup and activation of virtualenv (env that prevents python packages from being installed globaly on the machine)
Naviagate into the project folder.
`pip install virtualenv`
`virtualenv env`
`source env/bin/activate`
#### Install python requirements
`pip install -r requirements.txt`
**Note: Mac users may get an error related to psycopg2. To fix this try running:**
`pip install psycopg2==2.7.5`
#### Migrate database
`python manage.py migrate`
#### Create superuser
Create a local admin user by entering the following command:
`python manage.py createsuperuser`
Only username and password is required
#### Start the app
`python manage.py runserver`
#### Add initial data
You can add initial data either by going to the url the app is running on locally and adding `/admin` to the url.
Add some categories and you should be all set.
Or by entering
`python manage.py loaddata seed.json`
## Email
Copy `agreelance/local_settings_example.py` to `agreelance/local_settings.py` and replace the email placeholder values with values dscribes in the email section later in the instructions.
To support sending of email you will have to create a gmail account and turn on less secure apps. *Do not use your own email as Google might lock the account*. See https://support.google.com/accounts/answer/6010255?hl=en for instructions for turning on less secure apps.
To get email working on heroku you might have to visit https://accounts.google.com/DisplayUnlockCaptcha and click `continue` as the heroku server is in another location and Google thinks it is a hacking attempt.
## Continuous integration
Continuous integration will build the code pushed to master and push it to your heroku app so you get a live version of your latest code by just pushing your code to GitLab.
1. Create a heroku account and an app.
2. Set the project in the .gitlab-cs.yml file by replacing `<Your-herokuproject-name>` with the name of the Heroku app you created
`- dpl --provider=heroku --app=<Your-herokuproject-name> --api-key=$HEROKU_STAGING_API_KEY`
3. Fork the project at GitLab
4. Set varibles at GitLab
* settings > ci > Environment Variables
* `HEROKU_STAGING_API_KEY` = heroku > Account Settings > API Key
4. Add heroku database
* Resources > Add ons > search for postgres > add first option
5. Set variables at heroku. Settings > Config vars > Reveal vars
* `DATABASE_URL` = Should be set by default. If not here is where you can find it: Resources > postgress > settings > view credentials > URI
* `EMAIL_HOST_PASSWORD` email password. Not mandatory if you do not want to send email
* `EMAIL_HOST_USER` email adress. Not mandatory if you do not want to send email
* `IS_HEROKU` = `IS_HEROKU`
6. On GitLab go to CI / CD in the repository menu and select `Run Pipeline` if it has not already started. When both stages complete the app should be available on heroku. Staging will fail from timeout as Heroku does not give the propper response to end the job. But the log should state that the app was deployed.
7. Setup the applications database.
* Install heroku CLI by following: https://devcenter.heroku.com/articles/heroku-cli
* Log in to the Heroku CLI by entering `heroku login`. This opens a webbrowser and you accept the login request.
* Migrate database by entering
`heroku run python manage.py migrate -a <heroku-app-name>`. `Heroku run` will run the folowing command on your heroku instance. Remember to replace `<heroku-app-name>` with your app name
* and create an admin account by running
`heroku run python manage.py createsuperuser -a <heroku-app-name>`.
* seed database `heroku run python manage.py loaddata seed.json -a <heroku-app-name>`
### Reset Database
`heroku pg:reset DATABASE_URL -a <heroku-app-name>`
## Data seeding
The data seed provided contains 3 users:
Username | Password | Description
---|---|---
admin|qwerty123|Admin user that owns one project
harrypotter|qwerty123|
joe|qwerty123|
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
# Turn on less secure apps to make it work
# https://support.google.com/accounts/answer/6010255?hl=en
EMAIL_HOST_USER = '<mail>@gmail.com'
EMAIL_HOST_PASSWORD = '<password>'
[
{
"model": "myapp.person",
"pk": 1,
"fields": {
"first_name": "John",
"last_name": "Lennon"
}
},
{
"model": "myapp.person",
"pk": 2,
"fields": {
"first_name": "Paul",
"last_name": "McCartney"
}
}
]
"""
Django settings for agreelance project.
Generated by 'django-admin startproject' using Django 2.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
import sys
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$n%^#g%qx#82w6t^dvjqwv)q*1cy+fwh1ohku7-rbjqcei2^jr'
ADMINS = [('APU', 'tdt4242apu@gmail.com')]
ALLOWED_HOSTS = ['127.0.0.1','localhost','0.0.0.0']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'projects.apps.ProjectConfig',
'home.apps.HomeConfig',
'user.apps.UserConfig',
'bootstrap4',
'django_icons',
'payment.apps.PaymentConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'agreelance.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'core'), os.path.join(BASE_DIR, 'templates'), ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'agreelance.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/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',
},
]
# Login redirect
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'agreelance/staticfiles')
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
TEST = 'test' in sys.argv
is_prod = os.environ.get('IS_HEROKU', None)
if not TEST and not is_prod:
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
try:
from agreelance.local_settings import *
except:
print("#########")
print("")
print("")
print("Could not load local email settings. Copy local_settings_example to local_settings.")
print("")
print("")
print("#########")
print("#########")
if is_prod:
DEBUG = False
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', None)
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', None)
django_heroku.settings(locals())
"""agreelance URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('home.urls')),
path('admin/', admin.site.urls),
path('user/', include('user.urls')),
path('projects/', include('projects.urls')),
path('payment/', include('payment.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
"""
WSGI config for agreelance project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "agreelance.settings")
application = get_wsgi_application()
{% extends "base.html" %}
{% load bootstrap4 %}
{% block title %}Error{% endblock %}
{% block content %}
<h2 class="mt-5">Woops this page doesn't exist.</h2>
<p>Go back to safe ground by clicking here: <a href="{% url 'home' %}">Home</a></p>
{% endblock %}
{% extends "admin/base_site.html" %}
{% load static %}
{% block extrahead %}
<link rel="shortcut icon" href="{% static 'favicon/favicon.ico' %}" />
{% endblock %}
<!DOCTYPE html>
<html>
<head>
{% load static %}
<!-- bootstrap -->
{% load bootstrap4 %}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
{% bootstrap_messages %}
<!-- Icons -->
{% load icons %}
<!-- Font Awesome CSS -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
rel="stylesheet"
integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
crossorigin="anonymous"
>
<title>{% block title %}{% endblock title %}</title>
<link rel="shortcut icon" href="{% static 'favicon/favicon.ico' %}"/>
<link rel="stylesheet" href="{% static 'css/main.css' %}"/>
</head>
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand font-weight-bold ml-5 mr-3" href="{% url 'home' %}">Agreelance</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse ml-1" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link font-weight-light" href="{% url 'home' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link font-weight-light" href="{% url 'projects' %}">Projects</a>
</li>
<!--
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
-->
</ul>
<div class="my-2 my-lg-0 mr-5">
{% if user.is_authenticated %}
<a role="button" class="btn btn-outline-primary my-2 my-sm-0" href="{% url 'new_project' %}">New project</a>
<a class="btn btn-link my-2 my-sm-0" href="{% url 'logout' %}" role="button">Sign out</a>
{% else %}
<a role="button" class="btn btn-link my-sm-0 mr-2" href="{% url 'signup' %}">Sign up</a>
<a role="button" class="btn btn-outline-primary my-2 my-sm-0" href="{% url 'login' %}">Sign in</a>
{% endif %}
</div>
</div>
</nav>
<div class="container">
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% block content %}{% endblock content %}
</div>
</body>
</html>
{% extends "base.html" %}
{% load static %}
{% load icons %}
{% load project_extras %}
{% load home_extras %}