Python django.template.context_processors.csrf() Examples

The following are 30 code examples of django.template.context_processors.csrf(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.template.context_processors , or try the search function .
Example #1
Source File: settings_views.py    From sal with Apache License 2.0 6 votes vote down vote up
def new_user(request):
    c = {}
    c.update(csrf(request))
    if request.method == 'POST':
        form = forms.NewUserForm(request.POST)
        if form.is_valid():
            user = form.save()
            user_profile = UserProfile.objects.get(user=user)
            user_profile.level = request.POST['user_level']
            user_profile.save()
            return redirect('manage_users')
    else:
        form = forms.NewUserForm()
    c = {'form': form}

    return render(request, 'forms/new_user.html', c) 
Example #2
Source File: views.py    From sal with Apache License 2.0 6 votes vote down vote up
def edit_business_unit(request, bu_id):
    business_unit = get_object_or_404(BusinessUnit, pk=int(bu_id))
    c = {}
    c.update(csrf(request))
    if request.method == 'POST':
        if request.user.is_staff:
            form = EditUserBusinessUnitForm(request.POST, instance=business_unit)
        else:
            form = EditBusinessUnitForm(request.POST, instance=business_unit)
        if form.is_valid():
            new_business_unit = form.save(commit=False)
            new_business_unit.save()
            form.save_m2m()
            return redirect('bu_dashboard', new_business_unit.id)
    else:
        if request.user.is_staff:
            form = EditUserBusinessUnitForm(instance=business_unit)
        else:
            form = EditBusinessUnitForm(instance=business_unit)
    c = {'form': form, 'business_unit': business_unit}
    return render(request, 'forms/edit_business_unit.html', c) 
Example #3
Source File: summary.py    From django-silk with MIT License 6 votes vote down vote up
def _create_context(self, request):
        raw_filters = request.session.get(self.filters_key, {})
        filters = [BaseFilter.from_dict(filter_d) for _, filter_d in raw_filters.items()]
        avg_overall_time = self._avg_num_queries(filters)
        c = {
            'request': request,
            'num_requests': models.Request.objects.filter(*filters).count(),
            'num_profiles': models.Profile.objects.filter(*filters).count(),
            'avg_num_queries': avg_overall_time,
            'avg_time_spent_on_queries': self._avg_time_spent_on_queries(filters),
            'avg_overall_time': self._avg_overall_time(filters),
            'longest_queries_by_view': self._longest_query_by_view(filters),
            'most_time_spent_in_db': self._time_spent_in_db_by_view(filters),
            'most_queries': self._num_queries_by_view(filters),
            'filters': raw_filters
        }
        c.update(csrf(request))
        return c 
Example #4
Source File: summary.py    From django-silk with MIT License 6 votes vote down vote up
def _create_context(self, request):
        raw_filters = request.session.get(self.filters_key, {})
        filters = [BaseFilter.from_dict(filter_d) for _, filter_d in raw_filters.items()]
        avg_overall_time = self._avg_num_queries(filters)
        c = {
            'request': request,
            'num_requests': models.Request.objects.filter(*filters).count(),
            'num_profiles': models.Profile.objects.filter(*filters).count(),
            'avg_num_queries': avg_overall_time,
            'avg_time_spent_on_queries': self._avg_time_spent_on_queries(filters),
            'avg_overall_time': self._avg_overall_time(filters),
            'longest_queries_by_view': self._longest_query_by_view(filters),
            'most_time_spent_in_db': self._time_spent_in_db_by_view(filters),
            'most_queries': self._num_queries_by_view(filters),
            'filters': raw_filters
        }
        c.update(csrf(request))
        return c 
Example #5
Source File: views.py    From nector with GNU General Public License v3.0 6 votes vote down vote up
def register_user(request):
    '''Registers user.
       Renders success page on success,
               register page on failure.'''

    # User is submitting form.
    # Read from form and save
    # form data as new user.
    if request.method == "POST":
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')
    args = {}
    args.update(csrf(request))
    args['form'] = MyRegistrationForm(request.POST)
    print args
    return render_to_response('register.html', args) 
Example #6
Source File: views.py    From django-htk with MIT License 6 votes vote down vote up
def thread_create(request, fid=None):
    forum = get_object_or_404(Forum, id=fid)
    data = wrap_data_forum(request)
    user = data['user']
    data.update(csrf(request)) 
    data['forum'] = forum
    success = False
    if request.method == 'POST':
        thread_creation_form = ThreadCreationForm(request.POST)
        if thread_creation_form.is_valid():
            thread = thread_creation_form.save(author=user, forum=forum)
            success = True
        else:
            for error in thread_creation_form.non_field_errors():
                data['errors'].append(error)
    else:
        thread_creation_form = ThreadCreationForm(None)
    if success:
        response = redirect(reverse('forum_thread', args=(thread.id,)))
    else:
        data['forms'].append(thread_creation_form)
        data['thread_creation_form'] = thread_creation_form
        response = _r('forum/thread_create.html', data)
    return response 
Example #7
Source File: views.py    From django-htk with MIT License 6 votes vote down vote up
def message_create(request, tid=None):
    thread = get_object_or_404(ForumThread, id=tid)
    data = wrap_data_forum(request)
    data['thread'] = thread
    user = data['user']
    data.update(csrf(request)) 
    success = False
    if request.method == 'POST':
        message_creation_form = MessageCreationForm(request.POST)
        if message_creation_form.is_valid():
            message = message_creation_form.save(author=user, thread=thread)
            success = True
        else:
            for error in auth_form.non_field_errors():
                data['errors'].append(error)
    else:
        message_creation_form = MessageCreationForm(None)
    if success:
        response = redirect(reverse('forum_thread', args=(thread.id,)))
    else:
        data['message_creation_form'] = message_creation_form
        response = _r('forum/message_create.html', data)

    return response 
Example #8
Source File: views.py    From django-htk with MIT License 6 votes vote down vote up
def prelaunch(request):
    if is_prelaunch_mode():
        data = get_view_context(request)
        data.update(csrf(request))

        success = False
        if request.method == 'POST':
            prelaunch_signup_form = PrelaunchSignupForm(request.POST)
            if prelaunch_signup_form.is_valid():
                site = get_current_site(request)
                prelaunch_signup = prelaunch_signup_form.save(site)
                success = True
            else:
                for error in prelaunch_signup_form.non_field_errors():
                    data['errors'].append(error)
        else:
            prelaunch_signup_form = PrelaunchSignupForm()
        data['prelaunch_signup_form'] = prelaunch_signup_form
        data['success'] = success
        prelaunch_template = htk_setting('HTK_PRELAUNCH_TEMPLATE', HTK_PRELAUNCH_TEMPLATE)
        response = _r(prelaunch_template, data)
    else:
        response = redirect(htk_setting('HTK_INDEX_URL_NAME'))
    return response 
Example #9
Source File: dashboard.py    From online with GNU Affero General Public License v3.0 5 votes vote down vote up
def widget(self):
        context = {'widget_id': self.id, 'widget_title': self.title, 'widget_icon': self.widget_icon,
                   'widget_type': self.widget_type, 'form': self, 'widget': self}
        context.update(csrf(self.request))
        self.context(context)
        return loader.render_to_string(self.template, context) 
Example #10
Source File: settings_views.py    From sal with Apache License 2.0 5 votes vote down vote up
def edit_user(request, user_id):
    the_user = get_object_or_404(User, pk=int(user_id))
    c = {}
    c.update(csrf(request))
    if request.method == 'POST':
        if the_user.has_usable_password:
            form = forms.EditUserForm(request.POST)
        else:
            form = forms.EditLDAPUserForm(request.POST)
        if form.is_valid():
            user = form.save()
            user_profile = UserProfile.objects.get(user=the_user)
            user_profile.level = request.POST['user_level']
            user_profile.save()
            if user_profile.level != 'GA':
                user.is_staff = False
                user.save()
            return redirect('manage_users')
    else:
        if the_user.has_usable_password:
            form = forms.EditUserForm(
                {'user_level': the_user.userprofile.level, 'user_id': the_user.id})
        else:
            form = forms.EditLDAPUserForm(
                {'user_level': the_user.userprofile.level, 'user_id': the_user.id})

    c = {'form': form, 'the_user': the_user}

    return render(request, 'forms/edit_user.html', c) 
Example #11
Source File: dashboard.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def widget(self):
        context = {'widget_id': self.id, 'widget_title': self.title, 'widget_icon': self.widget_icon,
                   'widget_type': self.widget_type, 'form': self, 'widget': self}
        context.update(csrf(self.request))
        self.context(context)
        return loader.render_to_string(self.template, context) 
Example #12
Source File: profiling.py    From django-silk with MIT License 5 votes vote down vote up
def _create_context(self, request, *args, **kwargs):
        request_id = kwargs.get('request_id')
        if request_id:
            silk_request = Request.objects.get(pk=request_id)
        else:
            silk_request = None
        show = request.GET.get('show', self.default_show)
        order_by = request.GET.get('order_by', self.defualt_order_by)
        if show:
            show = int(show)
        func_name = request.GET.get('func_name', None)
        name = request.GET.get('name', None)
        filters = request.session.get(self.session_key_profile_filters, {})
        context = {
            'show': show,
            'order_by': order_by,
            'request': request,
            'func_name': func_name,
            'options_show': self.show,
            'options_order_by': self.order_by,
            'options_func_names': self._get_function_names(silk_request),
            'options_names': self._get_names(silk_request),
            'filters': filters
        }
        context.update(csrf(request))
        if silk_request:
            context['silk_request'] = silk_request
        if func_name:
            context['func_name'] = func_name
        if name:
            context['name'] = name
        objs = self._get_objects(show=show,
                                 order_by=order_by,
                                 func_name=func_name,
                                 silk_request=silk_request,
                                 name=name,
                                 filters=[BaseFilter.from_dict(x) for _, x in filters.items()])
        context['results'] = objs
        return context 
Example #13
Source File: requests.py    From django-silk with MIT License 5 votes vote down vote up
def _create_context(self, request):
        show = request.GET.get('show', self.default_show)
        order_by = request.GET.get('order_by', self.default_order_by)
        order_dir = request.GET.get('order_dir', self.default_order_dir)
        if show:
            show = int(show)
        path = request.GET.get('path', None)
        raw_filters = request.session.get(self.session_key_request_filters, {})
        context = {
            'show': show,
            'order_by': order_by,
            'order_dir': order_dir,
            'request': request,
            'options_show': self.show,
            'options_order_by': self.options_order_by,
            'options_order_dir': self.options_order_dir,
            'options_paths': self._get_paths(),
            'options_status_codes': self._get_status_codes(),
            'options_methods': self._get_methods(),
            'view_names': self._get_views(),
            'filters': raw_filters
        }
        context.update(csrf(request))
        if path:
            context['path'] = path
        context['results'] = self._get_objects(show, order_by, order_dir, path,
                                               filters=[BaseFilter.from_dict(x) for _, x in raw_filters.items()])
        return context 
Example #14
Source File: profiling.py    From django-silk with MIT License 5 votes vote down vote up
def _create_context(self, request, *args, **kwargs):
        request_id = kwargs.get('request_id')
        if request_id:
            silk_request = Request.objects.get(pk=request_id)
        else:
            silk_request = None
        show = request.GET.get('show', self.default_show)
        order_by = request.GET.get('order_by', self.defualt_order_by)
        if show:
            show = int(show)
        func_name = request.GET.get('func_name', None)
        name = request.GET.get('name', None)
        filters = request.session.get(self.session_key_profile_filters, {})
        context = {
            'show': show,
            'order_by': order_by,
            'request': request,
            'func_name': func_name,
            'options_show': self.show,
            'options_order_by': self.order_by,
            'options_func_names': self._get_function_names(silk_request),
            'options_names': self._get_names(silk_request),
            'filters': filters
        }
        context.update(csrf(request))
        if silk_request:
            context['silk_request'] = silk_request
        if func_name:
            context['func_name'] = func_name
        if name:
            context['name'] = name
        objs = self._get_objects(show=show,
                                 order_by=order_by,
                                 func_name=func_name,
                                 silk_request=silk_request,
                                 name=name,
                                 filters=[BaseFilter.from_dict(x) for _, x in filters.items()])
        context['results'] = objs
        return context 
Example #15
Source File: monsters.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def monster_piece_edit(request, profile_name, instance_id):
    try:
        summoner = Summoner.objects.select_related('user').get(user__username=profile_name)
    except Summoner.DoesNotExist:
        return HttpResponseBadRequest()

    pieces = get_object_or_404(MonsterPiece, pk=instance_id)
    is_owner = (request.user.is_authenticated and summoner.user == request.user)
    template = loader.get_template('herders/profile/monster_inventory/monster_piece_form.html')

    if is_owner:
        form = MonsterPieceForm(request.POST or None, instance=pieces)
        form.helper.form_action = request.path

        if request.method == 'POST' and form.is_valid():
            new_piece = form.save()
            template = loader.get_template('herders/profile/monster_inventory/monster_piece_snippet.html')

            context = {
                'piece': new_piece,
                'is_owner': is_owner,
            }

            response_data = {
                'code': 'success',
                'instance_id': new_piece.pk.hex,
                'html': template.render(context),
            }
        else:
            # Return form filled in and errors shown
            context = {'form': form}
            context.update(csrf(request))

            response_data = {
                'code': 'error',
                'html': template.render(context),
            }

        return JsonResponse(response_data)
    else:
        raise PermissionDenied() 
Example #16
Source File: runes.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def rune_assign(request, profile_name, instance_id, slot=None):
    rune_queryset = RuneInstance.objects.filter(owner=request.user.summoner, assigned_to=None)
    filter_form = AssignRuneForm(request.POST or None, initial={'slot': slot}, prefix='assign')
    filter_form.helper.form_action = reverse('herders:rune_assign', kwargs={'profile_name': profile_name, 'instance_id': instance_id})

    if slot:
        rune_queryset = rune_queryset.filter(slot=slot)

    if request.method == 'POST' and filter_form.is_valid():
        rune_filter = RuneInstanceFilter(filter_form.cleaned_data, queryset=rune_queryset)
        template = loader.get_template('herders/profile/runes/assign_results.html')

        context = {
            'filter': rune_filter.qs,
            'profile_name': profile_name,
            'instance_id': instance_id,
        }
        context.update(csrf(request))

        response_data = {
            'code': 'results',
            'html': template.render(context)
        }
    else:
        rune_filter = RuneInstanceFilter(queryset=rune_queryset)
        template = loader.get_template('herders/profile/runes/assign_form.html')

        context = {
            'filter': rune_filter.qs,
            'form': filter_form,
            'profile_name': profile_name,
            'instance_id': instance_id,
        }
        context.update(csrf(request))

        response_data = {
            'code': 'success',
            'html': template.render(context)
        }

    return JsonResponse(response_data) 
Example #17
Source File: runes.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def rune_craft_edit(request, profile_name, craft_id):
    craft = get_object_or_404(RuneCraftInstance, pk=craft_id)
    try:
        summoner = Summoner.objects.select_related('user').get(user__username=profile_name)
    except Summoner.DoesNotExist:
        return HttpResponseBadRequest()

    is_owner = (request.user.is_authenticated and summoner.user == request.user)

    form = AddRuneCraftInstanceForm(request.POST or None, instance=craft)
    form.helper.form_action = reverse('herders:rune_craft_edit', kwargs={'profile_name': profile_name, 'craft_id': craft_id})
    template = loader.get_template('herders/profile/runes/add_craft_form.html')

    if is_owner:
        if request.method == 'POST' and form.is_valid():
            rune = form.save()
            messages.success(request, 'Saved changes to ' + str(rune))
            form = AddRuneInstanceForm()
            form.helper.form_action = reverse('herders:rune_craft_edit', kwargs={'profile_name': profile_name, 'craft_id': craft_id})

            context = {'form': form}
            context.update(csrf(request))

            response_data = {
                'code': 'success',
                'html': template.render(context)
            }
        else:
            # Return form filled in and errors shown
            context = {'form': form}
            context.update(csrf(request))

            response_data = {
                'code': 'error',
                'html': template.render(context)
            }

        return JsonResponse(response_data)
    else:
        return HttpResponseForbidden() 
Example #18
Source File: views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def token_view(request):
    context = RequestContext(request, processors=[csrf])
    template = Template('{% csrf_token %}')
    return HttpResponse(template.render(context)) 
Example #19
Source File: views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def non_token_view_using_request_processor(request):
    """Use the csrf view processor instead of the token."""
    context = RequestContext(request, processors=[csrf])
    template = Template('')
    return HttpResponse(template.render(context)) 
Example #20
Source File: test_context_processor.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_force_token_to_string(self):
        request = HttpRequest()
        test_token = '1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD'
        request.META['CSRF_COOKIE'] = test_token
        token = csrf(request).get('csrf_token')
        self.assertTrue(equivalent_tokens(str(token), test_token)) 
Example #21
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def csrf_view(request):
    return HttpResponse(csrf(request)['csrf_token']) 
Example #22
Source File: views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def token_view(request):
    context = RequestContext(request, processors=[csrf])
    template = Template('{% csrf_token %}')
    return HttpResponse(template.render(context)) 
Example #23
Source File: test_context_processor.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_force_token_to_string(self):
        request = HttpRequest()
        test_token = '1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD'
        request.META['CSRF_COOKIE'] = test_token
        token = csrf(request).get('csrf_token')
        self.assertTrue(equivalent_tokens(str(token), test_token)) 
Example #24
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def csrf_view(request):
    return HttpResponse(csrf(request)['csrf_token']) 
Example #25
Source File: dashboard.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def widget(self):
        context = {'widget_id': self.id, 'widget_title': self.title, 'widget_icon': self.widget_icon,
                   'widget_type': self.widget_type, 'form': self, 'widget': self}
        context.update(csrf(self.request))
        self.context(context)
        return loader.render_to_string(self.template, context) 
Example #26
Source File: views.py    From shortweb with MIT License 5 votes vote down vote up
def index(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('shorturl/index.html', c) 
Example #27
Source File: dashboard.py    From StormOnline with Apache License 2.0 5 votes vote down vote up
def widget(self):
        context = {'widget_id': self.id, 'widget_title': self.title, 'widget_icon': self.widget_icon,
                   'widget_type': self.widget_type, 'form': self, 'widget': self}
        context.update(csrf(self.request))
        self.context(context)
        return loader.render_to_string(self.template, context) 
Example #28
Source File: search.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def search_view(request):
    context = {}
    if request.POST:
        context.update(csrf(request))
        context['request'] = request.POST['package']
        context['package_list'] = Package.objects.filter(c_name__icontains=request.POST['package'])[:24]
    else:
        return HttpResponseBadRequest()
    return render(request, 'search.html', context) 
Example #29
Source File: dashboard.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def widget(self):
        context = {'widget_id': self.id, 'widget_title': self.title, 'widget_icon': self.widget_icon,
                   'widget_type': self.widget_type, 'form': self, 'widget': self}
        context.update(csrf(self.request))
        self.context(context)
        return loader.render_to_string(self.template, context) 
Example #30
Source File: views.py    From suponoff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def home(request, template_name="suponoff/index.html"):
    context = get_index_template_data()
    context.update(csrf(request))
    resp = render_to_response(template_name, context)
    return resp