desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Enforce CSRF validation for session based authentication.'
def enforce_csrf(self, request):
reason = CSRFCheck().process_view(request, None, (), {}) if reason: raise exceptions.AuthenticationFailed(('CSRF Failed: %s' % reason))
'Return a readable representation for use with eg. select widgets.'
def label_from_instance(self, obj):
desc = smart_text(obj) ident = smart_text(self.to_native(obj)) if (desc == ident): return desc return ('%s - %s' % (desc, ident))
'Return a readable representation for use with eg. select widgets.'
def label_from_instance(self, obj):
desc = smart_text(obj) ident = smart_text(self.to_native(obj.pk)) if (desc == ident): return desc return ('%s - %s' % (desc, ident))
'Given an object, return the URL that hyperlinks to the object. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf.'
def get_url(self, obj, view_name, request, format):
lookup_field = getattr(obj, self.lookup_field) kwargs = {self.lookup_field: lookup_field} try: return reverse(view_name, kwargs=kwargs, request=request, format=format) except NoReverseMatch: pass if (self.pk_url_kwarg != 'pk'): pk = obj.pk kwargs = {self.pk_url_kwarg:...
'Return the object corresponding to a matched URL. Takes the matched URL conf arguments, and the queryset, and should return an object instance, or raise an `ObjectDoesNotExist` exception.'
def get_object(self, queryset, view_name, view_args, view_kwargs):
lookup = view_kwargs.get(self.lookup_field, None) pk = view_kwargs.get(self.pk_url_kwarg, None) slug = view_kwargs.get(self.slug_url_kwarg, None) if (lookup is not None): filter_kwargs = {self.lookup_field: lookup} elif (pk is not None): filter_kwargs = {'pk': pk} elif (slug is n...
'Given an object, return the URL that hyperlinks to the object. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf.'
def get_url(self, obj, view_name, request, format):
lookup_field = getattr(obj, self.lookup_field, None) kwargs = {self.lookup_field: lookup_field} if (lookup_field is None): return None try: return reverse(view_name, kwargs=kwargs, request=request, format=format) except NoReverseMatch: pass if (self.pk_url_kwarg != 'pk'):...
'Returns the HTTP method. This allows the `method` to be overridden by using a hidden `form` field on a form POST request.'
@property def method(self):
if (not _hasattr(self, '_method')): self._load_method_and_content_type() return self._method
'Returns the content type header. This should be used instead of `request.META.get("HTTP_CONTENT_TYPE")`, as it allows the content type to be overridden by using a hidden form field on a form POST request.'
@property def content_type(self):
if (not _hasattr(self, '_content_type')): self._load_method_and_content_type() return self._content_type
'Returns an object that may be used to stream the request content.'
@property def stream(self):
if (not _hasattr(self, '_stream')): self._load_stream() return self._stream
'More semantically correct name for request.GET.'
@property def QUERY_PARAMS(self):
return self._request.GET
'Parses the request body and returns the data. Similar to usual behaviour of `request.POST`, except that it handles arbitrary parsers, and also works on methods other than POST (eg PUT).'
@property def DATA(self):
if (not _hasattr(self, '_data')): self._load_data_and_files() return self._data
'Parses the request body and returns any files uploaded in the request. Similar to usual behaviour of `request.FILES`, except that it handles arbitrary parsers, and also works on methods other than POST (eg PUT).'
@property def FILES(self):
if (not _hasattr(self, '_files')): self._load_data_and_files() return self._files
'Returns the user associated with the current request, as authenticated by the authentication classes provided to the request.'
@property def user(self):
if (not hasattr(self, '_user')): self._authenticate() return self._user
'Sets the user on the current request. This is necessary to maintain compatibility with django.contrib.auth where the user property is set in the login and logout functions.'
@user.setter def user(self, value):
self._user = value
'Returns any non-user authentication information associated with the request, such as an authentication token.'
@property def auth(self):
if (not hasattr(self, '_auth')): self._authenticate() return self._auth
'Sets any non-user authentication information associated with the request, such as an authentication token.'
@auth.setter def auth(self, value):
self._auth = value
'Return the instance of the authentication instance class that was used to authenticate the request, or `None`.'
@property def successful_authenticator(self):
if (not hasattr(self, '_authenticator')): self._authenticate() return self._authenticator
'Parses the request content into self.DATA and self.FILES.'
def _load_data_and_files(self):
if (not _hasattr(self, '_content_type')): self._load_method_and_content_type() if (not _hasattr(self, '_data')): (self._data, self._files) = self._parse()
'Sets the method and content_type, and then check if they"ve been overridden.'
def _load_method_and_content_type(self):
self._content_type = self.META.get('HTTP_CONTENT_TYPE', self.META.get('CONTENT_TYPE', '')) self._perform_form_overloading() if (not _hasattr(self, '_method')): self._method = self._request.method self._method = self.META.get('HTTP_X_HTTP_METHOD_OVERRIDE', self._method)
'Return the content body of the request, as a stream.'
def _load_stream(self):
try: content_length = int(self.META.get('CONTENT_LENGTH', self.META.get('HTTP_CONTENT_LENGTH'))) except (ValueError, TypeError): content_length = 0 if (content_length == 0): self._stream = None elif hasattr(self._request, 'read'): self._stream = self._request else: ...
'If this is a form POST request, then we need to check if the method and content/content_type have been overridden by setting them in hidden form fields or not.'
def _perform_form_overloading(self):
USE_FORM_OVERLOADING = (self._METHOD_PARAM or (self._CONTENT_PARAM and self._CONTENTTYPE_PARAM)) if ((not USE_FORM_OVERLOADING) or (self._request.method != 'POST') or (not is_form_media_type(self._content_type))): return self._data = self._request.POST self._files = self._request.FILES if (s...
'Parse the request content, returning a two-tuple of (data, files) May raise an `UnsupportedMediaType`, or `ParseError` exception.'
def _parse(self):
stream = self.stream media_type = self.content_type if ((stream is None) or (media_type is None)): empty_data = QueryDict('', self._request._encoding) empty_files = MultiValueDict() return (empty_data, empty_files) parser = self.negotiator.select_parser(self, self.parsers) if...
'Attempt to authenticate the request using each authentication instance in turn. Returns a three-tuple of (authenticator, user, authtoken).'
def _authenticate(self):
for authenticator in self.authenticators: try: user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException: self._not_authenticated() raise if (not (user_auth_tuple is None)): self._authenticator = authenticator ...
'Return a three-tuple of (authenticator, user, authtoken), representing an unauthenticated request. By default this will be (None, AnonymousUser, None).'
def _not_authenticated(self):
self._authenticator = None if api_settings.UNAUTHENTICATED_USER: self._user = api_settings.UNAUTHENTICATED_USER() else: self._user = None if api_settings.UNAUTHENTICATED_TOKEN: self._auth = api_settings.UNAUTHENTICATED_TOKEN() else: self._auth = None
'Proxy other attributes to the underlying HttpRequest object.'
def __getattr__(self, attr):
return getattr(self._request, attr)
'Return true if this MediaType satisfies the given MediaType.'
def match(self, other):
for key in self.params.keys(): if ((key != 'q') and (other.params.get(key, None) != self.params.get(key, None))): return False if ((self.sub_type != '*') and (other.sub_type != '*') and (other.sub_type != self.sub_type)): return False if ((self.main_type != '*') and (other.main_t...
'Return a precedence level from 0-3 for the media type given how specific it is.'
@property def precedence(self):
if (self.main_type == '*'): return 0 elif (self.sub_type == '*'): return 1 elif ((not self.params) or (self.params.keys() == ['q'])): return 2 return 3
'Return the 1-based index of the first item on this page.'
def start_index(self):
paginator = self.paginator if (paginator.count == 0): return 0 elif (self.number == 1): return 1 return ((((self.number - 2) * paginator.per_page) + paginator.first_page) + 1)
'Return the 1-based index of the last item on this page.'
def end_index(self):
paginator = self.paginator if (self.number == paginator.num_pages): return paginator.count return (((self.number - 1) * paginator.per_page) + paginator.first_page)
'Return the size of pages to use with pagination. If `PAGINATE_BY_PARAM` is set it will attempt to get the page size from a named query parameter in the url, eg. ?page_size=100 Otherwise defaults to using `self.paginate_by`.'
def get_paginate_by(self, queryset=None, **kwargs):
if ('HTTP_X_DISABLE_PAGINATION' in self.request.META): return None if (queryset is not None): warnings.warn('The `queryset` parameter to `get_paginate_by()` is due to be deprecated.', PendingDeprecationWarning, stacklevel=2) if self.paginate_by_param: try: ...
'Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view.'
def paginate_queryset(self, queryset, page_size=None):
if ('HTTP_X_DISABLE_PAGINATION' in self.request.META): return None if ('HTTP_X_LAZY_PAGINATION' in self.request.META): self.paginator_class = LazyPaginator deprecated_style = False if (page_size is not None): warnings.warn('The `page_size` parameter to `paginate_query...
'Alters the init arguments slightly. For example, drop \'template_name\', and instead use \'data\'. Setting \'renderer\' and \'media_type\' will typically be deferred, For example being set automatically by the `APIView`.'
def __init__(self, data=None, status=None, template_name=None, headers=None, exception=False, content_type=None):
super().__init__(None, status=status) self.data = data self.template_name = template_name self.exception = exception self.content_type = content_type if headers: for (name, value) in six.iteritems(headers): self[name] = value
'Returns reason text corresponding to our HTTP response status code. Provided for convenience.'
@property def status_text(self):
return responses.get(self.status_code, '')
'Remove attributes from the response that shouldn\'t be cached'
def __getstate__(self):
state = super().__getstate__() for key in ('accepted_renderer', 'renderer_context', 'data'): if (key in state): del state[key] return state
'Given the request rate string, return a two tuple of: <allowed number of requests>, <period of time in seconds>'
def parse_rate(self, rate):
if (rate is None): return None (num, period) = rate.split('/') num_requests = int(num) duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]] return (rate, num_requests, duration)
'If `base_name` is not specified, attempt to automatically determine it from the viewset.'
def get_default_base_name(self, viewset):
raise NotImplemented('get_default_base_name must be overridden')
'Return a list of URL patterns, given the registered viewsets.'
def get_urls(self):
raise NotImplemented('get_urls must be overridden')
'If `base_name` is not specified, attempt to automatically determine it from the viewset.'
def get_default_base_name(self, viewset):
model_cls = getattr(viewset, 'model', None) queryset = getattr(viewset, 'queryset', None) if ((model_cls is None) and (queryset is not None)): model_cls = queryset.model assert model_cls, '`base_name` argument not specified, and could not automatically determine the ...
'Augment `self.routes` with any dynamically generated routes. Returns a list of the Route namedtuple.'
def get_routes(self, viewset):
known_actions = flatten([route.mapping.values() for route in self.routes if isinstance(route, Route)]) detail_routes = [] list_routes = [] for methodname in dir(viewset): attr = getattr(viewset, methodname) httpmethods = getattr(attr, 'bind_to_methods', None) detail = getattr(att...
'Given a viewset, and a mapping of http methods to actions, return a new mapping which only includes any mappings that are actually implemented by the viewset.'
def get_method_map(self, viewset, method_map):
bound_methods = {} for (method, action) in method_map.items(): if hasattr(viewset, action): bound_methods[method] = action return bound_methods
'Given a viewset, return the portion of URL regex that is used to match against a single instance. Note that lookup_prefix is not used directly inside REST rest_framework itself, but is required in order to nicely support nested router implementations, such as drf-nested-routers. https://github.com/alanjds/drf-nested-r...
def get_lookup_regex(self, viewset, lookup_prefix=''):
base_regex = '(?P<{lookup_prefix}{lookup_field}>{lookup_value})' lookup_field = getattr(viewset, 'lookup_field', 'pk') lookup_value = getattr(viewset, 'lookup_value_regex', '[^/.]+') return base_regex.format(lookup_prefix=lookup_prefix, lookup_field=lookup_field, lookup_value=lookup_value)
'Use the registered viewsets to generate a list of URL patterns.'
def get_urls(self):
ret = [] for (prefix, viewset, basename) in self.registry: lookup = self.get_lookup_regex(viewset) routes = self.get_routes(viewset) for route in routes: mapping = self.get_method_map(viewset, route.mapping) if (not mapping): continue r...
'Return a view to use as the API root.'
def get_api_root_view(self):
api_root_dict = {} list_name = self.routes[0].name for (prefix, viewset, basename) in self.registry: api_root_dict[prefix] = list_name.format(basename=basename) class APIRoot(views.APIView, ): _ignore_model_permissions = True def get(self, request, format=None): ret =...
'Generate the list of URL patterns, including a default root view for the API, and appending `.json` style format suffixes.'
def get_urls(self):
urls = [] if self.include_root_view: root_url = url('^$', self.get_api_root_view(), name=self.root_view_name) urls.append(root_url) default_urls = super(DRFDefaultRouter, self).get_urls() urls.extend(default_urls) if self.include_format_suffixes: urls = format_suffix_patterns...
'Let\'s create the needed directory structrue before opening the file'
def open(self, name, mode='rb'):
directory = os.path.join(settings.MEDIA_ROOT, os.path.dirname(name)) if (not os.path.exists(directory)): try: if (self.directory_permissions_mode is not None): old_umask = os.umask(0) try: os.makedirs(directory, self.directory_permissions_m...
'Return a filtered queryset.'
def filter_queryset(self, request, queryset, view):
raise NotImplementedError('.filter_queryset() must be overridden.')
'Check the milestone name is not duplicated in the project'
def validate_name(self, attrs, source):
name = attrs[source] qs = self.project.milestones.filter(name=name) if qs.exists(): raise ValidationError(_('Name duplicated for the project')) return attrs
'Get notification level for specified project and user.'
def cached_notify_policy_for_user(self, user):
policy = self.cached_notify_policies.get(user.id, None) if (policy is None): model_cls = apps.get_model('notifications', 'NotifyPolicy') policy = model_cls.objects.create(project=self, user=user, notify_level=NotifyLevel.involved) del self.cached_notify_policies return policy
'Change logo to this project.'
@detail_route(methods=['POST']) def change_logo(self, request, *args, **kwargs):
self.object = get_object_or_404(self.get_queryset(), **kwargs) self.check_permissions(request, 'change_logo', self.object) logo = request.FILES.get('logo', None) if (not logo): raise exc.WrongArguments(_('Incomplete arguments')) try: pil_image(logo) except Exception: r...
'Remove the logo of a project.'
@detail_route(methods=['POST']) def remove_logo(self, request, *args, **kwargs):
self.object = get_object_or_404(self.get_queryset(), **kwargs) self.check_permissions(request, 'remove_logo', self.object) self.pre_conditions_on_save(self.object) self.object.logo = None self.object.save(update_fields=['logo']) serializer = self.get_serializer(self.object) return response.O...
'Check the name is not duplicated in the project. Check when: - create a new one - update the name - update the project (move to another project)'
def _validate_integrity_between_project_and_name(self, attrs, source):
data_id = attrs.get('id', None) data_name = attrs.get('name', None) data_project = attrs.get('project', None) if self.object: data_id = (data_id or self.object.id) data_name = (data_name or self.object.name) data_project = (data_project or self.object.project) model = self.Me...
'Check the points name is not duplicated in the project on creation'
def validate_name(self, attrs, source):
model = self.opts.model qs = None if (self.object and attrs.get(source, None)): qs = model.objects.filter(project=self.object.project, name=attrs[source]).exclude(id=self.object.id) if ((not self.object) and attrs.get('project', None) and attrs.get(source, None)): qs = model.objects.filt...
'Return the next `batch_size` examples from this data set.'
def next_batch(self, batch_size, fake_data=False):
if fake_data: fake_image = [1.0 for _ in xrange(784)] fake_label = 0 return ([fake_image for _ in xrange(batch_size)], [fake_label for _ in xrange(batch_size)]) start = self._index_in_epoch self._index_in_epoch += batch_size if (self._index_in_epoch > self._num_examples): ...
'Convenient method for outputing.'
def write_out(self, message, verbosity_level=1):
if (self.verbosity and (self.verbosity >= verbosity_level)): sys.stdout.write(smart_str(message)) sys.stdout.flush()
'Returns category\'s published entries.'
def entries_published(self):
return entries_published(self.entries)
'Returns category\'s tree path by concatening the slug of his ancestors.'
@property def tree_path(self):
if self.parent_id: return '/'.join(([ancestor.slug for ancestor in self.get_ancestors()] + [self.slug])) return self.slug
'Builds and returns the category\'s URL based on his tree path.'
@models.permalink def get_absolute_url(self):
return ('zinnia:category_detail', (self.tree_path,))
'Returns author\'s published entries.'
def entries_published(self):
return entries_published(self.entries)
'Builds and returns the author\'s URL based on his username.'
@models.permalink def get_absolute_url(self):
try: return super(Author, self).get_absolute_url() except AttributeError: return ('zinnia:author_detail', [self.get_username()])
'If the user has a full name, use it instead of the username.'
def __str__(self):
return (self.get_short_name() or self.get_full_name() or self.get_username())
'The preview is a cached property.'
@property def preview(self):
if (self._preview is None): self._preview = self.build_preview() return self._preview
'Boolean telling if the preview has hidden content.'
@property def has_more(self):
return bool((self.content and (self.preview != self.content)))
'Method used to render the preview in templates.'
def __str__(self):
return six.text_type(self.preview)
'Build the preview by: - Returning the lead attribut if not empty. - Checking if a split marker is present in the content Then split the content with the marker to build the preview. - Splitting the content to a fixed number of words.'
def build_preview(self):
if self.lead: return self.lead for splitter in self.splitters: if (splitter in self.content): return self.split(splitter) return self.truncate()
'Truncate the content with the Truncator object.'
def truncate(self):
return Truncator(self.content).words(self.max_words, self.more_string, html=True)
'Split the HTML content with a marker without breaking closing markups.'
def split(self, splitter):
soup = BeautifulSoup(self.content.split(splitter)[0], 'html.parser') last_string = soup.find_all(text=True)[(-1)] last_string.replace_with((last_string.string + self.more_string)) return soup
'Return the total of words contained in the content and in the lead.'
@cached_property def total_words(self):
return len(strip_tags(('%s %s' % (self.lead, self.content))).split())
'Return the number of words displayed in the preview.'
@cached_property def displayed_words(self):
return (len(strip_tags(self.preview).split()) - (len(self.more_string.split()) * int((not bool(self.lead)))))
'Return the number of words remaining after the preview.'
@cached_property def remaining_words(self):
return (self.total_words - self.displayed_words)
'Return the percentage of the content displayed in the preview.'
@cached_property def displayed_percent(self):
return ((self.displayed_words / self.total_words) * 100)
'Return the percentage of the content remaining after the preview.'
@cached_property def remaining_percent(self):
return ((self.remaining_words / self.total_words) * 100)
'Retrieve and convert the localized first week day at initialization.'
def __init__(self):
HTMLCalendar.__init__(self, AMERICAN_TO_EUROPEAN_WEEK_DAYS[get_format('FIRST_DAY_OF_WEEK')])
'Return a day as a table cell with a link if entries are published this day.'
def formatday(self, day, weekday):
if (day and (day in self.day_entries)): day_date = date(self.current_year, self.current_month, day) archive_day_url = reverse('zinnia:entry_archive_day', args=[day_date.strftime('%Y'), day_date.strftime('%m'), day_date.strftime('%d')]) return ('<td class="%s entry"><a href="%s" c...
'Return a weekday name translated as a table header.'
def formatweekday(self, day):
return ('<th class="%s">%s</th>' % (self.cssclasses[day], WEEKDAYS_ABBR[day].title()))
'Return a header for a week as a table row.'
def formatweekheader(self):
return ('<thead>%s</thead>' % super(Calendar, self).formatweekheader())
'Return a footer for a previous and next month.'
def formatfooter(self, previous_month, next_month):
footer = '<tfoot><tr><td colspan="3" class="prev">%s</td><td class="pad">&nbsp;</td><td colspan="3" class="next">%s</td></tr></tfoot>' if previous_month: previous_content = ('<a href="%s" class="previous-month">%s</a>' % (reverse('zinnia:entry_archive_month', args=[previous_month.st...
'Return a month name translated as a table row.'
def formatmonthname(self, theyear, themonth, withyear=True):
monthname = ('%s %s' % (MONTHS[themonth].title(), theyear)) return ('<caption>%s</caption>' % monthname)
'Return a formatted month as a table with new attributes computed for formatting a day, and thead/tfooter.'
def formatmonth(self, theyear, themonth, withyear=True, previous_month=None, next_month=None):
self.current_year = theyear self.current_month = themonth self.day_entries = [date.day for date in Entry.published.filter(publication_date__year=theyear, publication_date__month=themonth).datetimes('publication_date', 'day')] v = [] a = v.append a(('<table class="%s">' % ((self.day_entries an...
'Fake urlopen using test client'
def fake_urlopen(self, url):
if ('example' in url): response = StringIO('') return addinfourl(response, {'X-Pingback': '/xmlrpc.php', 'Content-Type': 'text/html; charset=utf-8'}, url) elif ('localhost' in url): response = StringIO('<link rel="pingback" href="/xmlrpc/">') return addinfourl(response, ...
'Fake urlopen using client if domain correspond to current_site else HTTPError'
def fake_urlopen(self, url):
(scheme, netloc, path, query, fragment) = urlsplit(url) if (not netloc): raise if (self.site.domain == netloc): response = six.BytesIO(self.client.get(url).content) return response raise HTTPError(url, 404, 'unavailable url', {}, None)
'https://github.com/Fantomas42/django-blog-zinnia/issues/104 OK, Here I will reproduce the original case: getting a discussion type feed, with a same slug. The correction of this case, will need some changes in the get_object method.'
def test_discussion_feed_with_same_slugs(self):
entry = self.create_published_entry() feed = EntryDiscussions() self.assertEqual(feed.get_object('request', 2010, 1, 1, entry.slug), entry) params = {'title': 'My test entry, part II', 'content': 'My content ', 'slug': 'my-test-entry', 'tags': 'tests', 'publication_date': datetime(2010...
'Deactivate the translation system.'
def tearDown(self):
deactivate()
'Convert aware datetime to local datetime.'
def make_local(self, date_time):
if timezone.is_aware(date_time): return timezone.localtime(date_time) return date_time
'Reproduce the issue encountred on my website, versus the expected result.'
def test_zinnia_pagination_on_my_website(self):
class FakeRequest(object, ): def __init__(self, get_dict={}): self.GET = get_dict source_context = Context({'request': FakeRequest()}) paginator = Paginator(range(40), 10) with self.assertNumQueries(0): for i in range(1, 5): context = zinnia_pagination(source_cont...
'In some languages like French, applying the widont filter before a punctuation sign preceded by a space, leads to ugly visual results, instead of a better visual results.'
def test_widont_pre_punctuation(self):
self.assertEqual(widont('Releases : django-blog-zinnia'), 'Releases&nbsp;:&nbsp;django-blog-zinnia') self.assertEqual(widont('Releases ; django-blog-zinnia'), 'Releases&nbsp;;&nbsp;django-blog-zinnia') self.assertEqual(widont('Releases ! django-blog-zinnia'), 'Releases&nbsp;!&nbsp;django-b...
'Sometimes applying the widont filter on just a punctuation sign, leads to ugly visual results, instead of better visual results.'
def test_widont_post_punctuation(self):
self.assertEqual(widont('Move !'), 'Move&nbsp;!') self.assertEqual(widont('Move it ! '), 'Move&nbsp;it&nbsp;! ') self.assertEqual(widont('Move it ?'), 'Move&nbsp;it&nbsp;?') self.assertEqual(widont('I like to move : it !'), 'I like to move&...
'Test the numbers of entries in context of an url.'
def check_publishing_context(self, url, first_expected, second_expected=None, friendly_context=None, queries=None):
if (queries is not None): with self.assertNumQueries(queries): response = self.client.get(url) else: response = self.client.get(url) self.assertEqual(len(response.context['object_list']), first_expected) if second_expected: self.create_published_entry() respon...
'Test simple views for the Weblog capabilities'
def check_capabilities(self, url, mimetype, queries=0):
with self.assertNumQueries(queries): response = self.client.get(url) self.assertEqual(response['Content-Type'], mimetype) self.assertTrue(('protocol' in response.context))
'https://github.com/Fantomas42/django-blog-zinnia/pull/367'
def test_zinnia_entry_shortlink_unpublished(self):
self.first_entry.sites.clear() with self.assertNumQueries(1): response = self.client.get(('/%s/' % base36(self.first_entry.pk))) self.assertEqual(response.status_code, 404)
'Test case reproducing issue #42 on category detail view paginated'
def test_zinnia_category_detail_paginated(self):
for i in range(PAGINATION): params = {'title': ('My entry %i' % i), 'content': ('My content %i' % i), 'slug': ('my-entry-%i' % i), 'publication_date': datetime(2010, 1, 1), 'status': PUBLISHED} entry = Entry.objects.create(**params) entry.sites.add(self.site) entry.catego...
'Test case reproducing issue #207 on author detail view paginated'
def test_zinnia_author_detail_paginated(self):
for i in range(PAGINATION): params = {'title': ('My entry %i' % i), 'content': ('My content %i' % i), 'slug': ('my-entry-%i' % i), 'publication_date': datetime(2010, 1, 1), 'status': PUBLISHED} entry = Entry.objects.create(**params) entry.sites.add(self.site) entry.author...
'https://github.com/Fantomas42/django-blog-zinnia/pull/307'
def test_manager_pollution(self):
self.assertNotEqual(get_user_model().objects.model, Author)
'https://github.com/Fantomas42/django-blog-zinnia/issues/145'
def test_do_email_authors_without_email(self):
comment = comments.get_model().objects.create(comment='My Comment', user=self.author, is_public=True, content_object=self.entry, submit_date=timezone.now(), site=self.site) self.assertEqual(len(mail.outbox), 0) moderator = EntryCommentModerator(Entry) moderator.email_authors = True moderator.mail...
'Return a queryset of published categories, with a count of their entries published.'
def get_queryset(self):
return Category.published.all().annotate(count_entries_published=Count('entries'))
'Retrieve the category by his path and build a queryset of her published entries.'
def get_queryset(self):
self.category = get_category_or_404(self.kwargs['path']) return self.category.entries_published()
'Add the current category in context.'
def get_context_data(self, **kwargs):
context = super(BaseCategoryDetail, self).get_context_data(**kwargs) context['category'] = self.category return context
'The model name is the category\'s slug.'
def get_model_name(self):
return self.category.slug
'Decorate the view dispatcher with permission_required.'
@method_decorator(permission_required('zinnia.add_entry')) def dispatch(self, *args, **kwargs):
return super(QuickEntry, self).dispatch(*args, **kwargs)
'GET only do a redirection to the admin for adding and entry.'
def get(self, request, *args, **kwargs):
return redirect('admin:zinnia_entry_add')
'Handle the datas for posting a quick entry, and redirect to the admin in case of error or to the entry\'s page in case of success.'
def post(self, request, *args, **kwargs):
now = timezone.now() data = {'title': request.POST.get('title'), 'slug': slugify(request.POST.get('title')), 'status': (DRAFT if ('save_draft' in request.POST) else PUBLISHED), 'sites': [Site.objects.get_current().pk], 'authors': [request.user.pk], 'content_template': 'zinnia/_entry_detail.html', 'detail_templa...