Web весна 2012 лекция 7

  • 115 views
Uploaded on

 

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
115
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
0
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Django Бекбулатов Александр a.bekbulatov@corp.mail.ru
  • 2. MVC Model-view-controller – схема использования нескольких шаблонов проектирования, с помощью которых модель данных приложения, пользовательский интерфейс и взаимодействие с пользователем разделены на три отдельных компонента так, что модификация одного из компонентов оказывает минимальное воздействие на остальные.
  • 3. Примеры • Без MVC — в чистом виде PHP, ASP • Реализации с неполным MVC — CPB • C MVC — фреймворки CodeIgniter, Yii, ASP.NET MVC Framework, Django, Pyramid, Ruby on Rails
  • 4. MVC
  • 5. MVC в Django
  • 6. Создание проекта django-admin.py startproject myblog myblog/ manage.py myblog/ __init__.py settings.py urls.py wsgi.py
  • 7. Создание проекта cd myblog python manage.py runserver
  • 8. Подключение базы данных vim myblog/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blog', 'USER': 'root', 'PASSWORD': '1', 'HOST': '', 'PORT': '', } } python manage.py syncdb
  • 9. Создание приложения python manage.py startapp blog blog/ __init__.py models.py tests.py views.py
  • 10. Подключаем приложение vim myblog/settings.py INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'blog', ) python manage.py syncdb
  • 11. Модель vim blog/models.py from django.db import models import datetime class Category(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True) def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): return ('category_detail', (self.pk,))
  • 12. Панель администрирования vim myblog/urls.py from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('‘, # url(r'^', include('blog.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )
  • 13. class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() category = models.ForeignKey(Category) creation_date = models.DateTimeField(default=datetime.datetime.now) def previous_post(self): """Return the previous entry""" entries = Post.objects.filter( creation_date__lt=self.creation_date)[:1] if entries: return entries[0] def next_post(self): """Return the next entry""" entries = Post.objects.filter( creation_date__gt=self.creation_date).order_ by('creation_date')[:1] if entries: return entries[0] def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): return ('post_detail', (self.pk,)) class Meta: ordering = ['-creation_date']
  • 14. Панель администрирования vim blog/admin.py from blog.models import Category, Post from django.contrib import admin admin.site.register(Category) admin.site.register(Post)
  • 15. Панель администрирования python manage.py runserver http://127.0.0.1:8000/admin/
  • 16. Панель администрирования
  • 17. Панель администрирования
  • 18. Панель администрирования
  • 19. Панель администрирования
  • 20. Контроллеры vim blog/views.py #-*- coding: utf-8 -*- from django.views.generic.simple import direct_to_template from django.shortcuts import get_object_or_404 from django.views.generic.detail import DetailView from django.views.generic.list import ListView from blog.models import Category, Post def category(request, pk): cat = get_object_or_404(Category, pk=pk) post_list = Post.objects.filter(category=cat) return direct_to_template(request, 'blog/category.html', { 'category': cat, 'post_list' : post_list }) class PostList(ListView): model = Post class PostDetail(DetailView): model = Post
  • 21. Роутинг vim blog/urls.py from django.conf.urls import patterns, url from blog.views import PostList, PostDetail urlpatterns = patterns('', (r'^$', PostList.as_view()), url(r'^post/(?P<pk>d+)/$', PostDetail.as_view(), name='post_detail'), url(r'^category/(?P<pk>d+)/$', 'blog.views.category', name='category_detail'), )
  • 22. Шаблоны vim myblog/settings.py import os def rel(*x): return os.path.join(os.path.abspath(os.path.dirname(__file__)), * x) TEMPLATE_DIRS = ( rel('../templates'), # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. )
  • 23. Шаблоны mkdir -p templates/blog vim templates/base.html <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Блог</title> </head> <body> <h1>Мой блог</h1> {% block content %}{% endblock %} </body> </html>
  • 24. Шаблоны vim templates/blog/post_list.html {% extends "base.html" %} {% block content %} <ul> {% for object in object_list %} <li><a href="{{ object.get_absolute_url }}">{{ object }}</a></li> {% endfor %} </ul> {% endblock %}
  • 25. Шаблоны
  • 26. Шаблоны vim templates/blog/post_detail.html {% extends "base.html" %} {% block content %} <h2>{{ object }}</h2> <p><small>{{ object.creation_date }} <a href="{{ object.category.get_absolute_url}}">{{ object.category }}</a></p> <div>{{ object.content }}</div> {% endblock %}
  • 27. Шаблоны
  • 28. Шаблоны vim templates/blog/category.html {% extends "base.html" %} {% block content %} <h2>{{ category }}</h2> <ul> {% for object in post_list %} <li><a href="{{ object.get_absolute_url}}">{{ object }}</a></li> {% endfor %} </ul> {% endblock %}
  • 29. Шаблоны
  • 30. Работа с формами vim blog/forms.py #-*- coding: utf-8 -*- from django import forms class ContactForm(forms.Form): email = forms.EmailField(label=u'Ваш e-mail', max_length=100) message = forms.CharField(label=u'Сообщение', widget=forms.Textarea)
  • 31. Работа с формами vim blog/views.py from blog.forms import ContactForm from django.core.mail import send_mail from django.http import HttpResponseRedirect def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = u'Сообщение с блога' message = form.cleaned_data['message'] sender = form.cleaned_data['email'] recipients = ['a.bekbulatov@corp.mail.ru'] send_mail(subject, message, sender, recipients) return HttpResponseRedirect('/') else: form = ContactForm() return direct_to_template(request, 'blog/contact.html', { 'form': form })
  • 32. Работа с формами vim blog/urls.py urlpatterns = patterns('', (r'^$', PostList.as_view()), url(r'^post/(?P<pk>d+)/$', PostDetail.as_view(), name='post_detail'), url(r'^category/(?P<pk>d+)/$', 'blog.views.category', name='category_detail'), (r'^contacts/$', 'blog.views.contact'), )
  • 33. Работа с формами vim templates/blog/contact.html {% extends "base.html" %} {% block content %} <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Отправить" /> </form> {% endblock %}
  • 34. Работа с формами python manage.py runserver http://127.0.0.1:8000/contacts/