before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
* Set up the handleKey binding and check for an aria-keyshortcuts attribute to
* use as a fallback if the key value is not set.
*/
initialize() {
this.handleKey = this.handleKey.bind(this);
if (!this.keyValue) {
const ariaKeyShortcuts = [...this.elementTargets, this.element]
.find((ele... | ```suggestion
this.handleFocus(targetElement);
```
If we simplify the types above, this is no longer needed, let's use `HTMLElement` throughout. |
/**
* Set up the handleKey binding and check for an aria-keyshortcuts attribute to
* use as a fallback if the key value is not set.
*/
initialize() {
this.handleKey = this.handleKey.bind(this);
if (!this.keyValue) {
const ariaKeyShortcuts = [...this.elementTargets, this.element]
.fi... | @@ -85,15 +99,36 @@ export class KeyboardController extends Controller<
}
/**
- * Handle the key event by preventing the default action and triggering a click on the target element.
+ * Handle the key event by preventing the default action and performing the specified action.
*/
handleKey(event: Even... | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.929 | refactor | 155 | 51 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
const searchInput = React.useRef<HTMLInputElement>(null);
const onSubmitForm = (e: React.FormEvent<HTMLFormElement>) => {
if (e.target instanceof HTMLFormElement) {
e.preventDefault();
if (isVisible) {
const inputElement = e.target.querySelector(
'input[name="q"]',
) as H... | Let's move this aria one above to under `action` so we keep the data attributes grouped together.
Let's also add a comment as to why we are doing this `action-value` dynamic behaviour.
These are small items, I can do when merging. | const searchInput = React.useRef<HTMLInputElement>(null);
const onSubmitForm = (e: React.FormEvent<HTMLFormElement>) => {
if (e.target instanceof HTMLFormElement) {
e.preventDefault();
if (isVisible) {
const inputElement = e.target.querySelector(
'input[name="q"]',
) as H... | @@ -45,6 +46,11 @@ export const SearchInput: React.FunctionComponent<SearchInputProps> = ({
action={searchUrl}
method="get"
onSubmit={onSubmitForm}
+ data-controller="w-kbd"
+ aria-keyshortcuts="/" | client/src/components/Sidebar/modules/Search.tsx | 26 | TypeScript | 0.643 | refactor | 236 | 51 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
from decimal import Decimal
import django.contrib.humanize.templatetags.humanize
import django.template.base
import django.template.defaultfilters
import django.templatetags.l10n
import django.utils.numberformat
from django.core.exceptions import ImproperlyConfigured
from django.utils import formats
from django.utils.... | Is the `try` / `except` serving any purpose here?
Besides that, I think the logic here is sound, but the way that we're patching `numberformat` unconditionally at the top and setting it back further down makes it look as if we're trying (badly) to restore its state on exit, when in reality we don't care what state w... | from contextlib import contextmanager
from decimal import Decimal
import django.contrib.humanize.templatetags.humanize
import django.template.base
import django.template.defaultfilters
import django.templatetags.l10n
import django.utils.numberformat
from django.core.exceptions import ImproperlyConfigured
from django.u... | @@ -17,6 +18,20 @@
original_numberformat = django.utils.numberformat.format
original_intcomma = django.contrib.humanize.templatetags.humanize.intcomma
+OriginalVariableNode = django.template.base.VariableNode
+
+
+class VariableNode(OriginalVariableNode):
+ def render(self, context):
+ django.utils.number... | wagtail/test/numberformat.py | 26 | Python | 0.571 | style | 565 | 51 | 51 | false | Only apply `WAGTAIL_CHECK_TEMPLATE_NUMBER_FORMAT` for Wagtail templates | 13,344 | wagtail/wagtail | 16,097 | Python | gasman | laymonage |
# template without explicitly passing it through one of |intcomma, |localize, |unlocalize or
# |filesizeformat will raise an exception. This helps to catch bugs where
# USE_THOUSAND_SEPARATOR = True incorrectly reformats numbers that are not intended to be
# human-readable (such as image dimensions, or IDs within data ... | I ended up adding a context manager instead so we can specify the templates to ignore in each test. Not sure if that's overengineering, though. Let me know if you'd rather us have a global list of templates to ignore. | # template without explicitly passing it through one of |intcomma, |localize, |unlocalize or
# |filesizeformat will raise an exception. This helps to catch bugs where
# USE_THOUSAND_SEPARATOR = True incorrectly reformats numbers that are not intended to be
# human-readable (such as image dimensions, or IDs within data ... | @@ -17,6 +19,34 @@
original_numberformat = django.utils.numberformat.format
original_intcomma = django.contrib.humanize.templatetags.humanize.intcomma
+OriginalVariableNode = django.template.base.VariableNode
+
+
+@contextmanager
+def ignore_numberformat(template_names):
+ class VariableNode(OriginalVariableNode... | wagtail/test/numberformat.py | 26 | Python | 0.5 | suggestion | 217 | 51 | 51 | false | Only apply `WAGTAIL_CHECK_TEMPLATE_NUMBER_FORMAT` for Wagtail templates | 13,344 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
if workflow_state.status == "in_progress":
return _("Sent to %(task_name)s %(started_at)s") % translation_context
return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context
@register.inclusion_tag(
"wagtailadmin/shared/keyboard_shortcuts_dialog.html",
takes_context=Tru... | Sorry to nitpick, but for consistency, this should be sentence case.
```suggestion
("text-editing", _("Text editing")): [
``` |
if workflow_state.status == "in_progress":
return _("Sent to %(task_name)s %(started_at)s") % translation_context
return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context
@register.inclusion_tag(
"wagtailadmin/shared/keyboard_shortcuts_dialog.html",
takes_context=Tru... | @@ -1331,7 +1331,7 @@ def keyboard_shortcuts_dialog(context):
return {
"shortcuts": {
- ("actions-common", _("Common actions")): [
+ ("text-editing", _("Text Editing")): [ | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.786 | suggestion | 138 | 51 | 51 | false | Reorganized the keyboard shortcuts | 13,359 | wagtail/wagtail | 16,097 | Python | Scotchester | dhruvipatel14 |
else _("Paste without formatting"),
f"{KEYS.MOD} + {KEYS.SHIFT} + v",
),
(_("Undo"), f"{KEYS.MOD} + z"),
(
_("Redo"),
f"{KEYS.MOD} + {KEYS.SHIFT} + z" if is_mac else f"{KEYS.MOD} + y",
... | I'm good with removing this. We probably don't want to encourage underline use, anyway, since it could fool people into thinking it's a link. | ],
# Translators: Shortcuts for admin actions that can be taken while working on core models
("admin-core-models", _("Actions")): [
(_("Save changes"), f"{KEYS.MOD} + s"),
(_("Preview"), f"{KEYS.MOD} + p"),
(_("Add or show comments"), f... | @@ -1347,23 +1347,23 @@ def keyboard_shortcuts_dialog(context):
f"{KEYS.MOD} + {KEYS.SHIFT} + z" if is_mac else f"{KEYS.MOD} + y",
),
],
- ("actions-model", _("Actions")): [
+ ("actions", _("Actions")): [
(_("Save changes"), f"{KE... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.429 | suggestion | 141 | 51 | 51 | false | Reorganized the keyboard shortcuts | 13,359 | wagtail/wagtail | 16,097 | Python | Scotchester | dhruvipatel14 |
(_("Paste"), f"{KEYS.MOD} + v"),
(
_("Paste and match style")
if is_mac
else _("Paste without formatting"),
f"{KEYS.MOD} + {KEYS.SHIFT} + v",
),
(_("Undo"), f"{KEYS.MOD} + z"),... | Don't forget to re-add "Insert or edit a link" to the "Text formatting" section :) | (_("Search"), "/"),
(_("Toggle sidebar"), "["),
(_("Toggle minimap"), "]"),
(_("Close modal dialogs (like this one)"), f"{KEYS.ESC}"),
],
# Translators: Shortcuts for admin actions that can be taken while working on core models
... | @@ -1347,23 +1347,23 @@ def keyboard_shortcuts_dialog(context):
f"{KEYS.MOD} + {KEYS.SHIFT} + z" if is_mac else f"{KEYS.MOD} + y",
),
],
- ("actions-model", _("Actions")): [
+ ("actions", _("Actions")): [
(_("Save changes"), f"{KE... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.214 | style | 82 | 51 | 51 | false | Reorganized the keyboard shortcuts | 13,359 | wagtail/wagtail | 16,097 | Python | Scotchester | dhruvipatel14 |
(_("Undo"), f"{KEYS.MOD} + z"),
(
_("Redo"),
f"{KEYS.MOD} + {KEYS.SHIFT} + z" if is_mac else f"{KEYS.MOD} + y",
),
],
("actions", _("Actions")): [
(_("Save changes"), f"{KEYS.MOD} + s"),
... | ```suggestion
(_("Strike-through"), f"{KEYS.MOD} + {KEYS.SHIFT} + x"),
```
White space missing. | (_("Save changes"), f"{KEYS.MOD} + s"),
(_("Preview"), f"{KEYS.MOD} + p"),
(_("Add or show comments"), f"{KEYS.CTRL} + {KEYS.ALT} + m")
if comments_enabled
else None,
],
# Translators: Shortcuts for common text editi... | @@ -1347,25 +1347,26 @@ def keyboard_shortcuts_dialog(context):
f"{KEYS.MOD} + {KEYS.SHIFT} + z" if is_mac else f"{KEYS.MOD} + y",
),
],
- ("actions-model", _("Actions")): [
- (_("Show keyboard shortcuts"), "?"),
+ ("actions", _("Ac... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.714 | suggestion | 116 | 51 | 51 | false | Reorganized the keyboard shortcuts | 13,359 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
def test_empty_queryset(self):
self.assertEqual(
Page.get_first_root_node(), Page.objects.none().first_common_ancestor()
)
def test_empty_queryset_strict(self):
with self.assertRaises(Page.DoesNotExist):
Page.objects.none().first_common_ancestor(strict=True)
... | This test file is for page queryset specifically. We don't have one for Task models, but the closest is probably this:
https://github.com/wagtail/wagtail/blob/dbeafb7b115bfab446407bba63c34eb853cc60e1/wagtail/tests/test_workflow.py#L28
Could we move this test method to that existing test class instead? | from io import StringIO
from unittest import mock
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.db.models import Count, Q
from django.test import TestCase, TransactionTestCase
from wagtail.models import Locale, ... | @@ -1365,3 +1373,23 @@ def test_defer_streamfields_with_specific(self):
self.assertNotIn("body", page.__dict__)
with self.assertNumQueries(1):
page.body
+
+
+class TestSpecificQueryForNonPage(TestCase):
+ def test_specific_gracefully_handles_missing_rows(self): | wagtail/tests/test_page_queryset.py | 26 | Python | 0.5 | refactor | 308 | 43 | 1,368 | false | Prevent error when iterating over specific tasks | 13,377 | wagtail/wagtail | 16,097 | Python | laymonage | lasse-cs |
if qs._specific_prefetch_related_lookups:
items = items.prefetch_related(
*qs._specific_prefetch_related_lookups
)
if qs._defer_streamfields and hasattr(items, "defer_streamfields"):
items = items.defer... | Perhaps we should use `getattr()` with a fall back to `str()` so we can still display some useful info about the object?
```suggestion
{"id": p.id, "title": getattr(p, "title", str(p)), "type": p.content_type}
``` |
if qs._specific_prefetch_related_lookups:
items = items.prefetch_related(
*qs._specific_prefetch_related_lookups
)
if qs._defer_streamfields and hasattr(items, "defer_streamfields"):
items = items.defer... | @@ -725,7 +725,7 @@ def __iter__(self):
"This is most likely because a database migration has removed "
"the relevant table or record since the item was created:\n{}".format(
[
- {"id": p.id, "title": p.title, "type": p.conten... | wagtail/query.py | 26 | Python | 1 | suggestion | 246 | 51 | 51 | false | Prevent error when iterating over specific tasks | 13,377 | wagtail/wagtail | 16,097 | Python | laymonage | lasse-cs |
# benefit to splitting the result
yield tuple(queryset)
else:
# Iterate through the queryset, returning the rows in manageable
# chunks for self.__iter__() to fetch full instances for
current_chunk = []
for r in queryset.iterator(self.chunk... | ```suggestion
f"branch: <{obj.__class__.__name__} id='{obj.id}' title='{getattr(obj, 'title', str(obj)}'"
``` |
def _get_chunks(self, queryset) -> Iterable[tuple[dict[str, Any]]]:
if not self.chunked_fetch:
# The entire result will be stored in memory, so there is no
# benefit to splitting the result
yield tuple(queryset)
else:
# Iterate through the queryset, r... | @@ -774,7 +774,7 @@ def __iter__(self):
warnings.warn(
"A specific version of the following object could not be returned "
"because the specific model is not present on the active "
- f"branch: <{obj.__class__.__name__} id='{obj.id}' title='{... | wagtail/query.py | 26 | Python | 0.714 | suggestion | 131 | 31 | 36 | false | Prevent error when iterating over specific tasks | 13,377 | wagtail/wagtail | 16,097 | Python | laymonage | lasse-cs |
print("Uploading", f.name) # noqa: T201
s3 = boto3.client("s3")
s3.upload_file(
str(f),
"releases.wagtail.io",
"nightly/dist/" + f.name,
ExtraArgs={"ACL": "public-read"},
)
# Redundant upload to a fixed filename for ease of use with package managers
print("Uploading latest.whl") # noqa: T201
s3.uploa... | I'm not sure if this is a good idea, I guess this could cause code that uses `grep` or a similar tool that looks for `https://[^"]*`, such as how I did it for [our bakerydemo nightly](https://github.com/wagtail/bakerydemo/blob/6a16f1b7d3c53d424361825abb9507032b5b31a4/Dockerfile#L38-L40), to end up with multiple results... | sys.exit()
print("Uploading", f.name) # noqa: T201
s3 = boto3.client("s3")
s3.upload_file(
str(f),
"releases.wagtail.io",
"nightly/dist/" + f.name,
)
# Redundant upload to a fixed filename for ease of use with package managers
print("Uploading latest.whl") # noqa: T201
s3.upload_file(
str(f),
... | @@ -28,6 +36,7 @@
Body=json.dumps(
{
"url": "https://releases.wagtail.org/nightly/dist/" + f.name,
+ "latestUrl": "https://releases.wagtail.org/nightly/dist/latest.whl", | scripts/nightly/upload.py | 26 | Python | 0.643 | suggestion | 340 | 30 | 40 | false | Upload redundant latest.whl nightly build for ease of use with package managers | 13,395 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
import boto3
dist_folder = pathlib.Path.cwd() / "dist"
try:
f = next(dist_folder.glob("*.whl"))
except StopIteration:
print("No .whl files found in ./dist!") # noqa: T201
sys.exit()
print("Uploading", f.name) # noqa: T201
s3 = boto3.client("s3")
s3.upload_file(
str(f),
"releases.wagtail.io",
... | **Question:** won't responses be cached by Cloudfront for some amount of time? That would result in users unexpectedly downloading an older nightly if the Cloudfront cache was refreshed just before we upload a new latest.whl. Or does uploading a new object to S3 clear the cache for that key? | import uuid
import boto3
dist_folder = pathlib.Path.cwd() / "dist"
try:
f = next(dist_folder.glob("*.whl"))
except StopIteration:
print("No .whl files found in ./dist!") # noqa: T201
sys.exit()
print("Uploading", f.name) # noqa: T201
s3 = boto3.client("s3")
s3.upload_file(
str(f),
"releases.wa... | @@ -20,6 +20,14 @@
"nightly/dist/" + f.name,
ExtraArgs={"ACL": "public-read"},
)
+# Redundant upload to a fixed filename for ease of use with package managers
+print("Uploading latest.whl") # noqa: T201
+s3.upload_file(
+ str(f),
+ "releases.wagtail.io",
+ "nightly/dist/latest.whl",
+ ExtraArgs=... | scripts/nightly/upload.py | 26 | Python | 0.5 | performance | 293 | 39 | 50 | false | Upload redundant latest.whl nightly build for ease of use with package managers | 13,395 | wagtail/wagtail | 16,097 | Python | Stormheg | laymonage |
const wordCount = getWordCount(content.lang, content.innerText);
const readingTime = getReadingTime(content.lang, wordCount);
const metrics = { wordCount, readingTime };
this.dispatch('content', { detail: { content, metrics } });
renderContentMetrics(metrics);
}
/**
* Extracts the rendere... | Two promises:
- One for the `POST` request to update the preview content, resolved after the backend returns a response. May result in the reloading of an iframe, may also not (e.g. data is invalid).
- One for reloading the iframe, resolved after the new iframe has dispatched the `load` event and scroll restoration has... | // previewed page shows an error response), skip doing anything with it.
if (!content) return;
const wordCount = getWordCount(content.lang, content.innerText);
const readingTime = getReadingTime(content.lang, wordCount);
const lixScore = getLIXScore(content.lang, content.innerText);
const reada... | @@ -967,6 +980,13 @@ export class PreviewController extends Controller<HTMLElement> {
* @returns An `ExtractedContent` object with `lang`, `innerText`, and `innerHTML` properties.
*/
async extractContent(options?: ContentExtractorOptions) {
+ if (!this.ready) {
+ // Preview panel likely hasn't been o... | client/src/controllers/PreviewController.ts | 26 | TypeScript | 0.571 | suggestion | 330 | 51 | 51 | false | Allow PreviewController.extractContent() to work without opening the preview panel first | 13,462 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
*/
formPayload = '';
/** Timeout before displaying the loading spinner. */
spinnerTimeout: ReturnType<typeof setTimeout> | null = null;
/** Interval for the auto-update. */
updateInterval: ReturnType<typeof setOptionalInterval> = null;
/**
* Promise for the current update request. This is resolved ... | Might be a bit funny to store the resolver function but this allows minimal changes to the existing code | * whether an update should be performed. Note that we currently do not handle
* file inputs.
*/
formPayload = '';
/** Timeout before displaying the loading spinner. */
spinnerTimeout: ReturnType<typeof setTimeout> | null = null;
/** Interval for the auto-update. */
updateInterval: ReturnType<typeof... | @@ -278,6 +278,15 @@ export class PreviewController extends Controller<HTMLElement> {
*/
updatePromise: Promise<boolean> | null = null;
+ /**
+ * Promise for the current iframe reload. This is resolved when the new
+ * iframe's `load` event is fired and the scroll position has been restored.
+ */
+ rel... | client/src/controllers/PreviewController.ts | 26 | TypeScript | 0.429 | suggestion | 104 | 51 | 51 | false | Allow PreviewController.extractContent() to work without opening the preview panel first | 13,462 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
ko: 226, // Korean
es: 278, // Spanish
sv: 218, // Swedish
};
export const getReadingTime = (lang: string, wordCount: number): number => {
const locale = lang.split('-')[0];
// Fallback to English reading speed if the locale is not found
const readingSpeed = readingSpeeds[locale] || readingSpeeds.en;
con... | ```suggestion
// Count long words (7+ characters)
``` | ko: 226, // Korean
es: 278, // Spanish
sv: 218, // Swedish
};
export const getReadingTime = (lang: string, wordCount: number): number => {
const locale = lang.split('-')[0];
// Fallback to English reading speed if the locale is not found
const readingSpeed = readingSpeeds[locale] || readingSpeeds.en;
con... | @@ -41,9 +41,50 @@ export const getReadingTime = (lang: string, wordCount: number): number => {
return readingTime;
};
+export const getReadabilityScore = (lang: string, text: string): string => {
+ const segmenter = new Intl.Segmenter(lang, { granularity: 'sentence' });
+ const sentences: Intl.SegmentData[] = ... | client/src/includes/contentMetrics.ts | 26 | TypeScript | 0.571 | suggestion | 55 | 51 | 51 | false | Implement readability score based on LIX formula. Fix #13361 | 13,473 | wagtail/wagtail | 16,097 | Python | thibaudcolas | thibaudcolas |
sv: 218, // Swedish
};
export const getReadingTime = (lang: string, wordCount: number): number => {
const locale = lang.split('-')[0];
// Fallback to English reading speed if the locale is not found
const readingSpeed = readingSpeeds[locale] || readingSpeeds.en;
const readingTime = Math.round(wordCount / rea... | ```suggestion
if (segment.isWordLike && segment.segment.length >= 7) {
``` | sv: 218, // Swedish
};
export const getReadingTime = (lang: string, wordCount: number): number => {
const locale = lang.split('-')[0];
// Fallback to English reading speed if the locale is not found
const readingSpeed = readingSpeeds[locale] || readingSpeeds.en;
const readingTime = Math.round(wordCount / rea... | @@ -41,9 +41,50 @@ export const getReadingTime = (lang: string, wordCount: number): number => {
return readingTime;
};
+export const getReadabilityScore = (lang: string, text: string): string => {
+ const segmenter = new Intl.Segmenter(lang, { granularity: 'sentence' });
+ const sentences: Intl.SegmentData[] = ... | client/src/includes/contentMetrics.ts | 26 | TypeScript | 0.571 | suggestion | 78 | 51 | 51 | false | Implement readability score based on LIX formula. Fix #13361 | 13,473 | wagtail/wagtail | 16,097 | Python | thibaudcolas | thibaudcolas |
import axe from 'axe-core';
import { ngettext, gettext } from '../utils/gettext';
export const getWordCount = (lang: string, text: string): number => {
const segmenter = new Intl.Segmenter(lang, { granularity: 'word' });
const segments: Intl.SegmentData[] = Array.from(segmenter.segment(text));
const wordCount = ... | ```suggestion
readabilityScoreContainer.textContent = readabilityScore;
``` | export const renderContentMetrics = ({
wordCount,
readingTime,
readabilityScore,
}: ContentMetrics) => {
const wordCountContainer = document.querySelector<HTMLElement>(
'[data-content-word-count]',
);
const readingTimeContainer = document.querySelector<HTMLElement>(
'[data-content-reading-time]',
... | @@ -127,4 +172,8 @@ export const renderContentMetrics = ({
'%(num)s mins',
readingTime,
).replace('%(num)s', `${readingTime}`);
+
+ if (readabilityScoreContainer) {
+ readabilityScoreContainer.textContent = readabilityScore.toString(); | client/src/includes/contentMetrics.ts | 26 | TypeScript | 0.571 | suggestion | 79 | 180 | 29 | false | Implement readability score based on LIX formula. Fix #13361 | 13,473 | wagtail/wagtail | 16,097 | Python | thibaudcolas | thibaudcolas |
const longWordCount = words.reduce((count, segment) => {
if (segment.isWordLike && segment.segment.length > 6) {
return count + 1;
}
return count;
}, 0);
// If no sentences found, return "Poor"
if (sentenceCount === 0 || wordCount === 0) {
return gettext('Good');
}
// LIX formula: (A... | I think it would be useful to split this into two separate functions: one for getting the LIX score, and one for determining the actual label we use for display. It would make it easier to support different score ranges for different languages, and people interested in the value can listen to the `w-preview:content` e... | for (const { segment, isWordLike } of wordSegmenter.segment(text)) {
if (isWordLike) {
words += 1;
if (segment.length > 6) {
longWords += 1;
}
}
}
// If 0 or too little content is found, return 0.
// Readability scoring is not relevant on very short content.
if (sentences ==... | @@ -41,9 +41,50 @@ export const getReadingTime = (lang: string, wordCount: number): number => {
return readingTime;
};
+export const getReadabilityScore = (lang: string, text: string): string => {
+ const segmenter = new Intl.Segmenter(lang, { granularity: 'sentence' });
+ const sentences: Intl.SegmentData[] = ... | client/src/includes/contentMetrics.ts | 26 | TypeScript | 0.643 | refactor | 364 | 51 | 51 | false | Implement readability score based on LIX formula. Fix #13361 | 13,473 | wagtail/wagtail | 16,097 | Python | laymonage | thibaudcolas |
export class KeyboardController extends Controller<
HTMLButtonElement | HTMLAnchorElement
> {
static targets = ['element'];
static values = {
action: { default: '', type: String },
key: { default: '', type: String },
scope: { default: '', type: String },
};
/** The action to perform when the key... | Please remove these changes to the KeyboardController and tests. | export class KeyboardController extends Controller<
HTMLButtonElement | HTMLAnchorElement
> {
static targets = ['element'];
static values = {
action: { default: '', type: String },
key: { default: '', type: String },
scope: { default: '', type: String },
};
/** The action to perform when the key... | @@ -79,7 +79,7 @@ export class KeyboardController extends Controller<
* If custom keyboard shortcuts are disabled by user in settings then controller will not be loaded.
*/
static get shouldLoad() {
- return !!WAGTAIL_CONFIG.KEYBOARD_SHORTCUTS_ENABLED;
+ return true; | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.286 | suggestion | 65 | 51 | 51 | false | Showing warning/info in the keyboard_shortcuts dialog | 13,476 | wagtail/wagtail | 16,097 | Python | lb- | p-r-a-v-i-n |
response = self.client.get(reverse("wagtailadmin_home"))
self.assertEqual(response.status_code, 200)
soup = self.get_soup(response.content)
shortcuts_dialog = soup.select_one("#keyboard-shortcuts-dialog")
self.assertIsNotNone(shortcuts_dialog)
account_link = shortcuts_d... | This tests that the template renders the right content.
However, we'll also need a test for the template being given the right values based on the user profile.
Maybe have a look at some of the tests that were added in https://github.com/wagtail/wagtail/pull/13258/files - specifically the test_account_management fi... | "data-w-kbd-key-value": "?",
}
),
sidebar_data,
)
def test_keyboard_shortcuts_dialog(self):
response = self.client.get(reverse("wagtailadmin_home"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(
... | @@ -67,6 +68,50 @@ class TestKeyboardShortcutsDialog(WagtailTestUtils, TestCase):
def setUp(self):
self.login()
+ def render_modal(self, keyboard_shortcuts_enabled=True, comments_enabled=False):
+ """
+ Helper to render the keyboard shortcuts dialog template with various settings.
+ ... | wagtail/admin/tests/test_keyboard_shortcuts.py | 26 | Python | 0.5 | suggestion | 528 | 51 | 51 | false | Showing warning/info in the keyboard_shortcuts dialog | 13,476 | wagtail/wagtail | 16,097 | Python | lb- | p-r-a-v-i-n |
window.HTMLFormElement.prototype.requestSubmit = null; // mock not being available in a browser
window.HTMLFormElement.prototype.submit = submit;
const select = document.querySelector('select');
select.value = 'Z-A';
select.dispatchEvent(new CustomEvent('change'));
expect(submit).toHaveBeenCal... | ```suggestion
input.dispatchEvent(new CustomEvent('change'));
``` | window.HTMLFormElement.prototype.requestSubmit = null; // mock not being available in a browser
window.HTMLFormElement.prototype.submit = submit;
const select = document.querySelector('select');
select.value = 'Z-A';
select.dispatchEvent(new CustomEvent('change'));
expect(submit).toHaveBeenCal... | @@ -53,4 +53,31 @@ describe('SubmitController', () => {
expect(submit).toHaveBeenCalled();
expect(lastFormCalled).toEqual(document.getElementById('form'));
});
+
+ it('should throw an error if there is no form associated with the controlled element', async () => {
+ const errorSpy = jest.spyOn(console,... | client/src/controllers/SubmitController.test.js | 26 | JavaScript | 0.643 | suggestion | 69 | 39 | 39 | false | Add unit test for `SubmitController` error handling | 13,479 | wagtail/wagtail | 16,097 | Python | laymonage | lb- |
import { AutosizeController } from './AutosizeController';
export default {
title: 'Stimulus / AutosizeController',
argTypes: {
children: {
control: 'text',
defaultValue: '',
},
debug: {
control: 'boolean',
defaultValue: false,
},
},
};
const definitions = [
{
ident... | I get React warnings that say we should use `defaultValue` or `value` props instead of setting the children of the `<textarea>`:
<img width="959" height="286" alt="Image" src="https://github.com/user-attachments/assets/8d67886b-9cc4-40e1-8f1a-16599610498b" />
```suggestion
<textarea data-controller="w-autosize" ... | import { AutosizeController } from './AutosizeController';
export default {
title: 'Stimulus / AutosizeController',
argTypes: {
value: {
control: 'text',
defaultValue: '',
},
debug: {
control: 'boolean',
defaultValue: false,
},
},
};
const definitions = [
{
identifi... | @@ -0,0 +1,40 @@
+import React from 'react';
+
+import { StimulusWrapper } from '../../storybook/StimulusWrapper';
+import { AutosizeController } from './AutosizeController';
+
+export default {
+ title: 'Stimulus / AutosizeController',
+ argTypes: {
+ children: {
+ control: 'text',
+ defaultValue: '',
+... | client/src/controllers/AutosizeController.stories.js | 26 | JavaScript | 0.857 | suggestion | 411 | 38 | 38 | false | Add a basic set of Storybook stories for the Stimulus Autosize controller | 13,480 | wagtail/wagtail | 16,097 | Python | laymonage | lb- |
def __init__(self, name=None, **kwargs):
super().__init__(name=name, **kwargs)
if not self.model:
raise ImproperlyConfigured(
"ModelViewSet %r must define a `model` attribute or pass a `model` argument"
% self
)
self.model_opts = self... | We should probably lean towards Django's naming of "path converter"
```suggestion
def pk_path_converter(self):
"""
:ref:`Path converter <topics/http/urls:path converters>` to use for
the model's primary key in URL patterns.
.. versionadded:: 7.3
The ``pk_path_converter``... |
def __init__(self, name=None, **kwargs):
super().__init__(name=name, **kwargs)
if not self.model:
raise ImproperlyConfigured(
"ModelViewSet %r must define a `model` attribute or pass a `model` argument"
% self
)
self.model_opts = self... | @@ -129,6 +131,16 @@ def __init__(self, name=None, **kwargs):
def permission_policy(self):
return ModelPermissionPolicy(self.model)
+ @property
+ def url_converter(self):
+ """What will be used to convert pks in urls""" | wagtail/admin/viewsets/model.py | 26 | Python | 0.857 | suggestion | 356 | 51 | 51 | false | Use correct converter depending on pk type for ModelViewSet | 13,490 | wagtail/wagtail | 16,097 | Python | laymonage | SebCorbin |
def register_reference_index(self):
if self.add_to_reference_index:
ReferenceIndex.register_model(self.model)
def get_permissions_to_register(self):
"""
Returns a queryset of :class:`~django.contrib.auth.models.Permission`
objects to be registered with the :ref:`regi... | ```suggestion
conv = self.pk_path_converter
``` | "permission_policy": self.permission_policy,
"edit_url_name": self.get_url_name("edit"),
},
)
def register_admin_url_finder(self):
register_admin_url_finder(self.model, self.url_finder_class)
def register_reference_index(self):
if self.add_to... | @@ -649,38 +661,55 @@ def register_permissions(self):
hooks.register("register_permissions", self.get_permissions_to_register)
def get_urlpatterns(self):
+ conv = self.url_converter | wagtail/admin/viewsets/model.py | 26 | Python | 0.571 | suggestion | 55 | 51 | 51 | false | Use correct converter depending on pk type for ModelViewSet | 13,490 | wagtail/wagtail | 16,097 | Python | laymonage | SebCorbin |
f"reorder/<{conv}:pk>/",
self.reorder_view,
name="reorder",
)
)
if self.inspect_view_enabled:
urlpatterns.append(
path(
f"inspect/<{conv}:pk>/",
self.inspe... | ```suggestion
if self.pk_path_converter not in get_converters():
raise ImproperlyConfigured(
f"{self.__class__.__name__}.pk_path_converter is not a "
"registered path converter"
)
``` |
if self.reorder_view_enabled:
urlpatterns.append(
path(f"reorder/<{conv}:pk>/", self.reorder_view, name="reorder")
)
if self.inspect_view_enabled:
urlpatterns.append(
path(f"inspect/<{conv}:pk>/", self.inspect_view, name="inspect")
... | @@ -649,38 +661,55 @@ def register_permissions(self):
hooks.register("register_permissions", self.get_permissions_to_register)
def get_urlpatterns(self):
+ conv = self.url_converter
urlpatterns = [
path("", self.index_view, name="index"),
path("results/", self.i... | wagtail/admin/viewsets/model.py | 26 | Python | 0.786 | suggestion | 247 | 50 | 47 | false | Use correct converter depending on pk type for ModelViewSet | 13,490 | wagtail/wagtail | 16,097 | Python | laymonage | SebCorbin |
class TestIncorrectConverter(SimpleTestCase):
def test_unknown_converter(self):
class BadViewSet(SnippetViewSet):
model = AdvertTag
url_converter = "foo"
with self.assertRaises(ImproperlyConfigured) as cm:
register_snippet(BadViewSet)
message = str(cm.e... | ```suggestion
with self.assertRaises(NoReverseMatch):
reverse(self.viewset.get_url_name("edit"), kwargs={"pk": 123})
``` |
class TestIncorrectConverter(SimpleTestCase):
def test_unknown_converter(self):
class BadViewSet(SnippetViewSet):
model = AdvertTag
pk_path_converter = "foo"
with self.assertRaises(ImproperlyConfigured) as cm:
register_snippet(BadViewSet)
message = str(... | @@ -60,6 +62,36 @@ def test_no_model_set_or_passed(self):
)
+class TestIncorrectConverter(SimpleTestCase):
+ def test_unknown_converter(self):
+ class BadViewSet(SnippetViewSet):
+ model = AdvertTag
+ url_converter = "foo"
+
+ with self.assertRaises(ImproperlyConfigur... | wagtail/snippets/tests/test_viewset.py | 26 | Python | 0.714 | suggestion | 140 | 51 | 51 | false | Use correct converter depending on pk type for ModelViewSet | 13,490 | wagtail/wagtail | 16,097 | Python | laymonage | SebCorbin |
def test_unknown_converter(self):
class BadViewSet(SnippetViewSet):
model = AdvertTag
url_converter = "foo"
with self.assertRaises(ImproperlyConfigured) as cm:
register_snippet(BadViewSet)
message = str(cm.exception)
self.assertEqual(
... | The `url_prefix` doesn't include `/admin/`, so we need to add that to trigger the error
```suggestion
response = self.client.get(f"/admin/{self.viewset.url_prefix}/edit/123/")
``` | def test_unknown_converter(self):
class BadViewSet(SnippetViewSet):
model = AdvertTag
pk_path_converter = "foo"
with self.assertRaises(ImproperlyConfigured) as cm:
register_snippet(BadViewSet)
message = str(cm.exception)
self.assertEqual(
... | @@ -60,6 +62,36 @@ def test_no_model_set_or_passed(self):
)
+class TestIncorrectConverter(SimpleTestCase):
+ def test_unknown_converter(self):
+ class BadViewSet(SnippetViewSet):
+ model = AdvertTag
+ url_converter = "foo"
+
+ with self.assertRaises(ImproperlyConfigur... | wagtail/snippets/tests/test_viewset.py | 26 | Python | 0.857 | suggestion | 188 | 51 | 51 | false | Use correct converter depending on pk type for ModelViewSet | 13,490 | wagtail/wagtail | 16,097 | Python | laymonage | SebCorbin |
with self.assertRaises(ImproperlyConfigured) as cm:
register_snippet(SnippetViewSet)
message = str(cm.exception)
self.assertIn("ModelViewSet", message)
self.assertIn(
"must define a `model` attribute or pass a `model` argument",
message,
)
cl... | Can probably merge this with `TestAdminURLs` a few lines below. We'll also need the same tests for `ModelViewSet` | with self.assertRaises(ImproperlyConfigured) as cm:
register_snippet(SnippetViewSet)
message = str(cm.exception)
self.assertIn("ModelViewSet", message)
self.assertIn(
"must define a `model` attribute or pass a `model` argument",
message,
)
cl... | @@ -60,6 +62,36 @@ def test_no_model_set_or_passed(self):
)
+class TestIncorrectConverter(SimpleTestCase):
+ def test_unknown_converter(self):
+ class BadViewSet(SnippetViewSet):
+ model = AdvertTag
+ url_converter = "foo"
+
+ with self.assertRaises(ImproperlyConfigur... | wagtail/snippets/tests/test_viewset.py | 26 | Python | 0.5 | suggestion | 113 | 51 | 51 | false | Use correct converter depending on pk type for ModelViewSet | 13,490 | wagtail/wagtail | 16,097 | Python | laymonage | SebCorbin |
The ``sort_order_field`` attribute was added in Wagtail 7.2.
"""
def __init__(self, name=None, **kwargs):
super().__init__(name=name, **kwargs)
if not self.model:
raise ImproperlyConfigured(
"ModelViewSet %r must define a `model` attribute or pass a `model` ar... | ```suggestion
@cached_property
``` | The ``sort_order_field`` attribute was added in Wagtail 7.2.
"""
def __init__(self, name=None, **kwargs):
super().__init__(name=name, **kwargs)
if not self.model:
raise ImproperlyConfigured(
"ModelViewSet %r must define a `model` attribute or pass a `model` ar... | @@ -129,6 +131,16 @@ def __init__(self, name=None, **kwargs):
def permission_policy(self):
return ModelPermissionPolicy(self.model)
+ @property | wagtail/admin/viewsets/model.py | 26 | Python | 0.429 | performance | 38 | 51 | 51 | false | Use correct converter depending on pk type for ModelViewSet | 13,490 | wagtail/wagtail | 16,097 | Python | laymonage | SebCorbin |
datastudio,
deviantart,
dipdive,
dipity,
dotsub,
etsy,
five_hundred_px,
five_min,
flickr,
funny_or_die,
geograph_gg,
geograph_uk,
github_gist,
gmep,
hlipp,
huffduffer,
hulu,
ifixit,
ifttt,
iheart,
issuu,
justin_tv,
kickstarter,
... | ```suggestion
loom,
major_league_gaming,
``` | datastudio,
deviantart,
dipdive,
dipity,
dotsub,
etsy,
five_hundred_px,
five_min,
flickr,
funny_or_die,
geograph_gg,
geograph_uk,
github_gist,
gmep,
hlipp,
huffduffer,
hulu,
ifixit,
ifttt,
iheart,
issuu,
justin_tv,
kickstarter,
... | @@ -668,6 +675,7 @@
kickstarter,
kinomap,
major_league_gaming,
+ loom, | wagtail/embeds/oembed_providers.py | 26 | Python | 0.429 | suggestion | 48 | 51 | 51 | false | Add oembed provider for Loom | 13,545 | wagtail/wagtail | 16,097 | Python | laymonage | Niicck |
}
default_ordering = "-created_at"
context_object_name = "images"
permission_policy = permission_policy
any_permission_required = ["add", "change", "delete"]
model = Image
filterset_class = ImagesFilterSet
show_other_searches = True
header_icon = "image"
page_title = gettext_lazy... | Should probably update this to https://github.com/wagtail/django-modelsearch/issues/51 instead | }
default_ordering = "-created_at"
context_object_name = "images"
permission_policy = permission_policy
any_permission_required = ["add", "change", "delete"]
model = Image
filterset_class = ImagesFilterSet
show_other_searches = True
header_icon = "image"
page_title = gettext_lazy... | @@ -80,7 +80,13 @@ def get_paginate_by(self, queryset):
return getattr(settings, "WAGTAILIMAGES_INDEX_PAGE_SIZE", 30)
def get_valid_orderings(self):
- return self.ORDERING_OPTIONS
+ orderings = self.ORDERING_OPTIONS.copy()
+ if self.is_searching:
+ # Ordering by usage cou... | wagtail/images/views/images.py | 26 | Python | 0.286 | suggestion | 94 | 51 | 51 | false | Disable usage count ordering when searching on documents and images listing views | 13,560 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
print("Uploading", f.name) # noqa: T201
s3 = boto3.client("s3")
s3.upload_file(
str(f),
"releases.wagtail.io",
"nightly/dist/" + f.name,
)
print("Updating latest.json") # noqa: T201
boto3.resource("s3").Object("releases.wagtail.io", "nightly/latest.json").put(
Body=json.dumps(
{
... | ```suggestion
"Quantity": 2,
```
Or store the items in a list and do `len(items)` |
print("Uploading", f.name) # noqa: T201
s3 = boto3.client("s3")
s3.upload_file(
str(f),
"releases.wagtail.io",
"nightly/dist/" + f.name,
)
print("Updating latest.json") # noqa: T201
boto3.resource("s3").Object("releases.wagtail.io", "nightly/latest.json").put(
Body=json.dumps(
{
... | @@ -18,16 +19,27 @@
str(f),
"releases.wagtail.io",
"nightly/dist/" + f.name,
- ExtraArgs={"ACL": "public-read"},
)
print("Updating latest.json") # noqa: T201
boto3.resource("s3").Object("releases.wagtail.io", "nightly/latest.json").put(
- ACL="public-read",
Body=json.dumps(
{
... | scripts/nightly/upload.py | 26 | Python | 0.571 | suggestion | 94 | 32 | 32 | false | Improve release upload scripts | 13,571 | wagtail/wagtail | 16,097 | Python | laymonage | RealOrangeOne |
# Results should not include images that just have 'even' in the title
self.assertNotContains(response, "Test image 3 is even better")
def test_construct_queryset_hook_browse(self):
image = Image.objects.create(
title="Test image shown",
file=get_test_image_file(),
... | #13382 didn't add any tests for loading the chooser view in list mode, so I'm adding one here |
# Results should not include images that just have 'even' in the title
self.assertNotContains(response, "Test image 3 is even better")
def test_construct_queryset_hook_browse(self):
image = Image.objects.create(
title="Test image shown",
file=get_test_image_file(),
... | @@ -2229,6 +2236,35 @@ def filter_images(images, request):
self.assertEqual(len(response.context["results"]), 1)
self.assertEqual(response.context["results"][0], image)
+ def test_list_mode(self): | wagtail/images/tests/test_admin_views.py | 26 | Python | 0.214 | suggestion | 93 | 51 | 51 | false | Use a separate and more efficient query for getting usage count on images and documents when not ordering by it | 13,597 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
)
link = soup.select_one(f"a[href='{expected_url}']")
self.assertIsNotNone(link)
self.assertEqual(link.text.strip(), "Used 0 times")
def test_order_by_usage_count(self):
doc1 = models.Document.objects.create(title="Used twice document")
doc2 = models.Document.objects... | I'm not sure how useful adding `assertNumQueries` here is... That's the only test I can think of that would fail before/pass after the fix 🤔
(Well, technically this one actually would pass before and after the fix, but the `assertNumQueries(12)` in the non-ordering case would fail because it previously didn't have t... | expected_url = reverse(
"wagtaildocs:document_usage",
args=(unused_document.pk,),
)
link = soup.select_one(f"a[href='{expected_url}']")
self.assertIsNotNone(link)
self.assertEqual(link.text.strip(), "Used 0 times")
def test_order_by_usage_count(self):... | @@ -341,7 +344,11 @@ def test_order_by_usage_count(self):
"-usage_count": [doc1, doc2],
}
for ordering, expected_order in cases.items():
- with self.subTest(ordering=ordering):
+ response = self.client.get(
+ reverse("wagtaildocs:index"),
+ ... | wagtail/documents/tests/test_admin_views.py | 26 | Python | 0.643 | bug | 345 | 51 | 51 | false | Use a separate and more efficient query for getting usage count on images and documents when not ordering by it | 13,597 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
return f" → {capfirst(field_name)}"
return capfirst(field_name)
def describe_source_field(self):
"""
Returns a string describing the field that this reference was extracted from.
For StreamField, this returns the label of the block that contains the reference.
F... | We're traversing the child field recursively, so we should call `get_field()` from the `child_field.related_model._meta` rather than the original `field.related_model.meta`.
```suggestion
child_field = child_field.related_model._meta.get_field(
```
Unfortunately the added test case didn't catch this b... |
@cached_property
def related_field(self):
"""
The final field in which the reference exists.
The field stored on the reference index can be a related field or a
reverse related field, depending on whether the reference was extracted
directly from a ``ForeignKey`` or thr... | @@ -795,8 +800,21 @@ def describe_source_field(self):
# ManyToOneRel (reverse accessor for ParentalKey) does not have a verbose name. So get the name of the child field instead
if isinstance(field, models.ManyToOneRel):
- child_field = field.related_model._meta.get_field(model_path_compon... | wagtail/models/reference_index.py | 26 | Python | 1 | bug | 556 | 51 | 51 | false | Issue 13614: ReferenceIndex not handling properly multiple ManyToOne fields. | 13,618 | wagtail/wagtail | 16,097 | Python | laymonage | non4me21 |
):
return field
raise
else:
return field
@cached_property
def related_field(self):
# The field stored on the reference index can be a related field or a
# reverse related field, depending on whether the reference was extracted
... | I don't think it's worth extracting into a method. We could instead collect the model names into a list and do a `.join()`. Also, we'll likely replace the right arrow with something more proper that works for RTL languages too, e.g. an icon, a translatable string, or some other trick. | The field from which the reference was extracted.
This may be a related field (e.g. ForeignKey), a reverse related field
(e.g. ManyToOneRel), a StreamField, or any other field that defines
extract_references().
"""
field_name = self.model_path_components[0]
model_... | @@ -783,6 +783,11 @@ def reverse_related_field(self):
# the on_delete attribute is stored.
return self.related_field.remote_field
+ def get_label(self, field_name, index):
+ if index > 2:
+ return f" → {capfirst(field_name)}"
+ return capfirst(field_name) | wagtail/models/reference_index.py | 26 | Python | 0.643 | refactor | 285 | 51 | 51 | false | Issue 13614: ReferenceIndex not handling properly multiple ManyToOne fields. | 13,618 | wagtail/wagtail | 16,097 | Python | laymonage | non4me21 |
def describe_source_field(self):
"""
Returns a string describing the field that this reference was extracted from.
For StreamField, this returns the label of the block that contains the reference.
For other fields, this returns the verbose name of the field.
"""
fie... | We'll need the same fix for `describe_on_delete()`, as otherwise we'd be getting the `on_delete` of the first parent. | def related_field(self):
"""
The final field in which the reference exists.
The field stored on the reference index can be a related field or a
reverse related field, depending on whether the reference was extracted
directly from a ``ForeignKey`` or through a parent ``Cluste... | @@ -783,6 +783,11 @@ def reverse_related_field(self):
# the on_delete attribute is stored.
return self.related_field.remote_field
+ def get_label(self, field_name, index):
+ if index > 2:
+ return f" → {capfirst(field_name)}"
+ return capfirst(field_name)
+
def descr... | wagtail/models/reference_index.py | 26 | Python | 0.5 | suggestion | 117 | 51 | 51 | false | Issue 13614: ReferenceIndex not handling properly multiple ManyToOne fields. | 13,618 | wagtail/wagtail | 16,097 | Python | laymonage | non4me21 |
register_snippet(CustomPermissionModel)
class RequiredDatePage(Page):
deadline = models.DateField()
content_panels = [
TitleFieldPanel("title", classname="title"),
FieldPanel("deadline"),
]
class CommentableJSONPage(Page):
commentable_body = CommentableJSONField()
uncommentabl... | I wonder if we can reuse some of the existing models, e.g. `EventPageSpeakerAward`, so that we don't add three new models just for testing this. | permissions = [
# Starts with can_ and "Can "
("can_start_trouble", "Can start trouble"),
# Doesn't start with can_ and "Can "
("cause_chaos", "Cause chaos for advanced permission model"),
# Starts with an action similar to a built-in permission "chang... | @@ -2707,3 +2707,33 @@ class CommentableJSONPage(Page):
("text", CharBlock()),
]
)
+
+
+@register_snippet
+class Book(ClusterableModel): | wagtail/test/testapp/models.py | 26 | Python | 0.571 | suggestion | 144 | 51 | 33 | false | Issue 13614: ReferenceIndex not handling properly multiple ManyToOne fields. | 13,618 | wagtail/wagtail | 16,097 | Python | laymonage | non4me21 |
@cached_property
def is_out_of_date(self):
# Check the autosave revision if present, otherwise fall back to the
# initially loaded revision.
submitted_revision_id = self.request.POST.get(
"overwrite_revision_id"
) or self.request.POST.get("loaded_revision_id")
... | In the non-JSON case, there are a few options we can do:
- Always allow and show a warning when this happens (#2565)
- Always allow, but only show the warning if the user has not explicitly acknowledged that prior to saving, i.e. via the "concurrent editing notification" popup.
- This can happen if the other session... | )
@cached_property
def is_out_of_date(self):
# Check the autosave revision if present, otherwise fall back to the
# initially loaded revision.
submitted_revision_id = self.request.POST.get(
"overwrite_revision_id"
) or self.request.POST.get("loaded_revision_i... | @@ -484,12 +484,31 @@ def is_cancelling_workflow(self):
and self.workflow_state.user_can_cancel(self.request.user)
)
+ @cached_property
+ def is_out_of_date(self):
+ # Check the autosave revision if present, otherwise fall back to the
+ # initially loaded revision.
+ s... | wagtail/admin/views/pages/edit.py | 26 | Python | 0.643 | suggestion | 675 | 51 | 51 | false | Prevent creating a new revision via JSON request if the loaded revision is not the latest | 13,684 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
and self.workflow_state.user_can_cancel(self.request.user)
)
@cached_property
def is_out_of_date(self):
# Check the autosave revision if present, otherwise fall back to the
# initially loaded revision.
submitted_revision_id = self.request.POST.get(
"overw... | If the intention is for `errorMessage` to be user-facing, we need to translate them and be consistent with using (or not using) a period at the end. Right now it's a bit inconsistent, especially since the `invalid_revision` error's `errorMessage` can come from `Revision.save_revision`, which at the moment doesn't use t... | bool(self.request.POST.get("action-cancel-workflow"))
and self.workflow_state
and self.workflow_state.user_can_cancel(self.request.user)
)
@cached_property
def is_out_of_date(self):
# Check the autosave revision if present, otherwise fall back to the
... | @@ -484,12 +484,31 @@ def is_cancelling_workflow(self):
and self.workflow_state.user_can_cancel(self.request.user)
)
+ @cached_property
+ def is_out_of_date(self):
+ # Check the autosave revision if present, otherwise fall back to the
+ # initially loaded revision.
+ s... | wagtail/admin/views/pages/edit.py | 26 | Python | 0.786 | suggestion | 341 | 51 | 51 | false | Prevent creating a new revision via JSON request if the loaded revision is not the latest | 13,684 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
self.user.save()
editors = Group.objects.get(name="Editors")
self.user.groups.add(editors)
session = EditingSession.objects.create(
user=self.user,
content_type=ContentType.objects.get_for_model(Advert),
object_id=snippet.pk,
last_seen_at=... | I noticed we don't have assertions for the messaging when the conflict is caused by the same user (in a different session). We have assertions in other test methods where the conflict is caused by a different user.
Just adding this for completeness sake. | self.assertEqual(
response_json["other_sessions"],
[
# The 'other' session of the same user is still shown
# as it has the latest revision, even though there are no
# other sessions to attach the revision to. The last_seen_at
... | @@ -937,6 +1106,32 @@ def test_ping_new_session_with_revision(self):
],
)
+ # The rendered HTML should use special messaging if the newer revision
+ # is made by the same user ("in another window"). | wagtail/admin/tests/test_editing_sessions.py | 26 | Python | 0.5 | suggestion | 255 | 51 | 51 | false | Prevent creating a new revision via JSON request if the loaded revision timestamp is not the latest | 13,688 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
submitted_revision_id = self.request.POST.get(
"overwrite_revision_id"
) or self.request.POST.get("loaded_revision_id")
return submitted_revision_id and (
submitted_revision_id != str(self.page.latest_revision_id)
)
def post(self, request, *args, **kwargs):
... | I think using `.isoformat()` and comparing as string *should* be safe even if the user has different timezone settings, but I'm only 80% sure.
Comparing the string also allows us to simplify this instead of having to do `.fromisoformat()` (and handling potentially malformed value for unknown clients...). Of course, th... | @cached_property
def is_out_of_date(self):
if not self.latest_revision:
return False
latest_revision_id = str(self.latest_revision.pk)
# Two different sessions cannot have the same autosave revision, so if
# autosave revision is present, it is either the latest or i... | @@ -486,17 +486,39 @@ def is_cancelling_workflow(self):
and self.workflow_state.user_can_cancel(self.request.user)
)
+ @cached_property
+ def latest_revision_created_at(self):
+ return self.latest_revision and self.latest_revision.created_at.isoformat()
+
@cached_property
... | wagtail/admin/views/pages/edit.py | 26 | Python | 0.643 | refactor | 544 | 51 | 51 | false | Prevent creating a new revision via JSON request if the loaded revision timestamp is not the latest | 13,688 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
# Silence warnings that are not due to missing references:
nitpick_ignore = [
# Sphinx currently cannot resolve type hint names, warns "target not found":
("py:class", "wagtail.images.models.Filter"),
("py:class", "wagtail.url_routing.RouteResult"),
("py:class", "wagtail.blocks.base.Block"),
("py:c... | I know there's issues with installing the spellchecker on M-series Macs (#12254), but is this necessary to build the llms.txt? |
# Silence warnings that are not due to missing references:
nitpick_ignore = [
# Sphinx currently cannot resolve type hint names, warns "target not found":
("py:class", "wagtail.images.models.Filter"),
("py:class", "wagtail.url_routing.RouteResult"),
("py:class", "wagtail.blocks.base.Block"),
("py:c... | @@ -99,8 +100,8 @@
"epub.unknown_project_files",
]
-if not on_rtd:
- extensions.append("sphinxcontrib.spelling")
+# if not on_rtd:
+# extensions.append("sphinxcontrib.spelling") | docs/conf.py | 26 | Python | 0.357 | question | 126 | 51 | 51 | false | Add first version of llms.txt generation for docs website | 13,691 | wagtail/wagtail | 16,097 | Python | laymonage | thibaudcolas |
from datetime import datetime
import django
import sphinx_wagtail_theme
from sphinx.builders.html import StandaloneHTMLBuilder
from wagtail import VERSION, __version__
# use png images as fallback, required to build pdf
StandaloneHTMLBuilder.supported_image_types = ["image/gif", "image/png"]
# on_rtd is whether we ... | We can remove this if `root_doc` accomplishes the same thing
```suggestion
``` | from datetime import datetime
import django
import sphinx_wagtail_theme
from sphinx.builders.html import StandaloneHTMLBuilder
from wagtail import VERSION, __version__
# use png images as fallback, required to build pdf
StandaloneHTMLBuilder.supported_image_types = ["image/gif", "image/png"]
# on_rtd is whether we ... | @@ -35,6 +35,10 @@
if rtd_version := os.environ.get("READTHEDOCS_VERSION", ""):
base_path += f"/{rtd_version}"
+html_context = {
+ "base_path": base_path,
+}
+ | docs/conf.py | 26 | Python | 0.643 | refactor | 80 | 51 | 51 | false | Add first version of llms.txt generation for docs website | 13,691 | wagtail/wagtail | 16,097 | Python | laymonage | thibaudcolas |
// outerHTML, beforebegin, or afterend modes.
// So, we move the cloned DocumentFragment from the template into the DOM
// using node-based operations instead. This would execute any scripts in
// the template, and allows the template to contain any type of content
// (including text node... | I don't quite recall what happened between a8bf1ab868b2a74e99702e6c3a04325e8c97f023, 2003e14a957d783e1a308765082b8d269c08b16c, and bb3e58abd041f8b36cc182394d2f6add25a72064, but apparently this doesn't really have any effect in the current code.
If you copy over the `it('should run inline scripts contained in the templ... | // to select the exact scripts that were in the template when using
// outerHTML, beforebegin, or afterend modes.
// So, we move the cloned DocumentFragment from the template into the DOM
// using node-based operations instead. This would execute any scripts in
// the template, and allows... | @@ -104,14 +176,6 @@ export class TeleportController extends Controller<HTMLTemplateElement> {
get templateFragment() {
const content = this.element.content;
const templateFragment = content.cloneNode(true) as typeof content;
-
- // HACK:
- // cloneNode doesn't run scripts, so we need to create new s... | client/src/controllers/TeleportController.ts | 26 | TypeScript | 0.643 | refactor | 1,299 | 51 | 51 | false | Add `mode` value to `w-teleport` to allow different DOM update strategies | 13,731 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
import { Controller } from '@hotwired/stimulus';
/**
* Modes for teleporting content.
*
* - `innerHTML`: Replace the `.innerHTML` of the target element
* - `outerHTML`: Replace the `.outerHTML` of the target element
* - `textContent`: Replace the `.textContent` of the target element, without parsing the template ... | This is somewhat stolen from https://htmx.org/attributes/hx-swap/, but they're common terms in DOM manipulation methods. | import { Controller } from '@hotwired/stimulus';
import { runInlineScripts } from '../utils/runInlineScripts';
/**
* Modes for teleporting content.
*
* - `innerHTML`: Replace the `.innerHTML` of the target element
* - `outerHTML`: Replace the `.outerHTML` of the target element
* - `textContent`: Replace the `.tex... | @@ -1,5 +1,25 @@
import { Controller } from '@hotwired/stimulus';
-import { runInlineScripts } from '../utils/runInlineScripts';
+
+/**
+ * Modes for teleporting content.
+ *
+ * - `innerHTML`: Replace the `.innerHTML` of the target element
+ * - `outerHTML`: Replace the `.outerHTML` of the target element
+ * - `textC... | client/src/controllers/TeleportController.ts | 23 | TypeScript | 0.357 | suggestion | 120 | 48 | 48 | false | Add `mode` value to `w-teleport` to allow different DOM update strategies | 13,731 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
// (including text nodes).
switch (this.modeValue) {
case TeleportMode.outerHTML:
target.replaceWith(this.templateFragment);
break;
case TeleportMode.innerHTML:
target.innerHTML = '';
target.append(this.templateFragment);
break;
case ... | From MDN:
> [`referenceNode`](https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore#referencenode)
> The node before which `newNode` is inserted. If this is `null`, then `newNode` is inserted at the end of node's child nodes.
where
- (current) node = `target`
- `newNode` = `this.templateFragment`
- `ref... | // the template, and allows the template to contain any type of content
// (including text nodes).
switch (this.modeValue) {
case TeleportMode.outerHTML:
target.replaceWith(this.templateFragment);
break;
case TeleportMode.innerHTML:
target.innerHTML = '';
... | @@ -49,7 +79,49 @@ export class TeleportController extends Controller<HTMLTemplateElement> {
const complete = () => {
if (completed) return;
if (this.resetValue) target.innerHTML = '';
- target.append(...this.templateFragment.childNodes);
+
+ // Using string-based operations like innerHTML,... | client/src/controllers/TeleportController.ts | 26 | TypeScript | 0.714 | suggestion | 439 | 51 | 51 | false | Add `mode` value to `w-teleport` to allow different DOM update strategies | 13,731 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
AddPageItem(self.object),
AccessibilityItem(),
]
else:
# Not a page.
items = [
AdminItem(),
AccessibilityItem(),
]
apply_userbar_hooks(requ... | I’d consider the `render` usage to be legacy but really it’s pretty unobtrusive to support indefinitely. So I’m not sure if it’s worthwhile to introduce a deprecation for this? | AddPageItem(self.object),
AccessibilityItem(),
]
else:
# Not a page.
items = [
AdminItem(),
AccessibilityItem(),
]
apply_userbar_hooks(requ... | @@ -359,10 +363,20 @@ def get_context_data(self, parent_context):
apply_userbar_hooks(request, items, self.object)
# Render the items
- rendered_items = [item.render(request) for item in items]
+ rendered_items = []
+ media = Media()
+ for item in ... | wagtail/admin/userbar.py | 26 | Python | 0.571 | question | 176 | 44 | 50 | false | Support custom client-side checks in accessibility checker - template components variant. Fix #12936 | 13,758 | wagtail/wagtail | 16,097 | Python | thibaudcolas | thibaudcolas |
import { Userbar } from '../../includes/userbar';
customElements.define('wagtail-userbar', Userbar);
window.wagtailUserbar = document.querySelector('wagtail-userbar');
| If we were to add more stuff that are accessible in the frontend site, we'd probably prefer having `window.wagtail.userbar` and `window.wagtail.otherstuff`. We already do this for the admin (at least for new things, as we still have older stuff like `window.wagtailConfig`).
I can see that we'd have to be a bit more ca... | import { Userbar } from '../../includes/userbar';
customElements.define('wagtail-userbar', Userbar);
window.wagtail = window.wagtail || {};
window.wagtail.userbar = document.querySelector('wagtail-userbar');
| @@ -1,3 +1,5 @@
import { Userbar } from '../../includes/userbar';
customElements.define('wagtail-userbar', Userbar);
+
+window.wagtailUserbar = document.querySelector('wagtail-userbar'); | client/src/entrypoints/admin/userbar.js | 5 | JavaScript | 0.643 | refactor | 763 | 6 | 7 | false | Support custom client-side checks in accessibility checker - template components variant. Fix #12936 | 13,758 | wagtail/wagtail | 16,097 | Python | laymonage | thibaudcolas |
/* global $ */
import { escapeHtml as h } from '../../../utils/text';
import { hasOwn } from '../../../utils/hasOwn';
import {
addErrorMessages,
removeErrorMessages,
} from '../../../includes/streamFieldErrors';
import { CollapsiblePanel } from './CollapsiblePanel';
import { initCollapsiblePanel } from '../../../i... | In #13812, there were additional changes made to the calls for `renderChild()`:
https://github.com/wagtail/wagtail/blob/520e00a9345987c95a0acdb5bdd8f6ce7eaca7b6/client/src/components/StreamField/blocks/StructBlock.ts#L156-L173
The `renderChild()` method is new in 7.3, and it can render either a block or a block group... | /* global $ */
import { escapeHtml as h } from '../../../utils/text';
import { hasOwn } from '../../../utils/hasOwn';
import {
addErrorMessages,
removeErrorMessages,
} from '../../../includes/streamFieldErrors';
import { CollapsiblePanel } from './CollapsiblePanel';
import { initCollapsiblePanel } from '../../../i... | client/src/components/StreamField/blocks/StructBlock.js | 1 | JavaScript | 0.643 | suggestion | 1,351 | 26 | 26 | false | [7.2.x] Prevent conflicting IDs in nested StructBlocks with blocks named `content` | 13,825 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage | |
backends.get('varnish').purge('http://www.wagtail.io/home/events/christmas/')
# then no exception is raised
# and mocked urlopen is called with a proper purge request
self.assertEqual(urlopen_mock.call_count, 1)
(purge_request,), _call_kwargs = urlopen_mock.call_args
sel... | No issues found. | backends.get('varnish').purge('http://www.wagtail.io/home/events/christmas/')
# then no exception is raised
# and mocked urlopen is called with a proper purge request
self.assertEqual(urlopen_mock.call_count, 1)
(purge_request,), _call_kwargs = urlopen_mock.call_args
sel... | @@ -3,12 +3,15 @@
import requests
+from azure.mgmt.cdn import CdnManagementClient
+from azure.mgmt.frontdoor import FrontDoorManagementClient
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from django.test.utils import override_settings
from wagtail.contrib.frontend_... | wagtail/contrib/frontend_cache/tests.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add Azure CDN and Front Door front-end cache invalidation support | 6,119 | wagtail/wagtail | 16,097 | Python | tm-kn | |
LOADING: 'Loading…',
NO_RESULTS: 'No results',
SERVER_ERROR: 'Server Error',
SEE_ALL: 'See all',
CLOSE_EXPLORER: 'Close explorer',
ALT_TEXT: 'Alt text',
WRITE_HERE: 'Write here…',
HORIZONTAL_LINE: 'Horizontal line',
LINE_BREAK: 'Line break',
UNDO: 'Undo',
REDO: 'Redo',
RE... | No issues found. | LOADING: 'Loading…',
NO_RESULTS: 'No results',
SERVER_ERROR: 'Server Error',
SEE_ALL: 'See all',
CLOSE_EXPLORER: 'Close explorer',
ALT_TEXT: 'Alt text',
WRITE_HERE: 'Write here…',
HORIZONTAL_LINE: 'Horizontal line',
LINE_BREAK: 'Line break',
UNDO: 'Undo',
REDO: 'Redo',
RE... | @@ -46,6 +46,19 @@ global.wagtailConfig = {
EDIT_PAGE: 'Edit \'{title}\'',
VIEW_CHILD_PAGES_OF_PAGE: 'View child pages of \'{title}\'',
PAGE_EXPLORER: 'Page explorer',
+ SAVE: 'Save',
+ SAVING: 'Saving...',
+ CANCEL: 'Cancel',
+ DELETING: 'Deleting...',
+ SHOW_RESOLVED_COMMENTS: 'Show reso... | client/tests/stubs.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Feature/field comment frontend | 6,530 | wagtail/wagtail | 16,097 | Python | emilytoppm | |
class Migration(migrations.Migration):
dependencies = [
("wagtailsearchpromotions", "0002_capitalizeverbose"),
]
operations = [
migrations.CreateModel(
name="Query",
fields=[
(
"id",
models.AutoField(
... | No issues found. |
class Migration(migrations.Migration):
dependencies = [
("wagtailsearchpromotions", "0002_capitalizeverbose"),
]
operations = [
migrations.CreateModel(
name="Query",
fields=[
(
"id",
models.AutoField(
... | @@ -0,0 +1,58 @@
+# Generated by Django 3.1.8 on 2021-06-22 14:19
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("wagtailsearchpromotions", "0002_capitalizeverbose"),
+ ]
+
+ operations = [
+ migrat... | wagtail/contrib/search_promotions/migrations/0003_query_querydailyhits.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Move Query model to search promotions | 7,277 | wagtail/wagtail | 16,097 | Python | kaedroho | |
slug='hello-world',
content="hello",
live=False,
has_unpublished_changes=True,
)
root_page.add_child(instance=self.page)
self.workflow, self.task_1 = self.create_workflow_and_tasks()
WorkflowPage.objects.create(workflow=self.workflow, pag... | No issues found. | slug='hello-world',
content="hello",
live=False,
has_unpublished_changes=True,
)
root_page.add_child(instance=self.page)
self.workflow, self.task_1 = self.create_workflow_and_tasks()
WorkflowPage.objects.create(workflow=self.workflow, pag... | @@ -1317,6 +1317,33 @@ def test_submitted_email_notifications_superuser_settings(self):
# with `WAGTAILADMIN_NOTIFICATION_INCLUDE_SUPERUSERS` off, the superuser should not get a workflow email
self.assertNotIn(self.superuser.email, workflow_submission_emailed_addresses)
+ @override_settings(WAGTA... | wagtail/admin/tests/test_workflows.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Notifications to active users only | 7,510 | wagtail/wagtail | 16,097 | Python | bwilliams3 | |
"https://s3.amazonaws.com/somebucket/static/wagtailadmin/images/email-header.jpg",
url,
)
class TestVersionedStatic(TestCase):
def test_versioned_static(self):
result = versioned_static("wagtailadmin/js/core.js")
self.assertRegex(result, r"^/static/wagtailadmin/js/c... | No issues found. | "https://s3.amazonaws.com/somebucket/static/wagtailadmin/images/email-header.jpg",
url,
)
class TestVersionedStatic(TestCase):
def test_versioned_static(self):
result = versioned_static("wagtailadmin/js/core.js")
self.assertRegex(result, r"^/static/wagtailadmin/js/c... | @@ -71,11 +71,15 @@ class TestNotificationStaticTemplateTag(TestCase):
def test_local_notification_static(self):
url = notification_static("wagtailadmin/images/email-header.jpg")
self.assertEqual(
- "{}/static/wagtailadmin/images/email-header.jpg".format(settings.BASE_URL),
+ ... | wagtail/admin/tests/test_templatetags.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Renaming base url setting | 8,268 | wagtail/wagtail | 16,097 | Python | sandilsranasinghe | |
# The page should have "has_unpublished_changes" flag set
child_page_new = SimplePage.objects.get(id=self.child_page.id)
self.assertTrue(child_page_new.has_unpublished_changes)
def go_to_dashboard_response(self):
response = self.client.get(reverse("wagtailadmin_home"))
self.... | No issues found. | # The page should have "has_unpublished_changes" flag set
child_page_new = SimplePage.objects.get(id=self.child_page.id)
self.assertTrue(child_page_new.has_unpublished_changes)
def go_to_dashboard_response(self):
response = self.client.get(reverse("wagtailadmin_home"))
self.... | @@ -92,15 +92,12 @@ def test_panel(self):
panel = RecentEditsPanel()
ctx = panel.get_context_data({"request": self.client})
+ page = Page.objects.get(pk=self.child_page.id).specific
+
# check if the revision is the revision of edited Page
- self.assertEqual(
- ctx["... | wagtail/admin/tests/pages/test_dashboard.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Use `GenericForeignKey` and `GenericRelation` for `Revision` | 8,571 | wagtail/wagtail | 16,097 | Python | laymonage | |
# Generated by Django 5.1.4 on 2025-01-19 21:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("tests", "0045_alter_streampage_body"),
]
operations = [
migrations.AlterUniqueTogether(
name="customrendition",
uniq... | No issues found. | # Generated by Django 5.1.4 on 2025-01-19 21:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("tests", "0045_alter_streampage_body"),
]
operations = [
migrations.AlterUniqueTogether(
name="customrendition",
uniq... | @@ -0,0 +1,24 @@
+# Generated by Django 5.1.4 on 2025-01-19 21:03
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("tests", "0045_alter_streampage_body"),
+ ]
+
+ operations = [
+ migrations.AlterUniqueTogether(
+ name="cus... | wagtail/test/testapp/migrations/0046_alter_custom_rendition_to_unique_constraint.py | 0 | Python | 1 | none | 16 | 25 | 25 | true | Adds support for constraints on AbstractRendition, as an alternative to unique_together | 8,716 | wagtail/wagtail | 16,097 | Python | ollz272 | |
class TestInspectView(TestCase, WagtailTestUtils):
fixtures = ["modeladmintest_test.json"]
def setUp(self):
self.login()
img = Image.objects.create(
title="LOTR cover",
file=get_test_image_file(),
)
book = Book.objects.get(title="The Lord of the Rings")
... | No issues found. | class TestInspectView(TestCase, WagtailTestUtils):
fixtures = ["modeladmintest_test.json"]
def setUp(self):
self.login()
img = Image.objects.create(
title="LOTR cover",
file=get_test_image_file(),
)
book = Book.objects.get(title="The Lord of the Rings")
... | @@ -595,6 +595,21 @@ def test_non_existent(self):
response = self.get_for_book(100)
self.assertEqual(response.status_code, 404)
+ def test_back_to_listing(self):
+ response = self.client.get("/admin/modeladmintest/author/inspect/1/")
+ # check that back to listing link exists
+ ... | wagtail/contrib/modeladmin/tests/test_simple_modeladmin.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Remove breadcrumbs from ModelAdmin | 8,743 | wagtail/wagtail | 16,097 | Python | PaarthAgarwal | |
object_list = context["object_list"]
headers = list(result_headers(view))
num_sorted_fields = 0
for h in headers:
if h["sortable"] and h["sorted"]:
num_sorted_fields += 1
context.update(
{
"result_headers": headers,
"num_sorted_fields": num_sorted_... | No issues found. | object_list = context["object_list"]
headers = list(result_headers(view))
num_sorted_fields = 0
for h in headers:
if h["sortable"] and h["sorted"]:
num_sorted_fields += 1
context.update(
{
"result_headers": headers,
"num_sorted_fields": num_sorted_... | @@ -118,7 +118,7 @@ def pagination_link_previous(current_page, view):
if current_page.has_previous():
previous_page_number0 = current_page.previous_page_number() - 1
tpl = get_template("wagtailadmin/shared/icon.html")
- icon_svg = tpl.render({"name": "arrow-left", "class_name": "default"})... | wagtail/contrib/modeladmin/templatetags/modeladmin_tags.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Ensure icon template tag can use `classname` instead of `class_name` by default | 9,769 | wagtail/wagtail | 16,097 | Python | lb- | |
def test_get_upgrade_check_setting_false(self):
self.assertFalse(self.panel.get_upgrade_check_setting())
@override_settings(WAGTAIL_ENABLE_UPDATE_CHECK="LTS")
def test_get_upgrade_check_setting_LTS(self):
self.assertEqual(self.panel.get_upgrade_check_setting(), "LTS")
@override_setting... | No issues found. | def test_get_upgrade_check_setting_false(self):
self.assertFalse(self.panel.get_upgrade_check_setting())
@override_settings(WAGTAIL_ENABLE_UPDATE_CHECK="LTS")
def test_get_upgrade_check_setting_LTS(self):
self.assertEqual(self.panel.get_upgrade_check_setting(), "LTS")
@override_setting... | @@ -5,8 +5,8 @@
class TestUpgradeNotificationPanel(TestCase, WagtailTestUtils):
- DATA_ATTRIBUTE_UPGRADE_CHECK = "data-upgrade"
- DATA_ATTRIBUTE_UPGRADE_CHECK_LTS = "data-upgrade-lts-only"
+ DATA_ATTRIBUTE_UPGRADE_CHECK = "data-w-upgrade"
+ DATA_ATTRIBUTE_UPGRADE_CHECK_LTS = "data-w-upgrade-lts-only"
... | wagtail/admin/tests/test_upgrade_notification.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Upgrade notification stimulus | 9,801 | wagtail/wagtail | 16,097 | Python | Lovelyfin00 | |
'error',
{
classes: {
memberTypes: ['signature', 'field', 'method'],
},
},
],
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'method',
format: ['camelCase'],
custom... | No issues found. | 'error',
{
classes: {
memberTypes: ['signature', 'field', 'method'],
},
},
],
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'method',
format: ['camelCase'],
custom... | @@ -1,12 +1,3 @@
-// Rules which have been enforced in configuration upgrades and flag issues in existing code.
-// We need to consider whether to disable those rules permanently, or fix the issues.
-const legacyCode = {
- 'default-param-last': 'off',
- 'no-continue': 'off',
- 'no-else-return': 'off',
- 'no-restric... | .eslintrc.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | removed legacyCode rules and the files being overridden and fixed lin… | 9,805 | wagtail/wagtail | 16,097 | Python | Lovelyfin00 | |
return True
except NotImplementedError:
return False
@contextmanager
def open_file(self):
# Open file if it is closed
close_file = False
f = self.file
if f.closed:
# Reopen the file
if self.is_stored_locally():
... | No issues found. | return True
except NotImplementedError:
return False
@contextmanager
def open_file(self):
# Open file if it is closed
close_file = False
f = self.file
if f.closed:
# Reopen the file
if self.is_stored_locally():
... | @@ -102,7 +102,7 @@ def open_file(self):
else:
# Some external storage backends don't allow reopening
# the file. Get a fresh file instance. #1397
- storage = self._meta.get_field("file").storage
+ storage = self.file.storage
... | wagtail/documents/models.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | correct the way of getting the storage of an image/document (#9904) | 10,412 | wagtail/wagtail | 16,097 | Python | engAmirEng | |
def test_filtered_searched_no_results(self):
lookup_values = {
"release_date": "2019-06-11",
"release_date__year__lte": "2023",
}
for backend, (url_namespace, lookup) in self.cases.items():
with self.subTest(backend=backend):
value = lookup... | No issues found. | def test_filtered_searched_no_results(self):
lookup_values = {
"release_date": "2019-06-11",
"release_date__year__lte": "2023",
}
for backend, (url_namespace, lookup) in self.cases.items():
with self.subTest(backend=backend):
value = lookup... | @@ -1,11 +1,16 @@
import datetime
from io import BytesIO
+from django.conf import settings
from django.contrib.admin.utils import quote
+from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from django.urls import reverse
+from django.utils.formats import date_format
+from ... | wagtail/admin/tests/viewsets/test_model_viewset.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Extract generic `HistoryView` and add it to `ModelViewSet` | 10,919 | wagtail/wagtail | 16,097 | Python | laymonage | |
)
self.assertDictEqual(filters.dict(), {"foo": "test3", "foo2": "test4"})
self.assertListEqual(filters.getlist("foo"), ["test1", "test2", "test3"])
self.assertEqual(query, "hello world")
class TestParseQueryString(SimpleTestCase):
def test_simple_query(self):
filters, quer... | No issues found. | )
self.assertDictEqual(filters.dict(), {"foo": "test3", "foo2": "test4"})
self.assertListEqual(filters.getlist("foo"), ["test1", "test2", "test3"])
self.assertEqual(query, "hello world")
class TestParseQueryString(SimpleTestCase):
def test_simple_query(self):
filters, quer... | @@ -1,8 +1,3 @@
-import datetime
-import json
-from io import StringIO
-
-from django.core import management
from django.test import SimpleTestCase, TestCase
from wagtail.search import models
@@ -13,7 +8,6 @@
parse_query_string,
separate_filters_from_query,
)
-from wagtail.test.utils import WagtailTestUt... | wagtail/search/tests/test_queries.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix & clean up Search & Search Promotions contrib module move | 10,959 | wagtail/wagtail | 16,097 | Python | lb- | |
"""
Replacement for django.contrib.auth.decorators.permission_required which returns a
more meaningful 'permission denied' response than just redirecting to the login page.
(The latter doesn't work anyway because Wagtail doesn't define LOGIN_URL...)
"""
def test(user):
return user.has_p... | No issues found. | """
Replacement for django.contrib.auth.decorators.permission_required which returns a
more meaningful 'permission denied' response than just redirecting to the login page.
(The latter doesn't work anyway because Wagtail doesn't define LOGIN_URL...)
"""
def test(user):
return user.has_p... | @@ -1,15 +1,13 @@
-import types
from functools import wraps
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from django.urls import reverse
-from django.utils.timezone import override as override_tz
from django.utils.translation import g... | wagtail/admin/auth.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Take preferred language into account in JavaScriptCatalog view | 11,075 | wagtail/wagtail | 16,097 | Python | bbliem | |
from django.http import Http404
from rest_framework import serializers
from wagtail.api.v2.filters import FieldsFilter, OrderingFilter, SearchFilter
from wagtail.api.v2.serializers import BaseSerializer
from wagtail.api.v2.views import BaseAPIViewSet
from wagtail.contrib.redirects.middleware import get_redirect
... | No issues found. | from django.http import Http404
from rest_framework import serializers
from wagtail.api.v2.filters import FieldsFilter, OrderingFilter, SearchFilter
from wagtail.api.v2.serializers import BaseSerializer
from wagtail.api.v2.views import BaseAPIViewSet
from wagtail.contrib.redirects.middleware import get_redirect
... | @@ -0,0 +1,39 @@
+from django.http import Http404
+from rest_framework import serializers
+
+from wagtail.api.v2.filters import FieldsFilter, OrderingFilter, SearchFilter
+from wagtail.api.v2.serializers import BaseSerializer
+from wagtail.api.v2.views import BaseAPIViewSet
+from wagtail.contrib.redirects.middlew... | wagtail/contrib/redirects/api.py | 0 | Python | 1 | none | 16 | 40 | 40 | true | Add Redirect API | 11,510 | wagtail/wagtail | 16,097 | Python | rohitsrma | |
sidebar_data = (
self.get_soup(response.content)
.select_one("#wagtail-sidebar-props")
.contents[0]
)
self.assertIn(
json.dumps(
{
"role": "button",
"data-a11y-dialog-show": "keyboard-shortc... | No issues found. |
sidebar_data = (
self.get_soup(response.content)
.select_one("#wagtail-sidebar-props")
.contents[0]
)
self.assertIn(
json.dumps(
{
"role": "button",
"data-a11y-dialog-show": "keyboard-shortc... | @@ -0,0 +1,84 @@
+import json
+import re
+
+from django.test import TestCase
+from django.test.client import Client
+from django.urls import reverse
+
+from wagtail.test.utils import WagtailTestUtils
+
+
+class TestKeyboardShortcutsDialog(WagtailTestUtils, TestCase):
+ def setUp(self):
+ self.login()
+
+ d... | wagtail/admin/tests/test_keyboard_shortcuts.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add a basic keyboard shortcuts overview dialog | 11,717 | wagtail/wagtail | 16,097 | Python | kituuu | |
return description
elif isinstance(description, Promise):
# description is a lazy object (e.g. the result of gettext_lazy())
return str(description)
else:
return ""
@property
def approved_schedule(self):
# `_approved_schedule` may be popul... | No issues found. | return description
elif isinstance(description, Promise):
# description is a lazy object (e.g. the result of gettext_lazy())
return str(description)
else:
return ""
@property
def approved_schedule(self):
# `_approved_schedule` may be popul... | @@ -1668,6 +1668,11 @@ def route(self, request, path_components):
try:
subpage = self.get_children().get(slug=child_slug)
+ # Cache the parent page on the subpage to avoid another db query
+ # Treebeard's get_parent will use the `_cached_parent_obj` attribut... | wagtail/models/__init__.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Update page routing, add tests | 11,737 | wagtail/wagtail | 16,097 | Python | Nigel2392 | |
{
"de": "German",
"en": "English",
},
)
@override_settings(
WAGTAIL_CONTENT_LANGUAGES=[
("en", _("English")),
("de", _("German")),
],
)
def test_can_be_a_translation_proxy(self):
self.assertEqual... | No issues found. | {
"de": "German",
"en": "English",
},
)
@override_settings(
WAGTAIL_CONTENT_LANGUAGES=[
("en", _("English")),
("de", _("German")),
],
)
def test_can_be_a_translation_proxy(self):
self.assertEqual... | @@ -479,6 +479,12 @@ def test_non_standard_port(self):
request = get_dummy_request(site=site)
self.assertEqual(request.get_host(), "other.example.com:8888")
+ def test_server_name_for_wildcard_allowed_hosts(self):
+ # Django's test runner adds "testserver" at the end of ALLOWED_HOSTS.
+ ... | wagtail/tests/test_utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix dummy request SERVER_NAME when running tests | 11,747 | wagtail/wagtail | 16,097 | Python | davidwtbuxton | |
# Generated by Django 5.0.1 on 2024-03-15 21:20
import django.db.models.manager
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("tests", "0034_custompermissionmodel"),
]
operations = [
migrations.CreateModel(
name="ModelWithCu... | No issues found. | # Generated by Django 5.0.1 on 2024-03-15 21:20
import django.db.models.manager
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("tests", "0034_custompermissionmodel"),
]
operations = [
migrations.CreateModel(
name="ModelWithCu... | @@ -0,0 +1,30 @@
+# Generated by Django 5.0.1 on 2024-03-15 21:20
+
+import django.db.models.manager
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tests", "0034_custompermissionmodel"),
+ ]
+
+ operations = [
+ migrations.CreateModel(... | wagtail/test/testapp/migrations/0035_modelwithcustommanager.py | 0 | Python | 1 | none | 16 | 31 | 31 | true | Use `default_manager` instead of `objects` in `ModelIndexView` | 11,766 | wagtail/wagtail | 16,097 | Python | jhonatan-lopes | |
beforeEach(() => {
// Create a placeholder to render the widget
document.body.innerHTML = '<div id="placeholder"></div>';
const widgetDef = window.telepath.unpack({
_type: 'wagtail.widgets.DraftailRichTextArea',
_args: [
{
entityTypes: [
{
_dict: {
... | No issues found. | beforeEach(() => {
// Create a placeholder to render the widget
document.body.innerHTML = '<div id="placeholder"></div>';
const widgetDef = window.telepath.unpack({
_type: 'wagtail.widgets.DraftailRichTextArea',
_args: [
{
entityTypes: [
{
_dict: {
... | @@ -46,10 +46,14 @@ describe('telepath: wagtail.widgets.Widget', () => {
test('getValue() returns the current value', () => {
expect(boundWidget.getValue()).toBe('The Value');
+ document.querySelector('input').value = 'New Value';
+ expect(boundWidget.getValue()).toBe('New Value');
});
test('get... | client/src/entrypoints/admin/telepath/widgets.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Eliminate jQuery from telepath widget classes | 11,839 | wagtail/wagtail | 16,097 | Python | gasman | |
self.assertEqual(page_id_list, [16, 18, 19])
def test_ordering_by_unknown_field_gives_error(self):
response = self.get_response(order="not_a_field")
content = json.loads(response.content.decode("UTF-8"))
self.assertEqual(response.status_code, 400)
self.assertEqual(
... | No issues found. | self.assertEqual(page_id_list, [16, 18, 19])
def test_ordering_by_unknown_field_gives_error(self):
response = self.get_response(order="not_a_field")
content = json.loads(response.content.decode("UTF-8"))
self.assertEqual(response.status_code, 400)
self.assertEqual(
... | @@ -1781,6 +1781,19 @@ def test_find_by_html_path_with_start_and_end_slashes_removed(self):
fetch_redirect_response=False,
)
+ def test_find_by_html_path_with_fields(self):
+ response = self.get_response(
+ html_path="/events-index/event-1/", fields="_,id,type"
+ )
+
... | wagtail/api/v2/tests/test_pages.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Retain fields parameter when redirecting from find_view of API | 12,141 | wagtail/wagtail | 16,097 | Python | ahosgood | |
def get_url(self, request=None, current_site=None):
"""
Return the 'most appropriate' URL for referring to this page from the pages we serve,
within the Wagtail backend and actual website templates;
this is the local URL (starting with '/') if we're only running a single site
... | No issues found. |
def get_url(self, request=None, current_site=None):
"""
Return the 'most appropriate' URL for referring to this page from the pages we serve,
within the Wagtail backend and actual website templates;
this is the local URL (starting with '/') if we're only running a single site
... | @@ -1429,6 +1429,10 @@ def get_indexed_instance(self):
except self.specific_class.DoesNotExist:
return None
+ def get_default_privacy_setting(self, request: HttpRequest):
+ """Set the default privacy setting for a page."""
+ return {"type": BaseViewRestriction.NONE}
+
@clas... | wagtail/models/pages.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add method to set default privacy option | 12,278 | wagtail/wagtail | 16,097 | Python | smark-1 | |
"varnish": {
"BACKEND": "wagtail.contrib.frontend_cache.backends.HTTPBackend",
"LOCATION": "http://localhost:8000/",
},
"cloudflare": {
"BACKEND": "wagtail.contrib.frontend_cache.backends.CloudflareBackend",
... | No issues found. | "varnish": {
"BACKEND": "wagtail.contrib.frontend_cache.backends.HTTPBackend",
"LOCATION": "http://localhost:8000/",
},
"cloudflare": {
"BACKEND": "wagtail.contrib.frontend_cache.backends.CloudflareBackend",
... | @@ -18,7 +18,7 @@
)
from wagtail.contrib.frontend_cache.utils import get_backends
from wagtail.models import Page
-from wagtail.test.testapp.models import EventIndex
+from wagtail.test.testapp.models import EventIndex, EventPage
from wagtail.utils.deprecation import RemovedInWagtail70Warning
from .utils import (... | wagtail/contrib/frontend_cache/tests.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Frontend cache: Fix n+1 query issues when batch purging page urls | 12,448 | wagtail/wagtail | 16,097 | Python | ababic | |
from django.test import TestCase
from wagtail.models import Page, Site
from wagtail.test.testapp.models import EventIndex
class AllowedHttpMethodsTestCase(TestCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
site = Site.objects.select_related("root_page").get(is_default_sit... | No issues found. | from django.test import TestCase
from wagtail.models import Page, Site
from wagtail.test.testapp.models import EventIndex
class AllowedHttpMethodsTestCase(TestCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
site = Site.objects.select_related("root_page").get(is_default_sit... | @@ -0,0 +1,32 @@
+from django.test import TestCase
+
+from wagtail.models import Page, Site
+from wagtail.test.testapp.models import EventIndex
+
+
+class AllowedHttpMethodsTestCase(TestCase):
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ site = Site.objects.select_related("ro... | wagtail/tests/test_page_allowed_http_methods.py | 0 | Python | 1 | none | 16 | 33 | 33 | true | Allow page types to easily restrict what type of requests they respond to | 12,473 | wagtail/wagtail | 16,097 | Python | ababic | |
<button
type="button"
data-controller="w-focus"
data-action="w-focus#focus"
data-w-focus-target-value=".section-top"
>
Skip to top
</button>
</section>
</main>`,
{ identifier: 'w-focus' },
);
});
it('should not ha... | No issues found. | <button
type="button"
data-controller="w-focus"
data-action="w-focus#focus"
data-w-focus-target-value=".section-top"
>
Skip to top
</button>
</section>
</main>`,
{ identifier: 'w-focus' },
);
});
it('should not ha... | @@ -0,0 +1,204 @@
+import { Application } from '@hotwired/stimulus';
+
+import { FocusController } from './FocusController';
+
+jest.useFakeTimers();
+
+describe('FocusController', () => {
+ let application;
+
+ const setup = async (
+ html = `<div>
+ <a id="skip" class="button" data-controller="w-focus" data-a... | client/src/controllers/FocusController.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Rename `SkipLinkController` to `FocusController`, update unit tests & add story | 12,555 | wagtail/wagtail | 16,097 | Python | lb- | |
expected_js = 'new PageChooser("{id}", {{"modelNames": ["{model}"], "canChooseRoot": false, "userPerms": null, "modalUrl": "/admin/choose-page/", "parentId": {parent}}});'.format(
id="id_page", model="tests.eventpage", parent=self.events_index_page.id
)
self.assertIn(expected_js, re... | No issues found. | expected_js = 'new PageChooser("{id}", {{"modelNames": ["{model}"], "canChooseRoot": false, "userPerms": null, "modalUrl": "/admin/choose-page/", "parentId": {parent}}});'.format(
id="id_page", model="tests.eventpage", parent=self.events_index_page.id
)
self.assertIn(expected_js, re... | @@ -1523,6 +1523,13 @@ def test_invalid_inlinepanel_declaration(self):
),
)
+ def test_get_heading_and_label_from_field(self):
+ panel = InlinePanel("social_links").bind_to_model(PersonPage)
+ # Heading is the plural term, derived from the relation's related_name
+ ... | wagtail/admin/tests/test_edit_handlers.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Set sensible defaults for InlinePanel heading and label | 12,556 | wagtail/wagtail | 16,097 | Python | gasman | |
"attrs": {},
},
[
{
"_type": "wagtail.sidebar.LinkMenuItem",
"_args": [
{
"name": "link",
... | No issues found. | "attrs": {},
},
[
{
"_type": "wagtail.sidebar.LinkMenuItem",
"_args": [
{
"name": "link",
... | @@ -283,7 +283,7 @@ def test_adapt(self):
],
{
"name": user.first_name or user.get_username(),
- "avatarUrl": "//www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=100&d=mp",
+ "avatarUrl": "//www.gr... | wagtail/admin/tests/ui/test_sidebar.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Enhanced get_gravatar_url & added unit test for it | 12,670 | wagtail/wagtail | 16,097 | Python | ayaan-qadri | |
usage_url = self.get_usage_url()
history_url = self.get_history_url()
if usage_url or history_url:
side_panels.append(
StatusSidePanel(
self.object,
self.request,
locale=self.locale,
trans... | No issues found. | usage_url = self.get_usage_url()
history_url = self.get_history_url()
if usage_url or history_url:
side_panels.append(
StatusSidePanel(
self.object,
self.request,
locale=self.locale,
trans... | @@ -1290,6 +1290,7 @@ class UnpublishView(HookResponseMixin, WagtailAdminTemplateMixin, TemplateView):
edit_url_name = None
unpublish_url_name = None
usage_url_name = None
+ page_title = gettext_lazy("Unpublish")
success_message = gettext_lazy("'%(object)s' unpublished.")
template_name = "wa... | wagtail/admin/views/generic/models.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Enable breadcrumbs by default and remove `_show_breadcrumbs` | 12,676 | wagtail/wagtail | 16,097 | Python | laymonage | |
);
// Simulate the keydown event & check that the default was prevented
expect(simulateKey({ key: 'j' })).toHaveProperty('keypress', false);
expect(buttonClickMock).toHaveBeenCalledTimes(1);
expect(buttonClickMock.mock.contexts).toEqual([
document.getElementById('btn'),
]);... | No issues found. | );
// Simulate the keydown event & check that the default was prevented
expect(simulateKey({ key: 'j' })).toHaveProperty('keypress', false);
expect(buttonClickMock).toHaveBeenCalledTimes(1);
expect(buttonClickMock.mock.contexts).toEqual([
document.getElementById('btn'),
]);... | @@ -188,4 +188,41 @@ describe('KeyboardController', () => {
expect(buttonClickMock).toHaveBeenCalledTimes(1);
});
});
+
+ describe('using an element target instead of controlled element', () => {
+ it('should call the click event when the `j` key is pressed after being registered', async () => {
+ ... | client/src/controllers/KeyboardController.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Added keyboard shortcut for main menu | 12,694 | wagtail/wagtail | 16,097 | Python | dhruvipatel14 | |
return True
except NotImplementedError:
return False
@contextmanager
def open_file(self):
# Open file if it is closed
close_file = False
f = self.file
if f.closed:
# Reopen the file
if self.is_stored_locally():
... | No issues found. | return True
except NotImplementedError:
return False
@contextmanager
def open_file(self):
# Open file if it is closed
close_file = False
f = self.file
if f.closed:
# Reopen the file
if self.is_stored_locally():
... | @@ -57,6 +57,7 @@ class AbstractDocument(CollectionMember, index.Indexed, models.Model):
],
),
index.FilterField("uploaded_by_user"),
+ index.FilterField("created_at"),
]
def clean(self): | wagtail/documents/models.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add created_at as a FilterField to enable sorting in Document search | 12,741 | wagtail/wagtail | 16,097 | Python | Srishti-j18 | |
from django.utils.translation import gettext_lazy
from wagtail.admin.forms.pages import WagtailAdminPageForm
from wagtail.models import Page
from wagtail.utils.decorators import cached_classmethod
from .group import ObjectList, TabbedInterface
Page.base_form_class = WagtailAdminPageForm
@cached_classmethod
def _ge... | No issues found. | from django.utils.translation import gettext_lazy
from wagtail.admin.forms.pages import WagtailAdminPageForm
from wagtail.models import Page
from wagtail.utils.decorators import cached_classmethod
from .group import ObjectList, TabbedInterface
Page.base_form_class = WagtailAdminPageForm
@cached_classmethod
def _ge... | @@ -1,50 +1,12 @@
-from django.conf import settings
from django.utils.translation import gettext_lazy
from wagtail.admin.forms.pages import WagtailAdminPageForm
from wagtail.models import Page
from wagtail.utils.decorators import cached_classmethod
-from .comment_panel import CommentPanel
-from .field_panel imp... | wagtail/admin/panels/page_utils.py | 0 | Python | 1 | none | 16 | 39 | 39 | true | Allow page models to extend base Page panel definitions without importing wagtail.admin | 12,750 | wagtail/wagtail | 16,097 | Python | gasman | |
def test_must_be_subset_of_django_languages(self):
with self.assertRaises(ImproperlyConfigured) as e:
get_content_languages()
self.assertEqual(
e.exception.args,
(
"The language zh is specified in WAGTAIL_CONTENT_LANGUAGES but not LANGUAGES. WAGTA... | No issues found. | def test_must_be_subset_of_django_languages(self):
with self.assertRaises(ImproperlyConfigured) as e:
get_content_languages()
self.assertEqual(
e.exception.args,
(
"The language zh is specified in WAGTAIL_CONTENT_LANGUAGES but not LANGUAGES. WAGTA... | @@ -1,6 +1,7 @@
import hashlib
import pickle
import unittest
+import warnings
from io import BytesIO
from pathlib import Path
@@ -27,6 +28,7 @@
string_to_ascii,
)
from wagtail.models import Page, Site
+from wagtail.utils.deprecation import RemovedInWagtail70Warning
from wagtail.utils.file import hash_fil... | wagtail/tests/test_utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | fix `stacklevel` in the `warn` call in `WidgetWithScript` | 12,754 | wagtail/wagtail | 16,097 | Python | jorenham | |
page_ids, {self.child_page.id, self.new_page.id, new_page_child.id}
)
self.assertContainsActiveFilter(
response,
"Page type: Simple page",
f"content_type={page_type_pk}",
)
# "Page" should not be listed as a content type
soup = sel... | No issues found. | page_ids, {self.child_page.id, self.new_page.id, new_page_child.id}
)
self.assertContainsActiveFilter(
response,
"Page type: Simple page",
f"content_type={page_type_pk}",
)
# "Page" should not be listed as a content type
soup = sel... | @@ -166,6 +166,37 @@ def test_ordering(self):
page_ids, [self.child_page.id, self.new_page.id, self.old_page.id]
)
+ def test_ordering_by_content_type(self):
+ orderings = {
+ "content_type": (
+ [self.child_page.id, self.new_page.id, self.old_page.id],
+ ... | wagtail/admin/tests/pages/test_explorer_view.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Stop rendering to content type in search result | 12,784 | wagtail/wagtail | 16,097 | Python | Srishti-j18 | |
"strings": {
"DELETE": "Delete",
"DUPLICATE": "Duplicate",
"MOVE_DOWN": "Move down",
"MOVE_UP": "Move up",
"DRAG": "Drag",
"ADD": "Add",
},
},
)
... | No issues found. | "strings": {
"DELETE": "Delete",
"DUPLICATE": "Duplicate",
"MOVE_DOWN": "Move down",
"MOVE_UP": "Move up",
"DRAG": "Drag",
"ADD": "Add",
},
},
)
... | @@ -93,6 +93,11 @@ def get_preview_value(self):
"specific_template_and_custom_value": [
blocks.Block(preview_template="foo.html", preview_value="bar"),
],
+ "unset_default_not_none": [
+ blocks.ListBlock(blocks.Block()),
+ blocks.Stream... | wagtail/tests/test_blocks.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix `Block.is_previewable` detection on blocks with non-`None` unset default values | 12,828 | wagtail/wagtail | 16,097 | Python | laymonage | |
modified_value = self.rhs.value.copy()
modified_value.invert = not modified_value.invert
rhs_connector = "-"
rsql, params = compiler.compile(modified_value)
else:
rsql, params = compiler.compile(self.rhs)
value_params.extend(params)
co... | No issues found. | modified_value = self.rhs.value.copy()
modified_value.invert = not modified_value.invert
rhs_connector = "-"
rsql, params = compiler.compile(modified_value)
else:
rsql, params = compiler.compile(self.rhs)
value_params.extend(params)
co... | @@ -51,13 +51,17 @@ def __init__(
self.prefix = prefix
self.invert = invert
self.weight = weight
+
+ if not value:
+ raise ValueError("Lexeme value cannot be empty.")
+ if re.search(r"\W+", value):
+ raise ValueError(
+ f"Lexeme value '{value... | wagtail/search/backends/database/mysql/query.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Validate against invalid characters in Lexeme values | 12,830 | wagtail/wagtail | 16,097 | Python | gasman | |
if is_valid:
# TODO: Handle request.FILES.
request.session[self.session_key] = request.POST.urlencode(), time()
is_available = True
else:
# Check previous data in session to determine preview availability
form = self.get_form(self._get_data_fr... | No issues found. |
if is_valid:
# TODO: Handle request.FILES.
request.session[self.session_key] = request.POST.urlencode(), time()
is_available = True
else:
# Check previous data in session to determine preview availability
form = self.get_form(self._get_data_fr... | @@ -197,6 +197,8 @@ def page_title(self):
def base_context(self):
# Do NOT use the name `block` in the context, as it will conflict with
# the current block inside a template {% block %} tag.
+ # If any changes are made here that needs to be publicly documented,
+ # make sure to upd... | wagtail/admin/views/generic/preview.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Expand docs for StreamField block previews | 12,840 | wagtail/wagtail | 16,097 | Python | laymonage | |
const lastDeviceInput =
this.sizeTargets.find((input) => input.value === lastDevice) ||
this.activeSizeInput ||
this.sizeTargets[0];
lastDeviceInput.click();
// If lastDeviceInput resolves to the default input, the click event will
// not trigger the togglePreviewSize method, so we nee... | No issues found. | const lastDeviceInput =
this.sizeTargets.find((input) => input.value === lastDevice) ||
this.activeSizeInput ||
this.sizeTargets[0];
lastDeviceInput.click();
// If lastDeviceInput resolves to the default input, the click event will
// not trigger the togglePreviewSize method, so we nee... | @@ -714,11 +714,13 @@ export class PreviewController extends Controller<HTMLElement> {
// not run the replacement logic in this case.
if (!newIframe.src) return;
- // Restore scroll position
- newIframe.contentWindow?.scroll(
- this.iframeTarget.contentWindow?.scrollX as number,
- this.ifram... | client/src/controllers/PreviewController.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Force preview panel scroll behavior to instant to avoid flickering | 12,869 | wagtail/wagtail | 16,097 | Python | laymonage | |
PageChooserForm = my_page_object_list.get_form_class()
form = PageChooserForm(instance=self.test_instance)
page_chooser_panel = my_page_chooser_panel.get_bound_panel(
instance=self.test_instance, form=form, request=self.request
)
result = page_chooser_panel.render_ht... | No issues found. | PageChooserForm = my_page_object_list.get_form_class()
form = PageChooserForm(instance=self.test_instance)
page_chooser_panel = my_page_chooser_panel.get_bound_panel(
instance=self.test_instance, form=form, request=self.request
)
result = page_chooser_panel.render_ht... | @@ -1778,6 +1778,15 @@ def test_comments_disabled_setting(self):
for panel in expand_panel_list(Page, Page.settings_panels)
)
)
+
+ self.login()
+ response = self.client.get(reverse("wagtailadmin_pages:edit", args=[3]))
+ self.assertEqual(response.status_code,... | wagtail/admin/tests/test_edit_handlers.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Removes imports from _editor_js.html | 12,882 | wagtail/wagtail | 16,097 | Python | saisrikardumpeti | |
buttons = []
if copy_url := self.get_copy_url():
buttons.append(
Button(
_("Copy"),
url=copy_url,
icon_name="copy",
priority=10,
)
)
if self.can_delete and (del... | No issues found. | buttons = []
if copy_url := self.get_copy_url():
buttons.append(
Button(
_("Copy"),
url=copy_url,
icon_name="copy",
priority=10,
)
)
if self.can_delete and (del... | @@ -1105,8 +1105,13 @@ def get_field_label(self, field_name, field):
return capfirst(label_for_field(field_name, model=self.model))
def get_field_display_value(self, field_name, field):
- # First we check for a 'get_fieldname_display' property/method on
+ # First we check for a `get_fieldn... | wagtail/admin/views/generic/models.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Allow customising InspectView field display value via methods on the view | 12,906 | wagtail/wagtail | 16,097 | Python | zerolab | |
response,
'<div class="w-label-3 w-text-primary">Invalid schedule</div>',
html=True,
)
num_errors = 2
# Should show the correct number on the badge of the toggle button
self.assertRegex(
response.content.decode(),
self.STATUS_... | No issues found. | response,
'<div class="w-label-3 w-text-primary">Invalid schedule</div>',
html=True,
)
num_errors = 2
# Should show the correct number on the badge of the toggle button
self.assertRegex(
response.content.decode(),
self.STATUS_... | @@ -457,11 +457,20 @@ def test_use_fallback_for_blank_title_field(self):
@override_settings(WAGTAIL_I18N_ENABLED=True)
-class TestLocaleSelectorOnList(WagtailTestUtils, TestCase):
+class TestLocaleFeaturesOnList(WagtailTestUtils, TestCase):
+ @classmethod
+ def setUpTestData(cls):
+ cls.fr_locale = Lo... | wagtail/snippets/tests/test_snippets.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add Locale column to generic listings | 12,917 | wagtail/wagtail | 16,097 | Python | zerolab | |
url_finder = AdminURLFinder(self.user)
expected_url = "/admin/searchpicks/%d/" % self.query.id
self.assertEqual(url_finder.get_edit_url(self.search_pick), expected_url)
self.assertBreadcrumbsItemsRendered(
[
{
"url": reverse("wagtailsearc... | No issues found. |
url_finder = AdminURLFinder(self.user)
expected_url = "/admin/searchpicks/%d/" % self.query.id
self.assertEqual(url_finder.get_edit_url(self.search_pick), expected_url)
self.assertBreadcrumbsItemsRendered(
[
{
"url": reverse("wagtailsearc... | @@ -4,6 +4,7 @@
from django.contrib.auth.models import Permission
from django.core import management
+from django.db.models import F
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
@@ -24,6 +25,18 @@
from wagtail.test.utils.template_tests import AdminTemplateTe... | wagtail/contrib/search_promotions/tests.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Use locale-appropriate formatting on Hits column in promo search report | 12,930 | wagtail/wagtail | 16,097 | Python | bmispelon | |
const queryString = '?' + searchParams.toString();
const url = this.srcValue;
this.replace(url + queryString).then(() => {
window.history.replaceState(null, '', queryString);
});
}
get formElement() {
return (
this.hasInputTarget ? this.inputTarget.form || this.element : this.elem... | No issues found. |
const queryString = '?' + searchParams.toString();
const url = this.srcValue;
this.replace(url + queryString).then(() => {
window.history.replaceState(null, '', queryString);
});
}
get formElement() {
return (
this.hasInputTarget ? this.inputTarget.form || this.element : this.elem... | @@ -12,41 +12,46 @@ import { WAGTAIL_CONFIG } from '../config/wagtailConfig';
* values.
*
* @example - A form that will update the results based on the form's input
- * <div id="results"></div>
- * <form
- * data-controller="w-swap"
- * data-action="input->w-swap#submitLazy"
- * data-w-swap-src-value="... | client/src/controllers/SwapController.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Cleanup Stimulus controller imports, JSDoc & linting | 12,952 | wagtail/wagtail | 16,097 | Python | lb- | |
class StreamForm(WagtailAdminModelForm):
class Meta:
model = JSONMinMaxCountStreamModel
fields = ["body"]
defer_required_on_fields = ["body"]
form_data = nested_form_data(
{
"body": streamfield(
... | No issues found. | class StreamForm(WagtailAdminModelForm):
class Meta:
model = JSONMinMaxCountStreamModel
fields = ["body"]
defer_required_on_fields = ["body"]
form_data = nested_form_data(
{
"body": streamfield(
... | @@ -8,6 +8,7 @@
from django.utils.safestring import SafeString
from wagtail import blocks
+from wagtail.admin.forms import WagtailAdminModelForm
from wagtail.blocks import StreamBlockValidationError, StreamValue
from wagtail.fields import StreamField
from wagtail.images.models import Image
@@ -22,6 +23,7 @@
... | wagtail/tests/test_streamfield.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Defer validation of StreamField min block counts when saving drafts | 12,964 | wagtail/wagtail | 16,097 | Python | gasman | |
self.reset_index()
for page in Page.objects.all():
self.backend.add(page)
self.refresh_index()
def reset_index(self):
if self.backend.rebuilder_class:
index = self.backend.get_index_for_model(Page)
rebuilder = self.backend.rebuilder_class(index)
... | No issues found. | self.reset_index()
for page in Page.objects.all():
self.backend.add(page)
self.refresh_index()
def reset_index(self):
if self.backend.rebuilder_class:
index = self.backend.get_index_for_model(Page)
rebuilder = self.backend.rebuilder_class(index)
... | @@ -1,9 +1,14 @@
from django.conf import settings
+from django.db.models import F
from django.test import TestCase
from wagtail.models import Page
from wagtail.search.backends import get_search_backend
-from wagtail.search.backends.base import BaseSearchQueryCompiler, BaseSearchResults
+from wagtail.search.backen... | wagtail/search/tests/test_page_search.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix database backends failing on complex order_by | 12,965 | wagtail/wagtail | 16,097 | Python | SebCorbin | |
return self.client.get(
reverse("wagtailadmin_collections:edit", args=(collection_id,)), params
)
def post(self, collection_id, post_data={}):
return self.client.post(
reverse("wagtailadmin_collections:edit", args=(collection_id,)), post_data
)
def test_... | No issues found. | return self.client.get(
reverse("wagtailadmin_collections:edit", args=(collection_id,)), params
)
def post(self, collection_id, post_data={}):
return self.client.post(
reverse("wagtailadmin_collections:edit", args=(collection_id,)), post_data
)
def test_... | @@ -810,3 +810,63 @@ def test_get_private_child(self):
args=(self.root_collection.pk,),
)
self.assertEqual(link.get("href"), parent_edit_url)
+
+
+class TestCollectionPrivacyStatusLabels(WagtailTestUtils, TestCase):
+ def setUp(self):
+ self.user = self.login()
+
+ self.r... | wagtail/admin/tests/test_collections_views.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | fix privacy collection status label being incorrect | 12,974 | wagtail/wagtail | 16,097 | Python | smark-1 | |
# Model has a foreign key to EventPage, which we want to autodetect
# instead of specifying the page type in PageChooserPanel
my_page_object_list = ObjectList([PageChooserPanel("page")]).bind_to_model(
EventPageChooserModel,
)
my_page_chooser_panel = my_page_object_li... | No issues found. | # Model has a foreign key to EventPage, which we want to autodetect
# instead of specifying the page type in PageChooserPanel
my_page_object_list = ObjectList([PageChooserPanel("page")]).bind_to_model(
EventPageChooserModel,
)
my_page_chooser_panel = my_page_object_li... | @@ -4,6 +4,7 @@
from typing import Any, Optional
from unittest import mock
+from django import VERSION as DJANGO_VERSION
from django import forms
from django.conf import settings
from django.contrib.auth import get_user_model
@@ -216,6 +217,22 @@ def test_get_form_for_model_with_widget_overrides_by_instance(self... | wagtail/admin/tests/test_edit_handlers.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Avoid deprecation warnings about URLField assume_scheme on Django 5.x | 12,976 | wagtail/wagtail | 16,097 | Python | laymonage | |
"wagtailadmin_pages:preview_on_edit", args=(self.event_page.id,)
)
response = self.client.post(
preview_url,
{
"carousel_items-TOTAL_FORMS": 0,
"carousel_items-INITIAL_FORMS": 0,
"speakers-TOTAL_FORMS": 0,
... | No issues found. | "wagtailadmin_pages:preview_on_edit", args=(self.event_page.id,)
)
response = self.client.post(
preview_url,
{
"carousel_items-TOTAL_FORMS": 0,
"carousel_items-INITIAL_FORMS": 0,
"speakers-TOTAL_FORMS": 0,
... | @@ -173,7 +173,10 @@ def test_preview_on_create_with_invalid_data(self):
)
self.assertNotIn(preview_session_key, self.client.session)
- response = self.client.post(preview_url, {**self.post_data, "title": ""})
+ response = self.client.post(
+ preview_url,
+ {**sel... | wagtail/admin/tests/pages/test_preview.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Defer validation of required text fields in previews | 12,982 | wagtail/wagtail | 16,097 | Python | laymonage | |
# Find the page and check it
page = Page.objects.get(
path__startswith=self.root_page.path, slug="hello-world"
).specific
self.assertEqual(
PageViewRestriction.objects.filter(
page=page, restriction_type="login"
).count(),
... | No issues found. | # Find the page and check it
page = Page.objects.get(
path__startswith=self.root_page.path, slug="hello-world"
).specific
self.assertEqual(
PageViewRestriction.objects.filter(
page=page, restriction_type="login"
).count(),
... | @@ -18,6 +18,7 @@
)
from wagtail.signals import page_published
from wagtail.test.testapp.models import (
+ Advert,
BusinessChild,
BusinessIndex,
BusinessSubIndex,
@@ -32,7 +33,7 @@
StandardIndex,
)
from wagtail.test.utils import WagtailTestUtils
-from wagtail.test.utils.form_data import nest... | wagtail/admin/tests/pages/test_create_page.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Defer validation on inline panels when saving drafts | 12,984 | wagtail/wagtail | 16,097 | Python | gasman |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.