Python django.shortcuts.HttpResponse() Examples
The following are 30
code examples of django.shortcuts.HttpResponse().
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.shortcuts
, or try the search function
.
Example #1
Source File: views.py From chain with Apache License 2.0 | 6 votes |
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 #2
Source File: all_promises.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #3
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #4
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: views.py From django-webssh with Apache License 2.0 | 6 votes |
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
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #7
Source File: views.py From chain with Apache License 2.0 | 6 votes |
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 #8
Source File: views.py From chain with Apache License 2.0 | 6 votes |
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 #9
Source File: views.py From chain with Apache License 2.0 | 6 votes |
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
Source File: views.py From chain with Apache License 2.0 | 6 votes |
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
Source File: views.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: views.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: views.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: views.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: views.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: views.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: info.py From ASKCOS with Mozilla Public License 2.0 | 6 votes |
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
Source File: export.py From ASKCOS with Mozilla Public License 2.0 | 6 votes |
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
Source File: v1.py From onlinestudy with MIT License | 6 votes |
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
Source File: views.py From janeway with GNU Affero General Public License v3.0 | 5 votes |
def orphaned_preprints(request): """ Displays a list of preprints that have bee orphaned from subjects. :param request: HttpRequest object :return: HttpResponse """ orphaned_preprints = preprint_logic.list_articles_without_subjects() template = 'admin/preprints/orphaned_preprints.html' context = { 'orphaned_preprints': orphaned_preprints } return render(request, template, context)
Example #21
Source File: views.py From janeway with GNU Affero General Public License v3.0 | 5 votes |
def preprints_review(request, article_id): """ Presents information for the user to review before completing the submission process. :param request: HttpRequest :param article_id: Article object PK :return: HttpRedirect or HttpResponse """ article = get_object_or_404(submission_models.Article.preprints, pk=article_id, owner=request.user, date_submitted__isnull=True) if request.POST and 'next_step' in request.POST: # TODO: reduce this code to an article function submit_preprint? article.date_submitted = timezone.now() article.stage = submission_models.STAGE_PREPRINT_REVIEW article.current_step = 5 article.save() kwargs = {'request': request, 'article': article} event_logic.Events.raise_event(event_logic.Events.ON_PREPRINT_SUBMISSION, **kwargs) messages.add_message(request, messages.SUCCESS, 'Article {0} submitted'.format(article.title)) return redirect(reverse('preprints_dashboard')) template = 'preprints/review.html' context = { 'article': article, } return render(request, template, context)
Example #22
Source File: views.py From chain with Apache License 2.0 | 5 votes |
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 #23
Source File: views.py From janeway with GNU Affero General Public License v3.0 | 5 votes |
def preprints_editors(request): """ Displays lists of preprint editors by their subject group. :param request: HttpRequest :return: HttpResponse """ subjects = models.Subject.objects.filter(enabled=True) template = 'preprints/editors.html' context = { 'subjects': subjects, } return render(request, template, context)
Example #24
Source File: views.py From janeway with GNU Affero General Public License v3.0 | 5 votes |
def preprints_manager(request): """ Displays preprint information and management interfaces for them. :param request: HttpRequest :return: HttpResponse or HttpRedirect """ unpublished_preprints = preprint_logic.get_unpublished_preprints(request) published_preprints = preprint_logic.get_published_preprints(request) incomplete_preprints = submission_models.Article.preprints.filter(date_published__isnull=True, date_submitted__isnull=True) rejected_preprints = submission_models.Article.preprints.filter(date_declined__isnull=False) metrics_summary = preprint_logic.metrics_summary(published_preprints) version_queue = models.VersionQueue.objects.filter(date_decision__isnull=True) subjects = models.Subject.objects.filter(enabled=True) template = 'admin/preprints/manager.html' context = { 'unpublished_preprints': unpublished_preprints, 'published_preprints': published_preprints, 'incomplete_preprints': incomplete_preprints, 'rejected_preprints': rejected_preprints, 'version_queue': version_queue, 'metrics_summary': metrics_summary, 'subjects': subjects, } return render(request, template, context)
Example #25
Source File: views.py From django-gateone with GNU General Public License v3.0 | 5 votes |
def user_logout(self, request, redirect=None): if not redirect: # Try getting it from the query string redirect = self.request.GET.get("redirect", None) if redirect: return HttpResponse(redirect) else: return HttpResponse(getsettings('url_prefix','/'))
Example #26
Source File: views.py From django-gateone with GNU General Public License v3.0 | 5 votes |
def get(self,request): check = self.request.GET.get('check',False) if check in ['true','false',False]:#solve ast malformed string exception check = {'true':True,'false':False}[str(check).lower()] else: check = ast.literal_eval(check) if self.request.user == 'AnonymousUser': user = {'upn': 'ANONYMOUS'} else: user = {'upn': str(self.request.user)} if check and self.request.user.is_authenticated(): response = HttpResponse(u'authenticated') response["Access-Control-Allow-Origin"] = "*" response["Server"] = "GateOne" return response logout_get = self.request.GET.get("logout", None) if logout_get: logout(request) response = HttpResponse('/') response.delete_cookie('gateone_user') self.user_logout(request) return response next_url = self.request.GET.get("next", None) if next_url: return redirect(next_url) return redirect(getsettings('url_prefix','/'))
Example #27
Source File: views.py From docker-box with MIT License | 5 votes |
def search_images(request): term = request.POST['term'] images = requests.get('http://localhost:' + DOCKER_API_PORT + '/images/search?term=' + term) return HttpResponse(json.dumps(images.json()), content_type='application/json')
Example #28
Source File: views.py From coursys with GNU General Public License v3.0 | 5 votes |
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 #29
Source File: draw.py From ASKCOS with Mozilla Public License 2.0 | 5 votes |
def draw_reaction(request, smiles): ''' Returns a png response for a SMILES reaction string ''' from makeit.utilities.io.draw import ReactionStringToImage response = HttpResponse(content_type='image/jpeg') ReactionStringToImage(str(smiles)).save(response, 'png', quality=70) return response #@login_required
Example #30
Source File: draw.py From ASKCOS with Mozilla Public License 2.0 | 5 votes |
def draw_smiles(request, smiles): ''' Returns a png response for a target smiles ''' from makeit.utilities.io.draw import MolsSmilesToImage response = HttpResponse(content_type='image/jpeg') MolsSmilesToImage(str(smiles)).save(response, 'png', quality=70) return response #@login_required