Разработка архитектуры закрытой корпоративной сети с использованием фреймворка Django - Дипломная работа

бесплатно 0
4.5 156
Анализ корпоративных сетей, определение их преимуществ и недостатков: ASmallWorld, Decayenne и Evrika. Структура web-приложения, методика и принципы его разработки, оценка практической эффективности. База данных и административная, логическая часть.

Скачать работу Скачать уникальную работу

Чтобы скачать работу, Вы должны пройти проверку:


Аннотация к работе
В данной работе полностью реализована главная страница пользователя, осуществлен доступ к другим страницам пользователей, возможность загружать документы себе на страницу и скачивать со страниц других пользователей, личная лента новостей и страница новостей всех пользователей, с возможностью поиска новости по словам в тексте и заголовке, фильтрация по тегам и по датам. Класс Profile описывает структуру таблицы profile, которая ссылается на таблицу User, (сгенерированную при подключении приложения django.contrib.auth), с помощью поля user (объект класса FOREIGNKEY, атрибут-указатель которого будет модель User). user = models. FOREIGNKEY (User, related_name="profile", verbose_name = ("User"), blank = True, null=True) Так же в этой модели описаны два поля friends и friesnd_requests, которые являются объектами класса MANYTOMANYFIELD (отношение многие-ко-многим) и ссылаются на свою же модель («self»), для определения, какие объекты Profile находятся в друзьях и кто хочется стать другом. friends = models. Модель Chat служит для объединения в один объект всех объектов из модели Message, у которых получатель или отправитель соответствует полям person1 и person2, которые в свою очередь ссылаются на модель User (рисунок 9).

Список литературы
1 Django 1.5 documentation [Электронный ресурс] // Django 1.5 documentation. URL: https://docs.djangoproject.com/en/1.5/. (Дата обращения: 1.09.2013)

2 Форсье, Дж. Django. Разработка веб-приложений на Python./ Дж. Форсье, П. Биссекс, У. Чан, - СПБ.: Символ-Плюс, 2010. - 456 с.

3 Лутц М. Программирование на Python, том ?- ? ?, 4-е издание/ М. Лутц - СПБ.: Символ-Плюс, 2011. - 922 с.

4 Бизли, Д. Python. Подробный справочник, 4-е издание/ Д. Бизли - М.: Символ-Плюс, 2010. - 326 с.

5 Object-Relational Mapping! [Электронный ресурс] // ORM. URL: http://ru.wikipedia.org/wiki/ORM. (Дата обращения: 12.03.2012).

6 Django [Электронный ресурс] // Django. URL: http://ru.wikipedia.org/wiki/Django. (Дата обращения: 2.09.2013)

7 Buter-Brod [Электронный ресурс] // Представляем корпоративную сеть asmallworld.net для богатых и знаменитых. URL: http://buter-brot.ru/Moda/prdedstavlyaem-soczialnuyu-set-asmallworldnet-dlya-bogatyx-i-znamenityx.html/. (Дата обращения: 4.04.2014).

8 ASMALLWORLD. Корпоративная сеть [Электронный ресурс] // URL: https://www.asmallworld.com/. (Дата обращения: 4.30.2014).

9 Adamant [Электронный ресурс] // Оператор системных решений. URL: http://www.adamant.ua/projects/corporate-network/. (Дата обращения: 4.04.2014).

Приложение A Файл manage.py

#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module("settings") # Assumed to be in the same directory. except IMPORTERROR: import sys sys.stderr.write («Error: Can"t find the file "settings.py" in the directory containing % r. It appears you"ve customized things.\NYOU"ll have to run django-admin.py, passing it your settings module.

»% __file__) sys.exit(1) import settings if __name__ == «__main__»: execute_manager(settings)

Приложение Б

Папка settings: Файл __init.py__ (содержит все настройки Django): # -* - encoding: utf-8 -*- import os, sys from django.contrib import messages from django.utils.translation import ugettext_lazy as _ import os.path

DEBUG = True

PROJECT_ROOT = os.path.realpath (os.path.join (os.path.dirname (__file__),»../.»)) rel = lambda p: os.path.join (PROJECT_ROOT, p)

TEMPLATE_DEBUG = DEBUG

MANAGERS = ADMINS

EMAIL_BACKEND = "django.core.mail.backends.filebased. EMAILBACKEND"

EMAIL_FILE_PATH = os.path.join (PROJECT_ROOT, "_emails")

EMAIL_HOST = "localhost"

EMAIL_PORT = "8000"

EMAIL_HOST_USER = ""

EMAIL_HOST_PASSWORD = ""

EMAIL_USE_TLS = True

DATABASES = {

"default": {

"ENGINE": "django.db.backends.postgresql_psycopg2",#mysql", "NAME": "diplom", "USER": "postgres", "PASSWORD": "postgres", "HOST": "127.0.0.1", "PORT": "5432", }

}

ALLOWED_HOSTS = []

TIME_ZONE = "Europe/Moscow"

LANGUAGE_CODE = "ru-ru"

SITE_ID = 1

USE_I18N = True

USE_L10N = True

USE_TZ = True

LOCALE_PATHS = (os.path.join (PROJECT_ROOT, "locale"),)

MEDIA_ROOT = os.path.join (PROJECT_ROOT, "private/media/")

MEDIA_URL = "/media/"

STATIC_ROOT = os.path.join (PROJECT_ROOT, "public/static/")

STATIC_URL = "/static/"

ADMIN_MEDIA_PREFIX = "/static/admin/"

STATICFILES_DIRS = ( os.path.join (PROJECT_ROOT, "diplom/static/"), )

DEFAULT_HOST = "www.example.com"

STATICFILES_FINDERS = (

"django.contrib.staticfiles.finders. FILESYSTEMFINDER", "django.contrib.staticfiles.finders. APPDIRECTORIESFINDER", )

SECRET_KEY = "_z (8gb-k c^y5^1r3b02^km64ve0) bja % soa3@a23d5@*geodf"

TEMPLATE_DEBUG = DEBUG

TEMPLATE_CONTEXT_PROCESSORS = (

"django.core.context_processors.request", "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages", )

TEMPLATE_LOADERS = (

"django.template.loaders.filesystem. Loader", "django.template.loaders.app_directories. Loader", "django.template.loaders.eggs. Loader", )

TEMPLATE_DIRS = ( os.path.join (PROJECT_ROOT, "templates/"), )

«» «Middleware related settings.»"»

MIDDLEWARE_CLASSES = (

"django.middleware.common. COMMONMIDDLEWARE", "django.contrib.sessions.middleware. SESSIONMIDDLEWARE", "django.middleware.locale. LOCALEMIDDLEWARE", "django.middleware.csrf. CSRFVIEWMIDDLEWARE", "django.contrib.auth.middleware. AUTHENTICATIONMIDDLEWARE", "django.contrib.messages.middleware. MESSAGEMIDDLEWARE", "django.middleware.clickjacking.XFRAMEOPTIONSMIDDLEWARE", )

AUTHENTICATION_BACKENDS = (

"django.contrib.auth.backends. MODELBA

EMAIL_HOST = "localhost"

EMAIL_PORT = 1025

EMAIL_HOST_USER = ""

EMAIL_HOST_PASSWORD = ""

EMAIL_USE_TLS = False

DEFAULT_FROM_EMAIL = "info@google.ru"

LOGGING = {

"version": 1, "disable_existing_loggers": False, "filters": {

"require_debug_false": {

"()": "django.utils.log. REQUIREDEBUGFALSE"

}

}, "handlers": {

"mail_admins": {

"level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log. ADMINEMAILHANDLER"

}

}, "loggers": {

"django.request": {

"handlers": ["mail_admins"], "level": "ERROR", "propagate": True, }, }

}

AUTH_PROFILE_MODULE = "profile. Profile"ckend", # this is default

"guardian.backends. OBJECTPERMISSIONBACKEND", )

ANONYMOUS_USER_ID = -1

ROOT_URLCONF = "diplom.urls"

MESSAGE_TAGS = { messages.DEBUG: "debug", messages.INFO: "alert-info", messages.SUCCESS: "alert-success", messages.WARNING: "alert-warning", messages.ERROR: "alert-error", }

FIXTURE_DIRS = ( os.path.join (PROJECT_ROOT, "diplom/fixtures"), )

WSGI_APPLICATION = "diplom.wsgi.application"

INSTALLED_APPS = (

"django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.flatpages", "django.contrib.redirects", "filebrowser", "grappelli.dashboard", "grappelli", "guardian", "django.contrib.admin", "django.contrib.admindocs", "south", "registration", "diplom", "profile", "blog", "messages", ) from installed_apps.grappelli import * from installed_apps.logs import * from installed_apps.filebrowser import *

SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSERIALIZER"

DEFAULT_FROM_EMAIL = "info@google.ru"

LOGGING = {

"version": 1, "disable_existing_loggers": False, "filters": {

"require_debug_false": {

"()": "django.utils.log. REQUIREDEBUGFALSE"

}

}, "handlers": {

"mail_admins": {

"level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log. ADMINEMAILHANDLER"

}

}, "loggers": {

"django.request": {

"handlers": ["mail_admins"], "level": "ERROR", "propagate": True, }, }

}

AUTH_PROFILE_MODULE = "profile. Profile"

Файл installed_apps/filebrowser.py (содержит все настройки для Filebrowser): # -* - encoding: utf-8 -*- from django.utils.translation import ugettext_lazy as _

FILEBROWSER_DIRECTORY = "uploads/"

FILEBROWSER_CONVERT_FILENAME = True

FILEBROWSER_NORMALIZE_FILENAME = True

FILEBROWSER_VERSIONS = {

"admin_thumbnail": {"verbose_name": _("Admin Thumbnail"), "width": 60, "height": 60, "opts": "crop"}, "thumbnail": {"verbose_name": _("Thumbnail (1 col)"), "width": 60, "height": 60, "opts": "crop"}, "news_logo": {"verbose_name": (u"Логотип новости"), "width": 100, "height": 75, "opts": "crop"}, "services_thumbnail": {"verbose_name": (u"Миниатюры для услуг"), "width": 120, "height": 90, "opts": "crop"}, "our_face": {"verbose_name": (u"Фотографии наших сотрудников"), "width": 216, "height": 278, "opts": "crop"}, "profile_photo": {"verbose_name": (u"Фотография пользователя"), "width": 205, "height": 250, "opts": "crop"}, "admin_list_blog": {"verbose_name":u"Изображение для списока блогов (655*215)", "width": 655, "height": 215, "opts": "crop"}, }

FILEBROWSER_ADMIN_VERSIONS = ["thumbnail", "news_logo", "services_thumbnail", "our_face", "profile_photo", "admin_list_blog"] #"small", "medium", "big", "large", FILEBROWSER_ADMIN_THUMBNAIL = "admin_thumbnail"

FILEBROWSER_MAX_UPLOAD_SIZE = 60485760

FILEBROWSER_IMAGE_MAXBLOCK = 1024*1024

FILEBROWSER_EXTENSIONS = {

"Folder": [""], "Image": [".jpg", ".jpeg", ".gif", ".png", ".tif", ".tiff"], "Document": [".pdf", ".doc", ".rtf", ".txt", ".xls", ".csv"], "video": [".mov", ".wmv", ".mpeg", ".mpg", ".avi", ".rm"], "audio": [".mp3", ".mp4", ".wav", ".aiff", ".midi", ".m4p"]

}

FILEBROWSER_SELECT_FORMATS = {

"file": ["Folder", "Image", "Document", "video", "audio"], "image": ["Image"], "document": ["Document"], "media": ["video", "audio"], }

Файл diplom/urls.py (содержит все url настроек и сслыки на urls.py других приложений): from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin from filebrowser.sites import site from.forms import REGISTRATIONFORMPROFILE from profile.views import PROFILESETTINGVIEW, UPLOADVIEW import registration import os admin.autodiscover() urlpatterns = patterns ("", (r"^accounts/", include ("registration.urls")), url (r"^grappelli/", include ("grappelli.urls")), (r"^accounts/", include ("registration.urls")), (r"^accounts/profile/$", "profile.views.profile_return"), (r"^accounts/edit/profile/$", PROFILESETTINGVIEW.as_view()), url (r"^admin/filebrowser/", include (site.urls)), url (r"^admin/", include (admin.site.urls)), url (r"^media/(? P.*)$", "django.views.static.serve", {"document_root": settings.MEDIA_ROOT}), url (r"^admin/doc/", include ("django.contrib.admindocs.urls")), (r"^upload_file/$", UPLOADVIEW.as_view()), url (r"^profile/", include ("profile.urls")), url (r"^message/", include ("messages.urls")), url (r"^blog/", include ("blog.urls")), )

Приложение PROFILE: Файл profile/urls.py (содержит все url-ы приложения profile): from django.conf.urls import patterns, include, url from views import PROFILEVIEW urlpatterns = patterns ("", url (r"^$", PROFILEVIEW.as_view(), name= «profile»), url (r"^friend/(? P\d )/$", PROFILEVIEW.as_view(), name= «profile_friend»), url (r"^friends/all/$", "profile.views.search_person"), url (r"^friends/add/(? P[^/] )/$", "profile.views.add_person"), url (r"^friends/del/(? P[^/] )/$", "profile.views.del_person"), url (r"^friends/accept/(? P[^/] )/$", "profile.views.accept_friend"), url (r"^friends/reject/(? P[^/] )/$", "profile.views.reject_friend"), )

Файл profile/models.py (содержит модели Profile и FILEPROFILE приложения profile): # -* - coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from diplom.settings import * from filebrowser.fields import FILEBROWSEFIELD from django.core.urlresolvers import reverse import datetime class Profile (models. Model): user = models. FOREIGNKEY (User, related_name="profile", verbose_name=("User"), blank=True, null=True) thumbnail = FILEBROWSEFIELD (u «Иконка», max_length=200, directory="uploads/", format="image", null=True, blank=True) requisites = models. TEXTFIELD (u"Дополнительные сведения", blank=True) login = models. CHARFIELD (u"Логин", max_length=150, blank=True, null=True) last_name = models. CHARFIELD (u"Фамилия", max_length=150, blank=True) first_name = models. CHARFIELD (u"Имя", max_length=150, blank=True) midlle_name = models. CHARFIELD (u"Отчество", max_length=150, blank=True) friends = models. MANYTOMANYFIELD («self», blank=True, null=True, symmetrical = False, related_name="friends_targets") friend_requests = models. MANYTOMANYFIELD («self», blank=True, null=True, symmetrical = False, related_name="friend_requests_targets")

icq = models. CHARFIELD (u"ICQ", max_length=150, blank=True) skype = models. CHARFIELD (u"Skype", max_length=150, blank = True) telephone = models. CHARFIELD (u"Телефон", max_length=150, blank = True) party = models. BOOLEANFIELD (u"Является участником сообщества", blank=True, default=False) def __unicode__(self): return u" % s"% (self.user) def get_absolute_url(self): return reverse («profile», kwargs={}) def get_files(self): return FILEPROFILE.objects.filter (user = self) class Meta: verbose_name = u "Пользователь» verbose_name_plural = u "Пользователи»

class FILEPROFILE (models. Model): user = models. FOREIGNKEY (Profile, related_name="profile", verbose_name=("User"), blank=True, null=True) title = models. CHARFIELD (u «Заголовок», max_length=64, blank=True, null=True) date = models. DATETIMEFIELD (verbose_name=u"Дата загрузки файла", blank=True, null=True, default = datetime.datetime.now) file = FILEBROWSEFIELD (u «Файл», directory="uploads/files/", max_length=100, format = "document", null=True, blank=True)

def __unicode__(self): return u" % s"% (self.user) class Meta: verbose_name = u "Файл пользователя» verbose_name_plural = u "Файлы пользователей»

Файл profile/admins.py (содержит подключение и настройки модели Profile, FILEPROFILE для административной части): from django.contrib import admin from models import Profile, FILEPROFILE class PROFILECONTENTADMIN (admin. TABULARINLINE): model = FILEPROFILE fields = ("title", "file",) extra = 1 class FILEPROFILEADMIN (admin. MODELADMIN): list_display = ("user", "title", "file", "date") ordering = ("user", "date") list_filter = ("user", "date") class PROFILEADMIN (admin. MODELADMIN): list_display = ("user", "last_name", "first_name", "midlle_name", "party") ordering = ("user",) list_filter = ("user",) inlines = [PROFILECONTENTADMIN] admin.site.register (Profile, PROFILEADMIN) admin.site.register (FILEPROFILE, FILEPROFILEADMIN)

Файл profile/forms.py (содержит модельные формы PROFILEFORM, BLOGFORM, FILEFORM приложения profile): # -* - encoding: utf-8 -*- from django import forms from models import Profile, FILEPROFILE from blog.models import Blog class PROFILEFORM (forms. MODELFORM): class Meta: model = Profile exclude = ("user", "thumbnail", "login", "friends", "friend_requests", "party") image = forms. FILEFIELD (max_length=200, label= «Иконка», required=False) new_password = forms. CHARFIELD (max_length=150, required=False, label="Новый пароль") confirm_password = forms. CHARFIELD (max_length=150, required=False, label="Подтвердить пароль") class BLOGFORM (forms. MODELFORM): class Meta: model = Blog exclude = ("number", "author", "date_of_publication", "image", "tags") thumbnail = forms. FILEFIELD (max_length=200, label= «Обложка новости», required=False) class FILEFORM (forms. MODELFORM): class Meta: model = FILEPROFILE exclude = ("user", "date", "file") doc = forms. FILEFIELD (max_length=200, label= «Файл», required=False)

Файл profile/views.py (содержит View описывающие функционал главной страницы пользователя и страницы поиска других пользователей): # -* - coding: utf-8 -*- from django.views.generic import LISTVIEW, DETAILVIEW, TEMPLATEVIEW, View from models import Profile from messages.models import Chat, Message from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render_to_response from django.contrib.auth.models import User from forms import PROFILEFORM, BLOGFORM, FILEFORM from django.views.generic.edit import FORMVIEW, CREATEVIEW, UPDATEVIEW from django.template import REQUESTCONTEXT from django import forms from django.db.models import Q from django.http import HTTPRESPONSE, HTTPRESPONSEREDIRECT import datetime from django.shortcuts import render_to_response, redirect from blog.models import Blog, Tags from django.core.urlresolvers import reverse from django.core.files.storage import default_storage from django.core.files.base import CONTENTFILE from filebrowser.base import FILEOBJECT def profile_return(request): return render_to_response ("profile/return.html", {}, context_instance=REQUESTCONTEXT(request)) class UPLOADVIEW(View): def post (self, request, *args, **kwargs): form = FILEFORM (request.POST, request.FILES) if form.is_valid: instance = form.save (commit=False) path = default_storage.save ("uploads/files/file.pdf", CONTENTFILE (self.request.FILES["doc"].read())) instance.file = FILEOBJECT(path) instance.user = Profile.objects.get (user = request.user) instance.save() return redirect (self.get_absolute_url()) def get_absolute_url(self): return reverse («profile», kwargs={}) class PROFILEVIEW(CREATEVIEW): template_name = «profile/profile.html» form_class = BLOGFORM def create_object_profile (self, pk): vector = User.objects.get (pk = pk) object = Profile() object.user_id = vector.id object.first_name = vector.first_name object.last_name = vector.last_name object.save() return object def get_context_data (self, **kwargs): context = super (PROFILEVIEW, self).get_context_data(**kwargs) if (self.request.user.is_authenticated()) and (Profile.objects.get (pk=self.request.user.id).party==True) and (not "pk" in self.kwargs): person_obj = self.request.user if Profile.objects.filter (pk=person_obj.id).count()==0: self.create_object_profile (person_obj.id) person_pk = person_obj.id elif self.request.user.is_authenticated() and "pk" in self.kwargs and self.kwargs["pk"]: person_pk = self.kwargs["pk"] if Profile.objects.filter (pk=person_pk).count()==0: self.create_object_profile (person_pk) person_obj = User.objects.get (pk = person_pk) else: self.template_name = «profile/error.html» context["ERRORTEXT"] = u "Вы не авторизированны» context["blog"] = Blog.objects.filter (author=person_obj.username).order_by ("-number",) context["person"] = Profile.objects.get (pk = person_pk) context ["form_file"] = FILEFORM return context def form_valid (self, form): arr_obj_tags=[] all_tags = self.request.POST["tag"].split (", " or ", ") for elem in all_tags: max_num_tags = Tags.objects.all().order_by ("-number") [0] obj_tag = Tags (number = max_num_tags.number 1, name = elem) obj_tag.save() arr_obj_tags.append (obj_tag) instance = form.save (commit=False) blogs = Blog.objects.filter (author=self.request.user.username).order_by ("-number") if blogs.count() > 0: instance.number = blogs[0].number 1 else: instance.number = 1 instance.author = self.request.user.username instance.date_of_publication = datetime.datetime.now() path = default_storage.save ("uploads/mar.jpg", CONTENTFILE (self.request.FILES["thumbnail"].read())) obj_image = FILEOBJECT(path).version_generate ("admin_list_blog") instance.image = obj_image instance.save() for elem in arr_obj_tags: instance.tags.add(elem) return redirect (self.get_absolute_url()) def get_absolute_url(self): return reverse («profile», kwargs={}) class PROFILESETTINGVIEW (TEMPLATEVIEW, View): template_name = «user_profile/user_settings.html» http_method_names = ["get", "post"] def post (self, request, *args, **kwargs): object = Profile.objects.get (user = request.user) form = PROFILEFORM (request.POST, request.FILES, instance = object) # A form bound to the POST data if form.is_valid(): form.save (commit = False) path = default_storage.save ("uploads/mar.jpg", CONTENTFILE (request.FILES["image"].read())) obj_image = FILEOBJECT(path).version_generate ("profile_photo") object.thumbnail = obj_image object.save()

# Новый пароль и Подверждение пароля new_password = request.POST ["new_password"] confirm_password = request.POST ["confirm_password"]

# Выбираем обьект User для изменеия пароля index = User.objects.get (pk = request.user.id) index.set_password (new_password) if new_password == «: mes = "Поле (новый пароль) пусто:" else: if confirm_password == new_password: mes = "Пароли совпадают!" index.save() else: mes = "Пароли не совпадают!" form.save() return redirect (reverse(«profile», kwargs={})) def get_context_data (self, **kwargs): context = super (PROFILESETTINGVIEW, self).get_context_data(**kwargs) if self.request.user.is_authenticated() and Profile.objects.get (pk=self.request.user.id).party==True: object = Profile.objects.get (user = self.request.user) context["object"] = object user_id = self.request.user context["form"] = PROFILEFORM (instance = object) if not Profile.objects.filter (pk = user_id.id): person = Profile() person.pk = user_id.id person.user = user_id person.save() return context else: template_name = «profile/error.html» context["ERRORTEXT"] = u "Вы не авторизированны» return context

@csrf_exempt def search_person(request): ERROR = None if request.user.is_authenticated() and Profile.objects.get (pk=request.user.id).party==True: class CONTACTFORM (forms. Form): last_name = forms. CHARFIELD (max_length=150, required=False) first_name = forms. CHARFIELD (max_length=150, required=False) user = forms. CHARFIELD (max_length=150, required=False) midlle_name = forms. CHARFIELD (max_length=150, required=False) current_user = request.user.get_profile if request.method == "POST": form = CONTACTFORM (request.POST) params = [] if form.is_valid(): last_name = form.cleaned_data ["last_name"] first_name = form.cleaned_data ["first_name"] midlle_name = form.cleaned_data ["midlle_name"] user = form.cleaned_data["user"] kargs = {"last_name__icontains":last_name} params.append (apply(Q, (), kargs)) params.append (Q(first_name__icontains = first_name)) params.append (Q(midlle_name__icontains = midlle_name)) params.append (Q(user__username__icontains = user)) search_result = Profile.objects.filter(*params) context = {"form": form, "search_result": search_result, "User":current_user} else: form = CONTACTFORM() context = {"form":form, "User":current_user} return render_to_response ("friends/search_person.html", context, context_instance=REQUESTCONTEXT(request)) else: return render_to_response («friends/error.html», {"ERRORTEXT": u» Вы не авторизированны»}) def add_person (request, id): obj = Profile.objects.get (user = id) user = Profile.objects.get (user = request.user.get_profile) user.friends.add(obj) obj.friend_requests.add(user) return HTTPRESPONSEREDIRECT ("/profile/friends/all/") def del_person (request, id): obj = Profile.objects.get (user = id) user = Profile.objects.get (user = request.user.get_profile) user.friends.remove(obj) return HTTPRESPONSEREDIRECT ("/profile/friends/all/") def accept_friend (request, objid): obj = Profile.objects.get (user= request.user.get_profile) obj_friend = Profile.objects.get (user = objid) obj.friends.add (obj_friend) obj.friend_requests.remove (obj_friend) return HTTPRESPONSEREDIRECT ("/profile/friends/all/") def reject_friend (request, objid): obj = Profile.objects.get (user = request.user.get_profile) obj_friend = Profile.objects.get (user = objid) obj.friend_requests.remove (obj_friend) return HTTPRESPONSEREDIRECT ("/profile/friends/all/")

@csrf_exempt def my_friends(request): ERROR = None if request.user.is_authenticated() and Profile.objects.get (pk=request.user.id).party==True: friends = User.objects.all() if request.method == "POST": pass context = {"friends": friends} return render_to_response ("friends/choice_friend.html", context, context_instance=REQUESTCONTEXT(request)) else: # если не залогинен

# хорошо бы сделать из этой проверки декоратор, чтоб всюду ее не тоскать за собой return render_to_response («friends/error.html», {"ERRORTEXT": u» Вы не авторизированны»})

Приложение BLOG: Файл urls.py для приложения blog: from django.conf.urls import patterns, include, url from.views import BLOGLIST, ARTICLEMONTHARCHIVEVIEW, BLOGDETAIL, FILTERTAGSVIEW, BLOGSEARCHVIEW urlpatterns = patterns ("", url (r"^list/$", BLOGLIST.as_view(), name="blog_list"), url (r"^(? P\d{4})/(? P\d )/$", ARTICLEMONTHARCHIVEVIEW.as_view (month_format=" % m"), name= «archive_month_numeric»), url (r"^detail/(? P\d )/$", BLOGDETAIL.as_view(), name="blog_detail"), url (r"^filter/tag/(? P\d )/", FILTERTAGSVIEW.as_view(), name="filter_tags"), url (r"^search/$", BLOGSEARCHVIEW.as_view(), name="blog_search"), )

Файл models.py для приложения blog: # -* - coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from filebrowser.fields import FILEBROWSEFIELD from model_utils.fields import SPLITFIELD from model_utils.models import TIMESTAMPEDMODEL import datetime from django.db.models import permalink from django.core.urlresolvers import reverse class Tags (models. Model): number = models. INTEGERFIELD (u"Порядковый номер", blank=True, null=True) name = models. CHARFIELD (u"Название тега", max_length=500) def __unicode__(self): return u" % s"% (self.name) class Meta: verbose_name = u "Тег» verbose_name_plural = u "Теги» class Blog (models. Model): number = models. INTEGERFIELD (u «Порядкоый номер», blank=True, null=True) zagol = models. CHARFIELD (u «Заголовок», max_length=64, blank=True, null=True) author = models. CHARFIELD (u «Автор», max_length=200, blank=True) image = FILEBROWSEFIELD (u «Фото», max_length=200, directory="images/blog/", format="image", null=True, blank=True) date_of_publication = models. DATETIMEFIELD (verbose_name=u"Дата публикации новости", blank=True, null=True, default = datetime.datetime.now) text = SPLITFIELD (u"Текст", blank=True) tags = models. MANYTOMANYFIELD (Tags, verbose_name=u"Теги", blank=True) def __unicode__(self): return u" % s"% (self.zagol,) class Meta: verbose_name = u "Блог» verbose_name_plural = u "Блог» class Comment (models. Model): blog=models. FOREIGNKEY (Blog, verbose_name=u"От какого блога", related_name="link_blog", blank=True, null=True) author_name=models. CHARFIELD (u «Автор», max_length=120, blank=True) text=models. TEXTFIELD (u"Комментарий", blank=True) pub_date=models. DATETIMEFIELD (u"Дата публикации", default = datetime.datetime.now, blank=True) admin_comment=models. BOOLEANFIELD (u"Допущена администратором", default=False, blank=True) def __unicode__(self): return self.author_name def count_comment(self): return Comment.objects.filter (article=self.article).count() class Meta: verbose_name = u "Комментарий» verbose_name_plural = u "Комментарии» ordering=["pub_date",]

Файл admin.py для приложения blog: # -* - encoding: utf-8 -*- from django.contrib import admin from.models import Blog, Comment, Tags class BLOGADMIN (admin. MODELADMIN): list_display = ("number", "zagol",) list_display_links = ("number", "zagol",) list_filter = () readonly_fields = () ordering = ("number",) date_hierarchy="date_of_publication" class TAGSADMIN (admin. MODELADMIN): list_display = ("number", "name",) list_display_links = ("number", "name",) list_filter = () readonly_fields = () ordering = ("name",) class COMMENTADMIN (admin. MODELADMIN): list_display=("pub_date", "author_name",) search_fields=("text",) list_filter=("author_name",) date_hierarchy="pub_date" admin.site.register (Blog, BLOGADMIN) admin.site.register (Tags, TAGSADMIN) admin.site.register (Comment, COMMENTADMIN)

Файл forms.py для приложения blog: # -* - coding: utf-8 -*- from django import forms from registration.forms import REGISTRATIONFORMUNIQUEEMAIL from django.core.mail import send_mail from.models import Blog class REGISTRATIONFORMPROFILE(REGISTRATIONFORMUNIQUEEMAIL): requisites = forms. CHARFIELD (label = "Работа") class BLOGFORM (forms. Form): name = forms. CHARFIELD (max_length=150) email = forms. EMAILFIELD() message = forms. CHARFIELD (widget=forms. Textarea) def send_email (self, subject, message, from_email, recipient_list=["viktori2000@qip.ru"], fail_silently=False): return send_mail (subject, message, from_email, recipient_list, fail_silently)

Файл views.py для приложения blog: # -* - coding: utf-8 -*- from django.views.generic import LISTVIEW, DETAILVIEW, TEMPLATEVIEW from.models import Blog, Tags, Comment from django.contrib.auth.models import User from django.views.generic.edit import FORMVIEW, CREATEVIEW, UPDATEVIEW from django.forms import MODELFORM from django import forms from django.db.models import Q from django.contrib.auth.models import User import datetime from.forms import BLOGFORM from django.views.generic.edit import CREATEVIEW from django.views.generic.dates import MONTHARCHIVEVIEW from profile.models import Profile from django.shortcuts import redirect from django.core.urlresolvers import reverse class CREATENEWS(CREATEVIEW): model = Blog fields = ["number", "zagol", "author", "image", "date_of_publication", "text", "tags"] def get_context_data (self, **kwargs): if self.request.user.is_authenticated() and Profile.objects.get (pk=self.request.user.id).party==True: context = super (CREATENEWS, self).get_context_data(**kwargs) context["object"] = Profile.objects.get (pk = self.request.user.id) return context class BLOGLIST(LISTVIEW): model = Blog context_object_name = «blog» def get_context_data (self, **kwargs): context = super (BLOGLIST, self).get_context_data(**kwargs) if self.request.user.is_authenticated() and Profile.objects.get (pk=self.request.user.id).party==True: date_obj = [] for obj in Blog.objects.dates ("created", "month"): date_obj.append(obj) context["archives"] = date_obj context ["active_main_menu"]="main_blog" else: self.template_name = «profile/error.html» context["ERRORTEXT"] = u "Вы не авторизированны» return context class FILTERTAGSVIEW(DETAILVIEW): model = Blog template_name = «blog/blog_list.html» queryset = Blog.objects.all() def get_context_data (self, **kwargs): context = super (FILTERTAGSVIEW, self).get_context_data(**kwargs) if self.request.user.is_authenticated() and Profile.objects.get (pk=self.request.user.id).party==True: date_obj = [] for obj in Blog.objects.dates ("created", "month"): date_obj.append(obj) object = super (FILTERTAGSVIEW, self).get_object() context["blog"] = Blog.objects.filter (tags__pk = object.pk) context["archives"] = date_obj context ["active_main_menu"]="main_blog" return context class BLOGSEARCHVIEW(LISTVIEW): template_name = "blog/blog_list.html" model = Blog def get_context_data (self, **kwargs): context = super (BLOGSEARCHVIEW, self).get_context_data(**kwargs) if self.request.user.is_authenticated() and Profile.objects.get (pk=self.request.user.id).party==True: date_obj = [] for obj in Blog.objects.dates ("created", "month"): date_obj.append(obj) context["archives"] = date_obj context ["active_main_menu"]="main_blog" search_word = self.request.GET ["search_box"].lower() arr = [] arr.append (Blog.objects.filter (Q(zagol__icontains = search_word))) context["blog"]=Blog.objects.filter (Q(zagol__icontains = search_word)|Q (author__icontains = search_word)|Q (text__icontains = search_word)) return context class ARTICLEMONTHARCHIVEVIEW(MONTHARCHIVEVIEW): queryset = Blog.objects.all() date_field = «created» make_object_list = True allow_future = True def get_context_data (self, **kwargs): if self.request.user.is_authenticated() and Profile.objects.get (pk=self.request.user.id).party==True: context = super (ARTICLEMONTHARCHIVEVIEW, self).get_context_data(**kwargs) date_obj = [] for obj in Blog.objects.dates ("created", "month"): date_obj.append(obj) context["archives"] = date_obj context ["active_main_menu"]="main_blog" return context class BLOGDETAIL(CREATEVIEW): template_name = «blog/blog_detail.html» model = Comment exclude = ["article", "author_name", "pub_date", "admin_comment"] def get_context_data (self, **kwargs): if self.request.user.is_authenticated() and Profile.objects.get (pk=self.request.user.id).party==True: context = super (BLOGDETAIL, self).get_context_data(**kwargs) date_obj = [] for obj in Blog.objects.dates ("created", "month"): date_obj.append(obj) context["blog"] = Blog.objects.get (pk = self.kwargs["pk"]) context["archives"] = date_obj context ["active_main_menu"] = "main_blog" context["comments"] = Comment.objects.filter (article = context["blog"], admin_comment=True) return context def form_valid (self, form): instance = form.save (commit=False) instance.article = Blog.objects.get (pk=self.kwargs["pk"]) instance.author_name = self.request.user.username instance.pub_date = datetime.datetime.now() instance.save() return redirect (self.get_absolute_url()) def get_absolute_url(self): return reverse («blog_detail», kwargs={«pk»: self.kwargs["pk"]})

Приложение MESSAGE: Файл urls.py для приложения message: from django.conf.urls import patterns, include, url urlpatterns = patterns ("", url (r"^$", "messages.views.all_message"), url (r"^sendmessage/(? P[^/] )/$", "messages.views.send_message"), )

Файл admin.py для приложения message: from django.contrib import admin from.models import Message, Chat class MESSAGEADMIN (admin. MODELADMIN): list_display = ("recipient", "sender", "date", "title") ordering = ("recipient", "sender") list_filter = ("recipient", "sender") admin.site.register (Message, MESSAGEADMIN) class CHATADMIN (admin. MODELADMIN): list_display = ("person1", "person2") ordering = ("person1", "person2") list_filter = ("person1", "person2") admin.site.register (Chat, CHATADMIN)

Файл views.py для приложения message: # -* - coding: utf-8 -*- from.models import Message, Chat from profile.models import Profile from django.views.decorators.csrf import csrf_exempt from django.template import REQUESTCONTEXT # нужно чтобы передавать реквест в контекст from django.forms import MODELFORM from django.http import HTTPRESPONSE, HTTPRESPONSEREDIRECT from django import forms from django.db.models import Q from django.shortcuts import render_to_response, redirect from django.contrib.auth.models import User import datetime import time

@csrf_exempt def all_message(request): ERROR = None if request.user.is_authenticated() and Profile.objects.get (pk=request.user.id).party==True: i_am = User.objects.get (pk = request.user.id) temp4 = Q (person2 = i_am) temp5 = Q (person1 = i_am) all_friend = Chat.objects.filter (temp4 | temp5) i_am = User.objects.get (pk = request.user.id) messages = Message.objects.filter (recipient = i_am).filter (reader = False).count() image = all_friend context = {"all_friend":all_friend, "messages": messages, "image":image} return render_to_response ("friends/all_message.html", context, context_instance=REQUESTCONTEXT(request)) else: return render_to_response («friends/error.html», {"ERRORTEXT": u» Вы не авторизированны»})

@csrf_exempt def send_message (request, id): class MESSAGEFORM (forms. Form): title = forms. CHARFIELD (max_length=350, required=False) message = forms. CHARFIELD (max_length=350, required=False, widget=forms. Textarea) friend = User.objects.get (pk = id) i_am = User.objects.get (pk = request.user.id) temp1 = Q (recipient = friend) & Q (sender = i_am) temp2 = Q (recipient = i_am) & Q (sender = friend) temp3 = temp1 | temp2 temp4 = Q (person2 = i_am) & Q (person1 = friend) temp5 = Q (person1 = i_am) & Q (person2 = friend) if len (Chat.objects.filter (temp4 | temp5)) == 0: chat = Chat() chat.person1 = i_am chat.person2 = friend chat.save() else: pass if request.method == "POST": all_message = Message.objects.filter(temp3).order_by("date") chat_obj = Chat.objects.get (temp4 | temp5) form = MESSAGEFORM (request.POST) if form.is_valid(): title = form.cleaned_data["title"] message = form.cleaned_data["message"] send_message = Message() send_message.recipient = friend send_message.sender = i_am send_message.date = datetime.datetime.now() send_message.title = title send_message.message = message send_message.reader = False send_message.save() chat_obj.messages.add (send_message) chat_obj.save() return redirect ("/message/sendmessage/" str(id) "/") else: all_message = Message.objects.filter(temp3).order_by("date") [0:1] temp4 = Q (person2 = i_am) & Q (person1 = friend) temp5 = Q (person1 = i_am) & Q (person2 = friend) person_type = Chat.objects.filter (temp4 | temp5) form = MESSAGEFORM() send = Message.objects.filter(temp2) for elem in send: if not elem.reader: elem.reader=True elem.save() context = {"form":form, "friend": friend, "all_message": all_message} return render_to_response ("friends/send_message.html", context, context_instance=REQUESTCONTEXT(request))

Приложение В

ККМОО «Молодежная лига развития национальных культур Кубани»

350000, г. Краснодар, ул. Красноармейская 53.

ИНН: 2310023918

КПП: 231001001

Счет №407038108000000000019

Банк: АО «Юг-Инвест банк», г. Краснодар

БИК 040349966

Счет №: 30101810600000000966

Код по ОКОНХ 98400

Код по ОКПО 39744165

Приложение №1 к договору № ________ от «__» ______ 2012 г.

Техническое задание для создания программной и визуальной части сайта: 1. Разработка дизайна для графической части сайта.

2. Разработка логотипа в векторном формате.

3. Создание программного обеспечения на языке программирования Python, в среде Django.

4. Создание социального раздела для общения между участниками «Клубов интернациональной дружбы».

5. Размещение файлов в сети интернет для отображения текстовой и графической информации в сети интернет, с возможностью вывода информации из базы данных и редактирования содержимого базы данных

6. Создание раздела для вновь созданных и создаваемых «Клубов интернациональной дружбы», в который можно будет добавлять текстовую, графическую и видео информацию, в том числе на английском языке.

Правообладатель __________________

Приобретатель _______________

Размещено на

Вы можете ЗАГРУЗИТЬ и ПОВЫСИТЬ уникальность
своей работы


Новые загруженные работы

Дисциплины научных работ





Хотите, перезвоним вам?