Python django.shortcuts.HttpResponse() Examples

The following are 30 code examples for showing how to use django.shortcuts.HttpResponse(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.shortcuts , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def download_current_events_csv(request, past=None):
    unit_ids = [unit.id for unit in request.units]
    units = Unit.objects.filter(id__in=unit_ids)
    if not past:
        events = OutreachEvent.objects.current(units)
        filestring = "current"
    else:
        events = OutreachEvent.objects.past(units)
        filestring = "past"
    response = HttpResponse(content_type='text/csv')

    response['Content-Disposition'] = 'inline; filename="outreach_events-%s-%s.csv"' % \
                                      (datetime.now().strftime('%Y%m%d'), filestring)
    writer = csv.writer(response)
    if events:
        writer.writerow(['Title', 'Start Date', 'End Date', 'Description', 'Location', 'Unit', 'Resources',
                         'Cost', 'Notes', 'Email', 'Attendance', 'Private Notes', 'Registration Link'])
        for e in events:
            writer.writerow([e.title, e.start_date, e.end_date, e.description, e.location, e.unit, e.resources, e.cost,
                             e.notes, e.email, e.registration_count(), e.private_notes,
                             request.build_absolute_uri(reverse('outreach:register', kwargs={'event_slug': e.slug}))])
    return response 
Example 2
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def download_visas_csv(request):
    visas = Visa.objects.visible_by_unit(Unit.sub_units(request.units))
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'inline; filename="visas-%s.csv"' % datetime.now().strftime('%Y%m%d')
    writer = csv.writer(response)
    writer.writerow(['Person', 'Email', 'Unit', 'Start Date', 'End Date', 'Type', 'Validity'])
    for v in visas:
        person = v.person
        email = v.person.email()
        unit = v.unit.name
        start_date = v.start_date
        end_date = v.end_date
        visa_type = v.status
        validity = v.get_validity()
        writer.writerow([person, email, unit, start_date, end_date, visa_type, validity])

    return response 
Example 3
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def inventory_download(request):
    unit_ids = [unit.id for unit in request.units]
    units = Unit.objects.filter(id__in=unit_ids)
    assets = Asset.objects.visible(units)
    response = HttpResponse(content_type='text/csv')

    response['Content-Disposition'] = 'inline; filename="inventory-%s.csv"' % datetime.datetime.now().strftime('%Y%m%d')
    writer = csv.writer(response)
    if assets:
        writer.writerow(['Name', 'Unit', 'Brand', 'Description', 'Serial', 'Service/Asset Tag', 'Express Service Code',
                         'Quantity', 'Minimum Re-Order Quantity', 'Quantity Ordered', 'Minimum Vendor Quantity',
                         'Price', 'Category', 'Location', 'PR/PO No.', 'Account No.', 'Supplier/Vendor',
                         'Calibration/Service Date', 'End of Life Date', 'Notes', 'Service Records',
                         'Attachments', 'Change Records', 'User', 'Date Shipped/Received', 'Currently in Use', 'URL'])
        for a in assets:
            url = request.build_absolute_uri(reverse('inventory:view_asset', kwargs={'asset_slug': a.slug}))
            writer.writerow([a.name, a.unit, a.brand, a.description, a.serial, a.tag, a.express_service_code,
                             a.quantity, a.min_qty, a.qty_ordered, a.min_vendor_qty, a.price, a.get_category_display(),
                             a.location, a.po, a.account, a.vendor, a.calibration_date, a.eol_date, a.notes,
                             a.service_records, a.has_attachments(), a.has_records(), a.user, a.date_shipped, a.in_use,
                             url])
    return response 
Example 4
Project: coursys   Author: sfu-fas   File: all_promises.py    License: GNU General Public License v3.0 6 votes vote down vote up
def download_promises(request, semester_name=None):
    if semester_name is None:
        semester = Semester.next_starting()
    else:
        semester = get_object_or_404(Semester, name=semester_name)
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'inline; filename="promises-%s-%s.csv"' % (semester.name,
                                                                                 datetime.now().strftime('%Y%m%d'))
    writer = csv.writer(response)
    writer.writerow(['Student', 'Program', 'Start Semester', 'Status', 'Promised', 'Received', 'Difference'])
    promises = Promise.objects.filter(end_semester=semester,
                                      student__program__unit__in=request.units)
    for p in promises:
        student = p.student.person.sortname()
        program = p.student.program.label
        start = p.student.start_semester.label()
        status = p.student.get_current_status_display()
        promised = p.amount
        received = p.received()
        difference = p.difference()
        writer.writerow([student, program, start, status, promised, received, difference])

    return response 
Example 5
Project: django-webssh   Author: huyuan1999   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def upload_ssh_key(request):
    if request.method == 'POST':
        pkey = request.FILES.get('pkey')
        ssh_key = pkey.read().decode('utf-8')

        while True:
            filename = unique()
            ssh_key_path = os.path.join(TMP_DIR, filename)
            if not os.path.isfile(ssh_key_path):
                with open(ssh_key_path, 'w') as f:
                    f.write(ssh_key)
                break
            else:
                continue

        return HttpResponse(filename) 
Example 6
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def post(request):
        ret = {'status': True, 'error': None, }
        try:
            if request.POST.get('nid'):
                ids = request.POST.get('nid', None)
                Tools.objects.get(id=ids).delete()
            else:
                ids = request.POST.getlist('id', None)
                idstring = ','.join(ids)
                Tools.objects.extra(
                    where=['id IN (' + idstring + ')']).delete()
        except Exception as e:
            ret['status'] = False
            ret['error'] = '删除请求错误,没有权限{}'.format(e)
        finally:
            return HttpResponse(json.dumps(ret)) 
Example 7
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def get_context_data(self, **kwargs):
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        name = Names.objects.get(username=self.request.user)
        task = ToolsResults.objects.get(id=pk)
        if name.is_superuser != 1:
            if task.add_user != name:
                return HttpResponse(status=500)
        try:
            results = TaskResult.objects.get(task_id=task.task_id)
        except Exception as e:
            logger.error(e)
            results = {'result': "还未完成,请稍后再查看!!"}

        context = {
            "tasks_active": "active",
            "tools_results_active": "active",
            "task": task,
            "results": results,
        }
        kwargs.update(context)
        return super().get_context_data(**kwargs) 
Example 8
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def post(request):
        ret = {'status': True, 'error': None, }
        try:
            if request.POST.get('nid'):
                ids = request.POST.get('nid', None)
                Names.objects.get(id=ids).delete()
            else:
                ids = request.POST.getlist('id', None)
                idstring = ','.join(ids)
                Names.objects.extra(
                    where=['id IN (' + idstring + ')']).delete()
        except Exception as e:
            ret['status'] = False
            ret['error'] = '删除请求错误,没有权限{}'.format(e)
        finally:
            return HttpResponse(json.dumps(ret)) 
Example 9
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def post(request):
        ret = {'status': True, 'error': None, }
        try:
            if request.POST.get('nid'):
                ids = request.POST.get('nid', None)
                Groups.objects.get(id=ids).delete()
            else:
                ids = request.POST.getlist('id', None)
                idstring = ','.join(ids)
                Groups.objects.extra(
                    where=['id IN (' + idstring + ')']).delete()
        except Exception as e:
            ret['status'] = False
            ret['error'] = '删除请求错误,没有权限{}'.format(e)
        finally:
            return HttpResponse(json.dumps(ret)) 
Example 10
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def post(request):
        ret = {'status': True, 'error': None, }
        try:
            if request.POST.get('nid'):
                ids = request.POST.get('nid', None)
                GroupObjectPermission.objects.get(id=ids).delete()
            else:
                ids = request.POST.getlist('id', None)
                idstring = ','.join(ids)
                GroupObjectPermission.objects.extra(
                    where=['id IN (' + idstring + ')']).delete()
        except Exception as e:
            ret['status'] = False
            ret['error'] = '删除请求错误,没有权限{}'.format(e)
        finally:
            return HttpResponse(json.dumps(ret)) 
Example 11
Project: janeway   Author: BirkbeckCTP   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def preprints_home(request):
    """
    Displays the preprints home page with search box and 6 latest preprints publications
    :param request: HttpRequest object
    :return: HttpResponse
    """
    preprints = submission_models.Article.preprints.filter(
        date_published__lte=timezone.now()).order_by('-date_published')[:3]

    subjects = models.Subject.objects.all().prefetch_related('preprints')

    template = 'preprints/home.html'
    context = {
        'preprints': preprints,
        'subjects': subjects,
    }

    return render(request, template, context) 
Example 12
Project: janeway   Author: BirkbeckCTP   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def preprints_dashboard(request):
    """
    Displays a list of an author's preprints.
    :param request: HttpRequest object
    :return: HttpResponse
    """
    preprints = submission_models.Article.preprints.filter(Q(authors=request.user) | Q(owner=request.user),
                                                           date_submitted__isnull=False).distinct()

    incomplete_preprints = submission_models.Article.preprints.filter(Q(authors=request.user) | Q(owner=request.user),
                                                                      date_submitted__isnull=True)

    template = 'admin/preprints/dashboard.html'
    context = {
        'preprints': preprints,
        'incomplete_preprints': incomplete_preprints,
    }

    return render(request, template, context) 
Example 13
Project: janeway   Author: BirkbeckCTP   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def preprints_submit(request, article_id=None):
    """
    Handles initial steps of generating a preprints submission.
    :param request: HttpRequest
    :return: HttpResponse or HttpRedirect
    """
    article = preprint_logic.get_preprint_article_if_id(request, article_id)
    additional_fields = submission_models.Field.objects.filter(press=request.press)
    form = forms.PreprintInfo(instance=article, additional_fields=additional_fields)

    if request.POST:
        form = forms.PreprintInfo(request.POST, instance=article, additional_fields=additional_fields)

        if form.is_valid():
            article = preprint_logic.save_preprint_submit_form(request, form, article, additional_fields)
            return redirect(reverse('preprints_authors', kwargs={'article_id': article.pk}))

    template = 'preprints/submit_start.html'
    context = {
        'form': form,
        'article': article,
        'additional_fields': additional_fields,
    }

    return render(request, template, context) 
Example 14
Project: janeway   Author: BirkbeckCTP   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def preprints_comments(request, article_id):
    """
    Presents an interface for authors and editors to mark comments as publicly readable.
    :param request: HttpRequest object
    :param article_id: PK of an Article object
    :return: HttpRedirect if POST, HttpResponse otherwise
    """
    preprint = get_object_or_404(submission_models.Article.preprints, pk=article_id)

    if request.POST:
        preprint_logic.comment_manager_post(request, preprint)
        return redirect(reverse('preprints_comments', kwargs={'article_id': preprint.pk}))

    template = 'admin/preprints/comments.html'
    context = {
        'preprint': preprint,
        'new_comments': preprint.comment_set.filter(is_reviewed=False),
        'old_comments': preprint.comment_set.filter(is_reviewed=True)
    }

    return render(request, template, context) 
Example 15
Project: janeway   Author: BirkbeckCTP   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def preprints_settings(request):
    """
    Displays and allows editing of various prepprint settings
    :param request: HttpRequest
    :return: HttpRedirect if POST else HttpResponse
    """
    form = forms.SettingsForm(instance=request.press)

    if request.POST:
        form = forms.SettingsForm(request.POST, instance=request.press)

        if form.is_valid():
            form.save()
            return redirect(reverse('preprints_settings'))

    template = 'admin/preprints/settings.html'
    context = {
        'form': form,
    }

    return render(request, template, context) 
Example 16
Project: janeway   Author: BirkbeckCTP   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def version_queue(request):
    """
    Displays a list of version update requests.
    :param request: HttpRequest
    :return: HttpResponse or HttpRedirect
    """
    version_queue = models.VersionQueue.objects.filter(date_decision__isnull=True)
    duplicates = preprint_logic.check_duplicates(version_queue)

    if request.POST:
        if 'approve' in request.POST:
            return preprint_logic.approve_pending_update(request)
        elif 'deny' in request.POST:
            return preprint_logic.deny_pending_update(request)

    template = 'admin/preprints/version_queue.html'
    context = {
        'version_queue': version_queue,
        'duplicates': duplicates,
    }

    return render(request, template, context) 
Example 17
Project: ASKCOS   Author: connorcoley   File: info.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def template_target_export(request, id):
    rx_ids = template_target(request, id, return_refs_only=True)
    
    txt = '{"fileName":"reaxys_query.json", "version":"1.0","content": {"id":"root","facts": ['
    for i, rx_id in enumerate(rx_ids):
        if i != 0:
            txt += ','
        txt += '{"id":"Reaxys487",'
        if i != 0:
            txt += '"logicOperator":"OR",'
        txt += '"fields": [{"value":"%i","boundOperator":"op_num_equal","id":"RX.ID","displayName":"Reaction ID"}],' % (rx_id)
        txt += '"fieldsLogicOperator":"AND","exist":false,"bio":false}'

    txt += '], "exist":false,"bio":false } }'

    response = HttpResponse(txt, content_type='text/csv')
    response['Content-Disposition'] = 'attachment;filename=reaxys_query.json'
    return response

#@login_required 
Example 18
Project: ASKCOS   Author: connorcoley   File: export.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def export_synth_results(request):
    if 'last_synth_interactive' not in request.session:
        return index(request, err='Could not find synth results to save?')
    
    synth_data = request.session['last_synth_interactive']
    #uncomment to export full data
    # txt = 'Forward prediction approach: %s\r\n' % synth_data['forward_scorer']
    # txt += 'Reactants: %s\r\n' % synth_data['reactants']
    # txt += 'Reagents: %s\r\n' % synth_data['reagents']
    # txt += 'Temperature: %s\r\n' % synth_data['temperature']
    # txt += 'Solvent: %s\r\n' % synth_data['solvent']
    # txt += '\r\n'
    txt = '%s\t%s\t%s\t%s\r\n' % ('Rank', 'SMILES', 'Probability', 'Score')
    for outcome in synth_data['outcomes']:
        txt += '%s\t%s\t%s\t%s\r\n' % (outcome['rank'], outcome['outcome']['smiles'], outcome['prob'], outcome['score'])
    response = HttpResponse(txt, content_type='text/csv')
    response['Content-Disposition'] = 'attachment;filename=export.csv'
    return response
    
#@login_required 
Example 19
Project: onlinestudy   Author: Eeyhan   File: v1.py    License: MIT License 6 votes vote down vote up
def change_view(self, request, pk, *args, **kwargs):
        """
        修改
        :param request:
        :return:
        """

        current_model_object = self.get_change_object(request, pk, *args, **kwargs)
        if not current_model_object:
            return HttpResponse('当前选择的对象不存在,请重试')
        model_form_class = self.get_model_form(False, request, pk, *args, **kwargs)
        if request.method == 'GET':
            form = model_form_class(instance=current_model_object)
            return render(request, self.change_template or 'startX/change.html', {'form': form})
        form = model_form_class(data=request.POST, instance=current_model_object)
        if form.is_valid():
            response = self.save(request, form, True, *args, **kwargs)
            # 在数据库保存成功后,跳转回列表页面(携带原来的参数)。
            return response or redirect(self.reverse_list_url(*args, **kwargs))
        return render(request, self.change_template or 'startX/change.html', {'form': form, 'errors': form.errors}) 
Example 20
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def keyform(request, booking_slug):
    booking = get_object_or_404(BookingRecord, slug=booking_slug, location__unit__in=Unit.sub_units(request.units))
    user = get_object_or_404(Person, userid=request.user.username)
    if not booking.has_key_request():
        k = KeyRequest(booking_record=booking, created_by=user)
        k.save()
        l = LogEntry(userid=request.user.username,
                     description="Added key request for booking %s" % booking,
                     related_object=k)
        l.save()
    response = HttpResponse(content_type="application/pdf")
    response['Content-Disposition'] = 'inline; filename="keyform-%s-%s.pdf"' % (booking.location.room_number, booking.person.userid)
    key_form(booking, response)
    return response 
Example 21
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def download_sessionals(request):
    sessionals = SessionalContract.objects.visible(request.units)
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'inline; filename="sessionals-%s.csv"' % \
                                      datetime.datetime.now().strftime('%Y%m%d')
    writer = csv.writer(response)
    writer.writerow(['Name', 'Account', 'Unit', 'SIN', 'Appointment Start', 'Appointment End', 'Pay Start', 'Pay End',
                     'Offering', 'Course Hours Breakdown', 'Appointment Guarantee', 'Appointment Type',
                     'Weekly Contact Hours', 'Total Salary', 'Notes'])
    for s in sessionals:
        writer.writerow([s.sessional.get_person(), s.account, s.unit, s.sin, s.appointment_start, s.appointment_end,
                         s.pay_start, s.pay_end, s.offering, s.course_hours_breakdown, s.get_appt_guarantee_display(),
                         s.get_appt_type_display(), s.contact_hours, s.total_salary, s.notes])
    return response 
Example 22
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def print_contract(request, contract_slug):
    contract = get_object_or_404(SessionalContract, slug=contract_slug, unit__in=request.units)
    # If no one has ever checked the 'I've verified the visa info for this person'
    # box, let's stop them from printing.  We don't want to send this anywhere, but
    # it's just for our own peace of mind.
    if not contract.visa_verified:
            messages.error(request, 'You must verify the sessional\'s visa information before printing')
            return HttpResponseRedirect(reverse('sessionals:view_contract',
                                                kwargs={'contract_slug': contract_slug}))
    response = HttpResponse(content_type="application/pdf")
    response['Content-Disposition'] = 'inline; filename="sessionalform.pdf"'
    sessional_form(contract, response)
    return response 
Example 23
Project: vulscan   Author: vulscanteam   File: views.py    License: MIT License 5 votes vote down vote up
def delete(request):
	context ={}
	
	ip= request.POST.get("ip")
	username= request.POST.get("username")
	password= request.POST.get("password")
	context = {"ip":ip,"username":username,"password":password,"result":False}
	#ippattern="(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)$"
	#if(re.match(ippattern,ip)):
	testip=ip.split(".")
	if(testip[0].isdigit() and testip[1].isdigit() and testip[2].isdigit()and testip[3].isdigit()):
		pass
	else:
		context['error']="ip格式不正确"
		log("error","[-] %s ip is error"%(ip))
		print ("[-] %s ip格式不正确"%(ip))
		#return render(request, 'test.html', context)
		return HttpResponse(json.dumps(context),content_type="application/json")

	try:
		if(executeScript.deleteScript(ip,username,password)):
			log("info","[+] %s File deleting on a remote server"%(ip))
			print ("[+] %s 远程服务器上文件删除成功"%(ip))
			return HttpResponse(json.dumps(context),content_type="application/json")
	except Exception as e:
		context['error']="远程服务器上文件删除失败"
		log("error","[-] %s File deletion failure on a remote server"%(ip))
		print ("[-] %s 远程服务器上文件删除失败"%(ip))
	return HttpResponse(json.dumps(context),content_type="application/json") 
Example 24
Project: lmgtdfy   Author: opendata   File: views.py    License: MIT License 5 votes vote down vote up
def get_csv(request, domain):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="%s.csv"' % domain
    writer = csv.writer(response)
    qs = DomainSearchResult.objects.filter(
        search_instance__domain__name=domain
    ).order_by('result').distinct()
    writer.writerow(["title", "format", "kilobyte_size", "url"])
    for result in qs:
        writer.writerow([result.title.encode("utf-8"), result.fmt.encode("utf-8"), 
                         result.size, result.result.encode("utf-8")])
    return response 
Example 25
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def taskstailperform(request):
    """
    执行 tail_log  命令
    """
    if request.method == "POST":
        ret = {'status': True, 'error': None, }
        name = Names.objects.get(username=request.user)
        ids = request.POST.get('id')
        tail = request.POST.get('tail', None)

        if not ids or not tail:
            ret['status'] = False
            ret['error'] = "请选择服务器,输入参数及日志地址."
            return HttpResponse(json.dumps(ret))

        asset_obj = AssetInfo.objects.get(id=ids)
        project_obj = AssetProject.objects.get(projects=asset_obj.project)
        hasperm = name.has_perm('cmd_assetproject', project_obj)
        if not hasperm:
            return HttpResponse(status=500)
        try:
            taillog(request, asset_obj.network_ip, asset_obj.port, asset_obj.user.username, asset_obj.user.password,
                    asset_obj.user.private_key, tail)
        except Exception as e:
            ret['status'] = False
            ret['error'] = "错误{0}".format(e)
            logger.error(e)
        return HttpResponse(json.dumps(ret)) 
Example 26
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def taskstailstopperform(request):
    """
    执行 tail_log  stop  命令
    """
    if request.method == "POST":
        ret = {'status': True, 'error': None, }
        name = request.user.username
        os.environ["".format(name)] = "false"
        return HttpResponse(json.dumps(ret)) 
Example 27
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def post(request):
        ret = {'status': True, 'error': None, }
        try:
            if request.POST.get('nid'):
                ids = request.POST.get('nid', None)
                CrontabSchedule.objects.get(id=ids).delete()
            else:
                ids = request.POST.getlist('id', None)
                idstring = ','.join(ids)
                CrontabSchedule.objects.extra(where=['id IN (' + idstring + ')']).delete()
        except Exception as e:
            ret['status'] = False
            ret['error'] = '删除请求错误,没有权限{}'.format(e)
        finally:
            return HttpResponse(json.dumps(ret)) 
Example 28
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def post(request):
        ret = {'status': True, 'error': None, }
        try:
            if request.POST.get('nid'):
                ids = request.POST.get('nid', None)
                IntervalSchedule.objects.get(id=ids).delete()
            else:
                ids = request.POST.getlist('id', None)
                idstring = ','.join(ids)
                IntervalSchedule.objects.extra(where=['id IN (' + idstring + ')']).delete()
        except Exception as e:
            ret['status'] = False
            ret['error'] = '删除请求错误,没有权限{}'.format(e)
        finally:
            return HttpResponse(json.dumps(ret)) 
Example 29
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def dispatch(self, *args, **kwargs):
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        name = Names.objects.get(username=self.request.user)
        project = AssetInfo.objects.get(id=pk).project
        project_obj = AssetProject.objects.get(projects=project)
        hasperm = name.has_perm('change_assetproject', project_obj)
        if not hasperm:
            return HttpResponse(status=500)
        return super().dispatch(*args, **kwargs) 
Example 30
Project: chain   Author: hequan2017   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def dispatch(self, *args, **kwargs):
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        name = Names.objects.get(username=self.request.user)
        project = AssetInfo.objects.get(id=pk).project
        project_obj = AssetProject.objects.get(projects=project)
        hasperm = name.has_perm('read_assetproject', project_obj)
        if not hasperm:
            return HttpResponse(status=500)
        return super().dispatch(*args, **kwargs)