2019 - Update 'MultiUsernameField' to handle display names (#6351)

Use Q for improved query
Fix issue where an invalid username forces full revision list
This commit is contained in:
smith 2024-11-18 15:32:50 -05:00 коммит произвёл GitHub
Родитель c477deb6e4
Коммит c760798d79
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
2 изменённых файлов: 14 добавлений и 19 удалений

Просмотреть файл

@ -4,6 +4,7 @@ from django import forms
from django.contrib.auth.models import User
from django.core import validators
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.utils.translation import gettext as _
@ -54,8 +55,9 @@ class TypedMultipleChoiceField(forms.MultipleChoiceField):
class MultiUsernameField(forms.Field):
"""Form field that takes a comma-separated list of usernames as input,
validates that users exist for each one, and returns the list of users."""
"""Form field that takes a comma-separated list of usernames OR profile
names (display names) as input, validates that users exist for each one,
and returns the list of users."""
def to_python(self, value):
if not value:
@ -67,18 +69,13 @@ class MultiUsernameField(forms.Field):
users = []
for username in value.split(","):
username = username.strip()
msg = ""
if username:
try:
user = User.objects.get(username=username)
users.append(user)
except User.DoesNotExist:
msg = _("{username} is not a valid username.")
else:
if not user.is_active:
msg = _("{username} is not an active user.")
if msg:
raise forms.ValidationError(msg.format(username=username))
user = User.objects.filter(
Q(username=username) | Q(profile__name=username)
).first()
if user:
if user.is_active:
users.append(user)
return users

Просмотреть файл

@ -1650,24 +1650,22 @@ def _show_revision_warning(document, revision):
def recent_revisions(request):
# Make writable
request.GET = request.GET.copy()
fragment = request.GET.pop("fragment", None)
form = RevisionFilterForm(request.GET)
# We are going to ignore validation errors for the most part, but
# this is needed to call the functions that generate `cleaned_data`
# This helps in particular when bad user names are typed in.
# Validate the form to populate cleaned_data, even with invalid usernames.
form.is_valid()
filters = {}
# If something has gone very wrong, `cleaned_data` won't be there.
if hasattr(form, "cleaned_data"):
if form.cleaned_data.get("locale"):
filters.update(document__locale=form.cleaned_data["locale"])
# Only apply user filter if there are valid users
if form.cleaned_data.get("users"):
filters.update(creator__in=form.cleaned_data["users"])
start = form.cleaned_data.get("start")
end = form.cleaned_data.get("end")
if start or end: