def remove_2_factor(request, guid): user = User.load(guid) try: user.delete_addon('twofactor') except AttributeError: page_not_found(request) return redirect(reverse_user(guid))
def isOwnerConnected (f): def wrapped (request, *args, **kwargs): #this check the connection exist, if not it will redirect to login page url = request.REQUEST.get('url') if url is None or len(url) == 0: if request.META.get('QUERY_STRING'): url = '%s?%s' % (request.META.get('PATH_INFO'), request.META.get('QUERY_STRING')) else: url = '%s' % (request.META.get('PATH_INFO')) conn = None try: conn = getBlitzConnection(request, useragent="OMERO.webadmin") except KeyError: return HttpResponseRedirect(reverse("walogin")+(("?url=%s") % (url))) except Exception, x: logger.error(traceback.format_exc()) return HttpResponseRedirect(reverse("walogin")+(("?error=%s&url=%s") % (str(x),url))) if conn is None: return HttpResponseRedirect(reverse("walogin")+(("?url=%s") % (url))) if kwargs.get('gid') is not None: if not conn.isOwner(kwargs.get('gid')): return page_not_found(request, "404.html") else: if not conn.isOwner(): return page_not_found(request, "404.html") kwargs["conn"] = conn return f(request, *args, **kwargs)
def get(self, request, username): """ User is editing profile... """ if request.user.username != username: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='403.html') try: user = User.objects.get(username=username) except ObjectDoesNotExist: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='404.html') user_form = forms.EditProfileForm(instance=user) if hasattr(user, 'consultant'): consult_form = forms.EditConsultantForm(instance=user.consultant) else: consult_form = None return render(request, 'profile/edit_profile.html', { 'user': user, 'is_owner': user == request.user, 'user_form': user_form, 'consult_form': consult_form, })
def handler404(request, param=None, template_name=u'404.html', ): from django.views.defaults import page_not_found page_not_found(request, ) from django.template.loader import get_template # template_name = u'category/show_basement_category.jinja2.html' t = get_template(template_name) from django.template import RequestContext c = RequestContext(request, {u'param_dict': param, }, ) # from django.template import Context # c = Context({'basement_categories': basement_categories, }, ) html = t.render(c) from django.http import HttpResponse response = HttpResponse(content=html, content_type='text/html; charset=utf-8', status=404, ) # from django.shortcuts import redirect # return redirect('/') # Мы не можем выяснить когда менялись внутринние подкатегории. # Поэтому мы не отдаем дату изменения текущей категории. ## from apps.utils.datetime2rfc import datetime2rfc ## response['Last-Modified'] = datetime2rfc(current_category.updated_at, ) return response
def wrapper(request, *args, **kwargs): try: return view_func(request, *args, **kwargs) except Http404: if django.VERSION < (1, 9): return page_not_found(request, template_name='wagtailadmin/404.html') else: return page_not_found(request, '', template_name='wagtailadmin/404.html')
def company_remove(request, company): try: company_obj = Company.objects.get(name=company) except ObjectDoesNotExist: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='404.html') if not Member.is_owner(request.user, company_obj): return page_not_found(request, exception=None, template_name='403.html') remove = get_object_or_404(Company, pk=company_obj.id) instance = Company.objects.get(id=company_obj.id) instance.delete() remove.delete() return redirect("/")
def process_exception(self, request, exception): logger.info("Processing unhandled exception {0}".format(exception)) if isinstance(exception, MongoDriver.NotFoundError): return page_not_found(request) if isinstance(exception, MongoDriver.DecodingError): logger.error("Unexpected Exception, returning not found. {0}".format(exception)) return page_not_found(request) if isinstance(exception, PermissionDenied): return HttpResponseForbidden() logger.info("Exception not handled, propagating...") logger.exception(exception)
def group_remove(request, group): try: group_obj = Group.objects.get(name=group) except ObjectDoesNotExist: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='404.html') if not Member.is_owner(request.user, group_obj): return page_not_found(request, exception=None, template_name='403.html') remove = get_object_or_404(Group, pk=group_obj.id) instance = Group.objects.get(id=group_obj.id) instance.delete() remove.delete() return redirect('entity:group_listing')
def send_document(request,id): #serverPathId = 2 documentObj = Documents.objects.get(id_document = id) serverPathObj = ServerPath.objects.get(id_path = 2) pathLocal = serverPathObj.nm_path print pathLocal filename = documentObj.nm_document logger.info("filename>> "+ filename) path = documentObj.path fullname = pathLocal + path + filename logger.info("fullname>> "+ fullname) #username = request.GET['username'] #print username try: f = open(fullname, "rb") if request.user.is_authenticated(): #user_logged_in = request.user userName = request.user #logger.error("User get document is>> "+ userName) print u= UserMessage(user_name = userName, message_string = filename) u.save() except Exception, e: return page_not_found(request, template_name='404.html')
def moveout_unit_memo_add(request, unit_lease_id): request.session["entity"] = "moveout_unit_memos" # Check only if the unit truly exists if unit_lease_id: try: UnitLeaseHistory.objects.get(id=unit_lease_id) except UnitLeaseHistory.DoesNotExist: return page_not_found(request) if request.method == "POST": form = PostMoveOutUnitMemoForm(request.POST) if form.is_valid(): # Assure that the tenant will be added into the current property if form.instance.property == request.session["property"]: if form.instance.unit_lease: form.instance.unit = form.instance.unit_lease.unit form.instance.created_by = request.user.username form.save() return redirect("opmarchive.views.moveout_unit_memos") else: return permission_denied(request) else: form = PostMoveOutUnitMemoForm( initial={"property": request.session.get("property", None), "unit_lease": unit_lease_id} ) return render_to_response( "archive/moveout_unit_memos/moveout_unit_memo.html", {"form": form}, context_instance=RequestContext(request) )
def remove_job(request, job_title, job_id): try: job_obj = Job.objects.get(pk=job_id) except ObjectDoesNotExist: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='404.html') entity_obj = Job.objects.get(title=job_title).company if not Member.is_owner(request.user, entity_obj): return page_not_found(request, exception=None, template_name='403.html') remove = get_object_or_404(Job, pk=job_obj.id) instance = Job.objects.get(id=job_obj.id) instance.delete() remove.delete() return redirect("/")
def redirectold(request, exception): path = request.path_info.lower() if path.endswith('index.html'): path = path[:-10] elif path.endswith('.html'): path = path[:-5] path = re.sub('^/fa-', '/fa/', path) path = re.sub('__+', '_', path).replace('-', '') path = settings.FORWARDS.get(path, path) if path.startswith('/who/'): nameslug = path[5:] for n in ALIASES.keys(): from django.utils.text import slugify if nameslug == slugify(n): match = name_alias(n) path = Creator.objects.get(name=match[0]).get_absolute_url() urlconf = getattr(request, 'urlconf', None) if (path != request.path_info and urlresolvers.is_valid_path(path, urlconf)): return HttpResponsePermanentRedirect("%s://%s%s" % ( 'https' if request.is_secure() else 'http', request.get_host(), path)) path = path + '/' if (path != request.path_info and urlresolvers.is_valid_path(path, urlconf)): return HttpResponsePermanentRedirect("%s://%s%s" % ( 'https' if request.is_secure() else 'http', request.get_host(), path)) return page_not_found(request, exception)
def get_thread(request, slug_cat, slug_thread): """Renders a thread page with all posts paginated. Posts are sorted by date in ascending order. :param request: Request object :param slug_cat: Category slug :param slug_thread: thread slug :return: rendered page """ context_dict = {} thread = Thread.objects.get(slug=slug_thread) if thread and thread.category.slug == slug_cat: page = request.GET.get("page") context_dict["thread"] = thread posts = Post.objects.filter(thread=thread).order_by("date") if posts: context_dict["first_post_pk"] = posts[0].pk paginator = Paginator(posts, posts_per_page) # Show 15 threads per page try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. posts = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. posts = paginator.page(paginator.num_pages) context_dict["posts"] = posts else: return page_not_found(request) if request.user.is_authenticated(): member = Member.objects.get(user=request.user) if member: context_dict["member"] = member return render(request, "thread.html", context_dict)
def view_404(request): if not request.path.startswith('/' + ASKBOT_URL): template_name = 'errors/404.html' else: template_name = '404.html' return page_not_found(request, template_name=template_name)
def comic(request, number): ''' number - number of the comic to view. Returns 404 page if request a comic that isn't visible yet. ''' if request.method == 'GET': try: comic = Comic.objects.get(number=number) except: return page_not_found(request) # Get commentary # Not sure what order to get? comments = comic.comment_set.all().order_by('datetime').values() # This works, but it seems inelegant context = {'comic': { 'title': comic.title, 'number': comic.number, 'image': comic.image, 'alt_text': comic.alt_text, 'commentary': comic.commentary, 'date_posted': comic.date_posted, 'is_first': comic.is_first(), 'is_last': comic.is_last(), }, 'comments': comments, } return render(request, 'comic.html', context)
def delete(self, request, *args, **kwargs): try: node, user = self.get_object() if node.remove_contributor(user, None, log=False): update_admin_log( user_id=self.request.user.id, object_id=node.pk, object_repr='Contributor', message='User {} removed from {} {}.'.format( user.pk, node.__class__.__name__.lower(), node.pk ), action_flag=CONTRIBUTOR_REMOVED ) # Log invisibly on the OSF. self.add_contributor_removed_log(node, user) except AttributeError: return page_not_found( request, AttributeError( '{} with id "{}" not found.'.format( self.context_object_name.title(), self.kwargs.get('guid') ) ) ) if isinstance(node, Node): return redirect(reverse_node(self.kwargs.get('guid')))
def view_post(request, slug_cat, slug_thread, post_number, relative_post_number): thread = Thread.objects.get(slug=slug_thread) if thread and thread.category.slug == slug_cat: page_number = int(math.ceil(int(relative_post_number) / threads_per_page)) + 1 return redirect("/category/" + slug_cat + "/thread/" + slug_thread + "?page=" + str(page_number)) else: return page_not_found(request)
def get_all_category_threads(request, slug): """Renders a category page with all threads paginated. Threads are sorted by pinned and then by most recently active. :param request: Request object :param slug: Category slug :return: rendered page """ context_dict = {} category = Category.objects.filter(slug=slug) if category: page = request.GET.get("page") context_dict["categories"] = category threads = Thread.objects.filter(category=category, visible=True).order_by("-pinned", "-last_modified") paginator = Paginator(threads, threads_per_page) # Show 15 threads per page try: threads = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. threads = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. threads = paginator.page(paginator.num_pages) context_dict["threads"] = [[thread, str(thread.post_set.count() - 1)] for thread in threads] context_dict["paginated_threads"] = threads else: return page_not_found(request) return render(request, "category.html", context_dict)
def delete(self, request, *args, **kwargs): try: user = self.get_object() flag = None message = None if user.date_disabled is None: user.disable_account() flag = USER_REMOVED message = 'User account {} disabled'.format(user.pk) else: user.date_disabled = None subscribe_on_confirm(user) flag = USER_RESTORED message = 'User account {} reenabled'.format(user.pk) user.save() if flag is not None: update_admin_log( user_id=self.request.user.id, object_id=user.pk, object_repr='User', message=message, action_flag=flag ) except AttributeError: return page_not_found( request, AttributeError( '{} with id "{}" not found.'.format( self.context_object_name.title(), self.kwargs.get('guid') ) ) ) return redirect(reverse_user(self.kwargs.get('guid')))
def delete(self, request, *args, **kwargs): try: node, user = self.get_object() if node.remove_contributor(user, None, log=False): update_admin_log( user_id=self.request.user.id, object_id=node.pk, object_repr="Contributor", message="User {} removed from node {}.".format(user.pk, node.pk), action_flag=CONTRIBUTOR_REMOVED, ) # Log invisibly on the OSF. osf_log = NodeLog( action=NodeLog.CONTRIB_REMOVED, user=None, params={"project": node.parent_id, "node": node.pk, "contributors": user.pk}, date=datetime.utcnow(), should_hide=True, ) osf_log.save() except AttributeError: return page_not_found( request, AttributeError( '{} with id "{}" not found.'.format(self.context_object_name.title(), kwargs.get("node_id")) ), ) return redirect(reverse_node(self.kwargs.get("node_id")))
def handle404(request): if "application/json" in request.META.get("HTTP_ACCEPT", ""): return HttpResponse( json.dumps(handlers.NOT_FOUND_JSON_RESPONSE), status=status.HTTP_404_NOT_FOUND, content_type="application/json", ) return defaults.page_not_found(request)
def get(self, request, *args, **kwargs): uuid = kwargs.get('uuid_curto') try: l = Link.objects.by_uuid(uuid) self.url = urllib2.unquote(l.url) return super(GoToRedirectView, self).get(request, *args, **kwargs) except Link.DoesNotExist: return page_not_found(request)
def get(self, request, company): try: company_obj = Company.objects.get(name=company) except ObjectDoesNotExist: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='404.html') if not Member.is_editor(request.user, company_obj): return page_not_found(request.path, exception=None, template_name='403.html') form = EditCompanyForm(instance=company_obj) return render(request, 'company/edit_comp_profile.html', { 'company': company_obj, 'is_owner': Member.is_owner(request.user, company_obj), 'is_editor': Member.is_editor(request.user, company_obj), 'form': form, })
def page_not_found(request): template_name = '404.html' module = request.path.split('/')[1] try: template_name = module + '/404.html' t = loader.get_template(template_name) except TemplateDoesNotExist: template_name = '404.html' return defaults.page_not_found(request, template_name)
def download_file(request, filename): ''' see http://stackoverflow.com/questions/1609273/how-to-make-a-private-download-area-with-django ''' fullname = settings.SECURE_MEDIA + filename try: f = file(fullname, "rb") except Exception, e: return page_not_found(request, template_name='404.html')
def section(request, section): """ Function view for the global sections of the blog """ model = {"informe": Report, "tecnicismo": Tech, "articulo": Article} if section in model: object_list = model[section].objects.all().order_by("-pub_date") articles, pages = add_paginator(object_list, request) return render(request, 'section.html', {"title": section, "articles": articles, "pages": pages}) else: return page_not_found(request)
def test_custom_templates_wrong(self): """ Default error views should raise TemplateDoesNotExist when passed a template that doesn't exist. """ rf = RequestFactory() request = rf.get('/') with self.assertRaises(TemplateDoesNotExist): bad_request(request, Exception(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): permission_denied(request, Exception(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): page_not_found(request, Http404(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): server_error(request, template_name='nonexistent')
def rfc_delete(request, id): try: _rfc = ChangeRequest.objects.get(id=id) except ChangeRequest.DoesNotExist: return page_not_found(request) if not (tools.has_access(request, ["managers"]) and _rfc.cur_state == 0): return permission_denied(request) logger.log_action(user=request.user, action=logger.ACTION_REMOVE_RFC, rfc=_rfc) _rfc.delete() return redirect('/list/')
def get(self, request, *args, **kwargs): path = self.get_path() try: requested_file = default_storage.open(path) except IOError: return page_not_found(request) response = HttpResponse(FileWrapper(requested_file), content_type=guess_type(path)) response["Content-Disposition"] = "attachment" response["Content-Length"] = default_storage.size(path) return response
def handler404(request, *args, **kwargs): if 1 or '/api/' in request.path: uri = request.path if request.META.get('QUERY_STRING'): uri += '?' + request.META['QUERY_STRING'] return http.JsonResponse( {'error': 'Page not found {}'.format(uri)}, status=404 ) return page_not_found(request, *args, **kwargs)
def get(self, request, company): try: company_obj = Company.objects.get(name=company) except ObjectDoesNotExist: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='404.html') if not Member.is_editor(request.user, company_obj): return page_not_found(request.path, exception=None, template_name='403.html') form = EditCompanyForm(instance=company_obj) return render( request, 'company/edit_comp_profile.html', { 'company': company_obj, 'is_owner': Member.is_owner(request.user, company_obj), 'is_editor': Member.is_editor(request.user, company_obj), 'form': form, })
def url_redirect(request, short): id = Baco.to_dec(short, base62) try: url = URL.objects.get(id=id) except URL.DoesNotExist as e: return page_not_found(request, e, 'url/404.html') # Get a more precise request datetime ip = get_real_ip(request) or '0.0.0.0' Click.objects.create(url=url, ip=ip) return HttpResponseRedirect(url.url)
def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) cotizacion = Cotizacion.objects.get(pk=kwargs['pk']) if cotizacion.corredor.pk != request.user.pk: return page_not_found(request) context['cotizacion'] = cotizacion context['form'] = CotizacionUpdateForm() context['pk1'] = kwargs['pk1'] context['pk2'] = kwargs['pk2'] context['pk3'] = kwargs['pk3'] context['pk4'] = kwargs['pk4'] return self.render_to_response(context)
def get(self, request): """ User wants to apply """ user = request.user if user.is_consultant(): return page_not_found(request, exception=None, template_name='403.html') form = forms.ConsultantApplicationForm() return render(request, 'consultant/apply.html', {'form': form})
def build_view(request, id): try: # Intentamos buscar el edificio por su identificador info_edificio = Edificio.objects.get( edificio_id=id) # Almacenamos toda la informacion del edificio # Almacenamos el objeto de todas las imagenes en el diccionario de la informacion del edificio para poder enviarla toda img = Imagene.objects.filter(edificio=id) imagenes = [] for imagen in img: imagenes.append( url(imagen.url, width=750, height=550) ) # Nos traemos la URL de la imagen del servidor convertida a 750x550 info_edificio.imagenes = imagenes CronicasFiltradas = Cronica.objects.filter(edificio=id) Fotos = [] usuarios_fotos = [] CronicasFiltradas.test = [] for croniquilla in CronicasFiltradas: usuario_info = Informacion_personale.objects.get( user_id=croniquilla.usuario) #usuarios_fotos.append(url(usuario_info.foto_perfil, width=100, height=100)) usuarios_fotos.append(url(usuario_info.foto_perfil)) Cronicas = zip(CronicasFiltradas, usuarios_fotos) info_edificio.CronicasFiltradas = CronicasFiltradas info_edificio.view = True # Agregamos la propiedad view=True para que se pueda agregar el js y el css de la plantilla vista __init__(request) # Renderizamos la pagina return render( request, 'Edificio/build_view.html', { 'Informacion': getUser_info, 'info_edificio': info_edificio, 'Cronicas': Cronicas, 'building_view': True }) except Edificio.DoesNotExist: # Si no existe el edificio enviamos un 404 return page_not_found(request, "404.html")
def WebsiteRender(request, *args, **kwargs): template_name = 'business_site/landing_pages/template1/index.html' form_class = SendMessageForm temp = WebDomain.objects.filter(domain=request.domain_name).first() if temp: wc = WebsiteControl.objects.filter(website=temp.website).first() if wc.status == 8: # wc = WebsiteControl.objects.filter(website=temp.website).first() #Si el dominio esta refistrado para un business y si el website esta en estado publicado # if wc.status == 8 and temp: template = temp.website.template basic_info = BasicInfo.objects.filter(website=temp.website).first() logo = basic_info.logo gallery_object = Gallery.objects.filter( website=temp.website).first() gallery_comments = gallery_object.comments photo_list = Photo.objects.filter(gallery=gallery_object, asbackground=False) background_photo = Photo.objects.filter(gallery=gallery_object, asbackground=True).first() social_links = Links.objects.filter(website=temp.website).first() contact_info = ContactUs.objects.filter( website=temp.website).first() staff_services = StaffServices.objects.filter(website=temp.website) menu_list = Menu.objects.filter(category__website=temp.website) context = { 'template': template, 'basic_info': basic_info, 'logo': logo, 'gallery_comments': gallery_comments, 'photo_list': photo_list, 'background_photo': background_photo, 'social_links': social_links, 'contact_info': contact_info, 'staff_services': staff_services, 'form': form_class, 'menu_list': menu_list } return render_to_response(template_name, RequestContext(request, context), status=200) else: return render_to_response('business_site/unpblished.html', RequestContext(request)) else: return page_not_found(request, 'Exception', template_name='template/404.html')
def post(self, request): form = login_form(request.POST) if form.is_valid(): username = form.data['username'] password = form.data['password'] PARAMS = {'userName': username, 'password': password} user = authenticate(username=username, password=password) if user is None: r = requests.get(url=ACCESS_RIGHT, params=PARAMS) if r.status_code is 200: json_data = r.json() _permissions = [] #data = json.loads(json_data) user = User.objects.create_user(username, '', password) for _group in Group.objects.filter( name=json_data['access']).all(): user.groups.add(_group) user.save() user = authenticate(username=username, password=password) else: template = jinja_template.get_template( 'login/page-relogin.html') return HttpResponse(template.render(request=request)) if user.is_active: request.session.set_expiry( 7200) #sets the exp. value of the session login(request, user) #the user is now logged in request.user = user # template = jinja_template.get_template('home.html') # return HttpResponse(template.render(request=request)) return redirect('home', permanent=True) else: return HttpResponse( defaults.page_not_found( request, Exception( 'message', 'Error while trying to login.. Please try again..' ), template_name='500.html')) else: template = jinja_template.get_template('login/page-relogin.html') return HttpResponse(template.render(request=request))
def test_error_pages(self): request = self.request_factory.get('/') for response, title in ( (bad_request(request, Exception()), b'Bad Request (400)'), (permission_denied(request, Exception()), b'403 Forbidden'), (page_not_found(request, Http404()), b'Not Found'), (server_error(request), b'Server Error (500)'), ): with self.subTest(title=title): self.assertIn(b'<!doctype html>', response.content) self.assertIn(b'<html lang="en">', response.content) self.assertIn(b'<head>', response.content) self.assertIn(b'<title>%s</title>' % title, response.content) self.assertIn(b'<body>', response.content)
def delete(self, request, *args, **kwargs): try: node = self.get_object() flag = None osf_flag = None message = None if node.is_deleted: node.is_deleted = False node.deleted_date = None flag = NODE_RESTORED message = 'Node {} restored.'.format(node.pk) osf_flag = NodeLog.NODE_CREATED elif not node.is_registration: node.is_deleted = True node.deleted_date = timezone.now() flag = NODE_REMOVED message = 'Node {} removed.'.format(node.pk) osf_flag = NodeLog.NODE_REMOVED node.save() if flag is not None: update_admin_log( user_id=self.request.user.id, object_id=node.pk, object_repr='Node', message=message, action_flag=flag ) if osf_flag is not None: # Log invisibly on the OSF. osf_log = NodeLog( action=osf_flag, user=None, params={ 'project': node.parent_id, }, date=timezone.now(), should_hide=True, ) osf_log.save() except AttributeError: return page_not_found( request, AttributeError( '{} with id "{}" not found.'.format( self.context_object_name.title(), kwargs.get('guid') ) ) ) return redirect(reverse_node(self.kwargs.get('guid')))
def handler404(request): if getattr(settings, 'ARECIBO_SERVER_URL', None): # Make a distinction between Http404 and Resolver404. # Http404 is an explicity exception raised from within the views which # might indicate the wrong usage of arguments to a view for example. # Resolver404 is an implicit exception that Django raises when it can't # resolve a URL to an appropriate view or handler. # We're not interested in sending Arecibo exceptions on URLs like # /blablalb/junk/junk # but we might be interested in /dashboard?from=20LL-02-31 exception = sys.exc_info()[0] if isinstance(exception, Http404) or exception is Http404: django_arecibo.wrapper.post(request, 404) return page_not_found(request)
def get(self, request, *args, **kwargs): id = kwargs.get('id') if id: try: Product.objects.filter(id=id).delete() return HttpResponseRedirect(reverse('product')) except: return JsonResponse({'errors': 'Error al eliminar'}, safe=False, status=400) else: return page_not_found(request, 'Not Found', template_name='base/404.html')
def listt(request, app, cls, subset=None): if not request.user.is_authenticated: return httprr(request, '/admin/login/?next={}'.format(request.get_full_path())) try: _model = apps.get_model(app, cls) except LookupError as e: return page_not_found(request, e, 'error404.html') title = get_metadata(_model, 'verbose_name_plural') subsetp = None list_display = None list_filter = None search_fields = None if subset: subset_func = getattr(_model.objects.get_queryset(), subset) can_view = get_metadata(subset_func, 'can_view') list_display = get_metadata(subset_func, 'list_display') list_filter = get_metadata(subset_func, 'list_filter') search_fields = get_metadata(subset_func, 'search_fields') title = '{} - {}'.format(title, get_metadata(subset_func, 'verbose_name')) else: tid = request.GET.get('tid') subsetp = request.GET.get('tab{}'.format(tid)) if tid and subsetp: subset_func = getattr(_model.objects.get_queryset(), subsetp) subset_title = get_metadata(subset_func, 'verbose_name') can_view = get_metadata(subset_func, 'can_view') title = '{} - {}'.format(title, get_metadata(subset_func, 'verbose_name')) if not permissions.check_group_or_permission(request, can_view): return httprr(request, '/admin/login/?next={}'.format(request.get_full_path())) else: permission = '{}.list_{}'.format(app, cls) if not request.user.has_perm(permission): return httprr(request, '/admin/login/?next={}'.format(request.get_full_path())) qs = _model.objects.all(request.user) if subset: subset_func = getattr(qs, subset) parameters = get_role_values_for_condition(subset_func, request.user) qs = subset_func(*parameters) list_subsets = subset and [subset] or None paginator = Paginator(request, qs, title, list_subsets=list_subsets, is_list_view=True, list_display=list_display, list_filter=list_filter, search_fields=search_fields) paginator.process_request() paginator.load_actions() return render(request, 'default.html', locals())
def dispatcher(request, path=None): if path == 'favicon.ico': return HttpResponse() tokens = path.split('/') try: app_label, view_name, params = tokens[0], tokens[1], tokens[2:-1] except: return page_not_found(request) full_app_name = settings.APP_MAPPING.get(app_label, app_label) fromlist = full_app_name.split('.') try: views = __import__('%s.views' % full_app_name, fromlist=fromlist) if hasattr(views, view_name): func = getattr(views, view_name) else: return page_not_found(request) except ImportError: traceback.print_exc() return page_not_found(request) return func(request, *params)
def car_sys_view(request, carid): cars_qs = Cars.objects.filter(id=carid) if cars_qs.exists(): car_obj = cars_qs.first() else: return page_not_found(request, f'Not found Car: [{carid}]') mis_obj = car_obj.mis_id mis_id = mis_obj.id context = get_car_context(request, mis_obj) context["car"] = car_obj context["is_mis_admin"] = "True" context["refresh"] = False return render(request, "car_sys.html", context)
def delete_name_by_id(request, id=1): dict_csv = {} with open('names.csv', 'r') as f: csv_reader = csv.DictReader(f) for row in csv_reader: dict_csv[row['id']] = row['name'] if '1' in dict_csv.keys(): del dict_csv['1'] with open('del_csv.csv', 'w') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=columns) writer.writeheader() for key, value in dict_csv.items(): writer.writerow({"id": key, "name": value}) return render(request, 'users/delete_name.html') else: return defaults.page_not_found(request, '404.html')
def get_name_by_id(request, id=1): dict_csv = {} with open('names.csv', 'r') as f: csv_reader = csv.DictReader(f) for row in csv_reader: dict_csv[row['id']] = row['name'] #if row['id'] == id: # name = row['name'] if '1' in dict_csv.keys(): #print(dict_csv) name = dict_csv['1'] return render(request, 'users/name_by_id.html', {'name': name}) else: return defaults.page_not_found(request, '404.html')
def post(self, request, *args, **kwargs): id = kwargs.get('id') if id: Recipe.objects.filter(id=id).delete() data = { 'name': 'pizza de cebolla', 'items': [{ 'igredient': 1, 'measure': 1, 'cant': 5 }, { 'igredient': 2, 'measure': 1, 'cant': 10 }] } if data.get('name') != '' and len(data.get('items')) > 0: recipe = Recipe() recipe.name = data.get('name') recipe.business = Business.objects.get_business_by_user( self.request.user) try: recipe.save() except: return HttpResponse(status=400) for item in data.get('items'): recing = RecipeIngredients() recing.recipe = recipe recing.ingredient = Ingredients.objects.filter( id=item.get('igredient')).first() recing.measure = Measure.objects.filter( id=item.get('measure')).first() recing.cant = item.get('cant') try: recing.save() except Exception as e: return HttpResponse(status=500) return HttpResponseRedirect(reverse('recipe')) else: return HttpResponse(status=400) else: return page_not_found(request, 'Not Found', template_name='base/404.html')
def get(self, request, job_title, job_id): try: job = Job.objects.get(pk=job_id) except ObjectDoesNotExist: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='404.html') company_obj = job.company return render( request, 'jobs/details.html', { 'job': job, 'is_owner': Member.is_owner(request.user, company_obj), 'is_editor': Member.is_editor(request.user, company_obj), })
def form_valid(self, form): guid = form.cleaned_data['guid'] name = form.cleaned_data['name'] email = form.cleaned_data['email'] if guid or email: if email: try: user = OSFUser.objects.filter(Q(username=email) | Q(emails__address=email)).get() guid = user.guids.first()._id except OSFUser.DoesNotExist: return page_not_found(self.request, AttributeError('User with email address {} not found.'.format(email))) self.redirect_url = reverse('users:user', kwargs={'guid': guid}) elif name: self.redirect_url = reverse('users:search_list', kwargs={'name': name}) return super(UserFormView, self).form_valid(form)
def post(self, request): """ User submits the application form """ user = request.user if user.is_consultant(): return page_not_found(request, exception=None, template_name='403.html') form = forms.ConsultantApplicationForm(request.POST) if form.is_valid(): app = form.save(commit=False) app.user = user app.save() return redirect('/consultants/')
def log(request, app, cls, pk=None): try: _model = apps.get_model(app, cls) except LookupError as e: return page_not_found(request, e, 'error404.html') if pk: obj = _model.objects.get(pk=pk) qs = obj.get_logs() title = 'Log - {}'.format(obj) else: content_type = ContentType.objects.get_for_model(_model) qs = content_type.log_set.all() title = 'Logs - {}'.format(get_metadata(_model, 'verbose_name_plural')) paginator = Paginator(request, qs, 'Log') return render(request, 'default.html', locals())
def post(self, request, event_title, event_id): try: event_obj = Event.objects.get(pk=event_id) except ObjectDoesNotExist: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='404.html') form = EditEventForm(instance=event_obj, data=request.POST) if form.is_valid(): form.save() messages.success(request, 'The event has successfully been updated.') form = EditEventForm() return HttpResponseRedirect(request.path)
def view(request, app, cls, pk, tab=None): if not request.user.is_authenticated: return httprr(request, '/admin/login/?next={}'.format(request.get_full_path())) try: _model = apps.get_model(app, cls) except LookupError as e: return page_not_found(request, e, 'error404.html') obj = _model.objects.all(request.user).filter(pk=pk).first() obj.request = request obj._user = request.user if 'one_to_many_count' in request.GET: # TODO create a specific view for this purpose return HttpResponse(getattr2(obj, request.GET['one_to_many_count'])) if not permissions.can_view(request, obj): return HttpResponseForbidden() title = str(obj) parent = request.GET.get('parent', None) printable = get_metadata(_model, 'pdf', False) widget_panel = ModelDashboard(request, obj, tab, parent, printable=printable) widget_panel.process_request() if widget_panel.model_panel.message: return httprr(request, request.get_full_path(), widget_panel.model_panel.message) log_data = get_metadata(obj.__class__, 'log', False) if log_data and request.user.is_superuser and request.user.has_perm( 'admin.list_log'): url = '/log/{}/{}/'.format(app, cls) widget_panel.model_panel.drop_down.add_action( '{} {}'.format(_('View'), _('Log')), url, 'ajax', 'fa fa-history') return render(request, 'default.html', locals())
def register(request, user_id=None): if user_id != None: c = Contestant.objects.all() arr = [] for i in c: arr.append(i.id) if user_id not in arr: return page_not_found(request, 'Page Not Found!') if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] phone = request.POST['phone'] email = request.POST['email'] c = Contestant.objects.all() arr = [] for i in c: arr.append(i.email) arr.append(i.phone) if phone in arr or email in arr: return render(request, 'PromoRegister.html', {'same': True}) cur = Contestant.objects.create(first_name=first_name, last_name=last_name, phone=phone, email=email, entries=1) subject = 'Welcome to the HoneyMint contest!' html_message = render_to_string('Mail.html', {'id': cur.id}) plain_message = strip_tags(html_message) from_email = '*****@*****.**' to = cur.email send_mail(subject, plain_message, from_email, [to], html_message=html_message) if user_id != None: inv = Contestant.objects.get(id=user_id) inv.entries = inv.entries + 1 inv.save() return render(request, 'PromoRegister.html', {'success': True}) return render(request, 'PromoRegister.html', {'success': False})
def story(request, section, title): """ View function for all the content except the reports """ url = settings.LOCALHOST + "/" + section + "/" + title model = {"tecnicismo": Tech, "articulo": Article} templates = {"tecnicismo": "tech", "articulo": "article"} resource = get_object_or_404(model[section], url=url) context = {"resource": resource} if section == "tecnicismo": reports = Tech.objects.get(url=url).report_set.all().order_by("-pub_date") context["reports"] = reports[:5] aux = [] for line in resource.toc.split("\n"): entry = re.split("\s*->", line) aux.append({"href": resource.url + "#" + entry[1].strip(), "content": entry[0]}) context["toc"] = aux if section in model: return render(request, templates[section] + ".html", context) else: return page_not_found(request)
def get(self, request, event_title, event_id): event = Event.objects.get(pk=event_id) form = EditEventForm(instance=event) entity_obj = event.entity try: event_obj = Event.objects.get(pk=event_id) except ObjectDoesNotExist: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='404.html') return render( request, 'events/edit_event.html', { 'form': form, 'is_owner': Member.is_owner(request.user, entity_obj), 'is_editor': Member.is_editor(request.user, entity_obj), 'event': event_obj, })
def get(self, request, event_title, event_id): try: event = Event.objects.get(pk=event_id) except ObjectDoesNotExist: return page_not_found(request, exception=ObjectDoesNotExist(), template_name='404.html') entity_obj = event.entity location = Nominatim.geocode(self=Nominatim(), query=event.location) return render( request, 'events/event_details.html', { 'event': event, 'is_owner': Member.is_owner(request.user, entity_obj), 'is_editor': Member.is_editor(request.user, entity_obj), 'lat': location.latitude, 'lon': location.longitude })
def post(self, request, *args, **kwargs): form = self.form_class(self.request.POST) id = kwargs.get('id') if id: ingredients = Ingredients.objects.filter(id=id).first() if form.is_valid(): ingredients.name = form.cleaned_data.get('name') ingredients.description = form.cleaned_data.get('description') ingredients.measure = form.cleaned_data.get('measure') ingredients.business = Business.objects.get_business_by_user( user=self.request.user) try: ingredients.save() return HttpResponseRedirect(reverse('ingredients')) except: return JsonResponse(form.errors, safe=False) else: return page_not_found(request, 'Not Found', template_name='base/404.html')
def page_not_found(request, template_name='404.html'): """ Mobile 404 handler. Templates: `404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ user_agent = utils.get_user_agent(request) if user_agent: template_list = ( 'mobileadmin/%s/404.html' % user_agent, template_name, ) return HttpResponseNotFound( loader.render_to_string(template_list, { 'request_path': request.path, }, context_instance=RequestContext(request))) return defaults.page_not_found(request, template_name)
def delete(self, request, *args, **kwargs): try: node, user = self.get_object() if node.remove_contributor(user, None, log=False): update_admin_log(user_id=self.request.user.id, object_id=node.pk, object_repr='Contributor', message='User {} removed from {} {}.'.format( user.pk, node.__class__.__name__.lower(), node.pk), action_flag=CONTRIBUTOR_REMOVED) # Log invisibly on the OSF. self.add_contributor_removed_log(node, user) except AttributeError: return page_not_found( request, AttributeError('{} with id "{}" not found.'.format( self.context_object_name.title(), self.kwargs.get('guid')))) if isinstance(node, Node): return redirect(reverse_node(self.kwargs.get('guid')))