예제 #1
0
파일: page.py 프로젝트: vden/TsoguNG
    def template_conf(self, request):
        import simplejson

        keys = ('tags', 'description', 'text', 'photo', 'signature', 'content',
                'links', 'files', 'comments')
        values = dict(photo=('block', 'albom', 'gallery'),
                      content=('with_date', 'without_date', 'with_image'))

        if request.method == 'POST':
            config = dict([
                (key, value) for key, value in request.POST.items()
                if key in keys and value in values.get(key, ('on', ))
            ])
            self.config()['template_conf'] = simplejson.dumps(config)
            raise Http302(self.get_absolute_url())
        else:
            if 'default' in request.GET:
                if 'template_conf' in self.config():
                    del self.config()['template_conf']
                raise Http302(self.get_absolute_url())
            else:
                try:
                    config = simplejson.loads(self.config()['template_conf'])
                except:
                    config = self.template_default_conf

        return {'config': config, 'object': self}
예제 #2
0
파일: views.py 프로젝트: vden/TsoguNG
def student_status_confirm(request):
    import urllib
    import simplejson as json
    from hashlib import md5

    import settings

    user = request.user
    if not user.is_authenticated():
        raise Http302('/login/')
    try:
        userprofile = user.get_profile()
    except:
        userprofile = Profile(user=user)
    login = request.POST.get('login', '')
    password = md5(request.POST.get('password',
                                    '').encode('utf-8')).hexdigest()
    params = "login=%s&password=%s" % (login.encode('utf-8'), password)
    result = urllib.urlopen(
        settings.EDUCON_URL,
        params).read() or u"Произошла досадная ошибка, попробуйте позже."
    try:
        userprofile.student_id = int(result)
        userprofile.save()
        return HttpResponse(u"Статус студента подтверждён, обновите профиль.",
                            mimetype="text/plain")
    except:
        return HttpResponse(content=result, mimetype="text/plain", status=500)
예제 #3
0
def login(request):
    logged_in = False
    errors = False
    if request.method == 'GET':
        frm = AuthenticationForm()
    else:
        frm = AuthenticationForm(data=request.POST)
        if frm.is_valid():
            djlogin(request, frm.get_user())
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            logged_in = True
            raise Http302(request.POST.get('next'))
        else:
            print "Errors: ", frm.errors
            errors = True

    # если у нас есть сохраненный путь -- переходим на него после логина
    # если логин с главной или пути нет -- переходим на рабочую зону
    next_page = request.GET.get(
        'next',
        request.session.has_key('old_request')
        and request.session['old_request']['path'] or "/")
    next_page = next_page in ["/", "/portal/logout/"
                              ] and "/portal/workspace/" or next_page

    return {
        'frm': frm,
        'logged_in': logged_in,
        'errors': errors,
        'next': next_page
    }
예제 #4
0
파일: poll.py 프로젝트: vden/TsoguNG
 def _edit(self, request):
     if request.method == 'POST':
         form = DefaultGeneralPollForm(request.POST, instance=self)
         if form.is_valid():
             form.save()
             raise Http302(self.get_absolute_url() + 'act/edit/')
     else:
         form = DefaultGeneralPollForm(instance=self)
     return {'object': self, 'form': form}
예제 #5
0
파일: videofile.py 프로젝트: vden/TsoguNG
	def edit(self, request):
		if request.method == 'POST':
			form = DefaultGeneralVideoFileForm(request.POST, request.FILES, instance=self)
			if form.is_valid():
				form.save()
				raise Http302(self.get_absolute_url())
		else:
			form = DefaultGeneralVideoFileForm(instance=self)
		return {'object':self, 'form':form}
예제 #6
0
파일: views.py 프로젝트: vden/TsoguNG
def update(request):
    context = {}
    user = request.user
    if not user.is_authenticated():
        raise Http302('/login/')
    try:
        context['profile'] = user.get_profile()
    except:
        context['profile'] = None
    return context
예제 #7
0
파일: page.py 프로젝트: vden/TsoguNG
 def _edit(self, request):
     if request.method == 'POST':
         form = DefaultGeneralPageForm(request.POST,
                                       instance=self._drop_status())
         if form.is_valid():
             form.save()
             self._update_history(request)
             raise Http302(self.get_absolute_url())
     else:
         form = DefaultGeneralPageForm(instance=self)
     return {'object': self, 'form': form}
예제 #8
0
def registration(request):
	if 'POST' == request.method:
		form = RegistrationForm(request.POST)
	else:
		form = RegistrationForm()
	if form.is_valid():
		form.save()
		user = authenticate(username=request.POST['username'], password=request.POST['password'])
		login(request, user)
		raise Http302('/portal/workspace/?portal_message=account_complete')
	return {'form': form}
예제 #9
0
파일: views.py 프로젝트: vden/TsoguNG
def edit(request):
    from forms import ProfileForm
    context = {}
    user = request.user
    if not user.is_authenticated():
        raise Http302('/login/')
    try:
        profile = user.get_profile()
    except:
        profile = None
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user.last_name = data['last_name']
            user.first_name = data['first_name']

            drop_email = user.email != data['email']

            user.email = data['email']
            user.save()
            if data['middle_name'] or data['subscription']:
                if profile:
                    profile.middle_name = data['middle_name']
                    profile.subscription = data['subscription']
                else:
                    profile = Profile(user=user,
                                      middle_name=data['middle_name'],
                                      subscription=data['subscription'])

                if drop_email:
                    profile.is_email_confirmed = False

                profile.save()
            return u'Данные успешно сохранены'
        context['form'] = form
    else:
        data = {
            'last_name': user.last_name,
            'first_name': user.first_name,
            'email': user.email
        }
        if profile:
            data['middle_name'] = profile.middle_name
            data['subscription'] = profile.subscription
        context['form'] = ProfileForm(initial=data)
    context['profile'] = profile
    return template_loader.get_template("profile/edit.html").render(
        RequestContext(request, context))
예제 #10
0
파일: views.py 프로젝트: vden/TsoguNG
def dispatcher(request, path_info, action, redirect=False):
    if redirect:
        raise Http302(path_info)

    if path_info:
        obj = request.main_object
        objectaction = REGISTRUM['types'][obj.get_class_name()]['actions'].get(
            action)
        if not objectaction:
            raise Http404(
                u'Запрашиваемый action (%s) в системе не зарегистрирован.' %
                action)
        func = getattr(obj, action)

    else:
        act = REGISTRUM['actions'].get('portal_%s' % action)
        if not act:
            raise Http404(
                u'Запрашиваемый action (%s) в системе не зарегистрирован.' %
                action)
        func = act['function']
    return func and func(request=request) or HttpResponse(u'PASS')
예제 #11
0
파일: views.py 프로젝트: vden/TsoguNG
def send_email_confirm(request):
    from django.core.mail import send_mail
    from uuid import uuid5, UUID
    import settings

    if not request.user.is_authenticated():
        raise Http302('/login/')

    code = uuid5(UUID(settings.UUID_NAMESPACE_FOR_EMAIL_CONFIRM),
                 str(request.user.email))
    subj = u'[www.tsogu.ru] Подтверждение email'
    body = u'Доброго времени суток.\n\nПользователь %s отправил запрос на подтверждение электронной почты. Для подтверждения электронной почты на сайте ТюмГНГУ пройдите по ссылке:\nhttp://www.tsogu.ru/userprofile/email_confirm/%s/%s/\nЕсли данное письмо попало к Вам по ошибке - удалите его.\n\n---\nС уважением,\nАдминистрация портала www.tsogu.ru,\[email protected]' % (
        request.user.username, request.user.id, code)

    try:
        send_mail(subj,
                  body,
                  settings.DEFAULT_FROM_EMAIL, [request.user.email],
                  fail_silently=False)
        return u'Пароль подтверждения отправлен на электронную почту'
    except:
        return u'Произошел сбой при отправке почты. Повторите попытку позже или сообщите вебмастеру о сбое.'