1. Alexander Popelnukhin
  2. kiwitest

Commits

Alexander Popelnukhin  committed 7c50c2f

Add authorization by login and email, middleware for sql-queries, context processor for settings, tag for edit any model in admin, command that shows groups.

  • Participants
  • Parent commits 1f5e494
  • Branches default

Comments (0)

Files changed (21)

File auth_backends.py

View file
  • Ignore whitespace
+from django.contrib.auth.models import User
+from django.core.validators import email_re
+
+class BasicBackend:
+    def get_user(self, user_id):
+        try:
+            return User.objects.get(pk=user_id)
+        except User.DoesNotExist:
+            return None
+
+class EmailBackend(BasicBackend):
+    def authenticate(self, username=None, password=None):
+
+        #If username is an email address, then try to pull it up
+        if email_re.search(username):
+            try:
+                user = User.objects.get(email=username)
+            except User.DoesNotExist:
+                return None
+        else:
+            #We have a non-email address username we should try username
+            try:
+                user = User.objects.get(username=username)
+            except User.DoesNotExist:
+                return None
+        if user.check_password(password):
+            return user
+  

File context_processors.py

View file
  • Ignore whitespace
+def settings_processor(request):
+    from django.conf import settings
+    return  dict(settings=settings)
+  

File local.db

  • Ignore whitespace
Binary file modified.

File middlewares.py

View file
  • Ignore whitespace
+#!-*- coding: utf-8 -*-
+from django.db import connection
+from django.template import Template, Context
+from django.utils.encoding import smart_unicode
+
+class SQLLogMiddleware:
+
+    def process_response(self, request, response):
+
+        content_types = ('text/plain', 'text/html')
+
+        if request.META['CONTENT_TYPE'] not in content_types:
+            return response
+
+        time = sum([float(q['time']) for q in connection.queries])
+
+        template = Template("""<div class="debug">
+                <p>Выполнено запросов: {{ count }}</p>
+                <p>Время выполнения: {{ time }} с.</p>
+            <div>
+            """)
+
+        renderred_template = template.render(Context(dict(time=time, count=len(connection.queries))))
+
+
+        content = response.content.decode('utf-8')
+
+        body = '</body>'
+        body_position = content.find(body)
+
+        content = content[:body_position] + renderred_template + content[body_position:]
+        
+        response.content = content.encode('utf-8')
+
+        return  response

File settings.py

View file
  • Ignore whitespace
 
 DEBUG = True
 TEMPLATE_DEBUG = DEBUG
+COPYRIGHT = 'Alexander Popelnukhin <mail@laqie.net> (c) 2011'
 
 ADMINS = (
     ('Alexander Popelnukhin', 'mail@laqie.net'),
 # Examples: "http://foo.com/static/admin/", "/static/admin/".
 ADMIN_MEDIA_PREFIX = '/static/admin/'
 
+
+
+AUTHENTICATION_BACKENDS = (
+    'KiwiTest.auth_backends.EmailBackend',
+)
+
 # Additional locations of static files
 STATICFILES_DIRS = (
     # Put strings here, like "/home/html/static" or "C:/www/django/static".
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
+    'KiwiTest.middlewares.SQLLogMiddleware',
 )
 
 ROOT_URLCONF = 'KiwiTest.urls'
 
+TEMPLATE_CONTEXT_PROCESSORS = (
+    'django.core.context_processors.auth',
+    'django.core.context_processors.debug',
+    'django.core.context_processors.i18n',
+    'django.core.context_processors.request',
+    'KiwiTest.context_processors.settings_processor',
+)
+
 TEMPLATE_DIRS = (
     # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
     # Always use forward slashes, even on Windows.

File students/management/__init__.py

  • Ignore whitespace
Empty file added.

File students/management/commands/__init__.py

  • Ignore whitespace
Empty file added.

File students/management/commands/showgroups.py

View file
  • Ignore whitespace
+from django.core.management.base import BaseCommand
+
+class Command(BaseCommand):
+
+    help = "Show groups and count students in it"
+
+    def handle(self, *args, **options):
+        from KiwiTest.students.models import Group
+        groups = Group.objects.all()
+
+        for group in groups:
+            print "%s   \t%d" % (group.title, group.students.count())
+        

File students/models.py

View file
  • Ignore whitespace
 
 class Group(models.Model):
     title = models.CharField(verbose_name=u'Название', max_length=200)
-    head = models.ForeignKey('students.Student', verbose_name=u'Староста', blank=True, null=True, on_delete=models.SET_NULL)
+    head = models.ForeignKey('students.Student',
+                             verbose_name=u'Староста',
+                             blank=True,
+                             null=True,
+                             on_delete=models.SET_NULL)
 
     def __unicode__(self):
         return self.title

File students/templatetags/__init__.py

View file
  • Ignore whitespace
+
+  

File students/templatetags/students_tags.py

View file
  • Ignore whitespace
+from django import template
+from django.core import urlresolvers
+from django.contrib.contenttypes.models import ContentType
+
+register = template.Library()
+
+@register.inclusion_tag('tags/edit_list.html')
+def edit_list(instance, link=None):
+    if link == None:
+        link = 'edit in admin'
+    content_type = ContentType.objects.get_for_model(instance.__class__)
+    admin_url = urlresolvers.reverse("admin:%s_%s_change" % (content_type.app_label, content_type.model), args=(instance.pk,))
+
+    return dict(link=link, admin_url=admin_url)

File students/views.py

View file
  • Ignore whitespace
 # -*-coding: utf-8-*-
 from django.shortcuts import get_object_or_404, render_to_response, redirect
 from django.template import RequestContext
+from django.contrib.auth.decorators import login_required
 
 from students.models import Group, Student
 from students.forms import StudentForm, GroupForm, YesNoForm
     groups = Group.objects.all()
 
     data = dict(groups=groups)
-    return render_to_response('students/index.html', data)
+    return render_to_response('students/index.html',
+                              data,
+                              context_instance=RequestContext(request))
 
 
 def group(request, group_id):
     students = group.students.all()
 
     data = dict(group=group, students=students)
-    return render_to_response('students/group.html', data)
+    return render_to_response('students/group.html',
+                              data,
+                              context_instance=RequestContext(request))
 
 
-def add_student(request, student_id=None, group_id=None):
+@login_required(login_url='/login/')
+def manage_student(request, student_id=None, group_id=None):
 
     if student_id:
         student = get_object_or_404(Student, pk=student_id)
                               data,
                               context_instance=RequestContext(request))
 
-def add_group(request, group_id=None):
+
+@login_required(login_url='/login/')
+def manage_group(request, group_id=None):
 
     if group_id:
         group = get_object_or_404(Group, pk=group_id)
                               data,
                               context_instance=RequestContext(request))
 
+
+@login_required(login_url='/login/')
 def delete_instance(request, instance_id, instance_type):
     if instance_type == 1:
         instance = get_object_or_404(Student, pk=instance_id)

File templates/_base.html

View file
  • Ignore whitespace
+<!DOCTYPE html>
+<html>
+<head>
+    <title>{% block title %}Title{% endblock %}</title>
+</head>
+<body>
+
+{% block auth %}
+    {% if user %}
+        {% if user.is_authenticated %}
+            <p>Вы вошли как {{ user }}, <a href="/logout/">выйти</a></p>
+        {% else %}
+            <p>Вы не авторизованы, <a href="/login/">войти</a></p>
+        {% endif %}
+    {% endif %}
+{% endblock %}
+
+{% block content %}content{% endblock %}
+
+{% block footer %}
+    <p>Copyright: {{ settings.COPYRIGHT }}</p>
+{% endblock %}
+
+</body>
+</html>

File templates/login.html

View file
  • Ignore whitespace
+{% extends '_base.html' %}
+{% load url from future %}
+
+{% block title %}Вход{% endblock %}
+
+{% block auth %}{% endblock %}
+
+{% block content %}
+    <a href="{% url 'KiwiTest.students.views.index' %}">В начало</a>
+    <h1>Вход</h1>
+    {% if form.errors %}
+        <p>Your username and password didn't match. Please try again.</p>
+    {% endif %}
+
+    <form method="post" action="{% url 'django.contrib.auth.views.login' %}">
+    {% csrf_token %}
+    <table>
+    <tr>
+        <td>Имя пользователя или E-mail</td>
+        <td>{{ form.username }}</td>
+    </tr>
+    <tr>
+        <td>Пароль</td>
+        <td>{{ form.password }}</td>
+    </tr>
+    </table>
+
+    <input type="submit" value="login" />
+    <input type="hidden" name="next" value="{{ next }}" />
+    </form>
+{% endblock %}

File templates/students/add_group.html

View file
  • Ignore whitespace
-<!DOCTYPE html>
-<html>
-<head>
-    <title>{% if group_id %}Редактирование{% else %}Добавление{% endif %} группы</title>
-</head>
-<body>
-<a href="{% url index %}">В начало</a>
-<h1>{% if group_id %}Редактирование{% else %}Добавление{% endif %} группы</h1>
-<form action="{% if group_id %}{% url edit_group group_id %}{% else %}{% url add_group %}{% endif %}" method="POST">
-    {% csrf_token %}
-    <table rules="rows" cellpadding="10" style="text-align: left;">
-        {{ form.as_table }}
-    </table>
-    <input type="submit" value="Сохранить">
-</form>
-</body>
-</html>
+{% extends '_base.html' %}
+
+{% block title %}
+    {% if group_id %}
+        Редактирование
+    {% else %}
+        Добавление
+    {% endif %} группы
+{% endblock %}
+
+{% block content %}
+    <a href="{% url index %}">В начало</a>
+    <h1>{% if group_id %}Редактирование{% else %}Добавление{% endif %} группы</h1>
+    <form action="{% if group_id %}{% url edit_group group_id %}{% else %}{% url add_group %}{% endif %}" method="POST">
+        {% csrf_token %}
+        <table rules="rows" cellpadding="10" style="text-align: left;">
+            {{ form.as_table }}
+        </table>
+        <input type="submit" value="Сохранить">
+    </form>
+{% endblock %}

File templates/students/add_student.html

View file
  • Ignore whitespace
-<!DOCTYPE html>
-<html>
-<head>
-    <title>{% if student_id %}Редактирование{% else %}Добавление{% endif %} студента</title>
-</head>
-<body>
-<a href="{% url index %}">В начало</a>
-<h1>{% if student_id %}Редактирование{% else %}Добавление{% endif %} студента</h1>
-<form action="{% if student_id %}{% url edit_student student_id %}{% else %}{% url add_student %}{% endif %}" method="POST">
-    {% csrf_token %}
-    <table style="text-align: left;"  rules="rows" cellpadding="10">
-        {{ form.as_table }}
-    </table>
-    <input type="submit" value="Сохранить">
-</form>
-</body>
-</html>
+{% extends '_base.html' %}
+
+{% block title %}
+    {% if student_id %}
+        Редактирование
+    {% else %}
+        Добавление
+    {% endif %} студента
+{% endblock %}
+
+{% block content %}
+    <a href="{% url index %}">В начало</a>
+    <h1>{% if student_id %}Редактирование{% else %}Добавление{% endif %} студента</h1>
+    <form action="{% if student_id %}{% url edit_student student_id %}{% else %}{% url add_student %}{% endif %}" method="POST">
+        {% csrf_token %}
+        <table style="text-align: left;"  rules="rows" cellpadding="10">
+            {{ form.as_table }}
+        </table>
+        <input type="submit" value="Сохранить">
+    </form>
+{% endblock %}

File templates/students/delete_instance.html

View file
  • Ignore whitespace
-<!DOCTYPE html>
-<html>
-<head>
-    <title>Удаление {% if instance_type == 1 %}студента{% else %}группы{% endif %}</title>
-</head>
-<body>
-<a href="{% url index %}">В начало</a>
-<h1>Удаление  {% if instance_type == 1 %}студента{% else %}группы{% endif %} [ {{ instance }} ]</h1>
-<form method="POST" action="{% if instance_type == 1 %}{% url delete_student instance_id=instance_id %}{% else %}{% url delete_group instance_id=instance_id %}{% endif %}">
-    {% csrf_token %}
-    {{ form.as_p }}
-    <input type="submit" value="Подтвердить">
-</form>
+{% extends '_base.html' %}
 
+{% block title %}Удаление
+    {% if instance_type == 1 %}
+        студента
+    {% else %}
+        группы
+    {% endif %}
+{% endblock %}
 
-</body>
-</html>
+{% block content %}
+    <a href="{% url index %}">В начало</a>
+    <h1>Удаление  {% if instance_type == 1 %}студента{% else %}группы{% endif %} [ {{ instance }} ]</h1>
+    <form method="POST" action="{% if instance_type == 1 %}{% url delete_student instance_id=instance_id %}{% else %}{% url delete_group instance_id=instance_id %}{% endif %}">
+        {% csrf_token %}
+        {{ form.as_p }}
+        <input type="submit" value="Подтвердить">
+    </form>
+{% endblock %}

File templates/students/group.html

View file
  • Ignore whitespace
-<!DOCTYPE html>
-<html>
-<head>
-    <title>Группа {{ group.title }}</title>
-</head>
-<body>
+{% extends '_base.html' %}
+{% load students_tags %}
+
+{% block title %}Группа {{ group.title }}{% endblock %}
+
+{% block content %}
     <a href="{% url index %}">В начало</a>
     <h1>Группа {{ group.title }}</h1>
 
                 <td>{{ student.birthday|date:"d.m.Y" }} г.</td>
                 <td>
                     <a href="{{ student.get_edit_url }}">изменить</a> | 
-                    <a href="{{ student.get_delete_url }}">удалить</a>
+                    <a href="{{ student.get_delete_url }}">удалить</a> |
+                    {% edit_list student 'в админке' %}
                 </td>
             </tr>
         {% endfor %}
         </tbody>
     </table>
     <a href="{% url add_student_to_group group_id=group.pk %}">Добавить студента</a>
-</body>
-</html>
+{% endblock %}

File templates/students/index.html

View file
  • Ignore whitespace
-<!DOCTYPE html>
-<html>
-<head>
-    <title>Группы студентов</title>
-</head>
-<body>
-<h1>Группы студентов</h1>
+{% extends '_base.html' %}
+{% load students_tags %}
 
-<table border="0" rules="all" cellpadding="10" cellspacing="0" width="600">
-<thead>
-<tr style="font-weight: bold;">
-    <td width="150">Группа</td>
-    <td>Староста</td>
-    <td>Кол-во человек</td>
-    <td>Управление</td>
-</tr>
-</thead>
-<tbody>
-    {% for group in groups %}
-        <tr>
-            <td><a href="{{ group.get_absolute_url }}">{{ group.title }}</a></td>
-            <td>{{ group.head.get_name }}</td>
-            <td>{{ group.students.count }}</td>
-            <td>
-                <a href="{{ group.get_edit_url }}">изменить</a> |
-                <a href="{{ group.get_delete_url }}">удалить</a>
-            </td>
-        </tr>
-    {% endfor %}
-</tbody>
-</table>
-<br>
-<a href="{% url add_group %}">Добавить группу</a> | <a href="{% url add_student %}">Добавить студента</a>
-</body>
-</html>
+{% block title %}Группы студентов{% endblock %}
+
+
+
+{% block content %}
+    <h1>Группы студентов</h1>
+
+    <table border="0" rules="all" cellpadding="10" cellspacing="0" width="700">
+    <thead>
+    <tr style="font-weight: bold;">
+        <td width="150">Группа</td>
+        <td>Староста</td>
+        <td>Кол-во человек</td>
+        <td>Управление</td>
+    </tr>
+    </thead>
+    <tbody>
+        {% for group in groups %}
+            <tr>
+                <td><a href="{{ group.get_absolute_url }}">{{ group.title }}</a></td>
+                <td>{{ group.head.get_name }}</td>
+                <td>{{ group.students.count }}</td>
+                <td>
+                    <a href="{{ group.get_edit_url }}">изменить</a> |
+                    <a href="{{ group.get_delete_url }}">удалить</a> |
+                    {% edit_list group 'в админке' %}
+                </td>
+            </tr>
+        {% endfor %}
+    </tbody>
+    </table>
+    <br>
+    <a href="{% url add_group %}">Добавить группу</a> | <a href="{% url add_student %}">Добавить студента</a>
+{% endblock %}

File templates/tags/edit_list.html

View file
  • Ignore whitespace
+<a href="{{ admin_url }}">{{ link }}</a>

File urls.py

View file
  • Ignore whitespace
 urlpatterns = patterns('',
     url(r'^$', 'KiwiTest.students.views.index', name='index'),
     url(r'^group/(\d+)/$', 'KiwiTest.students.views.group', name='show_group'),
-    url(r'^student/add/$', 'KiwiTest.students.views.add_student', name='add_student'),
-    url(r'^student/add/(?P<group_id>\d+)/$', 'KiwiTest.students.views.add_student', name='add_student_to_group'),
-    url(r'^student/edit/(\d+)/$', 'KiwiTest.students.views.add_student', name='edit_student'),
-    url(r'^group/add/$', 'KiwiTest.students.views.add_group', name='add_group'),
-    url(r'^group/edit/(\d+)/$', 'KiwiTest.students.views.add_group', name='edit_group'),
+    url(r'^student/add/$', 'KiwiTest.students.views.manage_student', name='add_student'),
+    url(r'^student/add/(?P<group_id>\d+)/$', 'KiwiTest.students.views.manage_student', name='add_student_to_group'),
+    url(r'^student/edit/(\d+)/$', 'KiwiTest.students.views.manage_student', name='edit_student'),
+    url(r'^group/add/$', 'KiwiTest.students.views.manage_group', name='add_group'),
+    url(r'^group/edit/(\d+)/$', 'KiwiTest.students.views.manage_group', name='edit_group'),
     
     url(r'^student/delete/(?P<instance_id>\d+)/',
         'KiwiTest.students.views.delete_instance',
         kwargs={'instance_type': 2}),
 
     # url(r'^KiwiTest/', include('KiwiTest.foo.urls')),
-
+    (r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
+    (r'^logout/$', 'django.contrib.auth.views.logout_then_login', {'login_url': '/login/'}),
+    (r'^accounts/profile/', 'django.views.generic.simple.redirect_to', {'url': '/'}),
     url(r'^admin/', include(admin.site.urls)),
 )