Alexander Popelnukhin avatar Alexander Popelnukhin committed 1f5e494

Create views for add/delete/update students and groups

Comments (0)

Files changed (10)

Binary file modified.

students/forms.py

+#!-*-coding: utf-8-*-
+from django.forms import ModelForm, DateField, BooleanField, Form, RadioSelect
+from students.models import Student, Group
+
+class StudentForm(ModelForm):
+    birthday = DateField(help_text=u'Например: 1687-03-24', label=u'Дата рождения')
+    class Meta:
+        model = Student
+
+class GroupForm(ModelForm):
+    class Meta:
+        model = Group
+
+YES_OR_NO = (
+    (True, u'Да, удалить'),
+    (False, u'Нет, не удалять')
+)
+class YesNoForm(Form):
+    choice = BooleanField(
+        widget=RadioSelect(choices=YES_OR_NO),
+        initial=False,
+        required=False,
+        label=u'Действительно хотите удалить?')

students/models.py

+# -*-coding: utf-8-*-
 from django.db import models
 
 class Student(models.Model):
-    name = models.CharField(max_length=50)
-    surname = models.CharField(max_length=100)
-    patronymic = models.CharField(max_length=50)
-    birthday = models.DateField()
-    student_ID = models.CharField(max_length=10)
-    student_group = models.ForeignKey('students.Group', blank=True, null=True, related_name='students')
+    surname = models.CharField(verbose_name=u'Фамилия', max_length=100)
+    name = models.CharField(verbose_name=u'Имя', max_length=50)
+    patronymic = models.CharField(verbose_name=u'Отчество', max_length=50)
+    birthday = models.DateField(verbose_name=u'Дата рождения')
+    student_ID = models.CharField(verbose_name=u'№ зачетки', max_length=10)
+    student_group = models.ForeignKey('students.Group', verbose_name=u'Группа', blank=True, null=True, related_name='students')
 
     def __unicode__(self):
         return "%s - %s %s. %s." % (self.student_group.title, self.surname, self.name[0], self.patronymic[0])
     def get_name(self):
         return "%s %s.%s." % (self.surname, self.name[0], self.patronymic[0])
 
+    @models.permalink
+    def get_edit_url(self):
+        return  'edit_student', (self.pk, )
+
+    @models.permalink
+    def get_delete_url(self):
+        return 'delete_student', (self.pk, )
+
+    class Meta:
+        ordering = ('student_group', 'surname')
+
 class Group(models.Model):
-    title = models.CharField(max_length=200)
-    head = models.ForeignKey('students.Student', blank=True, null=True)
+    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)
 
     def __unicode__(self):
         return self.title
 
     @models.permalink
     def get_absolute_url(self):
-        return ('show_group', (self.pk, ))
+        return 'show_group', (self.pk, )
+
+    @models.permalink
+    def get_edit_url(self):
+        return  'edit_group', (self.pk,)
+
+    @models.permalink
+    def get_delete_url(self):
+        return 'delete_group', (self.pk, )
+
+    class Meta:
+        ordering = ('title', )

students/views.py

 # -*-coding: utf-8-*-
-from students.models import Group
-from django.shortcuts import get_object_or_404, render_to_response
+from django.shortcuts import get_object_or_404, render_to_response, redirect
+from django.template import RequestContext
+
+from students.models import Group, Student
+from students.forms import StudentForm, GroupForm, YesNoForm
 
 def index(request):
+    
     groups = Group.objects.all()
 
     data = dict(groups=groups)
 
 
 def group(request, group_id):
+
     group = get_object_or_404(Group, pk=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)
+
+
+def add_student(request, student_id=None, group_id=None):
+
+    if student_id:
+        student = get_object_or_404(Student, pk=student_id)
+    else:
+        student = None
+
+    if group_id:
+        group = get_object_or_404(Group, pk=group_id)
+    else:
+        group = None
+
+
+    if request.method == 'POST':
+        
+        if student:
+            form = StudentForm(request.POST, instance=student)
+        else:
+            form = StudentForm(request.POST)
+
+        if form.is_valid():
+            form.save()
+            return redirect('index')
+    else:
+        if student:
+            form = StudentForm(instance=student)
+        else:
+            form = StudentForm(initial={'student_group': group})
+            
+    data = dict(form=form, student_id=student_id)
+    return render_to_response('students/add_student.html',
+                              data,
+                              context_instance=RequestContext(request))
+
+def add_group(request, group_id=None):
+
+    if group_id:
+        group = get_object_or_404(Group, pk=group_id)
+    else:
+        group = None
+
+    if request.method == 'POST':
+        if group:
+            form = GroupForm(request.POST, instance=group)
+        else:
+            form = GroupForm(request.POST)
+        if form.is_valid():
+            form.save()
+            return redirect('index')
+    else:
+        if group:
+            form = GroupForm(instance=group)
+        else:
+            form = GroupForm()
+
+    data = dict(form=form, group_id=group_id)
+    return render_to_response('students/add_group.html',
+                              data,
+                              context_instance=RequestContext(request))
+
+def delete_instance(request, instance_id, instance_type):
+    if instance_type == 1:
+        instance = get_object_or_404(Student, pk=instance_id)
+    else:
+        instance = get_object_or_404(Group, pk=instance_id)
+
+
+
+    if request.method == 'POST':
+        form = YesNoForm(request.POST)
+        if form.is_valid():
+            choice = form.cleaned_data['choice']
+            if choice == True:
+                instance.delete()
+        return redirect('index')
+    else:
+        form = YesNoForm()
+    data = dict(form=form, instance_id=instance_id, instance=instance, instance_type=instance_type)
+    return render_to_response('students/delete_instance.html',
+                              data,
+                              context_instance=RequestContext(request))
+

templates/students/add_group.html

+<!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>

templates/students/add_student.html

+<!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>

templates/students/delete_instance.html

+<!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>
+
+
+</body>
+</html>

templates/students/group.html

                 <td>Имя</td>
                 <td>Отчество</td>
                 <td>Дата рождения</td>
+                <td>Управление</td>
             </tr>
         </thead>
         <tbody>
         {% for student in students %}
             <tr {% ifequal student group.head %}style="font-weight: bold;"{% endifequal %} >
-                <td>{{ student.student_ID }}</td>
+                <td>{{ student.student_ID }} </td>
                 <td>{{ student.surname }}</td>
                 <td>{{ student.name }}</td>
                 <td>{{ student.patronymic }}</td>
                 <td>{{ student.birthday|date:"d.m.Y" }} г.</td>
+                <td>
+                    <a href="{{ student.get_edit_url }}">изменить</a> | 
+                    <a href="{{ student.get_delete_url }}">удалить</a>
+                </td>
             </tr>
         {% endfor %}
-
-
         </tbody>
-
     </table>
+    <a href="{% url add_student_to_group group_id=group.pk %}">Добавить студента</a>
 </body>
 </html>

templates/students/index.html

     <td width="150">Группа</td>
     <td>Староста</td>
     <td>Кол-во человек</td>
+    <td>Управление</td>
 </tr>
 </thead>
 <tbody>
             <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>
 admin.autodiscover()
 
 urlpatterns = patterns('',
-    # Examples:
     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/delete/(?P<instance_id>\d+)/',
+        'KiwiTest.students.views.delete_instance',
+        name='delete_student',
+        kwargs={'instance_type': 1}),
+
+    url(r'^group/delete/(?P<instance_id>\d+)/',
+        'KiwiTest.students.views.delete_instance',
+        name='delete_group',
+        kwargs={'instance_type': 2}),
+
     # url(r'^KiwiTest/', include('KiwiTest.foo.urls')),
 
-    # Uncomment the admin/doc line below to enable admin documentation:
-    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
-
-    # Uncomment the next line to enable the admin:
     url(r'^admin/', include(admin.site.urls)),
 )
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.