예제 #1
0
def edit_post(request, id = '1'):
    template = "post/create_post.html"
    post = Post.objects.get(id=id)
    post_form = PostForm(instance = post)

    if not request.user.username == post.user.username:
        messages.error(request,"You can not edit posts by other users")
        return HttpResponseRedirect(reverse_lazy('post:create_post'))

    if request.method == "POST":
        if "post_button" in request.POST:   
            post_form = PostForm(instance = post, data=request.POST, files=request.FILES)
            if post_form.is_valid():
                post_form = post_form.save(commit=False)
                if post_form.content or post_form.image:
                    post_form.user = request.user
                    post_form.save()
                    post_form = PostForm(instance = post)
                    messages.success(request, "Post Successfully Edited")
                else:
                    post_form = PostForm()
                    messages.error(request, "Empty posts are restricted")                    
        elif "remove_post_button" in request.POST:
            user = post.user
            post.delete()
            messages.success(request, "Post successfully deleted")
            return HttpResponseRedirect(reverse_lazy('account:profile',kwargs={'username':user.username}))

    context = {
        'post_form':post_form,
        'page_title':'Edit Post',
        'post': post,
    }
    return render(request, template, context)
예제 #2
0
def domain_url(route, **kwargs):
    """Helps with switching between main site and client sites.

    Because client sites and the main site use two separate URLconfs, named
    routes in one can't be resolved in the other, so need to load appropriate
    URLconf (either client or admin URLconf) if linking across sites.

    Examples:
        To get the video creation form in the admin panel for a client site:
            <a href="{% domain_url admin_url_for_site=website_id %}></a>
        where website_id = get_current_site(self.request).id

        To link to a client site from a URL in the admin URLconf:
            <a href="{% domain_url client_site=website_id %}></a>
        where website_id is the site ID of some client site.
    """
    if 'admin_url_for_site' not in kwargs and 'client_site' not in kwargs:
        raise ValueError('Pass in either admin_url_for_site or client_site parameter.')

    if 'admin_url_for_site' in kwargs and 'client_site' in kwargs:
        raise ValueError('admin_url_for_site and client_site named parameters are mutually exclusive.')

    if 'client_site' in kwargs:
        # Switches to the client site from the admin site.
        site = Site.objects.get(pk=kwargs['client_site'])
        uri = reverse_lazy(route, urlconf=ROOT_URLCONF)
    else:
        # Switches to the admin site from a client site since the admin site
        # requires website_id in its URL.
        site = Site.objects.get(domain=ADMIN_DOMAIN)
        uri = reverse_lazy(route, urlconf=ADMIN_URLCONF, kwargs={'website_id': kwargs['admin_url_for_site']})

    absolute_url = 'http://%s%s' % (site.domain, uri)

    return absolute_url
예제 #3
0
파일: views.py 프로젝트: rcerqueira11/Shsa
    def post(self,request,*args,**kwargs):
        
        username = request.POST['usuario']
        password = request.POST['password']
        user  = authenticate(username=username,password=password)
        if user is not None:
            
            if user.is_active:
                request.session['usuario'] = user.id #sets the exp. value of the session 
                login(request, user) #the user is now logged in
            # if request.user.is_authenticated():
            #     mensaje = u'¡Ha cerrado sesión correctamente!'
            #     messages.info(self.request, mensaje)
            # return redirect(reverse_lazy('login'))
                # return render(request, 'rcs/dashboard.html',context)
                return redirect(reverse_lazy('dashboard'))
            else:
                return redirect(reverse_lazy('login'))

        else:
            mensaje_error= 'El usuario o contraseña es invalido.'
            errors = {
                'mensaje_error': mensaje_error,
            }
            return render(request, 'index.html', errors)
예제 #4
0
def teacher_classes(request):
    teacher = request.user.new_teacher
    requests = Student.objects.filter(pending_class_request__teacher=teacher)

    if not teacher.school:
        return HttpResponseRedirect(reverse_lazy("onboarding-organisation"))

    if request.method == "POST":
        form = ClassCreationForm(request.POST)
        if form.is_valid():
            created_class = create_class(form, teacher)
            messages.success(
                request,
                "The class '{className}' has been created successfully.".format(
                    className=created_class.name
                ),
            )
            return HttpResponseRedirect(
                reverse_lazy(
                    "onboarding-class",
                    kwargs={"access_code": created_class.access_code},
                )
            )
    else:
        form = ClassCreationForm(initial={"classmate_progress": "False"})

    classes = Class.objects.filter(teacher=teacher)

    return render(
        request,
        "portal/teach/onboarding_classes.html",
        {"form": form, "classes": classes, "requests": requests},
    )
    def get(self, request, *args, **kwargs):
        physical_exam = self.model.objects.get(pk=kwargs.get('id'))
        next_exam_record = self.model.objects.filter(medical_record=physical_exam.medical_record,
                                                     id__gt=physical_exam.id).order_by('id').first()
        prev_exam_record = self.model.objects.filter(medical_record=physical_exam.medical_record,
                                                     id__lt=physical_exam.id).order_by('-id').first()

        keys = list(PhysicalExamKey.objects.all().order_by('id'))
        key_list = []
        detail_list = []
        link_dict = {}

        if next_exam_record is not None:
            link_dict.update(
                {'next_link': reverse_lazy(PHYSICAL_EXAM_PROFILE_PAGE_NAME, kwargs={'id': str(next_exam_record.id)})})
        if prev_exam_record is not None:
            link_dict.update(
                {'prev_link': reverse_lazy(PHYSICAL_EXAM_PROFILE_PAGE_NAME, kwargs={'id': str(prev_exam_record.id)})})

        for key in keys:
            key_list.append(key.display_value)
            value_list = []
            values = list(
                PhysicalExamDetail.objects.filter(physical_exam=physical_exam, key=key))
            for value in values:
                value_list.append(value.str_value)
            detail_list.append(value_list)

        key_detail_zip = zip(key_list, detail_list)

        return render(request, self.template_name,
                      {'physical_exam': physical_exam, 'patient': physical_exam.medical_record.patient,
                       'key_detail_zip': key_detail_zip, 'link_dict': link_dict})
예제 #6
0
파일: views.py 프로젝트: randytung/bezzist
 def get_redirect_url(self, *args, **kwargs):
     try:
         confirmation = UserConfirmation.objects.get(confirmation_code=kwargs.get('code'))
         confirmation.confirm_user()
         return reverse_lazy('landing_view')
     except:
         return reverse_lazy('confirmation_fail_view')
예제 #7
0
파일: views.py 프로젝트: jmennen/group5
def add_users_to_circle(request, circle_id):
    user_ids = request.POST.getlist("add_members")
    for user_id in user_ids:
        try:
            follow_user = Profile.objects.get(pk=user_id)
        except ObjectDoesNotExist:
            # user to follow does not exist
            messages.error(request, "User mit id %s existiert nicht" % user_id)
            return HttpResponseRedirect(reverse_lazy('home'))
        try:
            my_profile = Profile.objects.get(pk=request.user)
        except ObjectDoesNotExist:
            # logged in user has no profile
            return HttpResponseRedirect(reverse_lazy('home'))
        try:
            chosen_circle = Circle.objects.get(pk=circle_id)
        except ObjectDoesNotExist:
            # circle does not exist
            messages.error(request, "Kreis existiert nicht")
            return HttpResponseRedirect(reverse_lazy('home'))
        try:
            check_follow_status = follow_user.follows.get(pk=request.user)
        except ObjectDoesNotExist:
            # user is not a follower
            messages.error(request, "Der User ist kein Follower")
            return HttpResponseRedirect(reverse_lazy('home'))
        chosen_circle.members.add(follow_user.user)
    messages.success(request, "User wurden dem Kreis hinzugefuegt")
    return HttpResponseRedirect(reverse_lazy("circle_details", args=(circle_id,)))
예제 #8
0
 def test_get_project(self):
     """tests get_project"""
     self._create_project('proj1', self.org.pk)
     other_org = Organization.objects.create(name='not my org')
     other_user = User.objects.create(
         username="******",
         email="*****@*****.**",
     )
     other_org.add_member(other_user)
     self._create_project('otherproj', other_org.pk, other_user)
     # standard case, should only see proj1, not other_proj
     self._set_role_level(ROLE_VIEWER)
     resp = self.client.get(
         reverse_lazy("projects:get_project"),
         {'organization_id': self.org.id, 'project_slug': 'proj1'},
         content_type='application/json',
     )
     self.assertDictEqual(
         json.loads(resp.content),
         {
             u'project': {
                 u'description': None,
                 u'id': json.loads(resp.content)['project']['id'],
                 u'is_compliance': False,
                 u'last_modified_by_id': self.user.pk,
                 u'name': u'proj1',
                 u'owner_id': self.user.pk,
                 u'slug': u'proj1',
                 u'status': 1,
                 u'super_organization_id': self.org.id
             },
             u'status': u'success'}
     )
     # test when user sends org id that the user is in, but a project in
     # a different org
     resp = self.client.get(
         reverse_lazy("projects:get_project"),
         {'organization_id': self.org.id, 'project_slug': 'otherproj'},
         content_type='application/json',
     )
     self.assertDictEqual(
         json.loads(resp.content),
         {
             'status': 'error',
             'message': 'Permission denied'
         }
     )
     # test for the case that a user does not belong to the org
     resp = self.client.get(
         reverse_lazy("projects:get_project"),
         {'organization_id': other_org.pk, 'project_slug': 'otherproj'},
         content_type='application/json',
     )
     self.assertDictEqual(
         json.loads(resp.content),
         {
             'status': 'error',
             'message': 'No relationship to organization'
         }
     )
예제 #9
0
    def test_get_projects_count(self):
        """tests get_projects_count"""
        self._create_project(name='proj_count', via_http=True)
        self._set_role_level(ROLE_VIEWER)

        # test standard case
        resp = self.client.get(
            reverse_lazy("projects:get_projects_count"),
            {'organization_id': self.org.id},
            content_type='application/json',
        )
        self.assertDictEqual(
            json.loads(resp.content),
            {
                'status': 'success',
                'projects_count': 1
            }
        )
        # test case where user is not in org
        other_org = Organization.objects.create(name='not my org')
        resp = self.client.get(
            reverse_lazy("projects:get_projects_count"),
            {'organization_id': other_org.id},
            content_type='application/json',
        )
        self.assertDictEqual(
            json.loads(resp.content),
            {
                'status': 'error',
                'message': 'No relationship to organization'
            }
        )
예제 #10
0
    def post(self, request, *args, **kwargs):
        CommitteeFormSet = modelformset_factory(Committee,
            form=CommitteeCreateForm)

        if 'form-TOTAL_FORMS' in request.POST:
            # It had a management form, so it was a formset; use formset logic.
            formset = CommitteeFormSet(request.POST)

            if formset.is_valid():
                formset.save()
                messages.add_message(request, messages.SUCCESS,
                    'Committee(s) created. You should reimport your data files'
                    'if you were trying to import potential appointments to '
                    'those committees.')
                return HttpResponseRedirect(reverse_lazy('data_ingest'))
            else:
                return self.render_to_response(
                    self.get_context_data(formset=formset))
        else:
            form = CommitteeCreateForm(request.POST)

            if form.is_valid():
                form.save()
                messages.add_message(request, messages.SUCCESS,
                    'Committee created. You should reimport your data files'
                    'if you were trying to import potential appointments to '
                    'those committees.')
                return HttpResponseRedirect(reverse_lazy('data_ingest'))
            else:
                return self.render_to_response(
                    self.get_context_data(form=form))
예제 #11
0
파일: views.py 프로젝트: Skaty/orbital
    def get_context_data(self, **kwargs):
        pref_instance, create = Preferences.objects.get_or_create(user=self.request.user)
        forms = [
            {
                'title': 'Update Preferences',
                'form': TimezonePreferenceForm(instance=pref_instance),
                'url': reverse_lazy('profiles:preferences-update')
            },
            {
                'title': 'Profile',
                'form': ProfileChangeForm(instance=self.request.user),
                'url': reverse_lazy('profiles:profile-update')
            }
        ]

        if self.request.user.has_usable_password():
            forms += [
                {
                    'title': 'Change Password',
                    'form': PasswordChangeForm(),
                    'url': reverse_lazy('profiles:password-update')
                }
            ]

        kwargs['forms'] = forms

        return super(PreferencesDisplay, self).get_context_data(**kwargs)
예제 #12
0
def Manage_Applications(request):
    # Manage Organization's Applications entry page

    account_model = get_user_model()
    access_field = settings.USERNAME_FIELD
    user = account_model.objects.get(**{access_field:request.user})

    org_name = user.organization

    if settings.DEBUG:
        print(settings.APPLICATION_TITLE,
              "in accounts.views.manage_account")
        print("with Organization Record:", org_name)

    if org_name == None:
        return HttpResponseRedirect(reverse_lazy('accounts:manage_account'))

    try:
        org = Organization.objects.get(name=org_name)
    except Organization.DoesNotExist:
        org = {}
        return HttpResponseRedirect(reverse_lazy("accounts:manage_account"))

    # get my Developer role
    try:
        my_dev = Developer.objects.get(member=user)
        my_role = my_dev.role
        if my_dev.role in ['1','2']:
            org_owner = True
        else:
            org_owner = False
    except Developer.DoesNotExist:
        my_dev = {}
        my_role = ""
        org_owner = False


    # Get the Applications for an Organization
    try:
        my_apps = BBApplication.objects.filter(organization=org_name).order_by('name')
    except BBApplication.DoesNotExist:
        my_apps = {}


    if settings.DEBUG:
        print("User:"******"Organization:", org, "[", org.name, "]")
        print("My_apps :", my_apps)
        print("Media is here:[ROOT]", settings.MEDIA_ROOT,
              "[URL]", settings.MEDIA_URL)

    context = {"user": user,
               "org": org,
               "org_owner": org_owner,
               "my_apps": my_apps,
               }

    # Using manage_applications template
    return render_to_response('appmgmt/manage_applications.html',
                              RequestContext(request, context, ))
예제 #13
0
파일: networks.py 프로젝트: bhuvi8/Plinth
def delete(request, uuid):
    """Handle deleting connections, showing a confirmation dialog first.

    On GET, display a confirmation page.
    On POST, delete the connection.
    """
    if request.method == 'POST':
        try:
            name = network.delete_connection(uuid)
            messages.success(request, _('Connection {name} deleted.')
                             .format(name=name))
        except network.ConnectionNotFound:
            messages.error(request, _('Failed to delete connection: '
                                      'Connection not found.'))

        return redirect(reverse_lazy('networks:index'))

    try:
        connection = network.get_connection(uuid)
        name = connection.get_id()
    except network.ConnectionNotFound:
        messages.error(request, _('Failed to delete connection: '
                                  'Connection not found.'))
        return redirect(reverse_lazy('networks:index'))

    return TemplateResponse(request, 'connections_delete.html',
                            {'title': _('Delete Connection'),
                             'subsubmenu': subsubmenu,
                             'name': name})
예제 #14
0
파일: views.py 프로젝트: neudesk/neucloud
 def activate(self):
     tenant = None
     if self.get_tenant_id():
         try:
             tenant = self.cli.tenants.get(self.get_tenant_id())
         except:
             self.result = """
             Invalid token, Token is not associated to any projects or tenants.
             Click <a href='%s'>here</a> to generate a new one.
             """ % reverse_lazy("request_activation")
         if tenant:
             if not tenant.enabled:
                 self.cli.tenants.update(tenant.id, enabled=True)
                 # users = self.cli.tenants.list_users(tenant)
                 # for u in users:
                 #     self.cli.users.update_enabled(u, True)
                 self.result = """
                 Congratulations,<br />
                 Your account is now activated.<br />
                 You may <a href='%s'>Sign in here</a>
                 """ % reverse_lazy("splash")
             else:
                 msg = """
                 Your account is already activated.
                 Please <a href='%s'>sign in</a>.
                 """ % reverse_lazy('splash')
                 self.result = mark_safe(msg)
     result = self.result
     return result
예제 #15
0
파일: views.py 프로젝트: mozillazg/mtum
def send(request, template_name='message/send.html', extra_context=None):
    if request.method == 'POST':
        form = SendForm(request.POST)
        if form.is_valid():
            sender = request.user
            recipient = form.cleaned_data['recipient']
            message = form.cleaned_data['message']
            reply_id = form.cleaned_data['reply_id']

            recipient = User.objects.get(username=recipient)
            if reply_id:
                reply = Message.objects.get(pk=reply_id, recipient=sender)
                Message.objects.create(sender=sender, recipient=recipient,
                                       message=message, reply=reply)
            else:
                Message.objects.create(sender=sender, recipient=recipient,
                                       message=message)
            return HttpResponseRedirect(reverse_lazy('inbox'))
    else:
        form = SendForm()

    context = {
        'form': form,
        'action_url': reverse_lazy('send'),
    }
    if extra_context:
        context.update(extra_context)
    return render_to_response(template_name, context,
                              context_instance=RequestContext(request))
예제 #16
0
파일: views.py 프로젝트: mgoeminne/Lexpage
 def get_redirect_url(self, **kwargs):
     post = get_object_or_404(BlogPost.published, pk=kwargs['pk'])
     try:
         return reverse_lazy('board_thread_show',
                             kwargs={'thread': post.blogboardlink.thread.pk, 'slug': post.blogboardlink.thread.slug})
     except ObjectDoesNotExist:
         return reverse_lazy('board_create_for_post', kwargs={'post': post.pk})
예제 #17
0
    def test_get_user_profile(self):
        """test for get_user_profile"""
        resp = self.client.get(
            reverse_lazy("apiv2:users-detail", args=[self.user.pk]),
            content_type='application/json',
        )
        self.assertEquals(
            json.loads(resp.content),
            {
                'status': 'success',
                'api_key': '',
                'email': '*****@*****.**',
                'first_name': 'Johnny',
                'last_name': 'Energy'

            })
        resp = self.client.post(
            reverse_lazy("apiv2:users-generate-api-key", args=[self.user.pk]),
            content_type='application/json',
        )
        resp = self.client.get(
            reverse_lazy("apiv2:users-detail", args=[self.user.pk]),
            content_type='application/json',
        )
        self.assertEquals(
            json.loads(resp.content),
            {
                'status': 'success',
                'api_key': User.objects.get(pk=self.user.pk).api_key,
                'email': '*****@*****.**',
                'first_name': 'Johnny',
                'last_name': 'Energy'
            })
예제 #18
0
파일: views.py 프로젝트: HanabiDev/Ursus
def edit_user(request, user_id):

	user = User.objects.get(id=user_id)

	if request.method == 'GET':
		
		form = UserEditForm(instance=user)
		if user.type == 'E':
			form = UserEditForm(initial={'role': user.role}, instance=user)

		return render_to_response('edit_user.html', {'form':form, 'site_user':user}, 
						context_instance=RequestContext(request))

	if request.method == 'POST':
		form = UserEditForm(request.POST, instance=user)

		if form.is_valid():

			user = form.save()

			if request.FILES:
				user.avatar = request.FILES.get('avatar')
			
			user.save()

			if user.type == 'C':
				return redirect(reverse_lazy('admin:users:clients'))
			
			return redirect(reverse_lazy('admin:users:employees'))


    	return render_to_response('edit_user.html', {'form':form, 'site_user':user}, 
						context_instance=RequestContext(request))
def research_detail(request, research_id, template="participant/research_detail.html", extra_context=None):
    study_type = request.GET.get("study_type", None)
    scientist_research = get_object_or_404(ScientistResearch, research__id=research_id, research__is_publish=True)
    research = scientist_research.research

    if request.method == "POST":
        study_type = request.POST.get("study_type", None)
        participant_research_list = ParticipantResearch.objects.filter(participant=request.user, research=research)
        scientist_research = ScientistResearch.objects.filter(scientist=request.user, research=research)

        if participant_research_list:
            if participant_research_list[0].confirmed:
                warning(request, _(u"You are already participants in this research."))
            else:
                warning(request, _(u"You are already have take part request."))
        elif scientist_research:
            warning(request, _(u"Can not participate in own research."))
        else:
            ParticipantResearch(participant=request.user, research=research).save()
            success(request, _(u"Take part request successful."))
        if research.is_on_web:
            return HttpResponseRedirect(reverse_lazy("research_list", args=[study_type]))
        else:
            return HttpResponseRedirect(reverse_lazy("research_list", args=[study_type]))

    context = {"research": research, "study_type": study_type}

    if extra_context:
        context.update(extra_context)
    return render_to_response(template, context, context_instance=RequestContext(request))
예제 #20
0
파일: views.py 프로젝트: Teplitsa/Rynda
def list(request, slug='all'):
    """ Main page """
    last_requests = generate_message_pane(
        _("Help requests"),
        Message.objects.active().type_is(Message.REQUEST)[:MAX_PANE_MESSAGES + 1],
        reverse_lazy("messages-list"))
    last_offers = generate_message_pane(
        _("Offers to help"),
        Message.objects.active().type_is(Message.OFFER)[:MAX_PANE_MESSAGES + 1],
        reverse_lazy("messages-list"))
    last_completed = generate_message_pane(
        _("Successful connections"),
        Message.objects.type_is(
            Message.REQUEST).closed()[:MAX_PANE_MESSAGES + 1],
        "/message/pomogli")
    return render(
        request,
        'index.html',
        {
            'regions': Region.objects.filter(id__gt=0),
            'requests': last_requests,
            'offers': last_offers,
            'completed': last_completed,
            'filter': MapMessageFilter()
        },)
예제 #21
0
파일: views.py 프로젝트: HanabiDev/Ursus
def new_profile(request):
	if not request.session.get('new_profile'):
		return redirect(reverse_lazy('dashboard:home'))
	
	user = User.objects.get(id=request.session['new_profile'])
	message = 'Para fines de contacto te pedimos por favor suministres algunos datos adicionales, luego de esto podrás iniciar sesión con tus credenciales.'
	
	form = NewProfileForm(initial={'type': 'C'}, instance=user)
	if request.method == 'GET':
		form = NewProfileForm(instance=user)
		
		return render_to_response('registry.html', {'form':form, 'editing':True, 'message':message}, 
						context_instance=RequestContext(request))

	elif request.method == 'POST':
		form = NewProfileForm(request.POST, instance=user)

		if form.is_valid():

			user = form.save()

			if user.genre == 'M':
				user.avatar = 'uploads/avatars/avatar.png'
			else:
				user.avatar = 'uploads/avatars/f_avatar.png'
			user.is_active = True
			user.save()
			notificate_registry(user)

			return redirect(reverse_lazy('authy:authy_login'))
			
    	return render_to_response('registry.html', {'form':form, 'editing':True, 'message':message}, 
						context_instance=RequestContext(request))
예제 #22
0
    def get_context_data(self, **kwargs):
        context = super(LabelsEditor, self).get_context_data(**kwargs)

        label_types = self.repository.label_types.all().prefetch_related('labels')
        for label_type in label_types:
            label_type.visible_labels = [l for l in label_type.labels.all() if l.github_status != GITHUB_STATUS_CHOICES.WAITING_DELETE]

        context.update({
            'label_types': label_types,
            'labels_without_type': self.repository.labels.exclude_deleting().order_by('lower_name').filter(label_type_id__isnull=True),
            'label_type_include_template': self.label_type_include_template,
        })

        reverse_kwargs = self.repository.get_reverse_kwargs()
        context['label_type_create_url'] = reverse_lazy(
                'front:repository:%s' % LabelTypeCreate.url_name, kwargs=reverse_kwargs)

        label_reverse_kwargs = dict(reverse_kwargs, label_id=0)
        context['base_label_edit_url'] = reverse_lazy(
                'front:repository:%s' % LabelEdit.url_name, kwargs=label_reverse_kwargs)
        context['base_label_delete_url'] = reverse_lazy(
                'front:repository:%s' % LabelDelete.url_name, kwargs=label_reverse_kwargs)
        context['label_create_url'] = reverse_lazy(
                'front:repository:%s' % LabelCreate.url_name, kwargs=reverse_kwargs)

        return context
예제 #23
0
파일: views.py 프로젝트: zhwei/qipei
def register(request):
    '''注册视图'''
    form = RegisterForm()
    if request.method == "POST":
        form = RegisterForm(request.POST.copy())
        if form.is_valid():
            username = form.cleaned_data["username"]
            email = form.cleaned_data["email"]
            password = form.cleaned_data["password"]
            re_password = form.cleaned_data["re_password"]
            real_name = form.cleaned_data["real_name"]
            if password == re_password:
                user = User.objects.create_user(username, email, password)
                user.is_staff = 0
                user.first_name=real_name
                user.save()
                try:
                    custom = Custom(user=user, is_custom = True)
                    custom.save()
                except IntegrityError:
                    last_user = User.objects.all().order_by('-id')[0]
                    last_user.delete()

                notify.send(User.objects.get(id=1),recipient=user, verb='register successfully!')

                _login(request, username, password)
                return HttpResponse('<script>alert("注册成功!");location.replace(document.referrer);;</script>')
            else:
                return HttpResponse('<script>alert("两次密码必须相同!");history.go(-1);</script>')
        else:
            reverse_lazy('404')
    else:
        reverse_lazy('501')

    return render_to_response("custom-register.html", locals(), context_instance = RequestContext(request))
예제 #24
0
    def test_set_password_only_put(self):
        """test for set_password only allowing put"""
        password_payload = {
            'current_password': '******',
            'password_1': 'new password',
            'password_2': 'new password'
        }
        resp = self.client.post(
            reverse_lazy("accounts:set_password"),
            json.dumps(password_payload),
            content_type='application/json',
        )
        user = User.objects.get(pk=self.user.pk)
        self.assertFalse(user.check_password('new password'))

        self.assertEquals(
            json.loads(resp.content),
            {
                'status': 'error', 'message': 'only HTTP PUT allowed',
            })

        resp = self.client.get(
            reverse_lazy("accounts:set_password"),
            password_payload,
            content_type='application/json',
        )
        user = User.objects.get(pk=self.user.pk)
        self.assertFalse(user.check_password('new password'))

        self.assertEquals(
            json.loads(resp.content),
            {
                'status': 'error', 'message': 'only HTTP PUT allowed',
            })
예제 #25
0
 def search_free(vrf, network, statuses):
     """
     Free blocks recursive search
     :param vrf: VRF
     :type vrf: Vrf
     :param network:  Network
     :type network: Network
     """
     f_ip = network.ip
     l_ip = network.broadcast_long()
     size = network.size()
     blocked_size = \
         vrf.prefixes().filter(status__in=statuses, first_ip_dec__gte=f_ip, last_ip_dec__lte=l_ip).aggregate(
             sum_size=Sum('size'))['sum_size']
     if not blocked_size:
         blocked_size = 0
     if size == blocked_size:
         return []
     elif blocked_size == 0:
         if vrf.prefixes().filter(first_ip_dec__lte=f_ip, last_ip_dec__gte=l_ip):
             parent = vrf.prefixes().filter(first_ip_dec__lte=f_ip, last_ip_dec__gte=l_ip).last()
         else:
             parent = None
         if size == 1:
             create_url = '{0}?prefix={1}'.format(reverse_lazy('ipam.host4_add', kwargs={'vrf': vrf.name}),
                                                  network.dq)
         else:
             create_url = '{0}?prefix={1}'.format(reverse_lazy('ipam.prefix4_add', kwargs={'vrf': vrf.name}),
                                                  network)
         return [{'prefix': str(network), 'parent': parent, 'create_url': create_url}]
     else:
         net_1 = Network('{0}/{1}'.format(network.to_tuple()[0], network.to_tuple()[1] + 1))
         net_2 = Network('{0}/{1}'.format(IP(net_1.broadcast_long() + 1).dq, network.subnet() + 1))
         return search_free(vrf, net_1, statuses) + search_free(vrf, net_2, statuses)
예제 #26
0
파일: views.py 프로젝트: jmennen/group5
def delete_reported_post(request, report_id):
    """
    delete reported message from admin, check if the message has answers,
    reported message with all answers would be delete, else delete only message
    TODO was ist, wenn eine Nachricht rebuzzed wurde
    :param request:
    :param message_id:
    :return:
    """
    try:
        report = CircleMessageReport.objects.get(pk=report_id)
    except ObjectDoesNotExist:
        messages.error(request, "Der Report existiert nicht")
        return HttpResponseRedirect(reverse_lazy("admin_frontpage"))
    # if the reported post has anwsers, delete all
    if not (request.user.is_superuser):
        messages.error(request, "Sie haben nicht die noetigen Zugangsrechte!")
        return HttpResponseRedirect(reverse("home"))
    post_to_del = report.reported_message
    answers = Circle_message.objects.filter(answer_to=post_to_del)
    answers.delete()
    post_to_del.delete()
    report.issuer = request.user
    report.valid = True
    report.closed = True
    messages.success(request, "Die Nachrichte wurde erfolgreich geloescht")
    return HttpResponseRedirect(reverse_lazy("admin_frontpage"))
예제 #27
0
파일: views.py 프로젝트: jmennen/group5
def ban_user(request, user_id):
    """
    set ban user and send email to him with reason,TODO provides ban user information to contact with admin user
    :param request:
    :param user_id:
    :return:
    """
    try:
        user_to_be_ban = User.objects.get(pk=user_id)
    except ObjectDoesNotExist:
        messages.error(request, "Der Benutzer existiert nicht")
        return HttpResponseRedirect(reverse_lazy("admin_frontpage"))

    if not (request.user.is_superuser):
        messages.error(request, "Sie haben nicht die ntigen Zugangsrechte!")
        return HttpResponseRedirect(reverse("home"))
    if not (user_to_be_ban.is_active):
        messages.info(request, "Der Benutzer ist bereits deaktiviert")
        return HttpResponseRedirect(reverse_lazy("admin_frontpage"))

    message_for_ban = request.GET.get("text", False)
    user_to_be_ban.is_active = False
    user_to_be_ban.save()
    send_mail("Deaktivieren dein Account", message="Grund zum Deaktivieren: '%s'" % message_for_ban,
              html_message="<html><h3>um Deinen Account zu wieder aktivieren, kontaktieren Sie bitte :</h3>" +
                           "<a href='%s'>Klicke hier um den Account wieder zu aktivieren!</a>." +
                           "</html>", from_email="*****@*****.**",
              recipient_list=(user_to_be_ban.email,))
    messages.info(request, "Der Benutzer ist deaktiviert")
    return HttpResponseRedirect(reverse_lazy("admin_frontpage"))
    def test_user_addedit_item(self):

        data={'itemname': 'item2', 'done': 'true' }
        data1={'itemname': 'newitem2', 'done': 'true' }
        emptydata={'itemname': '', 'done': '' }
        #test user can add bucketlist item
        response = self.client.post(reverse_lazy('additem', kwargs={
            'id': 1 }), data )
        self.assertEquals(response.status_code, 302)

        #test user should not submit empty add form
        response = self.client.post(reverse_lazy('additem', kwargs={
            'id': 1
            }), emptydata )
        self.assertEquals(response.status_code, 302)

        #test user can edit bucketlistitem
        response = self.client.post(reverse_lazy('delupdateitem', kwargs={
            'id': 19,
            'item_id': 33 }), data )
        self.assertEquals(response.status_code, 302)

        #test user can delete item created
        response = self.client.get(reverse_lazy('delupdateitem', kwargs={
            'id': 19,
            'item_id': 33
            }), data )
        self.assertEquals(response.status_code, 302)
예제 #29
0
def GetConversation(request):
    """Conversation search form"""
    if request.method == 'POST':
        u = ForumUser.objects.exclude(username=request.user)\
            .filter(username__istartswith=request.POST['query'])
        if u.count() == 1:
            c = Conversation.objects.filter(participants=request.user)\
                .filter(participants=u.get())
            if c.count() == 1:
                c = c.get()
                tag = '#' + str(c.messages.latest().pk)
                return HttpResponseRedirect(
                    reverse_lazy('pm:msg', kwargs={'pk': c.pk}) + tag)
            else:
                messages.error(
                    request,
                    ("Il n'existe pas de conversation avec"
                        " cet utilisateur : {:s}.".format(u.get().username))
                )
        elif u.count() > 1:
            messages.error(
                request,
                "Plusieurs utilisateurs possibles : {:s}.".format(
                    ", ".join([u.username for u in u]))
            )
        else:
            messages.error(request, "Aucun utilisateur trouvé.")
    return HttpResponseRedirect(reverse_lazy('pm:top'))
예제 #30
0
 def get_breadcrumbs(self):
     service = self.get_object()
     route = service.route
     return BrowseRoutes.breadcrumbs + [
         (route.get_short_name(), reverse_lazy('browse:route', kwargs={'pk': route.id})),
         (service.get_short_name(), reverse_lazy('browse:service', kwargs={'pk': service.id})),
     ]
예제 #31
0
 def setUp(self):
     super(DeleteParticularParticipantTeam, self).setUp()
     self.url = reverse_lazy(
         "participants:get_participant_team_details",
         kwargs={"pk": self.participant_team.pk},
     )
예제 #32
0
파일: views.py 프로젝트: nikakoss1/upw
 def get_success_url(self, *args, **kwargs):
     return reverse_lazy('partners:promo_list')
예제 #33
0
class ProductDeleteView(DeleteView):

    model = Product

    success_url = reverse_lazy("product-list")
예제 #34
0
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'



MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')


# Configure Django App for Heroku.
django_heroku.settings(locals())


# Email configurations remember to install python-decouple
EMAIL_USE_TLS = config('EMAIL_USE_TLS')
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT')
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')

LOGIN_REDIRECT_URL=reverse_lazy('welcome')
예제 #35
0
class IndexView(CheckoutSessionMixin, FormView):
    """
    First page of the checkout.  We prompt user to either sign in, or
    to proceed as a guest (where we still collect their email address).
    """
    template_name = 'checkout/gateway.html'
    form_class = GatewayForm
    success_url = reverse_lazy('checkout:shipping-address')

    def get(self, request, *args, **kwargs):
        # We redirect immediately to shipping address stage if the user is
        # signed in.
        if request.user.is_authenticated():
            # We raise a signal to indicate that the user has entered the
            # checkout process so analytics tools can track this event.
            signals.start_checkout.send_robust(
                sender=self, request=request)
            return self.get_success_response()
        return super(IndexView, self).get(request, *args, **kwargs)

    def get_form_kwargs(self):
        kwargs = super(IndexView, self).get_form_kwargs()
        email = self.checkout_session.get_guest_email()
        if email:
            kwargs['initial'] = {
                'username': email,
            }
        return kwargs

    def form_valid(self, form):
        if form.is_guest_checkout() or form.is_new_account_checkout():
            email = form.cleaned_data['username']
            self.checkout_session.set_guest_email(email)

            # We raise a signal to indicate that the user has entered the
            # checkout process by specifying an email address.
            signals.start_checkout.send_robust(
                sender=self, request=self.request, email=email)

            if form.is_new_account_checkout():
                messages.info(
                    self.request,
                    _("Create your account and then you will be redirected "
                      "back to the checkout process"))
                self.success_url = "%s?next=%s&email=%s" % (
                    reverse('customer:register'),
                    reverse('checkout:shipping-address'),
                    email
                )
        else:
            user = form.get_user()
            login(self.request, user)

            # We raise a signal to indicate that the user has entered the checkout
            # process.
            signals.start_checkout.send_robust(
                sender=self, request=self.request)

        return self.get_success_response()

    def get_success_response(self):
        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        return self.success_url
예제 #36
0
    def setUp(self):
        super(GetTeamsAndCorrespondingChallengesForAParticipant, self).setUp()

        self.user2 = User.objects.create(
            username="******",
            email="*****@*****.**",
            password="******",
        )

        EmailAddress.objects.create(
            user=self.user2,
            email="*****@*****.**",
            primary=True,
            verified=True,
        )

        self.participant_team2 = ParticipantTeam.objects.create(
            team_name="Team B", created_by=self.user2
        )  # created by user2 and not user

        self.participant2 = Participant.objects.create(
            user=self.user2,
            status=Participant.ACCEPTED,
            team=self.participant_team2,
        )

        self.challenge_host_team = ChallengeHostTeam.objects.create(
            team_name="Host Team 1", created_by=self.user2
        )

        self.challenge1 = Challenge.objects.create(
            title="Test Challenge 1",
            short_description="Short description for test challenge 1",
            description="Description for test challenge 1",
            terms_and_conditions="Terms and conditions for test challenge 1",
            submission_guidelines="Submission guidelines for test challenge 1",
            creator=self.challenge_host_team,
            published=False,
            is_registration_open=True,
            enable_forum=True,
            leaderboard_description="Lorem ipsum dolor sit amet, consectetur adipiscing elit",
            anonymous_leaderboard=False,
            start_date=timezone.now() - timedelta(days=2),
            end_date=timezone.now() + timedelta(days=1),
        )
        self.challenge1.slug = "{}-{}".format(
            self.challenge1.title.replace(" ", "-").lower(), self.challenge1.pk
        )[:199]
        self.challenge1.save()

        self.challenge2 = Challenge.objects.create(
            title="Test Challenge 2",
            short_description="Short description for test challenge 2",
            description="Description for test challenge 2",
            terms_and_conditions="Terms and conditions for test challenge 2",
            submission_guidelines="Submission guidelines for test challenge 2",
            creator=self.challenge_host_team,
            published=False,
            is_registration_open=True,
            enable_forum=True,
            anonymous_leaderboard=False,
            start_date=timezone.now() - timedelta(days=2),
            end_date=timezone.now() + timedelta(days=1),
        )

        self.url = reverse_lazy(
            "participants:get_teams_and_corresponding_challenges_for_a_participant",
            kwargs={"challenge_pk": self.challenge1.pk},
        )

        self.time = timezone.now()
예제 #37
0
    def test_invite_participant_to_team_when_user_cannot_be_invited(self):
        """
        NOTE
        user: host user
        user1: participant 1
        user2: participant 2
        """
        self.user2 = User.objects.create(
            username="******",
            email="*****@*****.**",
            password="******",
        )

        EmailAddress.objects.create(
            user=self.user2,
            email="*****@*****.**",
            primary=True,
            verified=True,
        )

        self.user3 = User.objects.create(
            username="******",
            email="*****@*****.**",
            password="******",
        )

        EmailAddress.objects.create(
            user=self.user3,
            email="*****@*****.**",
            primary=True,
            verified=True,
        )

        self.participant_team2 = ParticipantTeam.objects.create(
            team_name="Participant Team created by user 2",
            created_by=self.user2,
        )

        self.participant_team3 = ParticipantTeam.objects.create(
            team_name="Participant Team created by user 3",
            created_by=self.user3,
        )

        self.participant2 = Participant.objects.create(
            user=self.user2,
            status=Participant.ACCEPTED,
            team=self.participant_team2,
        )

        self.participant3 = Participant.objects.create(
            user=self.user3,
            status=Participant.ACCEPTED,
            team=self.participant_team3,
        )

        self.challenge_host_team = ChallengeHostTeam.objects.create(
            team_name="Test Challenge Host Team", created_by=self.user
        )

        self.challenge = Challenge.objects.create(
            title="Test Challenge",
            short_description="Short description for test challenge",
            description="Description for test challenge",
            terms_and_conditions="Terms and conditions for test challenge",
            submission_guidelines="Submission guidelines for test challenge",
            creator=self.challenge_host_team,
            published=False,
            enable_forum=True,
            leaderboard_description=None,
            anonymous_leaderboard=False,
            start_date=timezone.now() - timedelta(days=2),
            end_date=timezone.now() + timedelta(days=1),
        )

        self.client.force_authenticate(user=self.user2)

        self.challenge.participant_teams.add(self.participant_team2)
        self.challenge.participant_teams.add(self.participant_team3)

        self.data = {"email": self.user3.email}
        self.url = reverse_lazy(
            "participants:invite_participant_to_team",
            kwargs={"pk": self.participant_team2.pk},
        )

        expected = {
            "error": "Sorry, the invited user has already participated "
            "in atleast one of the challenges which you are already"
            " a part of. Please try creating a new team and then invite."
        }
        response = self.client.post(self.url, self.data)
        self.assertEqual(response.data, expected)
        self.assertEqual(response.status_code, status.HTTP_406_NOT_ACCEPTABLE)
예제 #38
0
class UpdateView(r_views.UpdateView):
    form_class = rforms.UpdateForm
    template_name = 'project/routers/update.html'
    success_url = reverse_lazy("horizon:admin:routers:index")
    submit_url = "horizon:admin:routers:update"
예제 #39
0
    def post(self, request, *args, **kwargs):
        gi = request.galaxy

        # Get a copy of the workflow with full details
        workflow = self.get_object().duplicate(gi)
        workflow.fetch_details(gi, self.restricted_toolset)

        context = self.get_context_data(object=self.object)

        # input file
        dataset_map = {}
        # tool params
        params = {}
        # Workflow inputs
        i_input = workflow.json['inputs'].keys()[0]

        # Handle workflow main input file
        # before creating the workspace etc.
        uploaded_file = request.FILES.get("file") or request.POST.get("file")
        # We check that a file has been given
        if not uploaded_file:
            context = self.get_context_data(object=self.object)
            context['fileerror'] = "No input file given"
            workflow.delete(gi)
            return render(request, self.template_name, context)
        # Then we check input file format
        try:
            tmp_file, uploadfile_name = self.process_file_to_upload(
                uploaded_file)
        except WorkflowInputFileFormatError as e:
            context = self.get_context_data(object=self.object)
            context['fileerror'] = str(e)
            workflow.delete(gi)
            return render(request, self.template_name, context)

        # We check form validity
        if not self.check_form_validity(request, context):
            workflow.delete(gi)
            return self.get(request, *args, **kwargs)

        # We create an history (local and on galaxy)
        wksph = create_history(
            self.request, name="NGPhylogeny Analyse - " + workflow.name)
        # we send the file to galaxy
        output = gi.tools.upload_file(path=tmp_file.name,
                                      file_name=uploadfile_name,
                                      history_id=wksph.history)
        galaxy_file = output.get('outputs')[0].get('id')
        dataset_map[i_input] = {'id': galaxy_file, 'src': 'hda'}

        # We analyze submited forms and upload files to
        # galaxy
        try:
            self.analyze_forms(request, context, workflow, params, gi, wksph)
        except WorkflowInvalidFormError as e:
            # if one form is not valid
            workflow.delete(gi)
            delete_history(wksph.history)
            return self.get(request, *args, **kwargs)

        # We run the galaxy workflow
        try:
            output = self.request.galaxy.workflows.invoke_workflow(
                workflow_id=workflow.id_galaxy,
                history_id=wksph.history,
                inputs=dataset_map,
                params=params,
                allow_tool_state_corrections=True,
            )

            self.succes_url = reverse_lazy("history_detail", kwargs={
                                           'history_id': wksph.history})
            # Start monitoring (for sending emails)
            monitorworkspace.delay(wksph.history)
            wksph.monitored = True
            wksph.save()

            return HttpResponseRedirect(self.succes_url)

        except Exception:
            delete_history(wksph.history)
            raise
        finally:
            # delete the workflow copy of oneclick workflow when
            # the workflow has been run
            workflow.delete(gi)
예제 #40
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.

import pytest

from django.core.urlresolvers import reverse_lazy

ADMIN_URL = reverse_lazy('pootle-admin')


@pytest.mark.django_db
def test_admin_not_logged_in(client):
    """Checks logged-out users cannot access the admin site."""
    response = client.get(ADMIN_URL)
    assert response.status_code == 403


@pytest.mark.django_db
def test_admin_regular_user(client, default):
    """Checks regular users cannot access the admin site."""
    client.login(username=default.username, password='')
    response = client.get(ADMIN_URL)
    assert response.status_code == 403

예제 #41
0
    url(r'^layers/(?P<layername>[^/]*)$', layer_detail, name="layer_detail"),
    )

urlpatterns = patterns('',
                       # Home
                       url(r'^$', IndexView.as_view(), name="index_view"),

                       # Adding Threaded Comments app
                       url(r'^articles/comments/', include('django_comments.urls')),

                       # Account
                       url(r"^account/signup/$", MapStorySignupView.as_view(), name="account_signup"),
                       url(r"^account/confirm_email/(?P<key>\w+)/$", MapStoryConfirmEmailView.as_view(), name="account_confirm_email"),

                       # Accounts
                       url(r'^accounts/profile/$', RedirectView.as_view(url=reverse_lazy('index_view'))),  #temp fix for social auth redirect
                       url(r'^accounts/verify/$', 'mapstory.views.account_verify',  name='account_verify'),

                       # Blog Comments
                       url(r'^blog/comments/', include('fluent_comments.urls')),

                       # Maps
                       url(r'^maps/(?P<mapid>\d+)/storyframes$', include('mapstory.apps.storyframes.urls')),
                       url(r'^maps/new/data$', 'mapstory.views.new_map_json', name='new_map_json'),
                       url(r'^maps/(?P<mapid>\d+)/data$', 'mapstory.views.mapstory_map_json', name='mapstory_map_json'),
                       url(r'^maps/new_map', new_map, name='new_map'),
                       url(r'^maps/(?P<storyid>[^/]+)/save$', 'mapstory.views.save_story', name='save_story'),

                       # Health Check status
                       url(r'^status/', include('health_check.urls'), name='health_check'),
예제 #42
0
    },
]

LANGUAGE_CODE = "en-us"
TIME_ZONE = "America/Indianapolis"
USE_I18N = True
USE_L10N = True
USE_TZ = True

STATIC_URL = "/static/"

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

LOGIN_REDIRECT_URL = reverse_lazy("app")
LOGIN_URL = reverse_lazy("login")

REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": (
        "rest_framework.renderers.BrowsableAPIRenderer",
        "rest_framework.renderers.JSONRenderer",
    ),
    "DEFAULT_PARSER_CLASSES": ("rest_framework.parsers.JSONParser", ),
    "DEFAULT_PERMISSION_CLASSES": (
        "rest_framework.permissions.IsAuthenticated",
        "backend.permissions.DjangoModelViewPermissions",
    ),
    "DEFAULT_AUTHENTICATION_CLASSES":
    ("rest_framework.authentication.SessionAuthentication", ),
    "DEFAULT_PAGINATION_CLASS":
예제 #43
0
파일: views.py 프로젝트: danirp13/tienda
class ZapatoDelete(DeleteView):
    model = Zapato
    success_url = reverse_lazy('zapato-list')
예제 #44
0
    "django.contrib.messages.context_processors.messages",
    "session_csrf.context_processor"
)

SECURE_CHECKS = [
    "djangosecure.check.sessions.check_session_cookie_secure",
    "djangosecure.check.sessions.check_session_cookie_httponly",
    "djangosecure.check.djangosecure.check_security_middleware",
    "djangosecure.check.djangosecure.check_sts",
    "djangosecure.check.djangosecure.check_frame_deny",
    "djangosecure.check.djangosecure.check_ssl_redirect",
    "scaffold.checks.check_session_csrf_enabled",
    "scaffold.checks.check_csp_is_not_report_only"
]

CSP_REPORT_URI = reverse_lazy('report_csp')
CSP_REPORTS_LOG = True
CSP_REPORTS_LOG_LEVEL = 'warning'
CSP_REPORTS_SAVE = True
CSP_REPORTS_EMAIL_ADMINS = False

ROOT_URLCONF = 'scaffold.urls'

WSGI_APPLICATION = 'scaffold.wsgi.application'


# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'
예제 #45
0
class StadlanderPayDirectFormView(FormView):
    template_name = 'stadlander/pay_direct.html'
    success_url = reverse_lazy('accounts_pay_direct')
    form_class = StadlanderPayDirectForm

    def get_form(self, form_class):
        """
        Overrides the base ``get_form`` method. Returns a form initialised with
        the user info for credit check.
        """
        cc3_profile = self.request.user.get_cc3_profile()

        if cc3_profile and cc3_profile.web_payments_enabled:
            kwargs = self.get_form_kwargs()
            kwargs['user'] = self.request.user
            return form_class(**kwargs)
        return None

    def _perform_payment(self, data):
        sender = self.request.user
        receiver = data['profile'].user
        amount = data['amount']

        description_elements = []

        reward_category = data.get('reward_category', None)
        reward_category_quantity = data.get('reward_category_quantity', None)
        other_activity = data.get('other_activity', None)
        other_activity_quantity = data.get('other_activity_quantity', None)
        bonus = data.get('bonus', None)

        if reward_category:
            description_elements.append(
                (reward_category, reward_category_quantity))

        if other_activity:
            description_elements.append(
                (other_activity, other_activity_quantity))

        if bonus:
            description_elements.append((u'bonus', bonus))

        description = u"".join([
            u"{0} ({1}) | ".format(description_element[0],
                                   description_element[1])
            for description_element in description_elements
        ])

        description = description[:-3]  # knock off last pipe

        try:
            # Cyclos transaction request.
            transaction = backends.user_payment(sender, receiver, amount,
                                                description)
            # Log the payment
            Transaction.objects.create(
                amount=amount,
                sender=sender,
                receiver=receiver,
                transfer_id=transaction.transfer_id,
            )
            messages.add_message(self.request, messages.SUCCESS,
                                 _('Payment made successfully.'))
        except TransactionException, e:
            error_message = _('Could not make payment at this time.')

            if 'NOT_ENOUGH_CREDITS' in e.args[0]:
                error_message = _('You do not have sufficient credit to '
                                  'complete the payment plus the '
                                  'transaction fee.')
            messages.add_message(self.request, messages.ERROR, error_message)
예제 #46
0
class AuthorDelete(DeleteView):
    model = Author
    success_url = reverse_lazy('author-list')
예제 #47
0
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+$zk!w5z8k6o7^xdf-mr*uonpwsk#$a3j8a(04$02@+@#z9du)'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

LOGIN_URL = reverse_lazy('login')

###################################---django_auth_ldap---######################################
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfUniqueNamesType

# Basic configuration.
AUTH_LDAP_SERVER_URI = "ldap://ldap.forumsys.com"
AUTH_LDAP_BIND_DN = "cn=read-only-admin,dc=example,dc=com"
AUTH_LDAP_BIND_PASSWORD = "******"

# Either AUTH_LDAP_USER_DN_TEMPLATE or AUTH_LDAP_USER_SEARCH need to be set
#AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,dc=example,dc=com"
AUTH_LDAP_USER_SEARCH = LDAPSearch("dc=example,dc=com", ldap.SCOPE_SUBTREE,
                                   "(uid=%(user)s)")
예제 #48
0
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os
from django.core.urlresolvers import reverse_lazy

from listproject.secret_settings import *

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

LOGIN_URL = reverse_lazy('todosite:login')

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'todosite',
    'pytz',
    'bootstrap3_datetime',
]
예제 #49
0
from django.conf.urls import url
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.views import password_reset, password_reset_done, password_reset_confirm, password_reset_complete

urlpatterns = [
    url(r'^password-reset/$',
        password_reset,
        {'post_reset_redirect': reverse_lazy('password_reset_done')},
        name='password_reset'),
    url(r'^password-reset/done/$',
        password_reset_done,
        name='password_reset_done'),
    url(r'^password-reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',
        password_reset_confirm,
        {'post_reset_redirect': reverse_lazy('password_reset_complete')},
        name='password_reset_confirm'),
    url(r'^password-reset/complete/$',
        password_reset_complete,
        name='password_reset_complete')
]
예제 #50
0
파일: views.py 프로젝트: sapcc/manila-ui
class SecurityServiceDetailView(ss_views.Detail):
    tab_group_class = ss_tabs.SecurityServiceDetailTabs
    template_name = "admin/security_services/detail.html"
    redirect_url = reverse_lazy('horizon:admin:security_services:index')
예제 #51
0
class BlogDeleteView(DeleteView):
    model = Post
    template_name = 'login_account/post_delete.html'
    success_url = reverse_lazy('post_list') 
예제 #52
0
    def test_update_project(self):
        """tests update_project"""
        project = json.loads(
            self._create_project(name='proj1',
                                 via_http=True).content)['project']
        self._set_role_level(ROLE_MEMBER)
        resp = self.client.get(
            reverse_lazy('api:v2:projects-detail', args=[project['slug']]),
            {'organization_id': self.org.id},
            content_type='application/json',
        )
        # using put requires all fields according to proper REST
        # semantics, so use values returned by create
        project['name'] = 'proj22'
        url = "{}?organization_id={}".format(
            reverse_lazy('api:v2:projects-detail', args=[project['slug']]),
            str(self.org.id))
        resp = self.client.put(
            url,
            data=json.dumps(project),
            content_type='application/json',
        )
        result = json.loads(resp.content)
        expected = self._expected_project(result['project']['modified'],
                                          result['project']['id'],
                                          False,
                                          name='proj22',
                                          slug='proj1')
        self.assertDictEqual(result, {
            'status': 'success',
            'project': expected
        })
        p = Project.objects.get(slug='proj1')
        self.assertEqual(p.name, 'proj22')

        # test partial update
        project['name'] = 'proj33'
        url = "{}?organization_id={}".format(
            reverse_lazy('api:v2:projects-detail', args=[project['slug']]),
            str(self.org.id))
        resp = self.client.patch(
            url,
            data=json.dumps({'name': 'proj33'}),
            content_type='application/json',
        )
        result = json.loads(resp.content)
        expected = self._expected_project(result['project']['modified'],
                                          result['project']['id'],
                                          False,
                                          name='proj33',
                                          slug='proj1')
        self.assertDictEqual(result, {
            'status': 'success',
            'project': expected
        })
        p = Project.objects.get(slug='proj1')
        self.assertEqual(p.name, 'proj33')

        # test that a view cannot update
        self._set_role_level(ROLE_VIEWER)
        url = "{}?organization_id={}".format(
            reverse_lazy('api:v2:projects-detail', args=[project['slug']]),
            str(self.org.id))
        resp = self.client.put(
            url,
            data=json.dumps(project),
            content_type='application/json',
        )
        self.assertDictEqual(json.loads(resp.content), {
            'status': 'error',
            'message': 'Permission denied'
        })
        resp = self.client.patch(
            url,
            data=json.dumps(project),
            content_type='application/json',
        )
        self.assertDictEqual(json.loads(resp.content), {
            'status': 'error',
            'message': 'Permission denied'
        })
예제 #53
0
 def get_success_url(self):
     return reverse_lazy('node:ViewClusterClient')
예제 #54
0
from django.conf.urls import patterns, include, url
from django.contrib import admin
from accounts.views import LoginView, LogoutView
from django.core.urlresolvers import reverse_lazy

admin.autodiscover()

urlpatterns = patterns(
    '',
    # Examples:
    # url(r'^$', 'djangotemplate.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^login/$', LoginView.as_view(), name="login"),
    url(r'^logout/$',
        LogoutView.as_view(), {"next_page": reverse_lazy("index")},
        name="logout"),
)
def eliminar_medicamento(request, pk):
    medicamento = Medicamento.objects.get(pk=pk)
    pk = medicamento.farmacia.pk
    medicamento.delete()
    return HttpResponseRedirect(
        reverse_lazy('ver_medicamentos', kwargs={'pk': pk}))
예제 #56
0
class RegistroUsuario(CreateView):
    model = Users
    template_name = "usuario/registrar.html"
    form_class = RegistroForm
    success_url = reverse_lazy('personal_data:personal_data_list')
예제 #57
0
#coding:utf-8

from django.contrib import admin
from django.core.urlresolvers import reverse_lazy
from navbar import navitem, include
from core import settings

navitems = navitem(
    settings.PROJECT_NAME,
    reverse_lazy("index"),
    navitem("ホーム", reverse_lazy("index"), icon="home"),
    include("navbar.navitems"),
    include("accounts.navitems"),
    navitem(
        "検索エンジン",
        None,
        navitem("Google", "http://google.com/"),
        navitem("Yahoo", "http://yahoo.co.jp/"),
        navitem("Bing", "http://bing.jp/"),
    ),
    # include() # ←acountsあたりを読む
)
예제 #58
0
 def get_success_url(self):
     return reverse_lazy('node:ViewClusterServer')
예제 #59
0
# https://docs.djangoproject.com/en/dev/howto/static-files/

STATIC_URL = '/static/'

ALLOWED_HOSTS = []

# Crispy Form Theme - Bootstrap 3
CRISPY_TEMPLATE_PACK = 'bootstrap3'

# For Bootstrap 3, change error alert to 'danger'
from django.contrib import messages
MESSAGE_TAGS = {messages.ERROR: 'danger'}

# Authentication Settings
AUTH_USER_MODEL = 'authtools.User'
LOGIN_REDIRECT_URL = reverse_lazy("profiles:show_self")
LOGIN_URL = reverse_lazy("accounts:login")

THUMBNAIL_EXTENSION = 'png'  # Or any extn for your thumbnails

import sys

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format':
            '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        }
    },
def eliminar_farmacia(request, pk):
    farmacia = Farmacia.objects.get(pk=pk)
    farmacia.delete()
    return HttpResponseRedirect(reverse_lazy('ver_farmacias'))