Python django.http.response 模块,HttpResponseRedirect() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.http.response.HttpResponseRedirect()

项目:mooder    作者:phith0n    | 项目源码 | 文件源码
def form_valid(self, form):
        if form.cleaned_data['rank'] <= 0:
            form.add_error('rank', 'Rank???0')
            return self.form_invalid(form)

        self.object = form.save(commit=False)
        self.object.verify = 'pass'

        self.object.author.rank += self.object.rank
        self.object.author.coin += self.object.rank

        self.object.save()
        self.object.author.save()
        models.log_coin(self.object.rank, self.object.author.coin, None, self.object.author)

        return HttpResponseRedirect(self.get_success_url())
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
def register(request):
    if request.method == 'POST':
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user = register_form.save()
            if user is not None:
                user = authenticate(username=register_form.cleaned_data['username'],password=register_form.cleaned_data['password'])
                auth_login(request,user)
                return HttpResponseRedirect(reverse('index-view'))
        else:
            auth_logout(request)
            return render(request, 'users/register.html', {'errors': register_form.errors})
    else:
        register_form = RegisterForm()
        user = None
    return render(request, 'users/register.html')
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
def password(request):
    user = request.user

    if request.method == "POST":
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            data = form.clean()
            if user.check_password(data["old_password"]):
                user.set_password(data["password"])
                user.save()
                messages.success(request, "?????????????")
                auth_logout(request)
                return HttpResponseRedirect(reverse("login"))
            else:
                messages.error(request,'????????')
                return render(request, "users/password.html", {'errors': form.errors})
    else:
        form = PasswordChangeForm()

    return render(request, "users/password.html")
项目:pony    作者:Eastwu5788    | 项目源码 | 文件源码
def login_handler(request):
    if request.method == "GET":
        return render(request, "auth/login/login.html")

    email = request.POST.get("email")
    pass_word = request.POST.get("pass_word")

    # TODO: email ? password ?????

    account = UserAccount.query_account_by_email(email)
    if not verify_password(pass_word, account.password):
        return render(request, "auth/login/login.html")

    # token??
    token = AccessToken.query_token_by_user_id(account.id)
    if not token:
        AccessToken.create_new_toke(account.id)

    request.session["access_token"] = token.access_token
    return HttpResponseRedirect("/index/")
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def password_reset_confirm(request, initial=False, extra_context={}, **kwargs):
    extra_context.update({
        'password_policy': password_validators_help_text_html()})

    response = auth_views.password_reset_confirm(
        request, extra_context=extra_context, **kwargs)

    if isinstance(
            response, HttpResponseRedirect) and response.status_code == 302:
        # Send password change confirmation email
        try:
            uid = force_text(urlsafe_base64_decode(kwargs['uidb64']))
            user = MunchUser.objects.get(pk=uid)
            if initial:
                user.send_invitation_complete_email()
            else:
                user.send_password_reset_complete_email()
        except (TypeError, ValueError, OverflowError, MunchUser.DoesNotExist):
            pass
    return response
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def form_valid(self, form, detalle_conformidad_servicio_formset):
        try:
            with transaction.atomic():
                self.object = form.save()
                referencia = self.object.orden_servicios
                detalles = []
                cont = 1
                for detalle_orden_servicios_form in detalle_conformidad_servicio_formset:
                    orden_servicios = detalle_orden_servicios_form.cleaned_data.get('orden_servicios')
                    cantidad = detalle_orden_servicios_form.cleaned_data.get('cantidad')
                    precio = detalle_orden_servicios_form.cleaned_data.get('precio')
                    valor = detalle_orden_servicios_form.cleaned_data.get('valor')
                    detalle_orden_servicios = DetalleOrdenServicios.objects.get(pk=orden_servicios)
                    if cantidad and precio and valor:
                        detalle_conformidad_servicio = DetalleConformidadServicio(detalle_orden_servicios = detalle_orden_servicios,
                                                                                  nro_detalle = cont,
                                                                                  conformidad = self.object,
                                                                                  cantidad=cantidad) 
                        detalles.append(detalle_conformidad_servicio)                        
                        cont = cont + 1
                DetalleConformidadServicio.objects.bulk_create(detalles, referencia)
                return HttpResponseRedirect(reverse('compras:detalle_conformidad_servicios', args=[self.object.codigo]))
        except IntegrityError:
                messages.error(self.request, 'Error guardando la cotizacion.')
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def form_valid(self, form):
        data = form.cleaned_data
        docfile = data['archivo']
        form.save()
        csv_filepathname = os.path.join(settings.MEDIA_ROOT, 'archivos', str(docfile))
        dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')
        for fila in dataReader:
            dni = fila[0]
            if dni != "":
                appaterno = fila[1].upper()
                apmaterno = fila[2].upper()
                nombres = fila[3].upper()
                try:
                    productor, creado = Productor.objects.get_or_create(dni=dni,
                                                                        defaults={'apellido_paterno': appaterno,
                                                                                  'apellido_materno': apmaterno,
                                                                                  'nombres': nombres})
                except:
                    pass
        return HttpResponseRedirect(reverse('administracion:maestro_productores'))
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def form_valid(self, form):
        data = form.cleaned_data
        docfile = data['archivo']            
        form.save()
        csv_filepathname = os.path.join(settings.MEDIA_ROOT,'archivos',str(docfile))
        dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')
        for fila in dataReader:
            try:
                cuenta = CuentaContable.objects.get(cuenta=fila[0])
                descripcion = fila[1] 
                grupo_productos, creado = GrupoProductos.objects.get_or_create(descripcion=unicode(descripcion, errors='ignore'),
                                                                               defaults={'ctacontable' : cuenta
                                                                                        })
            except CuentaContable.DoesNotExist:
                pass                       
        return HttpResponseRedirect(reverse('productos:grupos_productos'))
项目:django-lti-provider    作者:ccnmtl    | 项目源码 | 文件源码
def post(self, request, assignment_name=None):
        if request.POST.get('ext_content_intended_use', '') == 'embed':
            domain = self.request.get_host()
            url = '%s://%s/%s?return_url=%s' % (
                self.request.scheme, domain,
                settings.LTI_TOOL_CONFIGURATION.get('embed_url'),
                request.POST.get('launch_presentation_return_url'))
        elif assignment_name:
            assignments = settings.LTI_TOOL_CONFIGURATION['assignments']
            url = assignments[assignment_name]
        elif settings.LTI_TOOL_CONFIGURATION.get('new_tab'):
            url = reverse('lti-landing-page')
        else:
            url = settings.LTI_TOOL_CONFIGURATION['landing_url'].format(
                self.request.scheme, self.request.get_host())

        # custom parameters can be tacked on here
        url = self.add_custom_parameters(url)

        return HttpResponseRedirect(url)
项目:django-lti-provider    作者:ccnmtl    | 项目源码 | 文件源码
def post(self, *args, **kwargs):
        group_id = self.request.POST.get('group')
        faculty_group_id = self.request.POST.get('faculty_group')
        course_context = self.lti.course_context(self.request)
        title = self.lti.course_title(self.request)

        (ctx, created) = LTICourseContext.objects.get_or_create(
            group=get_object_or_404(Group, id=group_id),
            faculty_group=get_object_or_404(Group, id=faculty_group_id),
            lms_course_context=course_context)

        messages.add_message(
            self.request, messages.INFO,
            '<strong>Success!</strong> {} is connected to {}.'.format(
                title, settings.LTI_TOOL_CONFIGURATION.get('title')))

        url = reverse('lti-landing-page', args=[course_context])
        return HttpResponseRedirect(url)
项目:django-lti-provider    作者:ccnmtl    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        lti = LTI(self.request_type, self.role_type)

        # validate the user via oauth
        user = authenticate(request=request, lti=lti)
        if user is None:
            lti.clear_session(request)
            return HttpResponseRedirect(reverse('lti-fail-auth'))

        # login
        login(request, user)

        # configure course groups if requested
        try:
            self.course_configuration(request, lti)
        except (KeyError, ValueError, LTICourseContext.DoesNotExist):
            return HttpResponseRedirect(reverse('lti-course-config'))

        self.lti = lti
        return super(LTIAuthMixin, self).dispatch(request, *args, **kwargs)
项目:lykchat    作者:lykops    | 项目源码 | 文件源码
def index(self, request):
        '''
        web???????
        '''
        is_login = self._check_userlogin(request)
        if not is_login :
            return HttpResponseRedirect(reverse('login'))

        self._init_param(request)
        self.session_info_dict['username'] = request.session['username']

        if self.status < 200:
            self._getqr(request)
        elif self.status > 200 and self.status < 222:
            self._confirm(request)
        elif self.status == 222:
            self._checklogin(request)
        elif self.status == 200 or self.status == 221:
            self._init(request)
        else :
            self._getqr(request)

        display_html_dict = self._displayhtml(request)
        return render(request, self.display_html, display_html_dict)
项目:lykchat    作者:lykops    | 项目源码 | 文件源码
def wx_logout(self, request):
        '''
        ??????
        '''
        is_login = self._check_userlogin(request)
        if not is_login :
            return HttpResponseRedirect(reverse('login'))

        self._init_param(request)
        if self.status == 222 :
            wx_logout = Logout(self.session_info_dict)
            wx_logout.logout()
            self.session_info_dict['status'] = self.status = 444
            display_html_dict = self._displayhtml(request)
            return render(request, self.display_html, display_html_dict) 
        else :
            return HttpResponseRedirect(reverse('index'))
项目:Django-ERP    作者:andyzsf    | 项目源码 | 文件源码
def restart(request,app,model,object_id,instance):
    """

    :param request:
    :param app:
    :param model:
    :param object_id:
    :return:
    """
    try:
        inst = Instance.objects.get(id=int(instance))
        if request.user == inst.starter:
            inst.delete()
            messages.success(request,_("workflow restarted success"))
        else:
            messages.warning(request,_("you do not have the permission to restart,only the starter can restart"))
    except Exception,e:
        messages.error(request,e)
    return HttpResponseRedirect("/admin/%s/%s/%s"%(app,model,object_id))
项目:tickerbot    作者:shaileshahuja    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        try:
            code = request.GET.get('code', '')
            sc = SlackClient("")
            result = sc.api_call("oauth.access", client_id=settings.SLACK_CLIENT_ID,
                                 client_secret=settings.SLACK_CLIENT_SECRET, code=code,
                                 redirect_uri=request.build_absolute_uri(reverse('oauth')))
            if SlackAuth.objects.filter(team_id=result["team_id"]).exists():
                SlackAuth.objects.get(team_id=result["team_id"]).delete()
            slack_auth = SlackAuth.objects.create(access_token=result["access_token"], team_id=result["team_id"],
                                                  team_name=result["team_name"], bot_id=result["bot"]["bot_user_id"],
                                                  bot_access_token=result["bot"]["bot_access_token"])
            retrieve_channel_users.delay(slack_auth.pk)
            return HttpResponseRedirect(reverse("success"))
        except Exception:
            logger.error(traceback.format_exc())
            return HttpResponseRedirect(reverse("failure"))
项目:pyfeedback    作者:d120    | 项目源码 | 文件源码
def status_aendern_action(self, request, queryset):
        """Beschreibt eine Admin-Action für die Statusänderung."""
        form = None

        if 'apply' in request.POST:
            form = self.StatusAendernForm(request.POST)

            if form.is_valid():
                status = form.cleaned_data['status']

                queryset.update(status=status)
                for veranstaltung in queryset:
                    veranstaltung.log(request.user)

                self.message_user(request, "Status erfolgreich geändert.")
                return HttpResponseRedirect(request.get_full_path())

        if not form:
            form = self.StatusAendernForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})

        return render(request, 'admin/status_aendern.html', {'veranstaltungen': queryset, 'status': form, })
项目:pyfeedback    作者:d120    | 项目源码 | 文件源码
def keine_evaluation_action(self, request, queryset):
        """Beschreibt eine Admin-Action für die Option keine Evaluation."""
        form = None

        if 'apply' in request.POST:     #Dieser Teil reicht bereits zum ändern aus. In diesem Fall können auch Zeile 146-149 gelöscht werden (Kein Bestätigungsfenster erscheint.
            queryset.update(status=Veranstaltung.STATUS_KEINE_EVALUATION_FINAL)
            queryset.update(evaluieren=False)
            for veranstaltung in queryset:
                veranstaltung.log(request.user)

            self.message_user(request, "Veranstaltungen wurden erfolgreich auf Keine Evaluation gesetzt.")
            return HttpResponseRedirect(request.get_full_path())
            #nach dem return landet Python in status_aendern_action
        if not form:
            form = self.KeineEvaluationForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
        return render(request, 'admin/keine_evaluation.html', {'veranstaltungen': queryset, 'status':form, })
项目:issue-reporting    作者:6aika    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        issue = self.object = self.get_object()
        action = self.request.POST.get('action')
        if action.startswith('moderation:'):
            issue.moderation = action.split(':')[-1]
            issue.full_clean()
            issue.save(update_fields=('moderation',))

        elif action == 'log':
            form = self.get_log_form()
            if form.is_valid():
                log_entry = form.save()
                issue.updated_datetime = now()
                if log_entry.note:
                    issue.status_notes = log_entry.note
                if log_entry.status == 'done':
                    issue.status = 'closed'
                issue.save(update_fields=('updated_datetime', 'status_notes', 'status',))
        return HttpResponseRedirect(self.request.path)
项目:iguana    作者:iguana-project    | 项目源码 | 文件源码
def _process_grouped_forms(self, group_name, form_classes):
        """
        Perform the is_valid() check for a group of forms.
        """
        form_names = self.grouped_forms[group_name]
        forms = self.get_forms(form_classes, form_names)
        # check if all forms are valid
        if all([forms[formName].is_valid() for formName in forms if formName in form_names]):
            # process the group valid method
            self.forms_valid(forms, group_name, isGroup=True)

            # redirect to success url if at least one form was valid
            return HttpResponseRedirect(self.get_success_url())
        else:
            # process the group invalid method
            self.forms_invalid(forms, group_name, isGroup=True)

            # show errors instead
            return self.render_to_response(self.get_context_data(forms=forms))
项目:iguana    作者:iguana-project    | 项目源码 | 文件源码
def _process_all_forms(self, form_classes):
        """
        Perform the is_valid() check for all forms.
        """
        forms = self.get_forms(form_classes, None, True)
        # only proceed if all forms are valid
        if all([form.is_valid() for form in forms.values()]):
            for form_name in forms:
                # for every form call the valid method
                self.forms_valid(forms, form_name)

            # redirect to the success URL
            return HttpResponseRedirect(self.get_success_url())
        else:
            for form_name in [form for form in forms if not forms[form].is_valid()]:
                # for every invalid form call the invalid method
                self.forms_invalid(forms, form_name)

            # show errors instead
            return self.render_to_response(self.get_context_data(forms=forms))
项目:iguana    作者:iguana-project    | 项目源码 | 文件源码
def test_post(self):
        requestObj = self.tempForm.__class__.__dict__['request']
        actionParam = (fClassesNames[1], groupName, '')

        for i in range(0, 6):
            setattr(requestObj, 'POST', {'action': actionParam[i % 3]})

            response = self.tempForm.post(requestObj)
            if isinstance(response, HttpResponseRedirect):
                self.assertEqual(response.url, self.tempForm.success_url)
            else:
                self.assertEqual(response.status_code, 200)

            if i == 2:
                global form_valid
                form_valid = True

        setattr(requestObj, 'POST', requestMethodNames[0])
项目:djunin    作者:ercpe    | 项目源码 | 文件源码
def handle(self, request, q):
        node_q = Node.objects.filter(name=q)
        if node_q.count() == 1:
            return HttpResponseRedirect(reverse('graphs', args=(node_q[0].group, node_q[0].name)))

        node_q = Node.objects.filter(name__startswith=q)
        if node_q.count() == 1:
            return HttpResponseRedirect(reverse('graphs', args=(node_q[0].group, node_q[0].name)))

        group_q = Node.objects.filter(group=q)
        if group_q.exists():
            return HttpResponseRedirect(reverse('group_nodes', args=(group_q[0].group, )))

        response = render_to_response('not_found.html', {}, RequestContext(request))
        response.status_code = 404
        return response
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def content_fetch_view(request, objtype, guid):
    """Diaspora content fetch view.

    Returns the signed payload for the public content. Non-public content will return 404.

    If the content is not local, redirect to content author server.

    Args:
        objtype (str) - Diaspora content type. Currently if it is `status_message`, `post` or `reshare`,
            we try to find `Content`.
        guid (str) - The object guid to look for.
    """
    if objtype not in ["status_message", "post", "reshare", "comment"]:
        raise Http404()
    content = get_object_or_404(Content, guid=guid, visibility=Visibility.PUBLIC)
    if not content.local:
        url = "https://%s/fetch/%s/%s" % (
            content.author.handle.split("@")[1], objtype, guid
        )
        return HttpResponseRedirect(url)
    entity = make_federable_content(content)
    message = get_full_xml_representation(entity, content.author.private_key)
    document = MagicEnvelope(
        message=message, private_key=content.author.private_key, author_handle=content.author.handle
    )
    return HttpResponse(document.render(), content_type="application/magic-envelope+xml")
项目:django-datawatch    作者:RegioHelden    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        try:
            return super(ResultView, self).get(request, *args, **kwargs)
        except Http404:
            messages.add_message(self.request, messages.WARNING,
                                 _('Check result does not exist (anymore)'))
            return HttpResponseRedirect(redirect_to=reverse_lazy(
                'django_datawatch_index'))
项目:django-modeltranslation-wagtail    作者:benjaoming    | 项目源码 | 文件源码
def test_default_language(self):
        root = Page.get_first_root_node()
        translation.activate(settings.LANGUAGE_CODE)
        title_en = "The English Title"
        _created = models.Test(
            title=title_en,
            slug="test",
            url_path='/kiks/',
        )
        _created = root.add_child(instance=_created)
        test_object = models.Test.objects.get(id=_created.id)
        self.assertEqual(test_object.title, title_en)

        root_get = self.client.get("/")
        self.assertTrue(isinstance(root_get, HttpResponseRedirect))
项目:shuup-wishlist    作者:shuup    | 项目源码 | 文件源码
def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        if self.object.customer == request.customer:
            self.object.delete()
            return HttpResponseRedirect(self.success_url)
        else:
            raise Http404
项目:shuup-wishlist    作者:shuup    | 项目源码 | 文件源码
def delete(self, request, *args, **kwargs):
        wishlist = self.get_object()
        if wishlist.customer == request.customer:
            wishlist.products.remove(self.kwargs['product_pk'])
            messages.success(request, _("Product removed from wishlist."))
            return HttpResponseRedirect(reverse_lazy('shuup:wishlist_detail', kwargs=dict(pk=wishlist.pk)))
        else:
            raise Http404
项目:mooder    作者:phith0n    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.object.show = False
        self.object.save()

        return HttpResponseRedirect(request.META.get('HTTP_REFERER') or self.jump_url)
项目:mooder    作者:phith0n    | 项目源码 | 文件源码
def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.verify = 'failed'
        self.object.save()
        return HttpResponseRedirect(self.jump_url)
项目:mooder    作者:phith0n    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.object.show = False
        self.object.save()

        return HttpResponseRedirect(request.META.get('HTTP_REFERER') or reverse('management-post-list-verify'))
项目:mooder    作者:phith0n    | 项目源码 | 文件源码
def form_valid(self, form):
        self.object = form.save(commit=False)
        if self.object.coin < 0 and self.object.user.coin + self.object.coin < 0:
            self.object.coin = -self.object.user.coin

        self.object.admin = self.request.user
        self.object.user.coin += self.object.coin
        self.object.rest = self.object.user.coin

        self.object.user.save()
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
def logout(request):
    auth_logout(request)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
def updateImage(request):
    if request.method == 'POST':
        form = ChangeUserImageForm(request.POST,request.FILES)
        if form.is_valid():
            image = form.cleaned_data['image']
            user = request.user
            user.image = image
            user.save()
            return HttpResponseRedirect(reverse('index-view'))
    else:
        form = ChangeUserImageForm()
    return render(request, 'users/changeuserimage.html',{'form':form})
项目:pony    作者:Eastwu5788    | 项目源码 | 文件源码
def user_setting_handler(request):
    user_account = request.META["user_info"]
    user_info = UserInfo.query_format_info_by_user_id(user_account.id)
    if request.method == "GET":
        data = dict()
        user_info["email"] = UserAccount.query_user_by_id(user_account.id).email
        data["user_info"] = user_info
        return render(request, "about/setting.html", data)

    # ????
    avatar = UploadImage(request)
    image_list = avatar.save()

    nick_name = request.POST.get("nick_name")
    gender = request.POST.get("gender")

    user = UserInfo.objects.get(user_id=user_account.id)
    user.gender = gender
    if nick_name != user_info["nick_name"]:
        user.nick_name = nick_name
    if len(image_list) > 0:
        user.avatar = image_list[0].id
    user.save()

    # ????
    UserInfo.query_format_info_by_user_id(user_account.id, False)

    return HttpResponseRedirect("/user/info/" + str(user_account.id))
项目:pony    作者:Eastwu5788    | 项目源码 | 文件源码
def home_recommend_handler(request):

    operator = request.META["user_info"]

    if request.method == "GET":
        result = dict()
        article_id = request.GET.get("article_id")
        result["data"] = BlogArticle.query_article_by_id(article_id)
        result["operator"] = operator
        result["user_info"] = UserInfo.query_format_info_by_user_id(operator.id)
        return render(request, "manage/recommend.html", result)

    image_list = UploadImage(request).save()
    article_id = request.POST.get("article_id")
    introl = request.POST.get("intro")
    weight = request.POST.get("weight")

    # TODO:????

    recommend = HomeRecommend()
    recommend.share_id = article_id
    recommend.reco_cover = image_list[0].id
    recommend.reco_intro = introl
    recommend.weight = weight
    recommend.operator_id = operator.id
    recommend.status = 1
    recommend.save()

    return HttpResponseRedirect("/manage")
项目:pony    作者:Eastwu5788    | 项目源码 | 文件源码
def login_required(func):
    """
    ??????????
    """
    def do_auth(*args, **kwargs):
        user_info = args[0].META["user_info"]
        if not user_info:
            return HttpResponseRedirect("/auth/login")
        return func(*args, **kwargs)
    return do_auth
项目:pony    作者:Eastwu5788    | 项目源码 | 文件源码
def manager_required(func):
    """
    ?????????????????
    ?????????????????
    """
    def auth_check(*args, **kwargs):
        account = args[0].META["user_info"]
        try:
            user_info = UserInfo.objects.filter(user_id=account.id, status=1).get()
            if user_info.role_id != 9:
                return HttpResponseRedirect("/index")
        except UserInfo.DoesNotExist:
            return HttpResponseRedirect("/index")
        return func(*args, **kwargs)
    return auth_check
项目:ODM2WebSDL    作者:ODM2    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        user = User.objects.get(pk=request.user.pk)
        form = UserUpdateForm(request.POST, instance=user, initial={'organization': user.odm2user.affiliation.organization})
        if form.is_valid():
            form.save()
            messages.success(request, 'Your information has been updated successfully.')
            return HttpResponseRedirect(reverse('user_account'))
        else:
            messages.error(request, 'There were some errors in the form.')
            return render(request, self.template_name, {'form': form, 'organization_form': OrganizationForm()})
项目:ODM2WebSDL    作者:ODM2    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        site = self.get_object(self.get_queryset())
        if not site:
            raise Http404

        if request.user.id != site.django_user_id:
            # temporary error. TODO: do something a little bit more elaborate. or maybe not...
            raise Http404

        sampling_feature = site.sampling_feature
        data_logger_program = DataLoggerProgramFile.objects.filter(
            affiliation_id=site.affiliation_id,
            program_name__contains=sampling_feature.sampling_feature_code
        ).first()
        data_logger_file = data_logger_program.data_logger_files.first()

        feature_actions = sampling_feature.feature_actions.with_results().all()
        for feature_action in feature_actions:
            result = feature_action.results.first()
            delete_result(result)

        data_logger_file.delete()
        data_logger_program.delete()
        sampling_feature.site.delete()
        sampling_feature.delete()
        site.sensors.all().delete()
        site.delete()
        return HttpResponseRedirect(self.success_url)
项目:callisto-core    作者:project-callisto    | 项目源码 | 文件源码
def render_done(self):
        return HttpResponseRedirect(self.steps.done_url)
项目:callisto-core    作者:project-callisto    | 项目源码 | 文件源码
def render_last(self):
        return HttpResponseRedirect(self.steps.last_url)
项目:callisto-core    作者:project-callisto    | 项目源码 | 文件源码
def render_current(self):
        return HttpResponseRedirect(self.steps.current_url)
项目:LDERP    作者:Ignoramuss    | 项目源码 | 文件源码
def forms_valid(self, forms, form_name):
        form_valid_method = '%s_form_valid' % form_name
        if hasattr(self, form_valid_method):
            return getattr(self, form_valid_method)(forms[form_name])
        else:
            return HttpResponseRedirect(self.get_success_url(form_name))
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def home(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('task-list'))
    else:
        return render(request, 'stormtrooper/homepage.html')
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def get(self, request, pk):
        try:
            task_obj = Task.objects.get(pk=pk)
            if not task_obj.is_closed:
                exclude = request.GET.get('exclude')
                random_qn = task_obj.random_question(user=request.user,
                                                     exclude=exclude)
                if random_qn:
                    return HttpResponseRedirect(random_qn.get_absolute_url())
                messages.add_message(self.request, messages.ERROR, "There are no more unanswered questions")
            return HttpResponseRedirect(task_obj.get_absolute_url())
        except Task.DoesNotExist:
            return Http404
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def form_invalid(self, form):
        if form.errors and form.errors.get('task'):
            for form_error in form.errors['task']:
                messages.add_message(self.request, level=messages.ERROR, message=form_error)
        return HttpResponseRedirect(form.task.get_absolute_url())
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            return HttpResponseRedirect(reverse('home'))
        return super(LoginView, self).dispatch(request, *args, **kwargs)
项目:Intranet    作者:mituSkillologies-Interns    | 项目源码 | 文件源码
def vote(request, question_id):
    question = get_object_or_404(Question,pk = question_id)
    try:
        selected_choice = question.choice_set.get(pk = request.POST['choice'])
    except (KeyError, Choice.DoesNotExists):
        return render(request, 'polls/detail.html',{
            'question': question,
            'error_message' : "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args = (question.id)))
    #return HttpResponse("You're voting on question %s." % question_id)
项目:djamazing    作者:sunscrapers    | 项目源码 | 文件源码
def get(self, request):
        username = request.user.get_username()
        filename = request.GET['filename']
        signature = request.GET['signature']

        if not check_signature(signature, filename, username):
            return HttpResponseForbidden()
        return HttpResponseRedirect(
            redirect_to=self.storage.cloud_front_url(filename)
        )
项目:ah10-hel-govtech    作者:Lokenstein    | 项目源码 | 文件源码
def logout_view(request):
    logout(request)
    return HttpResponseRedirect("login")