First commit. Login/Registration/Logout works without email verification. Counts list view implemented

This commit is contained in:
Claudio Maggioni 2018-08-08 20:07:59 +02:00
commit f06207001d
34 changed files with 664 additions and 0 deletions

87
.gitignore vendored Normal file
View file

@ -0,0 +1,87 @@
### OSX ###
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# 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
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
*.pot
# Sphinx documentation
docs/_build/
# PyBuilder
target/
### Django ###
*.log
*.pot
*.pyc
__pycache__/
local_settings.py
.env
db.sqlite3

0
arrowcounter/__init__.py Normal file
View file

135
arrowcounter/settings.py Normal file
View file

@ -0,0 +1,135 @@
"""
Django settings for arrowcounter project.
Generated by 'django-admin startproject' using Django 2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'x7umjf5-9w*9iqb6p+9dy+7%66p=1xau+6kieblqvft*o=@)p#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
AUTH_USER_MODEL = 'user.CounterUser'
LOGIN_URL = "auth/login/"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"
ITEMS_PER_PAGE = 30
# Application definition
INSTALLED_APPS = [
'counter.apps.CounterConfig',
'user.apps.UserConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions'
]
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 = 'arrowcounter.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'arrowcounter.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'arrowcounter',
'USER': 'arrowcounter',
'PASSWORD': 'password',
'HOST': 'localhost',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Rome'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'

25
arrowcounter/urls.py Normal file
View file

@ -0,0 +1,25 @@
"""arrowcounter URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('counter.urls')),
path('admin/', admin.site.urls),
path('accounts/', include('user.urls')),
path('accounts/', include('django.contrib.auth.urls')),
]

16
arrowcounter/wsgi.py Normal file
View file

@ -0,0 +1,16 @@
"""
WSGI config for arrowcounter 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.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arrowcounter.settings')
application = get_wsgi_application()

0
counter/__init__.py Normal file
View file

4
counter/admin.py Normal file
View file

@ -0,0 +1,4 @@
from django.contrib import admin
from .models import ArrowCount
admin.site.register(ArrowCount)

5
counter/apps.py Normal file
View file

@ -0,0 +1,5 @@
from django.apps import AppConfig
class CounterConfig(AppConfig):
name = 'counter'

View file

@ -0,0 +1,26 @@
# Generated by Django 2.1 on 2018-08-07 20:10
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='ArrowCount',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField(auto_now=True, verbose_name='Training date')),
('count', models.PositiveIntegerField(verbose_name='Arrow count for the day')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]

View file

14
counter/models.py Normal file
View file

@ -0,0 +1,14 @@
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
class ArrowCount(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
date = models.DateField('Training date', auto_now = True)
count = models.PositiveIntegerField('Arrow count for the day')
def __str__(self):
return self.date.strftime("%x") + ": " + str(self.count)

View file

@ -0,0 +1,36 @@
#main-menu {
border-radius: 0;
}
form p, form .card .card-content p {
margin-top: 1em;
}
form span.helptext {
width: 100%;
display: inline-block;
background: #b3e5fc;
}
form span.helptext:empty, form ul:empty {
display: none;
}
form ul li, form span.helptext {
padding-left: .5em;
padding-right: .5em;
}
form ul, form span.helptext {
padding-bottom: .5em;
padding-top: .5em;
border-radius: 2px;
}
form ul {
background: #ffecb3;
}
form ul.errorlist {
background: #ffcdd2;
}

View file

@ -0,0 +1,3 @@
$(document).ready(function() {
$('.sidenav').sidenav();
});

View file

@ -0,0 +1,46 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock %} | Arrow Counter</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<link rel="stylesheet" href="{% static "css/main.css" %}">
{% block style %}{% endblock %}
</head>
<body>
<nav>
<div class="nav-wrapper">
<div class="container">
<a href="#!" class="brand-logo">Arrow Counter</a>
<a href="#" data-target="mobile-menu" class="sidenav-trigger">
<i class="material-icons">menu</i></a>
<ul class="right hide-on-med-and-down">
{% include "menu.html" %}
</ul>
</div>
</div>
</nav>
<ul class="sidenav" id="mobile-menu">
{% include "menu.html" with mobile=1 %}
</ul>
<div class="container">
<main>{% block content %}{% endblock %}</main>
</div>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<script src="{% static "js/main.js" %}"></script>
{% block scripts %}{% endblock %}
</body>
</html>

View file

@ -0,0 +1,27 @@
{% extends "base.html" %}
{% block title %}Counts{% endblock %}
{% block content %}
<h1 class="center">Counts</h1>
<table class="centered">
<thead>
<tr>
<th>Date</th>
<th>Arrow count</th>
</tr>
</thead>
<tbody>
{% for c in counts %}
<tr>
<td>{{ c.date }}</td>
<td>{{ c.count }}</td>
</tr>
{% empty %}
<tr>
<td colspan="2">No counts saved</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}

View file

@ -0,0 +1,6 @@
{% extends 'base.html' %}
{% block title %}index{% endblock %}
{% block content %}
<marquee>Viva luciano malusa!</marquee>
{% endblock %}

View file

@ -0,0 +1,23 @@
{% if mobile and user.is_authenticated %}
<div class="user-view">
<div class="background" style="background-color: #444444"></div>
<a href="#name">
<span class="white-text name">{{ user.username }}</span>
</a>
<a href="#email">
<span class="white-text email">{{ user.email }}</span>
</a>
</div>
{% endif %}
{% if user.is_authenticated %}
<li><a href="{% url "count_list" %}">Counts</a></li>
<li class="divider" tabindex="-1"></li>
{% if user.is_superuser %}
<li><a href="{% url "admin:index" %}">Admin</a></li>
{% endif %}
<li><a href="{% url "logout" %}">Logout</a></li>
{% else %}
<li><a href="{% url "login" %}">Login</a></li>
<li><a href="{% url "registration" %}">Register</a></li>
{% endif %}

3
counter/tests.py Normal file
View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

8
counter/urls.py Normal file
View file

@ -0,0 +1,8 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('count/list', views.arrow_count_list, name='count_list'),
]

29
counter/views.py Normal file
View file

@ -0,0 +1,29 @@
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import ArrowCount
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
def index(request):
template = loader.get_template('index.html')
return HttpResponse(template.render({}, request))
@login_required
def arrow_count_list(request):
page = request.GET.get('page')
if not page:
page = 1
else:
page = int(page)
if page <= 0:
raise SuspiciousOperation("page is negative or 0")
start = settings.ITEMS_PER_PAGE * (page - 1)
finish = settings.ITEMS_PER_PAGE + start
counts = ArrowCount.objects.filter(user = request.user)[start:finish]
template = loader.get_template('counter/list.html')
return HttpResponse(template.render({'counts': counts}, request))

15
manage.py Executable file
View file

@ -0,0 +1,15 @@
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arrowcounter.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)

0
user/__init__.py Normal file
View file

4
user/admin.py Normal file
View file

@ -0,0 +1,4 @@
from django.contrib import admin
from .models import CounterUser
admin.site.register(CounterUser)

5
user/apps.py Normal file
View file

@ -0,0 +1,5 @@
from django.apps import AppConfig
class UserConfig(AppConfig):
name = 'user'

21
user/forms.py Normal file
View file

@ -0,0 +1,21 @@
from django.contrib.auth.forms import (UserCreationForm, UsernameField,
AuthenticationForm)
from django import forms
from django.contrib.auth.models import User
from django.conf import settings
from .models import CounterUser
class RegistrationForm(UserCreationForm):
email = forms.EmailField(label = "Email")
class Meta:
model = CounterUser
fields = ("username", "email", )
field_classes = {'username': UsernameField, 'email': forms.EmailField}
def save(self, commit=True):
user = super(RegisterForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user

View file

@ -0,0 +1,44 @@
# Generated by Django 2.1 on 2018-08-07 20:10
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', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='CounterUser',
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=150, 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')),
('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': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]

View file

5
user/models.py Normal file
View file

@ -0,0 +1,5 @@
from django.db import models
from django.contrib.auth.models import AbstractUser
class CounterUser(AbstractUser):
pass

12
user/static/css/user.css Normal file
View file

@ -0,0 +1,12 @@
#login-form .card-content .row, #registration-form .card-content .row {
margin-bottom: 0;
}
#login-form button[type=submit], #registration-form button[type=submit] {
background: none !important;
border: none;
cursor: pointer;
padding: 0 !important;
color: inherit;
text-transform: uppercase;
}

View file

@ -0,0 +1,23 @@
{% extends "base.html" %}
{% load static %}
{% block style %}
<link rel="stylesheet" href="{% static "css/user.css" %}">
{% endblock %}
{% block title %}Login{% endblock %}
{% block content %}
<h1 class="center">Login</h1>
<form id="login-form" method="post" class="col s12">
{% csrf_token %}
<div class="card">
<div class="card-content">
{{ form.as_p }}
</div>
<div class="card-action">
<a href="#"><button type="submit">Login</button></a>
</div>
</div>
</form>
{% endblock %}

View file

@ -0,0 +1,24 @@
{% extends 'base.html' %}
{% load static %}
{% block style %}
<link rel="stylesheet" href="{% static "css/user.css" %}">
{% endblock %}
{% block title %}Register{% endblock %}
{% block content %}
<h1 class="center">Register</h1>
<form method="post">
<div class="col s12 card" id="registration-form">
<div class="card-content">
{% csrf_token %}
{{ form.as_p }}
</div>
<div class="card-action">
<a href="#"><button type="submit">Register</button></a>
</div>
</div>
</form>
{% endblock %}

3
user/tests.py Normal file
View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

7
user/urls.py Normal file
View file

@ -0,0 +1,7 @@
from django.urls import path
from . import views
urlpatterns = [
path('signup/', views.Registration.as_view(), name='registration')
]

8
user/views.py Normal file
View file

@ -0,0 +1,8 @@
from django.views import generic
from django.urls import reverse_lazy
from .forms import RegistrationForm
class Registration(generic.CreateView):
form_class = RegistrationForm
success_url = reverse_lazy('login')
template_name = 'registration/registration.html'