Commits

Kirill Nikolenko committed d8c9bde

add backend and auth

Comments (0)

Files changed (15)

+[{"pk": 1, "model": "students_crud.student", "fields": {"id_card": 123, "birthday": "2012-04-27", "group": 1, "full_name": "\u0418\u0432\u0430\u043d\u043e\u0432 \u0418\u0432\u0430\u043d \u0418\u0432\u0430\u043d\u043e\u0432\u0438\u0447"}}, {"pk": 2, "model": "students_crud.student", "fields": {"id_card": 55555, "birthday": "2012-04-27", "group": 1, "full_name": "\u041f\u0435\u0442\u0440\u043e\u0432 \u041f\u0435\u0442\u0440 \u041f\u0435\u0442\u0440\u043e\u0432\u0438\u0447"}}, {"pk": 3, "model": "students_crud.student", "fields": {"id_card": 111, "birthday": "2012-04-27", "group": 2, "full_name": "\u0418\u0432\u0430\u043d\u043e\u0432 \u041f\u0435\u0442\u0440 \u0418\u0432\u0430\u043d\u043e\u0432\u0438\u0447"}}, {"pk": 4, "model": "students_crud.student", "fields": {"id_card": 3333, "birthday": "2012-04-27", "group": 2, "full_name": "\u041f\u0435\u0442\u0440\u043e\u0432 \u0418\u0432\u0430\u043d \u041f\u0435\u0442\u0440\u043e\u0432\u0438\u0447"}}, {"pk": 1, "model": "students_crud.group", "fields": {"elder": 1, "name": "A-51"}}, {"pk": 2, "model": "students_crud.group", "fields": {"elder": 3, "name": "\u0430-77"}}, {"pk": 1, "model": "students_crud.signalstorage", "fields": {"action": "save", "sender": "Student"}}, {"pk": 2, "model": "students_crud.signalstorage", "fields": {"action": "save", "sender": "Group"}}, {"pk": 3, "model": "students_crud.signalstorage", "fields": {"action": "save", "sender": "Student"}}, {"pk": 4, "model": "students_crud.signalstorage", "fields": {"action": "save", "sender": "Student"}}, {"pk": 5, "model": "students_crud.signalstorage", "fields": {"action": "save", "sender": "Group"}}, {"pk": 6, "model": "students_crud.signalstorage", "fields": {"action": "save", "sender": "Student"}}, {"pk": 7, "model": "students_crud.signalstorage", "fields": {"action": "save", "sender": "Student"}}, {"pk": 8, "model": "students_crud.signalstorage", "fields": {"action": "save", "sender": "Group"}}]

students/settings.py

     "students_crud.context_proc.settings_templ",
 )
 
+AUTHENTICATION_BACKENDS = (
+    'django.contrib.auth.backends.ModelBackend',
+    'students_crud.backends.EmailOrUsernameModelBackend',
+)
+
+LOGIN_URL = '/login/'
+
 # A sample logging configuration. The only tangible logging
 # performed by this configuration is to send an email to
 # the site admins on every HTTP 500 error when DEBUG=False.
 
     url(r'^students/', include('students_crud.urls')),
 
+    url(r'^login/', 'django.contrib.auth.views.login', {'template_name': 'E:/code/MyProjects/testexercise/templates/login.html'}),
+    url(r'^logout/', 'django.contrib.auth.views.logout', {'next_page': '/students/'}),
+
     # Uncomment the admin/doc line below to enable admin documentation:
     url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
 

students_crud/backends.py

+from django.conf import settings
+from django.contrib.auth.models import User
+
+
+class EmailOrUsernameModelBackend(object):
+    def authenticate(self, username=None, password=None):
+        if '@' in username:
+            kwargs = {'email': username}
+        else:
+            kwargs = {'username': username}
+        try:
+            user = User.objects.get(**kwargs)
+            if user.check_password(password):
+                return user
+        except User.DoesNotExist:
+            return None
+
+    def get_user(self, user_id):
+        try:
+            return User.objects.get(pk=user_id)
+        except User.DoesNotExist:
+            return None

students_crud/managment/commands/data_list.py

+# -*- coding: utf-8 -*-
+import sys
+import os
+
+sys.path.append('E:/code/MyProjects/testexercise/students')
+os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
+
+from django.core.management.base import BaseCommand, CommandError
+from students.students_crud.models import Group
+
+
+class Command(BaseCommand):
+    help = 'Выводит список груп и студентов в консоль'
+    def handle(self, *args, **options):
+        group_list = Group.objects.all()
+        for group in group_list:
+            print group.name
+            for student in group.student_set.all():
+                print "    {0}".format(student.full_name)
+
+        

students_crud/models.py

 class Group(models.Model):
     name = models.CharField("Название", max_length=20)
     elder = models.ForeignKey(Student, related_name='+', 
-                                verbose_name="староста")
+                                verbose_name="староста", blank=True, null=True)
 
     def __unicode__(self):
         return self.name

students_crud/templatetags/admredir.py

 # -*- coding: utf-8 -*-
 from django import template
 
-register = template.Library()
+#from students.students_crud.models import Group, Student
+
+
+register = template.Library()
+
+
+class AdminLinkNode(template.Node):
+    
+    def __init__(self, obj_name):
+        self.root = '/admin/students_crud/'
+        self.name = obj_name
+        self.link = '<a href = "{0}{1}">{1}</a> '.format(self.root, obj_name)
+
+    def render(self, context):
+        return self.link
+
+
+def do_admin_limk(parser, token):
+    try:
+        tag_name, object_name = token.split_contents()
+    except ValueError:
+        raise template.TemplateSyntaxError("%r tag requires a single argument"                                % token.contents.split()[0])
+    return AdminLinkNode(object_name)
+
+
+register.tag('edit_link', do_admin_limk)

students_crud/tests.py

 # -*- coding: utf-8 -*-
 """
-This file demonstrates writing tests using the unittest module. These will pass
-when you run "manage.py test".
-
-Replace this with more appropriate tests for your application.
 """
 
 from django.test import TestCase
+from django.test.client import Client
 
 
 class SimpleTest(TestCase):
         Tests that 1 + 1 always equals 2.
         """
         self.assertEqual(1 + 1, 2)
+
+    def test_login(self):
+        c = Client()
+        c.login(username='kirll', password='123456')
+        print dir(c)
+        self.assertEqual(1+1, 2)

students_crud/urls.py

 from django.conf.urls import patterns, include, url
 from django.views.generic import DetailView, ListView
 
-from students_crud.models import Group, Student
+from students_crud.models import Group
 
 urlpatterns = patterns('',
     url(r'^$',
         DetailView.as_view(
             model=Group,
             template_name='detail.html')),
-
+    url(r'^edit/$', 'students_crud.views.edit_groups'),
+    url(r'(?P<group_id>\d+)/edit/', 'students_crud.views.edit_students'),
+    
 )

students_crud/views.py

 # -*- coding: utf-8 -*-
-# Create your views here.
+from django.http import HttpResponse
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+from django.contrib.auth.decorators import login_required
+
+from models import Group
+
+@login_required
+def edit_groups(request):
+    group_list = Group.objects.all()
+    return render_to_response('edit.html', {'group_list': group_list}, context_instance=RequestContext(request))
+
+@login_required
+def edit_students(request, group_id):
+    return HttpResponse("Hello, world. You're at the poll index{0}.{1}".format(group_id, request.user))

templates/base.html

+<!DOCTYPE html> 
+<html>
+<head>
+    <title>База данных студентов</title>
+    <style type="text/css">
+          .sql_info {
+            font: 0.5em "Lucida Grande", "Trebuchet MS", Verdana, sans-serif;
+            color: grey;
+          }
+    </style>
+</head>
+<body>
+<div id="header">
+    <p id="title">Заголовок</p>
+</div>
+{% block content%}
+
+{% endblock %}
+<p></p>
+<a href="/logout/">Выход</a>
+<div id="footer">
+    2012 ©
+</div>

templates/detail.html

-{% extends "templ.html" %}
-
+{% extends "base.html" %}
+{% load admredir %}
 {% block content %}
 
 <h1>{{ group.name }}</h1>
 
 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
-
+<table>
+<tr>
+    <td><p>Имя:</p></td> <td><p>Дата</p></td><td><p>№ Билета</p></td>
+</tr>
 {% for student in group.student_set.all %}
-    {{ student.full_name }} {{ student.birthday }} {{ student.id_card }} </br>
+    
+    <tr>
+        <td>{{ student.full_name }}</td> <td>{{ student.birthday }}</td> <td>{{ student.id_card }}</td> 
+    <tr>
+    
 {% endfor %}
+</table>
+<p><a href="edit/">Редактировать</a><p>
 
 {% endblock %}

templates/edit.html

+{% extends "base.html" %}
+{% load admredir %}
+{% block content %}
+
+<h3>Редактирование</h3>
+{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
+{% csrf_token %}
+{% for group in group_list %}
+    <input type="radio" name="group" id="group{{ forloop.counter }}" value="{{ group.id }}" />
+    <label for="group{{ forloop.counter }}">{{ group.name }}</label><br />
+{% endfor %}
+<input type="submit" value="G" />
+
+{% endblock %}

templates/index.html

-{% extends "templ.html" %}
-
+{% extends "base.html" %}
+{% load admredir %}
 {% block content %}
 
 {% if group_list %}
-    <ul>
+<table>
+<tr>
+    <td><p>Название:</p></td> 
+    <td><p>Кол-во человек</p></td>
+    <td><p>Староста</p></td>
+</tr>
     {% for group in group_list %}
-        <li><a href="{{ group.id }}/">{{ group.name }}</a> {{ group.student_set.count }}   {{ group.elder }}</li>
+        <tr>
+            <td><a href="{{ group.id }}/">{{ group.name }}</a></td> 
+            <td>{{ group.student_set.count }}</td>
+            <td>{{ group.elder }}</td>
+        </tr>
     {% endfor %}
-    </ul>
-{% else %}
-    <p>No polls are available.</p>
+</table>
+
 {% endif %}
 
-{% endblock %}
+<p><a href="edit/">Редактировать</a><p>
+
+{% edit_link group %}
+{% endblock %}

templates/login.html

+{% extends "base.html" %}
+
+{% block content %}
+
+{% if form.errors %}
+<p>Неправильный пароль/имя. Попробуйте ещё раз.</p>
+{% endif %}
+
+<form method="post" action="{% url django.contrib.auth.views.login %}">
+{% csrf_token %}
+<p>Имя пользователя или Электронная почта:</p>
+    {{ form.username }}
+
+<p>{{ form.password.label_tag }}:</p>
+   {{ form.password }}
+
+
+<p></p>
+<input type="submit" value="Войти" />
+<input type="hidden" name="next" value="{{ next }}" />
+</form>
+
+{% endblock %}