def test_requestsite_delete_notimplemented_msg(self): # Test response msg for RequestSite.delete NotImplementedError request = HttpRequest() request.META = { "HTTP_HOST": "example.com", } msg = 'RequestSite cannot be deleted.' with self.assertRaisesMessage(NotImplementedError, msg): RequestSite(request).delete()
def suggestions(request): user = request.user suggestions = Podcast.objects.filter(podcastsuggestion__suggested_to=user, podcastsuggestion__deleted=False) current_site = RequestSite(request) return render(request, 'suggestions.html', { 'entries': suggestions, 'url': current_site })
def get_context_data(self, **kwargs): context = super(ResourceDetail, self).get_context_data(**kwargs) context['site'] = RequestSite(self.request) context['heading'] = 'no' for data in context['resource'].content: if data.block_type == 'factoids': context['heading'] = 'yes' context['current_page'] = 'resource-detail' return context
def suggestions(request): user = request.user suggestions = Podcast.objects.filter(podcastsuggestion__suggested_to=user, podcastsuggestion__deleted=False) current_site = RequestSite(request) return render(request, "suggestions.html", { "entries": suggestions, "url": current_site })
def options(request): return render( request, 'options.html', { 'title': gl(settings.TITLE), 'domain': '{0}://{1}'.format('https' if request.is_secure() else 'http', RequestSite(request).domain), })
def home(request): if is_publisher(request.user): podcasts = Podcast.objects.filter(publishedpodcast__publisher=request.user)\ .prefetch_related('slugs') site = RequestSite(request) update_token = request.user.profile.get_token('publisher_update_token') form = SearchPodcastForm() return render( request, 'publisher/home.html', { 'update_token': update_token, 'podcasts': podcasts, 'form': form, 'site': site, }) else: site = RequestSite(request) return render(request, 'publisher/info.html', {'site': site})
def show_list(request): current_site = RequestSite(request) subscriptionlist = create_subscriptionlist(request) return render( request, 'subscriptions.html', { 'subscriptionlist': subscriptionlist, 'url': current_site, 'podcast_ad': Podcast.objects.get_advertised_podcast(), })
def view_article(request, article_id): try: article = Article.objects.get(id = article_id) error_flag = False if article.is_deleted or article.is_blocked: error_flag = True msg = 'Article is deleted' elif not article.is_published: error_flag = True msg = 'Article is not published' if error_flag: if request.ACCEPT_FORMAT == 'json': return JsonResponse(status = 404, data = {'error' : msg}) else: return HttpResponse(status = 404, content = msg) if request.ACCEPT_FORMAT == 'json': return JsonResponse(status = 200, data = article.as_json()) else: if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) question = Question.objects.filter(article=article).extra(select = { 'num_a' : 'SELECT COUNT(*) FROM zabo_answer WHERE zabo_question.id=zabo_answer.question_id', 'num_d_a' : 'SELECT COUNT(*) FROM zabo_answer WHERE zabo_answer.is_deleted = 1' + \ ' and zabo_question.id=zabo_answer.question_id' }, where = ['zabo_question.is_deleted = 0 OR ' + \ 'zabo_question.is_deleted = 1 AND "num_a" > "num_d_a"']) return render(request, 'zabo/article.html', { 'article' : article, 'site' : site, 'question' : question, 'participant' : map(lambda x : x.user, Participation.objects.filter(article = article)), 'is_participating' : Participation.objects.filter(user = request.user.id, article = article).exists(), 'is_owner' : len(article.owner.filter(id = request.user.id)) > 0, 'request' : request, }) except Article.DoesNotExist: if request.ACCEPT_FORMAT == 'json': return JsonResponse( status = 404, data = {'error' : 'Not Found: article_id : ' + article_id} ) else: return HttpResponse( status = 404, content = 'Not Found: article_id : ' + article_id )
def get_current_site(request): """ Version of sites.shortcuts.get_current_site that always uses the request """ # Imports are inside the function because its point is to avoid importing # the Site models when django.contrib.sites isn't installed. if apps.is_installed('django.contrib.sites'): return Site.objects._get_site_by_request(request) else: return RequestSite(request)
def make_absolute(context, uri): if '://' not in uri: request = context['request'] prefix = request.is_secure() and 'https' or 'http' if uri.startswith('//'): # we only need the prefix uri = '%s:%s' % (prefix, uri) else: uri = '%s://%s%s' % (prefix, RequestSite(request).domain, uri) return uri
def csrf_failure(request, reason=""): site = RequestSite(request) return render(request, 'csrf.html', { 'site': site, 'method': request.method, 'referer': request.META.get('HTTP_REFERER', _('another site')), 'path': request.path, 'get': request.GET, 'post': request.POST, })
def view_events(request): if request.method == 'GET': context = { 'events': fetch(request), 'site': RequestSite(request), 'protocol': 'https' if request.is_secure() else 'http' } return render_to_response('events.html', context) else: return post_event(request)
def _site_from_org(cls, org): # lint-amnesty, pylint: disable=missing-function-docstring configuration = SiteConfiguration.get_configuration_for_org(org, select_related=['site']) if configuration is None: try: return Site.objects.get(id=settings.SITE_ID) except Site.DoesNotExist: return RequestSite(crum.get_current_request()) else: return configuration.site
def register(self, **cleaned_data): if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(self.request) new_user = CustomRegistrationProfile.objects.create_inactive_user(cleaned_data, site) signals.user_registered.send(sender=self.__class__, user=new_user, request=self.request) new_user = authenticate(username=cleaned_data['username'], password=cleaned_data['password1']) login(self.request, new_user) return new_user
def get_site(request=None): site = None root_url = 'http://localhost' if Site._meta.installed: site = Site.objects.get_current() root_url = 'http://%s' % site.domain else: if request: site = RequestSite(request) return site, root_url
def get_current_site(request=None): if apps.is_installed('django.contrib.sites'): from .models import Site if not hasattr(settings, 'SITE_ID') and request is None: return _get_site_by_request(Site.objects, request) else: return Site.objects.get_current(request) else: from django.contrib.sites.requests import RequestSite return RequestSite(request)
def suggestions(request, count, format): count = parse_range(count, 1, 100, 100) user = request.user suggestions = Podcast.objects.filter(podcastsuggestion__suggested_to=user, podcastsuggestion__deleted=False) title = _('gpodder.net - %(count)d Suggestions') % {'count': len(suggestions)} domain = RequestSite(request).domain p_data = lambda p: podcast_data(p, domain) return format_podcast_list(suggestions, format, title, json_map=p_data, jsonp_padding=request.GET.get('jsonp'))
def get_default_context(self, event, request): context = {} prefix = request.is_secure() and 'https' or 'http' root_url = '%s://%s' % (prefix, RequestSite(request).domain) url = reverse('main:event', kwargs={'slug': event.slug}) context['absolute_url'] = root_url + url context['embedded'] = self.embedded context['no_warning'] = self.no_warning context['no_footer'] = request.GET.get('no-footer') return context
def _site_from_org(cls, org): configuration = SiteConfiguration.get_configuration_for_org( org, select_related=['site']) if configuration is None: try: return Site.objects.get(id=settings.SITE_ID) except Site.DoesNotExist: return RequestSite(crum.get_current_request()) else: return configuration.site
def solution_list(request, task_id, user_id=None): if (user_id and not request.user.is_trainer and not request.user.is_superuser): return access_denied(request) task = get_object_or_404(Task, pk=task_id) author = get_object_or_404(User, pk=user_id) if user_id else request.user solutions = task.solution_set.filter(author = author).order_by('-id') final_solution = task.final_solution(author) if task.publication_date >= datetime.now() and not request.user.is_trainer: raise Http404 if request.method == "POST": if task.expired() and not request.user.is_trainer: return access_denied(request) solution = Solution(task = task, author=author) formset = SolutionFormSet(request.POST, request.FILES, instance=solution) if formset.is_valid(): solution.save() formset.save() run_all_checker = bool(User.objects.filter(id=user_id, tutorial__tutors__pk=request.user.id) or request.user.is_trainer) solution.check_solution(run_all_checker) if solution.accepted: # Send submission confirmation email t = loader.get_template('solutions/submission_confirmation_email.html') c = { 'protocol': request.is_secure() and "https" or "http", 'domain': RequestSite(request).domain, 'site_name': settings.SITE_NAME, 'solution': solution, } with tempfile.NamedTemporaryFile(mode='w+') as tmp: tmp.write(t.render(c)) tmp.seek(0) [signed_mail, __, __, __, __] = execute_arglist(["openssl", "smime", "-sign", "-signer", settings.CERTIFICATE, "-inkey", settings.PRIVATE_KEY, "-in", tmp.name], ".", unsafe=True) connection = get_connection() message = ConfirmationMessage(_("%s submission confirmation") % settings.SITE_NAME, signed_mail, None, [solution.author.email], connection=connection) if solution.author.email: message.send() if solution.accepted or get_settings().accept_all_solutions: solution.final = True solution.save() return HttpResponseRedirect(reverse('solution_detail', args=[solution.id])) else: formset = SolutionFormSet() attestations = Attestation.objects.filter(solution__task=task, author__tutored_tutorials=request.user.tutorial) attestationsPublished = attestations[0].published if attestations else False return render(request, "solutions/solution_list.html", {"formset": formset, "task":task, "solutions": solutions, "final_solution":final_solution, "attestationsPublished":attestationsPublished, "author":author, "invisible_attestor":get_settings().invisible_attestor})
def import_user(request): """ View in the admin """ if request.method == 'POST': form = ImportForm(request.POST, request.FILES) if form.is_valid(): try: imported_user = User.import_user(form.files['file']) messages.success( request, "The import was successfull. %i users imported." % imported_user.count()) if form.cleaned_data['require_reactivation']: for user in [ user for user in imported_user if user.is_active ]: user.is_active = False user.set_new_activation_key() user.save() if form.cleaned_data['send_reactivation_email']: # Send activation email t = Template(form.cleaned_data['meassagetext']) c = { 'email': user.email, 'domain': RequestSite(request).domain, 'site_name': settings.SITE_NAME, 'uid': int_to_base36(user.id), 'user': user, 'protocol': request.is_secure() and 'https' or 'http', 'activation_key': user.activation_key, 'expiration_days': get_settings().acount_activation_days, } send_mail( _("Account activation on %s") % settings.SITE_NAME, t.render(c), None, [user.email]) return HttpResponseRedirect( reverse('admin:accounts_user_changelist')) except: raise from django.forms.utils import ErrorList msg = "An Error occured. The import file was probably malformed." form._errors["file"] = ErrorList([msg]) else: form = ImportForm() return render(request, 'admin/accounts/user/import.html', { 'form': form, 'title': "Import User" })
def post(self, request): """ Carries out the login, redirects to get if it fails """ # redirect target on successful login next_page = request.POST.get('next', '') # redirect target on failed login login_page = '{page}?next={next_page}'.format( page=reverse('login'), next_page=next_page ) username = request.POST.get('user', None) if not username: messages.error(request, _('Username missing')) return HttpResponseRedirect(login_page) password = request.POST.get('pwd', None) if not password: messages.error(request, _('Password missing')) return HttpResponseRedirect(login_page) # find the user from the configured login systems, and verify pwd user = authenticate(username=username, password=password) if not user: messages.error(request, _('Wrong username or password.')) return HttpResponseRedirect(login_page) if not user.is_active: send_activation_email(user, request) messages.error( request, _( 'Please activate your account first. ' 'We have just re-sent your activation email' ), ) return HttpResponseRedirect(login_page) # set up the user's session login(request, user) if next_page: domain = RequestSite(request).domain allowed_hosts = [domain] if is_safe_url(next_page, allowed_hosts): return HttpResponseRedirect(next_page) else: # TODO: log a warning that next_page is not # considered a safe redirect target pass return HttpResponseRedirect(DEFAULT_LOGIN_REDIRECT)
def get(self, request): """ Shows the login page """ # Do not show login page for already-logged-in users if request.user.is_authenticated: return HttpResponseRedirect(DEFAULT_LOGIN_REDIRECT) return render(request, 'login.html', { 'url': RequestSite(request), 'next': request.GET.get('next', ''), })
def manifest(request): return render( request, 'manifest.json', { 'title': gl(settings.TITLE), 'domain': '{0}://{1}'.format('https' if request.is_secure() else 'http', RequestSite(request).domain), }, content_type='application/json')
def documentation(request, default_context=None): context = default_context or {} endpoints = [] all_models = [] unique_model_names = set() for source in MODELS_MODULES: for name, value in inspect.getmembers(source): if name in unique_model_names: # model potentially in multiple modules continue if inspect.isclass(value): all_models.append(value) unique_model_names.add(name) for model in all_models: model_name = model.__name__ if model_name.endswith('Middleware'): model_name = model_name[:-10] try: if not is_valid_model_class(model): continue if model_name in API_DONT_SERVE_LIST: continue except TypeError: # most likely a builtin class or something continue model_inst = model() if ( model_inst.API_REQUIRED_PERMISSIONS and not has_permissions(request.user, model_inst.API_REQUIRED_PERMISSIONS) ): continue endpoints.append(_describe_model(model_name, model)) endpoints.sort(key=lambda ep: ep['name']) base_url = ( '%s://%s' % (request.is_secure() and 'https' or 'http', RequestSite(request).domain) ) if request.user.is_active: your_tokens = tokens_models.Token.objects.active().filter(user=request.user) else: your_tokens = tokens_models.Token.objects.none() context.update({ 'endpoints': endpoints, 'base_url': base_url, 'count_tokens': your_tokens.count() }) return render(request, 'api/documentation.html', context)
def welcome(request): current_site = RequestSite(request) lang = process_lang_params(request) toplist = Podcast.objects.all().toplist(lang) return render(request, 'home.html', { 'url': current_site, 'toplist': toplist, })
def welcome(request): current_site = RequestSite(request) lang = process_lang_params(request) toplist = Podcast.objects.all().toplist(lang) return render(request, "home.html", { "url": current_site, "toplist": toplist })
def form_valid(self, form): rval = super(KanisaRegistrationView, self).form_valid(form) cache.delete('kanisa_inactive_users') send_bulk_mail(users_with_perm('manage_users'), 'on_account_registration', { 'user': form.instance, 'site': RequestSite(self.request), }) return rval
def send_activation_email(user, request): """ Sends the activation email for the given user """ subj = render_to_string('registration/activation_email_subject.txt') # remove trailing newline added by render_to_string subj = subj.strip() msg = render_to_string('registration/activation_email.txt', { 'site': RequestSite(request), 'activation_key': user.profile.activation_key, }) user.email_user(subj, msg)
def show_list(request): current_site = RequestSite(request) subscriptionlist = create_subscriptionlist(request) return render( request, "subscriptions.html", { "subscriptionlist": subscriptionlist, "url": current_site, "podcast_ad": Podcast.objects.get_advertised_podcast(), }, )
class RequestSiteTests(SimpleTestCase): def setUp(self): request = HttpRequest() request.META = {'HTTP_HOST': 'example.com'} self.site = RequestSite(request) def test_init_attributes(self): self.assertEqual(self.site.domain, 'example.com') self.assertEqual(self.site.name, 'example.com') def test_str(self): self.assertEqual(str(self.site), 'example.com') def test_save(self): msg = 'RequestSite cannot be saved.' with self.assertRaisesMessage(NotImplementedError, msg): self.site.save() def test_delete(self): msg = 'RequestSite cannot be deleted.' with self.assertRaisesMessage(NotImplementedError, msg): self.site.delete()
def setUp(self): request = HttpRequest() request.META = {'HTTP_HOST': 'example.com'} self.site = RequestSite(request)