def tree_delete(request, nr_tree): tree = get_object_or_404(Tree, usuario=request.user, id=nr_tree) if request.method == "POST": tree.delete() return redirect('user_tree_list', username=request.user.username) if get_user_agent(request).is_mobile | get_user_agent(request).is_tablet: return render_to_response("confirm_delete_tree_mob.html", {'object': tree}, context_instance=RequestContext(request)) else: return render_to_response("confirm_delete_tree.html", {'object': tree}, context_instance=RequestContext(request))
def log_in(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): login(request, form.get_user()) return redirect(index) else: if get_user_agent(request).is_mobile | get_user_agent(request).is_tablet: return render(request, "login_mob.html", {"form": form}) else: return render(request, "login.html", {"form": form}) if get_user_agent(request).is_mobile | get_user_agent(request).is_tablet: return render(request, "login_mob.html", {"form": AuthenticationForm()}) else: return render(request, "login.html", {"form": AuthenticationForm()})
def delete(self, request, format=None): params = request.data noteId = params['noteId'] user_agent = get_user_agent(request) print(user_agent) details = getDeviceDetails(user_agent, request) try: for users in NotesDetails.objects.get( noteId=savedNoteData.objects.get( noteId=noteId)).sharedTo.all(): print(users) obj, notif = Notifications.objects.get_or_create( fromUser=UserDetails.objects.get(userId=request.user), toUser=UserDetails.objects.get( userId__username=users.sharedTo.userId.username), notification=str( request.user.username + " deleted note with title:- " + savedNoteData.objects.get(noteId=noteId).title + " that was shared With You from " + details)) if (notif): obj.save() except Exception as e: print("No Shared Users") try: savedNoteData.objects.get(noteId=noteId).delete() return JsonResponse({"message": "Ok Deleted", "status": "200"}) except Exception as e: print(e) stat = status.HTTP_404_NOT_FOUND return Response({"message": "Not Found", "status": "404"})
def get_context_data(self, **kwargs): """Extended method. Add product's images to context.""" context_ = super(IndexPage, self).get_context_data(**kwargs) mobile_view = get_user_agent(self.request).is_mobile tile_products = [] top_products = ( models.Product.objects.active() .bind_fields() .filter(id__in=settings.TOP_PRODUCTS) ) if not mobile_view: tile_products = top_products images_ctx = context.products.ProductImages( tile_products, Image.objects.all(), ).context() return { **context_, **images_ctx, 'tile_title': 'ТОП 10 ТОВАРОВ', 'category_tile': self.get_categories_tile(), 'tile_products': tile_products, }
def build_mock_request(url): """ Helper function to manually build a ``WSGIRequest`` object to be used to test the view. :param url: A string representing the URL for the request. :return: A prepared ``WSGIRequest`` object. """ # Build an interesting request. request = RequestFactory().get(url) request.COOKIES = { # Some silly cookies, just a PoC. 'company': 'MaykinMedia', 'worker': 'Jose', } request.META['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac ' \ 'OS X 10_10_5) AppleWebKit/537.36 ' \ '(KHTML, like Gecko) ' \ 'Chrome/49.0.2623.112 Safari/537.36' # Set up a known IP address to retrieve GeoIP data. This one is from # OpenDNS service, check https://www.opendns.com/ request.META['REMOTE_ADDR'] = '208.67.222.222' # Request is performed by a system user. request.user, _ = User.objects.get_or_create( username='******', first_name='Test', last_name='User', email='*****@*****.**') # Set up the 'django-user-agent' machinery in the request, as its own # middleware does. request.user_agent = SimpleLazyObject(lambda: get_user_agent(request)) return request
def signin(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return redirect(log_in) else: if get_user_agent(request).is_mobile | get_user_agent(request).is_tablet: return render(request, "signin_mob.html", {"form": form}) else: return render(request, "signin.html", {"form": form}) if get_user_agent(request).is_mobile | get_user_agent(request).is_tablet: return render(request, "signin_mob.html", {"form": UserForm() }) else: return render(request, "signin.html", {"form": UserForm() })
def list1(request): count = 1 if request.GET.get('page'): count = int(request.GET['page']) animal_maps = Animal_map.objects.filter().order_by( '-observed_date')[(count - 1) * 10:count * 10] print(animal_maps) sub_results = [] for odject in animal_maps: sub_file = Animal_Sub_file.objects.get(Animal_map_id=odject.id) sub_results.append(sub_file) user_agent = get_user_agent(request) # 모바일 pc 확인 if user_agent.is_mobile: print("모바일") return render(request, 'mobile/homelist.html', { 'animal_maps': animal_maps, 'sub_results': sub_results }) elif user_agent.is_pc: print("pc") return render(request, 'homelist.html', { 'animal_maps': animal_maps, 'sub_results': sub_results })
def mobile_address(request): user_agent = get_user_agent(request) if user_agent.is_mobile: if request.user.is_authenticated: saved_user_address = user_address_detail.objects.filter( buyer=request.user) context = { 'saved_user_address': saved_user_address, } return render(request, 'mobile_checkout/mobile_address.html', context) else: messages.warning(request, "please login first!.") return HttpResponseRedirect(reverse('login_signup_home')) else: return HttpResponseRedirect(reverse('checkout'))
def perform_sync_job(self, request, data): rows = [] if 'ID' in data: identifiers = data.getlist('ID') field_names = [field['name'] for field in DATALINK_FIELDS] rows = list( Datalink.objects.filter(ID__in=identifiers).values_list( *field_names)) # check for missing IDs and return error message for identifier in identifiers: if not any(filter(lambda row: row[0] == identifier, rows)): rows.append((identifier, None, None, 'NotFoundFault: {}'.format(identifier), None, None, None, None)) if data.get('RESPONSEFORMAT') == 'application/json': return JsonResponse( {'links': [{ 'href': row[1], 'text': row[4] } for row in rows]}) else: datalink_table = generate_votable(rows, DATALINK_FIELDS) user_agent = get_user_agent(request) content_type = 'application/xml' if user_agent.is_pc else DATALINK_CONTENT_TYPE return FileResponse(datalink_table, content_type=content_type)
def detect(self, request, template_name): user_agent = get_user_agent(request) if user_agent.is_mobile or user_agent.is_tablet: template_name = str(template_name) template_name = "mobile/" + template_name return template_name
def edit_event(request, event_id): user_agent = get_user_agent(request) if request.method == 'POST': form = EventEditForm(request.POST) if form.is_valid(): event_id = form.cleaned_data['event_id'] if event_id == 0: event = Event(time_start=timezone.now(), time_end=timezone.now()) else: event = Event.objects.get(pk=event_id) event.title = form.cleaned_data['title'] event.ingress_content = form.cleaned_data['ingress_content'] event.main_content = form.cleaned_data['main_content'] event.thumbnail = form.cleaned_data['thumbnail'] event.place = form.cleaned_data['place'] event.place_href = form.cleaned_data['place_href'] hour_start = int(form.cleaned_data['time_start'][:2]) minute_start = int(form.cleaned_data['time_start'][-2:]) hour_end = int(form.cleaned_data['time_end'][:2]) minute_end = int(form.cleaned_data['time_end'][-2:]) day = int(form.cleaned_data['date'][:2]) month = int(form.cleaned_data['date'][3:5]) year = int(form.cleaned_data['date'][-4:]) event.time_start = event.time_start.replace(hour=hour_start, minute=minute_start) event.time_start = event.time_start.replace(day=day, month=month, year=year) event.time_end = event.time_end.replace(hour=hour_end, minute=minute_end) event.time_end = event.time_end.replace(day=day, month=month, year=year) event.save() log_changes.change(request, event) return HttpResponseRedirect('/news/event/'+str(event.id)+'/') else: if int(event_id) == 0: form = EventEditForm(initial={ 'event_id': 0, 'time_start': '00:00', 'time_end': '00:00', 'date': formats.date_format(timezone.now(), 'd/m/Y'), }) else: requested_event = Event.objects.get(pk=event_id) form = EventEditForm(initial={ 'title': requested_event.title, 'event_id': event_id, 'ingress_content': requested_event.ingress_content, 'main_content': requested_event.main_content, 'thumbnail': requested_event.thumbnail, 'place': requested_event.place, 'place_href': requested_event.place_href, 'time_start': formats.date_format(requested_event.time_start, 'H:i'), 'time_end': formats.date_format(requested_event.time_end, 'H:i'), 'date': formats.date_format(requested_event.time_start, 'd/m/Y'), }) context = { 'form': form, 'event_id': event_id, 'mobile': user_agent.is_mobile, } return render(request, 'edit_event.html', context)
def test_disabled_cache(self): reload_module(utils) # re-import with patched settings request = RequestFactory(HTTP_USER_AGENT=iphone_ua_string).get('') user_agent = get_user_agent(request) self.assertIsInstance(user_agent, UserAgent) self.assertIsNone(cache.get(get_cache_key(iphone_ua_string)))
def search(request): # search system query = request.GET.get('search', None) results = Gamebook_art.objects.filter( Q(title__icontains=query)).order_by('-date') # end search system paginator = Paginator(results, 10) page = request.GET.get('page') try: art = paginator.page(page) except PageNotAnInteger: art = paginator.page(1) except EmptyPage: art = paginator.page(paginator.num_pages) # render context = {'art1': results, 'art': art} user_agent = get_user_agent(request) if user_agent.is_mobile: Gamebook_art.snp = 170 elif user_agent.is_pc: Gamebook_art.snp = 250 return render(request, 'search.html', context)
def upload_file(request): user_agent = get_user_agent(request) if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): title = str(form.cleaned_data['title']) while " " in title: title = title.replace(" ", "_") file = request.FILES['file'] number = 0 for element in Upload.objects.order_by('-time'): if title == element.title: number = element.number + 1 break ext = file.name.split(".")[-1:][0] file.name="/upload/"+title+"_"+str(number)+"."+ext instance = Upload(file=file, title=title, time=timezone.now(), number=number) instance.save() return HttpResponseRedirect('/news/upload-done') else: form = UploadForm() context = { 'form': form, 'mobile': user_agent.is_mobile, } return render(request, 'upload.html', context)
def length(self): """Max size of products list depends on the device type.""" is_mobile = get_user_agent(self.request).is_mobile return ( self.PRODUCTS_ON_PAGE_MOB if is_mobile else self.PRODUCTS_ON_PAGE_PC )
def index(request): geo_ip_country = pygeoip.GeoIP(settings.GEOIP_COUNTRY_PATH) geo_ip_isp = pygeoip.GeoIP(settings.GEOIP_ISP_PATH) input_address = request.GET.get('ip', None) if input_address is None: ip = get_ip(request) else: ip = prepare_ip(input_address) if ip: address = { 'ip': ip, 'country': geo_ip_country.country_name_by_addr(ip), 'isp': geo_ip_isp.isp_by_addr(ip), 'hostname': reverse_dns(ip), } else: address = {} context = { 'input_address': input_address, 'address': address, 'user_agent': get_user_agent(request), 'language': request.LANGUAGE_CODE } return render(request, 'pages/home.html', context)
def get_context_data(self, **kwargs): """Extended method. Add product's images to context.""" context = super(IndexPage, self).get_context_data(**kwargs) mobile_view = get_user_agent(self.request).is_mobile top_products = (models.Product.objects.filter( id__in=settings.TOP_PRODUCTS).prefetch_related( 'category').select_related('page')) images = Image.objects.get_main_images_by_pages( models.ProductPage.objects.filter( shopelectro_product__in=top_products)) categories = models.Category.objects.get_root_categories_by_products( top_products) prepared_top_products = [] if not mobile_view: prepared_top_products = [(product, images.get(product.page), categories.get(product)) for product in top_products] return { **context, 'category_tile': config.MAIN_PAGE_TILE, 'prepared_top_products': prepared_top_products, }
def change_password(request): user_agent = get_user_agent(request) error_message = None if request.method == 'POST': form = ChangePasswordForm(request.POST) if form.is_valid(): current_password = form.cleaned_data['current_password'] new_password = form.cleaned_data['new_password'] confirm_new_password = form.cleaned_data['confirm_new_password'] if request.user.check_password( current_password) and new_password == confirm_new_password: request.user.set_password(new_password) request.user.save() return HttpResponseRedirect(reverse('change_password_done')) else: error_message = "Password does not match!" else: error_message = "Invalid input!" else: form = ChangePasswordForm() context = { 'form': form, 'error_message': error_message, 'mobile': user_agent.is_mobile, } return render(request, 'change_password.html', context)
def login_mobile(request): user_agent = get_user_agent(request) error_message = None if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: error_message = 'Username or password is incorrect' else: error_message = 'Invalid input' else: form = LoginForm() context = { 'form': form, 'error_message': error_message, 'mobile': user_agent.is_mobile, } return render(request, 'login_mobile.html', context)
def index(request): #return HttpResponse("<H1>hello world!</H1>") ua = get_user_agent(request) template_file = 'frontend/index.html' #if ua.is_mobile or ua.is_tablet: #template_file = 'frontend/index_mobile.html' return render(request, template_file)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) or dict() context['competition'] = self.competition context['competition_sex'] = self.competition.subs.last().manager.sex context['get_params'] = str(self.get_params).replace("'", '"') # print(context['json_get_params']) context['user_agent'] = get_user_agent(self.request) # if self.kwargs context['filters'] = [ { 'title': 'Команда', 'field_name': 'team', 'choices': tuple([(team.pk, team.name) for team in self.get_teams()]) }, { 'title': 'Год', 'field_name': 'year', 'choices': tuple([(int(year), year) for year in self.get_years()]) }, { 'title': 'Розряд', 'field_name': 'level', 'choices': LevelChoice.choices }, ] return context
def login_logger(request, **kwargs): # no borrar nada de aqui user = User.objects.filter(username=request.user.username)[0] browser = get_user_agent(request) # TODO: mejorar esto despues if get_real_ip(request) is not None: UserLogger.objects.create(user=user, ip_address=get_real_ip(request), description=browser) if get_ip(request) is not None: UserLogger.objects.create(user=user, ip_address=get_ip(request), description=browser)
def cancelRequest(request): params = request.data user_agent = get_user_agent(request) print(user_agent) details = getDeviceDetails(user_agent, request) obj, notif = Notifications.objects.get_or_create( fromUser=UserDetails.objects.get(userId=request.user), toUser=UserDetails.objects.get(userId__username=params['username']), notification=str(request.user.username + " canceled the Friend Request from " + details)) if (notif): obj.save() print(params) if (FriendsFormedDetails.objects.filter( user=UserDetails.objects.get(userId=request.user), friend_name=UserDetails.objects.get( userId__username=params['username'])).count() == 1): FriendsFormedDetails.objects.get( user=UserDetails.objects.get(userId=request.user), friend_name=UserDetails.objects.get( userId__username=params['username'])).delete() return JsonResponse({"message": "Ok Saved", "status": "200"}) if (FriendsFormedDetails.objects.filter( user=UserDetails.objects.get(userId__username=params['username']), friend_name=UserDetails.objects.get( userId=request.user)).count() == 1): FriendsFormedDetails.objects.get( user=UserDetails.objects.get(userId__username=params['username']), friend_name=UserDetails.objects.get(userId=request.user)).delete() return JsonResponse({"message": "Ok Saved", "status": "200"}) else: return JsonResponse({"message": "Not Found", "status": "404"})
def app_download(request, platform, release_id): user_agent = get_user_agent(request) if str.lower(platform) == "ios": app = IosRelease.objects.select_related('ios_project__project_overview__project').filter(id=release_id)[0] ipa_file_url = request.build_absolute_uri(app.ipa_file.url) if user_agent.os.family == "iOS": response = write_manifest_send(request, app, ipa_file_url) return response else: file_name = app.ios_project.project_overview.project.project_code_name ipa_file = app.ipa_file response = HttpResponse(FileWrapper(ipa_file), content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=%s.ipa' % file_name return response elif str.lower(platform) == "android": app = AndroidRelease.objects.select_related('android_project__project_overview__project').filter(id=release_id)[0] apk= app.apk_file file_name = app.android_project.project_overview.project.project_code_name response = HttpResponse(apk, content_type='application/vnd.android.package-archive') response['Content-Disposition'] = 'attachment; filename=%s.apk' % file_name return response
def change_password(request): user_agent = get_user_agent(request) error_message = None if request.method == 'POST': form = ChangePasswordForm(request.POST) if form.is_valid(): current_password = form.cleaned_data['current_password'] new_password = form.cleaned_data['new_password'] confirm_new_password = form.cleaned_data['confirm_new_password'] if request.user.check_password(current_password) and new_password == confirm_new_password: request.user.set_password(new_password) request.user.save() return HttpResponseRedirect(reverse('change_password_done')) else: error_message = "Password does not match!" else: error_message = "Invalid input!" else: form = ChangePasswordForm() context = { 'form': form, 'error_message': error_message, 'mobile': user_agent.is_mobile, } return render(request, 'change_password.html', context)
def upload_file(request): user_agent = get_user_agent(request) if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): title = str(form.cleaned_data['title']) while " " in title: title = title.replace(" ", "_") file = request.FILES['file'] number = 0 for element in Upload.objects.order_by('-time'): if title == element.title: number = element.number + 1 break ext = file.name.split(".")[-1:][0] file.name = "/upload/" + title + "_" + str(number) + "." + ext instance = Upload(file=file, title=title, time=timezone.now(), number=number) instance.save() return HttpResponseRedirect('/news/upload-done') else: form = UploadForm() context = { 'form': form, 'mobile': user_agent.is_mobile, } return render(request, 'upload.html', context)
def classification(request): if request.method == "POST": form = Animal_classForm(request.POST, request.FILES) if form.is_valid(): form.save() Animal_classForm.soundfile = request.FILES['soundfile'] fs = 44100 return HttpResponseRedirect('/animalclassificationresult') # return render(request, 'animalclassificationresult.html', {'form': form}) else: # 데이터 삭제 if os.path.exists('./media/temporary'): for file in os.scandir('./media/temporary'): os.remove(file.path) form = Animal_classForm() # 모바일 pc 확인 user_agent = get_user_agent(request) if user_agent.is_mobile: return render(request, 'mobile/animalclassification.html', {'form': form}) elif user_agent.is_pc: return render(request, 'animalclassification.html', {'form': form})
def __call__(self, request): if '/admin/' not in request.path and not 'iam_ghosting' in request.session: match = resolve(str(request.path)) instance = None try: if '_' in str(match.kwargs.keys()): myfilter = {} for key, val in list(match.kwargs.items())[:1]: key_val = str(key).split('_') myfilter[f'{key_val[1]}'] = val Model = ContentType.objects.get( model=str(key_val[0])).model_class() instance = Model.objects.get(**myfilter) except Exception as e: # print(str(e)) pass # ----------------------------------------------------- protocol = urlsplit(request.build_absolute_uri(None)).scheme current_site = get_current_site(request) current_path = request.path url = ''.join( [str(protocol), '://', str(current_site), str(current_path)]) # ----------------------------------------------------- if request.user.is_authenticated: UserTracker.objects.create_by_model( user=request.user, url=url, instance=instance, user_agent=str(get_user_agent(request)), ip_address=get_client_ip(request)) else: try: th_user = get_object_or_404(User, phone=request.session['phone']) except: th_user = None UserTracker.objects.create_by_model( user=th_user, url=url, instance=instance, user_agent=str(get_user_agent(request)), ip_address=get_client_ip(request)) response = self.get_response(request) return response
def submitGitHubNote(request): permission_classes = (IsAuthenticated, ) parser_classes = [JSONParser] params = request.data user_agent = get_user_agent(request) print(user_agent) details = getDeviceDetails(user_agent, request) #print(params['content']) #print(type(params['content'])) js = json.loads(params['content']) print(js) print(type(js)) if ('caption' in params): obj, notif = savedNoteData.objects.get_or_create( userId=UserDetails.objects.get(userId=request.user), gitHubData=json.loads(params['content']), typeOfData="git", title=params['title'], caption=params['caption'], createdFrom=details, lastUpdated=timezone.now()) else: obj, notif = savedNoteData.objects.get_or_create( userId=UserDetails.objects.get(userId=request.user), gitHubData=json.loads(params['content']), typeOfData="git", title=params['title'], createdFrom=details, lastUpdated=timezone.now()) if notif is True: obj.save() import requests print(request.META.get('HTTP_AUTHORIZATION')) url = "https://shielded-dusk-55059.herokuapp.com/shared/shareNote/" res = requests.post(url, data={ "list[]": request.data['list[]'], "noteId": obj.noteId }, headers={ "Authorization": request.META.get('HTTP_AUTHORIZATION') }).json() if (res['status'] == "201"): return JsonResponse({ 'message': "Ok Created", "status": "201", "id": obj.noteId, "date": obj.createdAt }) else: return JsonResponse({'message': "Error", "status": "500"}) else: return JsonResponse({'message': "Error", "status": "500"})
def get_template_names(self): templates = [self.template_name] user_agent = get_user_agent(self.request) if user_agent.is_mobile: templates.insert(0, 'mobile/' + self.template_name) return templates
def home(request): user_agent = get_user_agent(request) if user_agent.is_mobile: return render(request, "fb_mobile.html") elif user_agent.is_tablet: return render(request, "fb_mobile.html") else: return render(request, "fb_home.html")
def get_and_set_user_agent(request): # If request already has ``user_agent``, it will return that, otherwise # call get_user_agent and attach it to request so it can be reused if hasattr(request, 'user_agent'): return request.user_agent request.user_agent = get_user_agent(request) return request.user_agent
def get(self, *args, **kwargs): user_agent = get_user_agent(self.request) self.player.useragent_is_mobile = user_agent.is_mobile self.player.useragent_is_bot = user_agent.is_bot self.player.useragent_browser_family = user_agent.browser.family self.player.useragent_os_family = user_agent.os.family self.player.useragent_device_family = user_agent.device.family return super().get()
def is_textmode(request): """ Return True if the User Agent is a known text mode browser. """ if request is None: # An error would cause this. return False ua = getattr(get_user_agent(request), 'ua_string', '').lower() return (('curl' in ua) or ('textmode' in ua) or ('elinks' in ua) or ('lynx' in ua))
def faq_page(request): user_agent = get_user_agent(request) if user_agent.is_tablet: return render(request, 'CAD/tablet/faq.html') elif user_agent.is_mobile: return render(request, 'CAD/mobile/faq.html') else: return render(request, 'CAD/desktop/faq.html')
def get_browser_name(request): """ return the user's browser name """ # get user agent user_agent = get_user_agent(request) if not user_agent: return None return user_agent.browser.family.lower()
def mobile_add_address(request): user_agent = get_user_agent(request) if user_agent.is_mobile: if request.user.is_authenticated: if request.method == 'POST': form = user_address_detail_form(request.POST) print('-------------form 1 errors ----------') print(form.errors) if form.is_valid(): print('valid') instance = form.save(commit=False) instance.buyer = request.user instance.save() saved_user_address = user_address_detail.objects.filter( buyer=request.user) context = { 'saved_user_address': saved_user_address, } return render(request, 'mobile_checkout/mobile_address.html', context) else: messages.warning( request, "you entered wrong information please try again or contact us at 8237377298." ) return HttpResponseRedirect(reverse('checkout')) else: saved_user_address = user_address_detail.objects.filter( buyer=request.user) context = { 'saved_user_address': saved_user_address, } return render(request, 'mobile_checkout/mobile_address.html', context) else: messages.warning(request, "please login first!.") return HttpResponseRedirect(reverse('login_signup_home')) else: return HttpResponseRedirect(reverse('checkout'))
def article(self, request, section=None, slug=None): try: article = ArticleHelper.get_article(request, slug) except: raise Http404('Article could not be found.') article.add_view() breaking = ArticleHelper.get_breaking_news().exclude(id=article.id).first() # determine if user is viewing from mobile article_type = 'desktop' user_agent = get_user_agent(request) if user_agent.is_mobile: article_type = 'mobile' if article.template == 'timeline': timeline_tag = article.tags.filter(name__icontains='timeline-') timelineArticles = Article.objects.filter(tags__in=timeline_tag, is_published=True) temp = list(timelineArticles.values('parent_id', 'template_data', 'slug', 'headline', 'featured_image')) try: temp = sorted(temp, key=lambda article: json.loads(article['template_data'])['timeline_date']) except: pass for i, a in enumerate(timelineArticles) : try: temp[i]['featured_image'] = a.featured_image.image.get_thumbnail_url() except: temp[i]['featured_image'] = None article.timeline_articles = json.dumps(temp) article.timeline_title = list(timeline_tag)[0].name.replace('timeline-', '').replace('-', ' ') ref = request.GET.get('ref', None) dur = request.GET.get('dur', None) if not ArticleHelper.is_explicit(article): article.content = ArticleHelper.insert_ads(article.content, article_type) popular = ArticleHelper.get_popular()[:5] context = { 'title': '%s - %s' % (article.headline, self.SITE_TITLE), 'meta': ArticleHelper.get_meta(article), 'article': article, 'reading_list': ArticleHelper.get_reading_list(article, ref=ref, dur=dur), # 'suggested': lambda: ArticleHelper.get_random_articles(2, section, exclude=article.id), 'base_template': 'base.html', 'popular': popular, 'reading_time': ArticleHelper.get_reading_time(article), 'explicit': ArticleHelper.is_explicit(article), 'breaking': breaking, } template = article.get_template_path() t = loader.select_template(['%s/%s' % (article.section.slug, template), template, 'article/default.html']) return HttpResponse(t.render(context))
def tree_update(request, nr_tree): tree = get_object_or_404(Tree, usuario=request.user, id=nr_tree) if request.method == "POST": form = TreeForm(request.POST, request.FILES, instance=tree) if form.is_valid(): form.save() return redirect('user_tree_list', username=request.user.username) else: form = TreeForm(instance=tree) if get_user_agent(request).is_mobile | get_user_agent(request).is_tablet: return render_to_response("tree_form_mob.html", {'form': form}, context_instance=RequestContext(request)) else: return render_to_response("tree_form.html", {'form': form}, context_instance=RequestContext(request))
def get(self, request, x0=None, y0=None, x1=None, y1=None): bbox = Polygon.from_bbox([x0, y0, x1, y1]) if x0 else None geom = get_geom_from_cache() ocorrencias = Ocorrencia.objects.filter_by_geom_and_bbox(geom, bbox) if not get_user_agent(request).is_mobile: ocorrencias = SearchForm(request.GET or None, queryset=ocorrencias).get_queryset() response = StreamingHttpResponse(streaming_ocorrencias(ocorrencias), content_type='application/json') response['Cache-Control'] = 'max-age=0, no-cache, no-store' return response
def events(request): event_list = Event.objects.order_by('-time_start') user_agent = get_user_agent(request) context = { 'event_list': event_list, 'mobile': user_agent.is_mobile, } return render(request, 'events_all.html', context)
def event(request, event_id): requested_event = Event.objects.get(pk=event_id) user_agent = get_user_agent(request) context = { 'event': requested_event, 'mobile': user_agent.is_mobile, } return render(request, 'event.html', context)
def articles(request): article_list = Article.objects.order_by('-pub_date') user_agent = get_user_agent(request) context = { 'article_list': article_list, 'mobile': user_agent.is_mobile, } return render(request, 'articles_all.html', context)
def article(request, article_id): requested_article = Article.objects.get(pk=article_id) user_agent = get_user_agent(request) context = { 'article': requested_article, 'mobile': user_agent.is_mobile, } return render(request, 'article.html', context)
def tree_create(request): if request.method == 'POST': form = TreeForm(request.POST, request.FILES) if form.is_valid(): tree = form.save(commit=False) tree.usuario = request.user tree.save() return redirect('user_tree_list', username=request.user.username) else: form = TreeForm() if get_user_agent(request).is_mobile | get_user_agent(request).is_tablet: return render_to_response("tree_form_mob.html", {'form': form}, context_instance=RequestContext(request)) else: return render_to_response("tree_form.html", {'form': form}, context_instance=RequestContext(request))
def my_view(request): user_agent = get_user_agent(request) if user_agent.is_mobile: return HttpResponse(user_agent) elif user_agent.is_tablet: return HttpResponse(user_agent) elif user_agent.is_touch_capable: return HttpResponse(user_agent) elif user_agent.is_pc: return HttpResponse(user_agent) elif user_agent.is_bot: return HttpResponse(user_agent)
def get_context_data(self, **kwargs): user_agent = get_user_agent(self.request) context = super(IndexView, self).get_context_data(**kwargs) context['params'] = self.request.POST if not user_agent.is_mobile: context['search_form'] = SearchForm(self.request.POST or None) else: context['search_form'] = None context['request'] = self.request context['user'] = self.request.user context['categorias'] = Categoria.objects.all() return context
def home(request): if not check_profile(request.user): return HttpResponseRedirect('/edit-profile') check_city(request) is_mobile = get_user_agent(request).is_mobile variables = { 'is_mobile': is_mobile, 'user': request.user, 'regions': Region.objects.all().order_by('alternate_names') } return render_to_response( 'home/index.html', variables )
def door_chart(request): user_agent = get_user_agent(request) try: door_obj = DoorStatus.objects.get(name='hackerspace') except DoorStatus.DoesNotExist: door_obj = DoorStatus(name='hackerspace', status=True, datetime=timezone.now()) s = "" for opendata in OpenData.objects.all(): s += '{"column-1": 0, "date": "' s += opendata.opened.strftime('%Y-%m-%d %H:%M:%S') s += '"},\n' s += '{"column-1": 1, "date": "' s += opendata.opened.strftime('%Y-%m-%d %H:%M:%S') s += '"},\n' s += '{"column-1": 1, "date": "' s += opendata.closed.strftime('%Y-%m-%d %H:%M:%S') s += '"},\n' s += '{"column-1": 0, "date": "' s += opendata.closed.strftime('%Y-%m-%d %H:%M:%S') s += '"},\n' if door_obj.status: s += '{"column-1": 0, "date": "' s += door_obj.datetime.strftime('%Y-%m-%d %H:%M:%S') s += '"},\n' s += '{"column-1": 1, "date": "' s += door_obj.datetime.strftime('%Y-%m-%d %H:%M:%S') s += '"},\n' s += '{"column-1": 1, "date": "' s += timezone.now().strftime('%Y-%m-%d %H:%M:%S') s += '"},\n' else: s += '{"column-1": 0, "date": "' s += timezone.now().strftime('%Y-%m-%d %H:%M:%S') s += '"},\n' import html.parser html_parser = html.parser.HTMLParser() s = html_parser.unescape(s) context = { 'open_data': s, 'mobile': user_agent.is_mobile, } return render(request, 'chart.html', context)
def forgot_password(request): user_agent = get_user_agent(request) error_message = None if request.method == 'POST': form = ForgotPasswordForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] try: user = User.objects.get(email=email) except User.DoesNotExist: error_message = 'User does not exist' context = { 'form': form, 'error_message': error_message, 'mobile': user_agent.is_mobile, } return render(request, 'forgot_password.html', context) else: auth_object = UserAuthentication.objects.create(user=user) auth_object.save() email_subject = 'New password @ hackerspace-ntnu.no' message = "Use this link to set a new password" email_message = render_to_string('signup_mail.html', {'request': request, 'message': message, 'hash_key': auth_object.key.hex},) thread = Thread(target=send_password_email, args=(email_subject, email_message, email)) thread.start() return HttpResponseRedirect(reverse('forgot_password_done')) else: error_message = "Invalid input!" else: form = ForgotPasswordForm() context = { 'form': form, 'error_message': error_message, 'mobile': user_agent.is_mobile, } return render(request, 'forgot_password.html', context)
def edit_article(request, article_id): user_agent = get_user_agent(request) if request.method == 'POST': form = ArticleEditForm(request.POST) if form.is_valid(): article_id = form.cleaned_data['article_id'] if article_id == 0: article = Article() else: article = Article.objects.get(pk=article_id) article.title = form.cleaned_data['title'] article.ingress_content = form.cleaned_data['ingress_content'] article.main_content = form.cleaned_data['main_content'] article.thumbnail = form.cleaned_data['thumbnail'] article.save() log_changes.change(request, article) return HttpResponseRedirect('/news/article/'+str(article.id)+'/') else: if int(article_id) == 0: form = ArticleEditForm(initial={ 'article_id': 0, }) else: requested_article = Article.objects.get(pk=article_id) form = ArticleEditForm(initial={ 'title': requested_article.title, 'article_id': article_id, 'ingress_content': requested_article.ingress_content, 'main_content': requested_article.main_content, 'thumbnail': requested_article.thumbnail, }) context = { 'form': form, 'article_id': article_id, 'mobile': user_agent.is_mobile, } return render(request, 'edit_article.html', context)
def ocorrencia_crud(request, pk=None): user_agent = get_user_agent(request) if not user_agent.is_mobile: template = 'ocorrencia_form.html' else: template = 'ocorrencia_form_mob.html' geom = EMPTY_STRING if pk: ocorrencia = get_object_or_404(Ocorrencia, pk=pk, user=request.user) geom = ocorrencia.ponto or ocorrencia.poligono title = u'Editar Ocorrência' else: ocorrencia = None title = u'Nova Ocorrência' form = OcorrenciaForm(request.POST or None, instance=ocorrencia, request_user=request.user) if request.method == 'POST': if form.is_valid(): ocorrencia = form.save() messages.success(request, u'É um prazer para nossa gestão ouvir sua solicitação. Obrigado, entraremos em contato em breve!') return redirect(reverse('ocorrencia_detail', args=(ocorrencia.pk,))) else: geom = form.cleaned_data.get('ponto', EMPTY_STRING) if geom != EMPTY_STRING: geom = '%s' % geom return render( request, template, { 'form': form, 'request': request, 'user': request.user, 'geom': geom, 'title': title } )
def login_user(request): event_list = Event.objects.order_by('-time_start')[:3] article_list = Article.objects.order_by('-pub_date')[:3] try: door_status = DoorStatus.objects.get(name='hackerspace').status except DoorStatus.DoesNotExist: door_status = True user_agent = get_user_agent(request) error_message = None if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: error_message = 'User is not activated' else: error_message = 'Username or password is incorrect' else: error_message = 'Invalid input' else: form = LoginForm() context = { 'article_list': article_list, 'event_list': event_list, 'form': form, 'door_status': door_status, 'error_message': error_message, 'mobile': user_agent.is_mobile, } return render(request, 'index.html', context)
def build_mock_request(url): """ Helper function to manually build a ``WSGIRequest`` object to be used to test the view. :param url: A string representing the URL for the request. :return: A prepared ``WSGIRequest`` object. """ # Build an interesting request. request = RequestFactory().get(url) request.COOKIES = { # Some silly cookies, just a PoC. 'company': 'MaykinMedia', 'worker': 'Jose', } request.META['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac ' \ 'OS X 10_10_5) AppleWebKit/537.36 ' \ '(KHTML, like Gecko) ' \ 'Chrome/49.0.2623.112 Safari/537.36' # Set up a known IP address to retrieve GeoIP data. This one is from # OpenDNS service, check https://www.opendns.com/ request.META['REMOTE_ADDR'] = '208.67.222.222' # Request is performed by a system user. request.user, _ = User.objects.get_or_create( username='******', first_name='Test', last_name='User', email='*****@*****.**' ) # Set up the 'django-user-agent' machinery in the request, as its own # middleware does. request.user_agent = SimpleLazyObject(lambda: get_user_agent(request)) return request
def activate_account(request, hash_key): user_agent = get_user_agent(request) error_message = None try: value = UUID(hash_key, version=4) auth_object = get_object_or_404(UserAuthentication, key=hash_key) if auth_object.expired(): raise Http404 if auth_object.user.is_active: if request.method == 'POST': form = SetPasswordForm(request.POST) if form.is_valid(): password = form.password_matches() if password: auth_object.set_password(password) return HttpResponseRedirect(reverse('set_password_done')) else: error_message = 'Passwords does not match' else: form = SetPasswordForm() context = { 'form': form, 'error_message': error_message, 'mobile': user_agent.is_mobile, 'hash_key': hash_key, } return render(request, 'set_password.html', context) else: auth_object.activate() return render(request, 'activation_done.html') except ValueError: raise Http404