예제 #1
0
def account_subscribe(request, username):
    try:
        obj1 = SubscribeVacancy.activs.filter(user=request.user)[0]
    except:
        form1 = None
    else:
        form1 = AddVacancySubscribeForm(request.POST or None, instance=obj1)
        if form1.is_valid() and 'AddVacancySubscribeForm' in request.POST:
            form1.save()
            messages.add_message(request, messages.SUCCESS,
                                 u'Подписка на вакансии успешно сохранена.')
            return HttpResponseReload(request)

    try:
        obj2 = SubscribeResume.activs.filter(user=request.user)[0]
    except:
        form2 = None
    else:
        form2 = AddResumeSubscribeForm(request.POST or None, instance=obj2)
        if form2.is_valid() and 'AddResumeSubscribeForm' in request.POST:
            form2.save()
            messages.add_message(request, messages.SUCCESS,
                                 u'Подписка на резюме успешно сохранена.')
            return HttpResponseReload(request)

    return {
        'form1': form1,
        'form2': form2,
        'account_active': 4,
    }
예제 #2
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def group_subscribe_admin_del(request, group_id, user_id):
    u"""
    Отписать пользователя от группы.
    
    """

    group = get_object_or_404(Group, id=group_id, is_active=True)
    is_staff = group.is_staff(request.user)
    if is_staff:
        user = get_object_or_404(User, id=user_id)
        obj = group.get_user_subscribe(user)
        if obj:
            obj.delete()
            messages.add_message(
                request, messages.SUCCESS, u'Пользователь успешно отписан от '
                u'конференции.')
        else:
            messages.add_message(
                request, messages.WARNING, u'Пользователь не является '
                u'участником конференции.')
    else:
        messages.add_message(request, messages.ERROR,
                             u'У вас недостаточно прав.')

    return HttpResponseReload(request)
예제 #3
0
파일: admin.py 프로젝트: boogiiieee/Iskcon
    def group_delete_email(self, request, id, form_url=''):
        u"""
        Удалить e-mail на почтовом сервере.
        
        """
        if not self.has_change_permission(request):
            raise PermissionDenied

        obj = get_object_or_None(self.queryset(request), pk=id)

        if obj and obj.is_has_server_email():
            if not obj.is_external_email():
                delete_email(obj.get_server_email_login())

            Mailbox.objects.filter(
                name=obj.get_server_email_title(), ).update(active=False)

            obj.server_email_login = u''
            obj.server_email_passw = u''
            obj.server_email_domain = u''
            obj.save()

        messages.success(request,
                         u'E-mail на почтовом сервере успешно удален.')
        return HttpResponseReload(request)
예제 #4
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def group_subscribe_admin_cancel(request, group_id, user_id):
    u"""
    Отклонить заявку на вступление
    
    """

    group = get_object_or_404(Group, id=group_id, is_active=True)
    is_staff = group.is_staff(request.user)
    if is_staff:
        user = get_object_or_404(User, id=user_id)
        req = group.is_request_in_group(user)
        if req:
            req.delete()
            messages.add_message(request, messages.SUCCESS,
                                 u'Заявка пользователя успешно '
                                 u'отклонена.')
        else:
            messages.add_message(
                request, messages.WARNING, u'Не найдена заявка пользователя '
                u'на вступление.')
    else:
        messages.add_message(request, messages.ERROR,
                             u'У вас недостаточно прав.')

    return HttpResponseReload(request)
예제 #5
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def group_subscribe_admin(request, group_id, user_id):
    u"""
    Подписать пользователя, подавшего заявку.
    
    """

    group = get_object_or_404(Group, id=group_id, is_active=True)
    is_staff = group.is_staff(request.user)
    if is_staff:
        user = get_object_or_404(User, id=user_id)
        req = group.is_request_in_group(user)
        if req:
            req.is_active = True
            req.save()
            messages.add_message(
                request, messages.SUCCESS, u'Пользователь успешно добавлен в '
                u'конференцию.')
        else:
            messages.add_message(
                request, messages.WARNING, u'Не найдена заявка пользователя '
                u'на вступление.')
    else:
        messages.add_message(request, messages.ERROR,
                             u'У вас недостаточно прав.')

    return HttpResponseReload(request)
예제 #6
0
def vacancy_subscribe_add(request):
    obj = SubscribeVacancy(user=request.user, city=request.location)
    form = AddVacancySubscribeForm(request.POST or None, instance=obj)
    if form.is_valid():
        if SubscribeVacancy.objects.filter(user=request.user).count():
            messages.add_message(
                request, messages.WARNING,
                u'Вы можете добавить не более одной подписки на вакансии.')
            return HttpResponseReload(request)
        else:
            if not request.user.email:
                messages.add_message(
                    request, messages.WARNING,
                    u'Чтобы получать уведомления вам необходимо заполнить поле "e-mail" в разделе "Профиль".'
                )

            form.save()
            messages.add_message(
                request, messages.SUCCESS,
                u'Подписка на вакансии успешно добавлена на 30 дней.')

            return HttpResponseRedirect(
                reverse('account_subscribe',
                        args=[],
                        kwargs={'username': request.user.username}))

    return {
        'form': form,
        'account_active': 4,
    }
예제 #7
0
def mark_geolocation_error(request, object_id):
    addr = get_object_or_404(DeliveryAddress, pk=object_id)
    if addr.user == request.user:
        addr.geolocation_error = True
        addr.perform_geolocation = False
        addr.save()
        messages.add_message(request, messages.INFO,
                             _('Thank you, we will try to correct this.'))
    return HttpResponseReload(request)
예제 #8
0
def email_link(request):
    if request.method == 'POST':
        form = request.user.uiform_set.get(pk=request.POST['pk'])
        send_mail(
            '%s has shared a UI Form with you!' % request.user,
            '%s has shared a UI Form with you! You can view the form here: %s'
            % (request.user, form.get_public_url), '*****@*****.**',
            [request.POST['email']])
        return HttpResponseReload()
예제 #9
0
def account_profile(request, username):
    form1 = ProfileForm(request.POST or None, instance=request.user)
    if form1.is_valid():
        form1.save()
        messages.add_message(request, messages.SUCCESS, 'Данные сохранены.')
        return HttpResponseReload(request)

    form2 = PasswordChangeForm(request.user)

    return {
        'form1': form1,
        'form2': form2,
        'account_active': 1,
    }
예제 #10
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def admin_moderate_ok(request, msg_id):
    u"""
    Модерация. Одобрить сообщение.
    
    """
    msg = get_object_or_404(Message, id=msg_id)
    if (msg.group
            and msg.group.is_staff(request.user)) or request.user.is_superuser:
        msg.is_moderate = True
        msg.save()
        messages.add_message(request, messages.SUCCESS, 'Сообщение одобрено.')
    else:
        raise Http404()

    return HttpResponseReload(request)
예제 #11
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def admin_contact_del(request, req_id):
    u"""
    Удалить запрос пользователя
    
    """
    req = get_object_or_404(MessageRequest, id=req_id)
    if (req.group
            and req.group.is_staff(request.user)) or request.user.is_superuser:
        req.delete()
        messages.add_message(request, messages.SUCCESS, u'Сообщение успешно '
                             u'удалено.')
    else:
        raise Http404()

    return HttpResponseReload(request)
예제 #12
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def group_subscribe_del(request, group_id):
    u"""
    Отписаться от группы.
    
    """

    obj = get_object_or_404(GroupUserRel,
                            group_id=group_id,
                            user=request.user,
                            is_active=True)
    obj.delete()

    messages.add_message(request, messages.SUCCESS,
                         u'Вы успешно отписались от конференции.')

    return HttpResponseReload(request)
예제 #13
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def group_subscribe_frozen(request, group_id):
    u"""
    Заморозить группу.
    
    """

    obj = get_object_or_404(GroupUserRel,
                            group_id=group_id,
                            user=request.user,
                            is_frozen=False,
                            is_active=True)
    obj.is_frozen = True
    obj.save()

    messages.add_message(request, messages.SUCCESS, u'Конференция заморожена.')

    return HttpResponseReload(request)
예제 #14
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def group_subscribe(request, group_id):
    u"""
    Подписаться или создать заявку на ступление в группу.
    
    """

    obj = get_object_or_404(Group, id=group_id, is_active=True)
    is_in_group = obj.is_in_group(request.user)

    if not is_in_group and not obj.has_perm_go_into_group():
        raise Http404()

    obj_rel, create = GroupUserRel.objects.get_or_create(group=obj,
                                                         user=request.user)
    if not create:
        if obj_rel.is_active:
            messages.add_message(
                request, messages.INFO, u'Вы уже являетесь участником '
                u'конференции.')
        else:
            messages.add_message(
                request, messages.INFO, u'Вы уже отправляли заявку на '
                u'вступление.')
    else:
        if obj.is_public():
            messages.add_message(request, messages.SUCCESS,
                                 u'Вы успешно вступили в '
                                 u'конференцию.')
        else:
            obj_rel.is_active = False
            obj_rel.save()
            messages.add_message(request, messages.SUCCESS,
                                 u'Заявка на вступление отправлена.')

            MessageRequest.objects.create(
                group=obj,
                user=request.user,
                theme=u'Заявка на вступление в конференцию',
                text=u'Пользователь %s подал заявку на вступление в '
                u'конференцию "%s".' % (
                    request.user.get_full_name()
                    if request.user.get_full_name() else request.user.username,
                    obj.get_title(),
                ))

    return HttpResponseReload(request)
예제 #15
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def item_edit(request,
              obj,
              Form,
              template_name,
              Formset=None,
              extra_context={},
              redirect_url=None):
    form = Form(request.POST or None, request.FILES or None, instance=obj)
    formset = None
    if not Formset is None:
        formset = Formset(request.POST or None,
                          request.FILES or None,
                          instance=obj)

    if form.is_valid():
        save = False

        if formset:
            if formset.is_valid():
                form.save()
                formset.save()
                save = True
        else:
            form.save()
            save = True

        if save:
            messages.add_message(request, messages.SUCCESS,
                                 u'Запись сохранена.')

            if redirect_url:
                return HttpResponseRedirect(redirect_url)
            else:
                return HttpResponseReload(request)

    c = RequestContext(request, {'obj': obj, 'form': form, 'formset': formset})

    if extra_context:
        for key, value in extra_context.items():
            c[key] = value

    t = loader.get_template(template_name)
    return HttpResponse(t.render(c))
예제 #16
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def admin_moderate_del(request, msg_id):
    u"""
    Модерация. Удалить сообщение.
    
    """

    msg = get_object_or_404(Message, id=msg_id)

    if request.method == 'POST':
        form = CauseForm(request.POST)
        if form.is_valid():
            if (msg.group and msg.group.is_staff(
                    request.user)) or request.user.is_superuser:
                msg.delete()
                messages.add_message(request, messages.SUCCESS,
                                     'Сообщение удалено.')

                domain = Site.objects.get_current().domain
                email_data = msg.group.get_email_data()

                text = form.cleaned_data['text']
                if not text:
                    text = u'Не указана.'

                threading_simple_send_mail(
                    'mail/conference_failure.html',
                    u'Отказано в публикации сообщения',
                    [msg.user.email],
                    {
                        'message': u'Причина отказа: %s' % text,
                        'domain': domain,
                        'sign': email_data['sign']
                    },
                    from_email=email_data['from_email'],
                    connection=email_data['backend'],
                    sender_name=msg.group.get_title(),
                )
            else:
                raise Http404()

            return HttpResponseReload(request)
    raise Http404()
예제 #17
0
파일: views.py 프로젝트: boogiiieee/Iskcon
def ban_del(request, group_id, user_id):
    u"""
    Удалить бан пользователя.
    
    """
    group = get_object_or_404(Group, id=group_id, is_active=True)
    is_staff = group.is_staff(request.user)
    if is_staff:
        user = get_object_or_404(User, id=user_id, is_active=True)
        if group.ban(user, datetime.datetime.now()):
            messages.add_message(request, messages.SUCCESS,
                                 u'Пользователь успешно '
                                 u'разблокирован.')
        else:
            messages.add_message(request, messages.WARNING,
                                 u'Пользователь не заблокирован.')
    else:
        messages.add_message(request, messages.ERROR,
                             u'У вас недостаточно прав.')
    return HttpResponseReload(request)
예제 #18
0
def account_vacancy_item(request, username, id):
    try:
        obj = Vacancy.activs.get(user=request.user, id=id)
    except:
        raise Http404()

    form = AddVacancyForm(request.POST or None,
                          request.FILES or None,
                          instance=obj)
    if form.is_valid():
        form.save()
        messages.add_message(
            request, messages.SUCCESS,
            u'Вакансия успешно сохранена. Изменения появятся на сайте в течение трех часов.'
        )
        return HttpResponseReload(request)

    return {
        'form': form,
        'account_active': 2,
    }
예제 #19
0
def account_resume_item(request, username, id):
    try:
        obj = Resume.activs.get(user=request.user, id=id)
    except:
        raise Http404()

    form = AddResumeForm(request.POST or None,
                         request.FILES or None,
                         instance=obj)
    if form.is_valid():
        form.save()
        messages.add_message(
            request, messages.SUCCESS,
            u'Резюме успешно сохранено. Изменения появятся на сайте в течение трех часов.'
        )
        return HttpResponseReload(request)

    return {
        'form': form,
        'account_active': 3,
        'search': SearchMinForm(type_search=TYPE_SEARCH[1][0]),
    }
예제 #20
0
파일: admin.py 프로젝트: boogiiieee/Iskcon
    def group_create_email(self, request, id, form_url=''):
        u"""
        Зарегистрировать e-mail на почтовом сервере.
        
        """
        if not self.has_change_permission(request):
            raise PermissionDenied

        obj = get_object_or_404(self.queryset(request), pk=id)

        if request.method == 'POST':
            form = self.group_create_email_form(request.POST, instance=obj)
            if form.is_valid():
                cd = form.cleaned_data

                protocol = cd.get('server_email_protocol')
                login = cd.get('server_email_login')
                passw = cd.get('server_email_passw')
                domain = cd.get('server_email_domain')
                port = cd.get('server_email_port')

                #Удаляем старый e-mail.
                if obj.is_has_server_email():
                    if not obj.is_external_email():
                        delete_email(obj.get_server_email_login())

                    Mailbox.objects.filter(
                        name=obj.get_server_email_title(), ).update(
                            active=False)

                    obj.server_email_login = u''
                    obj.server_email_passw = u''
                    obj.server_email_domain = u''
                    obj.save()

                obj.server_email_protocol = protocol
                obj.server_email_login = login
                obj.server_email_passw = passw
                obj.server_email_domain = domain
                obj.server_email_port = port

                if domain == MAIL_SERVER:
                    cursor = connections[DB_MAIL_NAME].cursor()
                    error_msg = u'Произошла ошибка. Повторите попытку позже.'

                    try:
                        cursor.execute(
                            "SELECT COUNT(*) FROM `mailbox` WHERE `username`=%s;",
                            [
                                login,
                            ])
                        row = cursor.fetchone()[0] or 0
                    except:
                        messages.error(request, error_msg)
                        return HttpResponseReload(request)

                    if row != 0 or login in MAIL_EXLUDE_LOGIN:
                        messages.error(
                            request, u'Пользователь с таким именем уже '
                            u'зарегистрирован.')
                        return HttpResponseReload(request)

                    passw = randstring(10)
                    hash_passwd = os.popen("openssl passwd -1 %s" %
                                           passw).read().strip()  #Только Linux

                    #Регистрируем новый e-mail.
                    try:
                        cursor.execute(
                            "INSERT INTO `mailbox` (username, password, name, domain, maildir) VALUES (%s, %s, %s, %s, %s);",
                            [
                                login, hash_passwd,
                                login.split(u'@')[0], MAIL_DOMAIN,
                                u'%s/%s/' % (MAIL_DOMAIN, login.split(u'@')[0])
                            ])
                        cursor.execute(
                            "INSERT INTO `alias` (address, goto, domain, created, active) VALUES (%s, %s, %s, NOW(), 1);",
                            [login, login, MAIL_DOMAIN])
                        cursor.connection.commit()
                    except:
                        messages.error(request, error_msg)
                        return HttpResponseReload(request)

                    obj.server_email_passw = passw

                obj.save()

                box = Mailbox.objects.create(
                    name=obj.get_server_email_title(),
                    uri=u'%s,%s,%s,%s,%s' % (
                        obj.get_server_email_protocol(),
                        urllib.quote(obj.get_server_email_login()),
                        obj.get_server_email_passw(),
                        obj.get_server_email_domain(),
                        obj.get_server_email_port(),
                    ),
                )

                messages.success(request, u'E-mail успешно создан!')
                return HttpResponseRedirect('..')
        else:
            form = self.group_create_email_form(
                initial={
                    'server_email_protocol': PROTOCOL_SSL,
                    'server_email_domain': MAIL_SERVER,
                    'server_email_port': MAIL_PORT,
                })

        fieldsets = [(None, {'fields': form.base_fields.keys()})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'title': u'Регистрация E-mail для конференции: %s' % escape(obj),
            'adminForm': adminForm,
            'form_url': mark_safe(form_url),
            'form': form,
            'is_popup': '_popup' in request.REQUEST,
            'add': True,
            'change': False,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_absolute_url': False,
            'opts': self.model._meta,
            'original': obj,
            'save_as': False,
            'show_save': True,
            'MAIL_SERVER': MAIL_SERVER,
        }
        return TemplateResponse(request, [self.group_create_email_template],
                                context,
                                current_app=self.admin_site.name)
예제 #21
0
파일: views.py 프로젝트: lip365/ebagu0.2
def unfollow(request, category_name_url):

    unfollow(request.user, Category.objects.get(name=category_name_url))
    return HttpResponseReload(request)