django.http.HttpResponseForbidden - python examples

Here are the examples of the python api django.http.HttpResponseForbidden taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : amitsaha
@cache_page(60*15)
def show_post(request, post_id=None):
    post = Post.objects.filter(id=post_id)[0]
    # if the post is not public, only viewable by the author
    if not post.public:
        if not post.author == request.user:
            return HttpResponseForbidden()
    post_tags = PostTag.objects.filter(post=post)
    return render(request, 'tilweb/view_post.html', {
        'post': post,
        'tags': post_tags if len(post_tags) else None,
    })

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : IntuitDeveloper
@csrf_exempt
@require_POST
def index(request):
	payload = request.body
	signature = request.META.get('HTTP_INTUIT_SIGNATURE')

	if signature is None:
		return HttpResponseForbidden('Permission denied.')
	
	if isValidPayload(signature, payload):	
		print(payload.decode())
		request.session['WebhooksPayload'] = (payload.decode(), None)
		return HttpResponse(payload.decode())

	else:
		return HttpResponseBadRequest('Payload not validated.')

3 View Complete Implementation : write.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@login_required
def clearProfileImage(request):
    if request.method == 'POST':
        try:
            account = Account.objects.get(user=request.user)

            # Clean up previous image
            account.profile_image.delete()
            account.save()

            return HttpResponse('Image Deleted')
        except Exception:
            return HttpResponseServerError(reason=str("default"))
    else:
        return HttpResponseForbidden('allowed only via POST')

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : aplanas
    def form_valid(self, form):
        # Check that the owner of the `subscription` is the current
        # user.  Usually this is not necessary, because of the
        # validation of the form.
        self.subscription = form.cleaned_data['subscription']
        if self.subscription.user != self.request.user:
            return HttpResponseForbidden()

        action = form.cleaned_data['action']
        if action in (Result.PENDING, Result.SENT):
            form.mark()
        elif action == IssueActionForm.SEND_NOW:
            form.send()

        return super(ResultMultipleUpdateView, self).form_valid(form)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
def add_to_task_queue(request, task_queue_pk, docameent_pk):
    """
    Add docameent to OR remove from Task Queue
    """
    task_queue = TaskQueue.objects.get(pk=task_queue_pk)
    if task_queue.docameents.filter(pk=docameent_pk).exists():
        if not request.user.is_admin and not request.user.is_manager:
            return HttpResponseForbidden()
        task_queue.docameents.remove(docameent_pk)
        message = 'removed from'
    else:
        task_queue.docameents.add(docameent_pk)
        message = 'added to'
    full_message = 'Docameent successfully %s %s' % (message, str(task_queue))
    if request.is_ajax():
        data = {'message': full_message, 'status': 'success'}
        return JsonResponse(data, encoder=DjangoJSONEncoder, safe=False)
    messages.success(request, full_message)
    return redirect(reverse('docameent:docameent-detail', args=[docameent_pk]))

3 View Complete Implementation : views.py
Copyright MIT License
Author : liangliangyy
@login_required
def show_maps(request):
    if request.user.is_superuser:
        defaultdate = str(datetime.datetime.now().date())
        date = request.GET.get('date', defaultdate)
        context = {
            'date': date
        }
        return render(request, 'owntracks/show_maps.html', context)
    else:
        from django.http import HttpResponseForbidden
        return HttpResponseForbidden()

3 View Complete Implementation : defaults.py
Copyright Apache License 2.0
Author : drexly
@requires_csrf_token
def permission_denied(request, exception, template_name='403.html'):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 2616) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(
        template.render(request=request, context={'exception': force_text(exception)})
    )

3 View Complete Implementation : defaults.py
Copyright Apache License 2.0
Author : edisonlz
@requires_csrf_token
def permission_denied(request, template_name='403.html'):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 2616) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(template.render(RequestContext(request)))

3 View Complete Implementation : views.py
Copyright MIT License
Author : enjoy-binbin
@login_required
def refresh_cache(request):
    """ 清空缓存 """
    if request.user.is_superuser:
        from django.core.cache import cache
        if cache and cache is not None:
            cache.clear()

        messages.success(request, '缓存刷新成功')
        return redirect(reverse('blog:index'))
    else:
        return HttpResponseForbidden()  # 403封装的HttpResponse

3 View Complete Implementation : decorators.py
Copyright The Unlicense
Author : nerosketch
def hash_auth_view(fn):
    @wraps(fn)
    def wrapped(request, *args, **kwargs):
        api_auth_secret = getattr(settings, 'API_AUTH_SECRET')
        sign = request.GET.get('sign')
        if sign is None or sign == '':
            return HttpResponseForbidden('Access Denied')

        # Transmittent get list without sign
        get_values = request.GET.copy()
        del get_values['sign']
        values_list = [l for l in get_values.values() if l]
        values_list.sort()
        values_list.append(api_auth_secret)
        if check_sign(values_list, sign):
            return fn(request, *args, **kwargs)
        else:
            return HttpResponseForbidden('Access Denied')
    return wrapped

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : respawner
    @action(detail=True, methods=["get", "post", "put", "patch"], url_path="configure")
    def configure(self, request, pk=None):
        router = self.get_object()

        # Check if the router runs on a supported platform
        if not router.platform:
            raise ServiceUnavailable("Unsupported router platform.")

        # Check user permission first
        if not request.user.has_perm("peering.deploy_configuration_router"):
            return HttpResponseForbidden()

        # Commit changes only if not using a GET request
        error, changes = router.set_napalm_configuration(
            router.generate_configuration(), commit=(request.method not in SAFE_METHODS)
        )
        return Response({"changed": not error, "changes": changes, "error": error})

3 View Complete Implementation : middleware.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
    def process_view(self, request, view_func, args, kwargs):
        if hasattr(view_func, 'view_clast') and hasattr(view_func.view_clast, 'sub_app'):
            current_sub_app = view_func.view_clast.sub_app
            from apps.extract.app_vars import STANDARD_LOCATORS, OPTIONAL_LOCATORS
            available_locators = set(STANDARD_LOCATORS.val) | set(OPTIONAL_LOCATORS.val)
            if current_sub_app not in available_locators:
                messages.error(request, 'This locator is not enabled.')
                if request.is_ajax() or request.META['CONTENT_TYPE'] == 'application/json':
                    return HttpResponseForbidden('Standard sub-application "%s" is not enabled.'
                                                 % current_sub_app)
                return redirect(reverse_lazy('common:application-settings'))

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
@login_required
@only_admins
def preload_devices(request):
    if not request.user.is_superuser:
        return HttpResponseForbidden('you have not super user')
    grp_id = request.GET.get('grp')
    dot_id = request.GET.get('dot')
    all_devices = Device.objects.filter(group__id=grp_id)
    dot_devices = Device.objects.filter(dot__id=dot_id)
    dot_devices_ids = tuple(dev.pk for dev in dot_devices.iterator())
    del dot_devices

    return render(request, 'maps/preload_devices_tmpl.html', {
        'all_devices': all_devices.iterator(),
        'dot_devices_ids': dot_devices_ids
    }, content_type='text/html')

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : Uninett
def handle_search(request, _searchform, form_target):
    account = get_account(request)
    if not account:
        return HttpResponseForbidden(
            "You must be logged in to access this resource")

    context = _build_context(request)

    context.update({'form_target': form_target})

    return render(request, 'syslogger/frag-search.html', context)

3 View Complete Implementation : csrf.py
Copyright Apache License 2.0
Author : edisonlz
def csrf_failure(request, reason=""):
    """
    Default view used when request fails CSRF protection
    """
    from django.middleware.csrf import REASON_NO_REFERER
    t = Template(CSRF_FAILURE_TEMPLATE)
    c = Context({'DEBUG': settings.DEBUG,
                 'reason': reason,
                 'no_referer': reason == REASON_NO_REFERER
                 })
    return HttpResponseForbidden(t.render(c), content_type='text/html')

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : amitsaha
def show_post(request, post_id=None):
    post = Post.objects.filter(id=post_id)[0]
    # if the post is not public, only viewable by the author
    if not post.public:
        if not post.author == request.user:
            return HttpResponseForbidden()
    post_tags = PostTag.objects.filter(post=post)
    return render(request, 'tilweb/view_post.html', {
        'post': post,
        'tags': post_tags if len(post_tags) else None,
    })

3 View Complete Implementation : views.py
Copyright MIT License
Author : ericls
@login_required
def create_appendix(request, pk):
    topic = Topic.objects.get(pk=pk)
    if not topic.user == request.user:
        return HttpResponseForbidden(_('You are not allowed to append other\'s topic'))
    if request.method == 'POST':
        form = AppendixForm(request.POST, topic=topic)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('niji:topic', kwargs={'pk': topic.pk}))
    else:
        form = AppendixForm()

    return render(request, 'niji/create_appendix.html', {
        'form': form, 'satle': _('Create Appendix'), 'pk': pk
    })

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : respawner
    @action(detail=True, methods=["get"], url_path="configuration")
    def configuration(self, request, pk=None):
        # Check user permission first
        if not request.user.has_perm("peering.view_configuration_router"):
            return HttpResponseForbidden()
        return Response({"configuration": self.get_object().generate_configuration()})

3 View Complete Implementation : views.py
Copyright MIT License
Author : wise-team
@login_required
def edit_feature(request, id, template_name="grid/update_feature.html"):
    """edits feature on a grid - this view has the same
    semantics as :func:`grid.views.add_feature`.

    Requires the user to be logged in.
    """

    if not request.user.profile.can_edit_grid_feature:
        return HttpResponseForbidden("permission denied")

    feature = get_object_or_404(Feature, id=id)
    form = FeatureForm(request.POST or None, instance=feature)

    if form.is_valid():
        feature = form.save()
        return HttpResponseRedirect(reverse('grid', kwargs={'slug': feature.grid.slug}))

    return render(request, template_name, {'form': form, 'grid': feature.grid})

3 View Complete Implementation : handy.py
Copyright GNU General Public License v3.0
Author : Kivou-2000607
def returnError(type=500, msg=None, home=True):
    import traceback
    from django.utils import timezone
    from django.http import HttpResponseServerError
    from django.http import HttpResponseForbidden
    from django.template.loader import render_to_string

    if type == 403:
        msg = "Permission Denied" if msg is None else msg
        return HttpResponseForbidden(render_to_string('403.html', {'exception': msg, 'home': home}))
    else:
        print("[{:%d/%b/%Y %H:%M:%S}] ERROR 500 \n{}".format(timezone.now(), traceback.format_exc()))
        return HttpResponseServerError(render_to_string('500.html', {'exception': traceback.format_exc().strip(), 'home': home}))

3 View Complete Implementation : views.py
Copyright MIT License
Author : wagtail
def toggle(request, segment_id):
    """Toggle the status of the selected segment.

    :param request: The http request
    :type request: django.http.HttpRequest
    :param segment_id: The primary key of the segment
    :type segment_id: int
    :returns: A redirect to the original page
    :rtype: django.http.HttpResponseRedirect

    """
    if request.user.has_perm('wagtailadmin.access_admin'):
        segment = get_object_or_404(Segment, pk=segment_id)

        segment.toggle()

        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

    return HttpResponseForbidden()

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
    def get(self, request, *args, **kwargs):
        if self.disallow_start():
            return HttpResponseForbidden(
                'Forbidden. Task "%s" is already started.' % self.task_name)
        else:
            form = self.form_clast()
            data = dict(header=form.header,
                        form_clast=self.html_form_clast,
                        form_data=form.as_p())
        return self.json_response(data)

3 View Complete Implementation : views.py
Copyright MIT License
Author : wise-team
@login_required
def build_search(request, template_name="searchv2/build_results.html"):

    if not request.user.is_superuser:
        return HttpResponseForbidden()

    results = []
    if request.method == 'POST':
        results = build_1(False)

    return render(request, template_name,
                {'results': results})

3 View Complete Implementation : views.py
Copyright MIT License
Author : ericls
    @method_decorator(login_required)
    def post(self, request, *args, **kwargs):
        current = Topic.objects.visible().get(pk=self.kwargs.get('pk'))
        if current.closed:
            return HttpResponseForbidden("Topic closed")
        topic_id = self.kwargs.get('pk')
        form = ReplyForm(
            request.POST,
            user=request.user,
            topic_id=topic_id
        )
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(
                reverse('niji:topic', kwargs={'pk': topic_id})
            )

3 View Complete Implementation : views.py
Copyright MIT License
Author : liangliangyy
@login_required
def refresh_memcache(request):
    try:

        if request.user.is_superuser:
            from DjangoBlog.utils import cache
            if cache and cache is not None:
                cache.clear()
            return HttpResponse("ok")
        else:
            return HttpResponseForbidden()
    except Exception as e:
        logger.error(e)
        return HttpResponse(e)

3 View Complete Implementation : defaults.py
Copyright GNU General Public License v2.0
Author : blackye
@requires_csrf_token
def permission_denied(request, template_name='403.html'):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 2616) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>')
    return http.HttpResponseForbidden(template.render(RequestContext(request)))

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : netbox-community
    def get(self, request, pk=None):

        if pk is not None:
            if not request.user.has_perm('users.change_token'):
                return HttpResponseForbidden()
            token = get_object_or_404(Token.objects.filter(user=request.user), pk=pk)
        else:
            if not request.user.has_perm('users.add_token'):
                return HttpResponseForbidden()
            token = Token(user=request.user)

        form = TokenForm(instance=token)

        return render(request, 'utilities/obj_edit.html', {
            'obj': token,
            'obj_type': token._meta.verbose_name,
            'form': form,
            'return_url': reverse('user:token_list'),
        })

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
@login_required
@only_admins
@json_view
def resolve_dots_by_group(request, grp_id):
    if not request.user.is_superuser:
        return HttpResponseForbidden('you have not super user')
    devs = Device.objects.filter(group__id=grp_id)
    dots = Dot.objects.filter(devices__in=devs).only('pk').values_list('pk')
    res = [dot[0] for dot in dots]
    return res

3 View Complete Implementation : views.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
@csrf_exempt
def multiuploader_delete(request, pk):
    """
    View for deleting photos with multiuploader AJAX plugin.
    made from api on:
    https://github.com/blueimp/jQuery-File-Upload
    """
    if request.method == 'POST':
#        log.info('Called delete image. Photo id='+str(pk))
        image = get_object_or_404(Photo, pk=pk)
        if image.place and image.place.owner != request.user:
            return HttpResponseForbidden()
        image.delete()
#        log.info('DONE. Deleted photo id='+str(pk))
        return HttpResponse(str(pk))
    else:
#        log.info('Recieved not POST request todelete image view')
        return HttpResponseBadRequest('Only POST accepted')

3 View Complete Implementation : account.py
Copyright GNU Affero General Public License v3.0
Author : maas
@csrf_exempt
def csrf(request):
    """Get the CSRF token for the authenticated user."""
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])
    if (
        request.user is None
        or not request.user.is_authenticated
        or not request.user.is_active
    ):
        return HttpResponseForbidden()
    token = get_token(request)
    # Don't mark the CSRF as used. If not done, Django will cycle the
    # CSRF and the returned CSRF will be un-usable.
    request.META.pop("CSRF_COOKIE_USED", None)
    return JsonResponse({"csrf": token})

3 View Complete Implementation : mixins.py
Copyright GNU Lesser General Public License v3.0
Author : longguikeji
    def dispatch(self, request, *args, **kwargs):
        # let preflight OPTIONS requests past
        if request.method.upper() == "OPTIONS":
            return super().dispatch(request, *args, **kwargs)

        # check if the request is valid and the protected resource may be accessed
        valid, r = self.verify_request(request)
        if valid:
            request.resource_owner = r.user
            return super().dispatch(request, *args, **kwargs)
        else:
            return HttpResponseForbidden()

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : sebst
@login_required
@ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, method=['GET'], block=True)
@ratelimit(key="user_or_ip", group="news-post", rate=DEFAULT_POST_RATE, method=['POST'], block=True)
def item_delete(request, pk):
    item, story, comment = _item_story_comment(pk)
    if not item.can_be_deleted_by(request.user):
        return HttpResponseForbidden()
    if request.method == "POST":
        redirect_url = '/'
        if comment is not None:
            redirect_url = item.to_story.get_absolute_url()
        item.delete()
        return HttpResponseRedirect(redirect_url)
    return render(request, 'news/item_delete.html', {'item': item})

3 View Complete Implementation : data_export_publishing.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def get_export_result(request, api_key, hash_id):
    job = Job.objects.get(hashid=hash_id)
    try:
        user_id = ApiKey.objects.get(key=api_key).user_id
        astert user_id == job.user.id
    except:
        return HttpResponseForbidden("This user did not request that file!")

    if job.status != "Complete":
        return HttpResponseNotFound("Export is not complete")
    filepath = settings.SENDFILE_ROOT + job.data
    return sendfile(request, filepath, attachment=True)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : PeteAndersen
    def get(self, request, *args, **kwargs):
        issue = self.get_object()
        if issue.user == self.request.user or issue.public or self.request.user.is_superuser:
            return super(IssueDetail, self).get(request, *args, **kwargs)
        else:
            return HttpResponseForbidden()

3 View Complete Implementation : views.py
Copyright MIT License
Author : ericls
def search_redirect(request):
    if request.method == 'GET':
        keyword = request.GET.get('keyword')
        return HttpResponseRedirect(reverse('niji:search', kwargs={'keyword': keyword}))
    else:
        return HttpResponseForbidden('Post you cannot')

3 View Complete Implementation : views.py
Copyright MIT License
Author : wagtail
def toggle_segment_view(request):
    """Toggle between the list view and dashboard view.

    :param request: The http request
    :type request: django.http.HttpRequest
    :returns: A redirect to the original page
    :rtype: django.http.HttpResponseRedirect

    """
    if request.user.has_perm('wagtailadmin.access_admin'):
        if request.session['segment_view'] == 'dashboard':
            request.session['segment_view'] = 'list'

        elif request.session['segment_view'] != 'dashboard':
            request.session['segment_view'] = 'dashboard'

        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

    return HttpResponseForbidden()

3 View Complete Implementation : decorators.py
Copyright MIT License
Author : diegojromerolopez
def administrator_required(the_func):
    """
    Force the view to be executed by an administrator.
    """

    def _decorated(request, *args, **kwargs):
        user = request.user
        if user_is_administrator(user):
            return the_func(request, *args, **kwargs)
        return HttpResponseForbidden()

    return _decorated

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : GovReady
def download_attachment(request, attachment_id):
    try:
        attachment = get_object_or_404(Attachment, id=attachment_id)
    except ValueError:
        raise Http404()
    if not attachment.comment.discussion.is_public() and not attachment.comment.discussion.is_participant(request.user):
        return HttpResponseForbidden()

    from dbstorage.views import get_file_content_view
    return get_file_content_view(request, attachment.file.name)
    

3 View Complete Implementation : decorators.py
Copyright MIT License
Author : rparent
def locks_object(model, get_object_id_fn):
    def decorator(view):
        def wrapped(request, *args, **kwargs):
            object_id = get_object_id_fn(request, *args, **kwargs)
            obj = model.objects.get(id=object_id)
            try:
                lock_for_session(obj, request.session)
            except AlreadyLockedError:
                return HttpResponseForbidden("The object you are trying to access is "
                                             "locked.")
            return view(request, *args, **kwargs)
        return wrapped
    return decorator

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
    def post(self, request, *args, **kwargs):
        if self.disallow_start():
            return HttpResponseForbidden('Forbidden. Such task is already started.')
        if self.form_clast is None:
            data = request.POST.dict()
        else:
            form = self.form_clast(data=request.POST, files=request.FILES)
            if not form.is_valid():
                return self.json_response(form.errors, status=400)
            data = form.cleaned_data
        data['user_id'] = request.user.pk
        data['metadata'] = self.get_metadata()
        data['module_name'] = getattr(self, 'module_name', None) or self.__module__.replace('views', 'tasks')
        self.start_task(data)
        return self.json_response('The task is started. It can take a while.')

3 View Complete Implementation : views.py
Copyright MIT License
Author : djk2
    def dispatch(self, request, *args, **kwargs):
        """Override to check settings"""
        if django.VERSION < (1, 10):
            is_auth = request.user.is_authenticated()
        else:
            is_auth = request.user.is_authenticated

        if not ADMIN_SHELL_ENABLE:
            return HttpResponseNotFound("Not found: Django admin shell is not enabled")
        elif is_auth is False or request.user.is_staff is False:
            return HttpResponseForbidden("Forbidden: To access Django admin shell you must have access the admin site")
        elif ADMIN_SHELL_ONLY_DEBUG_MODE and settings.DEBUG is False:
            return HttpResponseForbidden("Forbidden :Django admin shell require DEBUG mode")
        elif ADMIN_SHELL_ONLY_FOR_SUPERUSER and request.user.is_superuser is False:
            return HttpResponseForbidden("Forbidden: To access Django admin shell you must be superuser")
        return super(Shell, self).dispatch(request, *args, **kwargs)

3 View Complete Implementation : teams.py
Copyright Apache License 2.0
Author : PeteAndersen
@username_case_redirect
@login_required
def team_delete(request, profile_name, team_id):
    return_path = request.GET.get(
        'next',
        reverse('herders:teams', kwargs={'profile_name': profile_name})
    )
    team = get_object_or_404(Team, pk=team_id)

    # Check for proper owner before deleting
    if request.user.summoner == team.group.owner:
        team.delete()
        messages.warning(request, 'Deleted team %s - %s.' % (team.group, team))
        return redirect(return_path)
    else:
        return HttpResponseForbidden()

3 View Complete Implementation : offers.py
Copyright MIT License
Author : CodeForPoznan
    @staticmethod
    def get(request, pk):  # pylint: disable=invalid-name
        """Method which allows to delete selected offer

        :param request: WSGIRequest instance
        :param pk: Offer id
        """
        offer = get_object_or_404(Offer, pk=pk)
        if (
                request.user.is_authenticated() and
                request.user.userprofile.is_administrator
        ):
            offer.publish()
            messages.info(request, "Oferta została zaakceptowana.")
            return redirect(settings.ANGULAR_ROOT)

        return HttpResponseForbidden()

3 View Complete Implementation : views.py
Copyright MIT License
Author : ericls
@login_required
def edit_topic(request, pk):
    topic = Topic.objects.get(pk=pk)
    if topic.reply_count > 0:
        return HttpResponseForbidden(_('Editing is not allowed when topic has been replied'))
    if not topic.user == request.user:
        return HttpResponseForbidden(_('You are not allowed to edit other\'s topic'))
    if request.method == 'POST':
        form = TopicEditForm(request.POST, instance=topic)
        if form.is_valid():
            t = form.save()
            return HttpResponseRedirect(reverse('niji:topic', kwargs={'pk': t.pk}))
    else:
        form = TopicEditForm(instance=topic)

    return render(request, 'niji/edit_topic.html', {'form': form, 'satle': _('Edit Topic')})

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : GovReady
@login_required
def delete_discussion_comment(request):
    # get object
    comment = get_object_or_404(Comment, id=request.POST['id'])

    # can delete? must still be a participant of the discussion, to
    # prevent editing things that you are no longer able to see
    if not comment.can_delete(request.user):
        return HttpResponseForbidden()

    # mark deleted
    comment.deleted = True
    comment.save()

    # return new comment info
    return JsonResponse({ "status": "ok" })

3 View Complete Implementation : monsters.py
Copyright Apache License 2.0
Author : PeteAndersen
@username_case_redirect
@login_required()
def monster_piece_delete(request, profile_name, instance_id):
    return_path = request.GET.get(
        'next',
        reverse('herders:profile_default', kwargs={'profile_name': profile_name})
    )
    pieces = get_object_or_404(MonsterPiece, pk=instance_id)

    # Check for proper owner before deleting
    if request.user.summoner == pieces.owner:
        messages.warning(request, 'Deleted ' + str(pieces))
        pieces.delete()

        return redirect(return_path)
    else:
        return HttpResponseForbidden()

3 View Complete Implementation : views.py
Copyright MIT License
Author : wise-team
@login_required
def publish_project(request, slug):
    project = get_object_or_404(Project, slug=slug)
    try:
        project.publish(publisher=request.user)
        rebuild_project_search_index(project)
        messages.add_message(request, messages.INFO, 'Project is published!')
        return HttpResponseRedirect(reverse("package", kwargs={"slug": project.slug}))

    except PermissionError:
        return HttpResponseForbidden("permission denied")

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : sebst
def _vote(request, pk, vote=None, unvote=False):
    astert not unvote and vote is not None or unvote and vote is None
    item = get_object_or_404(Item, pk=pk)
    if (not unvote) and (vote is not None):
        votes = Vote.objects.filter(item=item, user=request.user)
        if request.method=="POST":
            if vote > 0:
                if not item.can_be_upvoted_by(request.user):
                    return HttpResponseForbidden()
            else:
                if not item.can_be_downvoted_by(request.user):
                    return HttpResponseForbidden()
            vote = Vote(vote=vote, item=item, user=request.user)
            vote.save()
            return HttpResponse("OK %s"%(vote.pk))
    if unvote:
        if request.method=="POST":
            Vote.objects.filter(item=item, user=request.user).delete()
            return HttpResponse("OK")

3 View Complete Implementation : csrf.py
Copyright GNU General Public License v2.0
Author : blackye
def csrf_failure(request, reason=""):
    """
    Default view used when request fails CSRF protection
    """
    from django.middleware.csrf import REASON_NO_REFERER
    t = Template(CSRF_FAILURE_TEMPLATE)
    c = Context({'DEBUG': settings.DEBUG,
                 'reason': reason,
                 'no_referer': reason == REASON_NO_REFERER
                 })
    return HttpResponseForbidden(t.render(c), content_type='text/html')

0 View Complete Implementation : monsters.py
Copyright Apache License 2.0
Author : PeteAndersen
@username_case_redirect
@login_required()
def monster_instance_duplicate(request, profile_name, instance_id):
    monster = get_object_or_404(MonsterInstance, pk=instance_id)

    # Check for proper owner before copying
    if request.user.summoner == monster.owner:
        newmonster = monster
        newmonster.pk = None
        newmonster.save()
        messages.success(request, 'Succesfully copied ' + str(newmonster))

        view_mode = request.session.get('profile_view_mode', DEFAULT_VIEW_MODE).lower()

        if view_mode == 'list':
            template = loader.get_template('herders/profile/monster_inventory/monster_list_row_snippet.html')
        else:
            template = loader.get_template('herders/profile/monster_inventory/monster_box_snippet.html')

        context = {
            'profile_name': profile_name,
            'is_owner': True,
            'instance': newmonster,
        }

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

        return JsonResponse(response_data)
    else:
        return HttpResponseForbidden()