admin.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. from django import forms
  2. from django.db.models import Q
  3. from django.contrib.auth import get_user_model
  4. from django.contrib.auth.password_validation import validate_password
  5. from django.utils.translation import ugettext_lazy as _
  6. from django.utils.translation import ungettext
  7. from misago.acl.models import Role
  8. from misago.conf import settings
  9. from misago.core import threadstore
  10. from misago.core.forms import IsoDateTimeField, YesNoSwitch
  11. from misago.core.validators import validate_sluggable
  12. from misago.users.models import Ban, DataDownload, Rank
  13. from misago.users.profilefields import profilefields
  14. from misago.users.utils import hash_email
  15. from misago.users.validators import validate_email, validate_username
  16. UserModel = get_user_model()
  17. class UserBaseForm(forms.ModelForm):
  18. username = forms.CharField(label=_("Username"))
  19. title = forms.CharField(label=_("Custom title"), required=False)
  20. email = forms.EmailField(label=_("E-mail address"))
  21. class Meta:
  22. model = UserModel
  23. fields = ['username', 'email', 'title']
  24. def clean_username(self):
  25. data = self.cleaned_data['username']
  26. validate_username(data, exclude=self.instance)
  27. return data
  28. def clean_email(self):
  29. data = self.cleaned_data['email']
  30. validate_email(data, exclude=self.instance)
  31. return data
  32. def clean_new_password(self):
  33. data = self.cleaned_data['new_password']
  34. if data:
  35. validate_password(data, user=self.instance)
  36. return data
  37. def clean_roles(self):
  38. data = self.cleaned_data['roles']
  39. for role in data:
  40. if role.special_role == 'authenticated':
  41. break
  42. else:
  43. message = _('All registered members must have "Member" role.')
  44. raise forms.ValidationError(message)
  45. return data
  46. class NewUserForm(UserBaseForm):
  47. new_password = forms.CharField(
  48. label=_("Password"),
  49. strip=False,
  50. widget=forms.PasswordInput,
  51. )
  52. class Meta:
  53. model = UserModel
  54. fields = ['username', 'email', 'title']
  55. class EditUserForm(UserBaseForm):
  56. IS_STAFF_LABEL = _("Is administrator")
  57. IS_STAFF_HELP_TEXT = _(
  58. "Designates whether the user can log into admin sites. "
  59. "If Django admin site is enabled, this user will need "
  60. "additional permissions assigned within it to admin "
  61. "Django modules."
  62. )
  63. IS_SUPERUSER_LABEL = _("Is superuser")
  64. IS_SUPERUSER_HELP_TEXT = _(
  65. "Only administrators can access admin sites. "
  66. "In addition to admin site access, superadmins "
  67. "can also change other members admin levels."
  68. )
  69. IS_ACTIVE_LABEL = _('Is active')
  70. IS_ACTIVE_HELP_TEXT = _(
  71. "Designates whether this user should be treated as active. "
  72. "Turning this off is non-destructible way to remove user accounts."
  73. )
  74. IS_ACTIVE_STAFF_MESSAGE_LABEL = _("Staff message")
  75. IS_ACTIVE_STAFF_MESSAGE_HELP_TEXT = _(
  76. "Optional message for forum team members explaining "
  77. "why user's account has been disabled."
  78. )
  79. new_password = forms.CharField(
  80. label=_("Change password to"),
  81. strip=False,
  82. widget=forms.PasswordInput,
  83. required=False,
  84. )
  85. is_avatar_locked = YesNoSwitch(
  86. label=_("Lock avatar"),
  87. help_text=_(
  88. "Setting this to yes will stop user from changing "
  89. "his/her avatar, and will reset his/her avatar to "
  90. "procedurally generated one."
  91. )
  92. )
  93. avatar_lock_user_message = forms.CharField(
  94. label=_("User message"),
  95. help_text=_(
  96. "Optional message for user explaining "
  97. "why he/she is banned form changing avatar."
  98. ),
  99. widget=forms.Textarea(attrs={'rows': 3}),
  100. required=False
  101. )
  102. avatar_lock_staff_message = forms.CharField(
  103. label=_("Staff message"),
  104. help_text=_(
  105. "Optional message for forum team members explaining "
  106. "why user is banned form changing avatar."
  107. ),
  108. widget=forms.Textarea(attrs={'rows': 3}),
  109. required=False
  110. )
  111. signature = forms.CharField(
  112. label=_("Signature contents"),
  113. widget=forms.Textarea(attrs={'rows': 3}),
  114. required=False,
  115. )
  116. is_signature_locked = YesNoSwitch(
  117. label=_("Lock signature"),
  118. help_text=_(
  119. "Setting this to yes will stop user from "
  120. "making changes to his/her signature."
  121. )
  122. )
  123. signature_lock_user_message = forms.CharField(
  124. label=_("User message"),
  125. help_text=_("Optional message to user explaining why his/hers signature is locked."),
  126. widget=forms.Textarea(attrs={'rows': 3}),
  127. required=False
  128. )
  129. signature_lock_staff_message = forms.CharField(
  130. label=_("Staff message"),
  131. help_text=_("Optional message to team members explaining why user signature is locked."),
  132. widget=forms.Textarea(attrs={'rows': 3}),
  133. required=False
  134. )
  135. is_hiding_presence = YesNoSwitch(label=_("Hides presence"))
  136. limits_private_thread_invites_to = forms.TypedChoiceField(
  137. label=_("Who can add user to private threads"),
  138. coerce=int,
  139. choices=UserModel.LIMIT_INVITES_TO_CHOICES
  140. )
  141. subscribe_to_started_threads = forms.TypedChoiceField(
  142. label=_("Started threads"), coerce=int, choices=UserModel.SUBSCRIBE_CHOICES
  143. )
  144. subscribe_to_replied_threads = forms.TypedChoiceField(
  145. label=_("Replid threads"), coerce=int, choices=UserModel.SUBSCRIBE_CHOICES
  146. )
  147. class Meta:
  148. model = UserModel
  149. fields = [
  150. 'username',
  151. 'email',
  152. 'title',
  153. 'is_avatar_locked',
  154. 'avatar_lock_user_message',
  155. 'avatar_lock_staff_message',
  156. 'signature',
  157. 'is_signature_locked',
  158. 'is_hiding_presence',
  159. 'limits_private_thread_invites_to',
  160. 'signature_lock_user_message',
  161. 'signature_lock_staff_message',
  162. 'subscribe_to_started_threads',
  163. 'subscribe_to_replied_threads',
  164. ]
  165. def __init__(self, *args, **kwargs):
  166. self.request = kwargs.pop('request')
  167. super().__init__(*args, **kwargs)
  168. profilefields.add_fields_to_admin_form(self.request, self.instance, self)
  169. def get_profile_fields_groups(self):
  170. profile_fields_groups = []
  171. for group in self._profile_fields_groups:
  172. fields_group = {
  173. 'name': group['name'],
  174. 'fields': [],
  175. }
  176. for fieldname in group['fields']:
  177. fields_group['fields'].append(self[fieldname])
  178. profile_fields_groups.append(fields_group)
  179. return profile_fields_groups
  180. def clean_signature(self):
  181. data = self.cleaned_data['signature']
  182. length_limit = settings.signature_length_max
  183. if len(data) > length_limit:
  184. raise forms.ValidationError(
  185. ungettext(
  186. "Signature can't be longer than %(limit)s character.",
  187. "Signature can't be longer than %(limit)s characters.",
  188. length_limit,
  189. ) % {'limit': length_limit}
  190. )
  191. return data
  192. def clean(self):
  193. data = super().clean()
  194. return profilefields.clean_form(self.request, self.instance, self, data)
  195. def UserFormFactory(FormType, instance):
  196. extra_fields = {}
  197. extra_fields['rank'] = forms.ModelChoiceField(
  198. label=_("Rank"),
  199. help_text=_(
  200. "Ranks are used to group and distinguish users. They are "
  201. "also used to add permissions to groups of users."
  202. ),
  203. queryset=Rank.objects.order_by('name'),
  204. initial=instance.rank
  205. )
  206. roles = Role.objects.order_by('name')
  207. extra_fields['roles'] = forms.ModelMultipleChoiceField(
  208. label=_("Roles"),
  209. help_text=_('Individual roles of this user. All users must have "member" role.'),
  210. queryset=roles,
  211. initial=instance.roles.all() if instance.pk else None,
  212. widget=forms.CheckboxSelectMultiple
  213. )
  214. return type('UserFormFinal', (FormType, ), extra_fields)
  215. def StaffFlagUserFormFactory(FormType, instance):
  216. staff_fields = {
  217. 'is_staff': YesNoSwitch(
  218. label=EditUserForm.IS_STAFF_LABEL,
  219. help_text=EditUserForm.IS_STAFF_HELP_TEXT,
  220. initial=instance.is_staff
  221. ),
  222. 'is_superuser': YesNoSwitch(
  223. label=EditUserForm.IS_SUPERUSER_LABEL,
  224. help_text=EditUserForm.IS_SUPERUSER_HELP_TEXT,
  225. initial=instance.is_superuser
  226. ),
  227. }
  228. return type('StaffUserForm', (FormType, ), staff_fields)
  229. def UserIsActiveFormFactory(FormType, instance):
  230. is_active_fields = {
  231. 'is_active': YesNoSwitch(
  232. label=EditUserForm.IS_ACTIVE_LABEL,
  233. help_text=EditUserForm.IS_ACTIVE_HELP_TEXT,
  234. initial=instance.is_active
  235. ),
  236. 'is_active_staff_message': forms.CharField(
  237. label=EditUserForm.IS_ACTIVE_STAFF_MESSAGE_LABEL,
  238. help_text=EditUserForm.IS_ACTIVE_STAFF_MESSAGE_HELP_TEXT,
  239. initial=instance.is_active_staff_message,
  240. widget=forms.Textarea(attrs={'rows': 3}),
  241. required=False
  242. ),
  243. }
  244. return type('UserIsActiveForm', (FormType, ), is_active_fields)
  245. def EditUserFormFactory(FormType, instance, add_is_active_fields=False, add_admin_fields=False):
  246. FormType = UserFormFactory(FormType, instance)
  247. if add_is_active_fields:
  248. FormType = UserIsActiveFormFactory(FormType, instance)
  249. if add_admin_fields:
  250. FormType = StaffFlagUserFormFactory(FormType, instance)
  251. return FormType
  252. class SearchUsersFormBase(forms.Form):
  253. username = forms.CharField(label=_("Username starts with"), required=False)
  254. email = forms.CharField(label=_("E-mail starts with"), required=False)
  255. profilefields = forms.CharField(label=_("Profile fields contain"), required=False)
  256. inactive = YesNoSwitch(label=_("Inactive only"))
  257. disabled = YesNoSwitch(label=_("Disabled only"))
  258. is_staff = YesNoSwitch(label=_("Admins only"))
  259. is_deleting_account = YesNoSwitch(label=_("Deleting their accounts"))
  260. def filter_queryset(self, criteria, queryset):
  261. if criteria.get('username'):
  262. queryset = queryset.filter(slug__startswith=criteria.get('username').lower())
  263. if criteria.get('email'):
  264. queryset = queryset.filter(email__istartswith=criteria.get('email'))
  265. if criteria.get('rank'):
  266. queryset = queryset.filter(rank_id=criteria.get('rank'))
  267. if criteria.get('role'):
  268. queryset = queryset.filter(roles__id=criteria.get('role'))
  269. if criteria.get('inactive'):
  270. queryset = queryset.filter(requires_activation__gt=0)
  271. if criteria.get('disabled'):
  272. queryset = queryset.filter(is_active=False)
  273. if criteria.get('is_staff'):
  274. queryset = queryset.filter(is_staff=True)
  275. if criteria.get('is_deleting_account'):
  276. queryset = queryset.filter(is_deleting_account=True)
  277. if criteria.get('profilefields', '').strip():
  278. queryset = profilefields.search_users(
  279. criteria.get('profilefields').strip(), queryset)
  280. return queryset
  281. def SearchUsersForm(*args, **kwargs):
  282. """
  283. Factory that uses cache for ranks and roles,
  284. and makes those ranks and roles typed choice fields that play nice
  285. with passing values via GET
  286. """
  287. ranks_choices = threadstore.get('misago_admin_ranks_choices', 'nada')
  288. if ranks_choices == 'nada':
  289. ranks_choices = [('', _("All ranks"))]
  290. for rank in Rank.objects.order_by('name').iterator():
  291. ranks_choices.append((rank.pk, rank.name))
  292. threadstore.set('misago_admin_ranks_choices', ranks_choices)
  293. roles_choices = threadstore.get('misago_admin_roles_choices', 'nada')
  294. if roles_choices == 'nada':
  295. roles_choices = [('', _("All roles"))]
  296. for role in Role.objects.order_by('name').iterator():
  297. roles_choices.append((role.pk, role.name))
  298. threadstore.set('misago_admin_roles_choices', roles_choices)
  299. extra_fields = {
  300. 'rank': forms.TypedChoiceField(
  301. label=_("Has rank"),
  302. coerce=int,
  303. required=False,
  304. choices=ranks_choices,
  305. ),
  306. 'role': forms.TypedChoiceField(
  307. label=_("Has role"),
  308. coerce=int,
  309. required=False,
  310. choices=roles_choices,
  311. )
  312. }
  313. FinalForm = type('SearchUsersFormFinal', (SearchUsersFormBase, ), extra_fields)
  314. return FinalForm(*args, **kwargs)
  315. class RankForm(forms.ModelForm):
  316. name = forms.CharField(
  317. label=_("Name"),
  318. validators=[validate_sluggable()],
  319. help_text=_(
  320. 'Short and descriptive name of all users with this rank. '
  321. '"The Team" or "Game Masters" are good examples.'
  322. )
  323. )
  324. title = forms.CharField(
  325. label=_("User title"),
  326. required=False,
  327. help_text=_(
  328. 'Optional, singular version of rank name displayed by user names. '
  329. 'For example "GM" or "Dev".'
  330. )
  331. )
  332. description = forms.CharField(
  333. label=_("Description"),
  334. max_length=2048,
  335. required=False,
  336. widget=forms.Textarea(attrs={'rows': 3}),
  337. help_text=_(
  338. "Optional description explaining function or status of "
  339. "members distincted with this rank."
  340. )
  341. )
  342. roles = forms.ModelMultipleChoiceField(
  343. label=_("User roles"),
  344. widget=forms.CheckboxSelectMultiple,
  345. queryset=Role.objects.order_by('name'),
  346. required=False,
  347. help_text=_("Rank can give additional roles to users with it.")
  348. )
  349. css_class = forms.CharField(
  350. label=_("CSS class"),
  351. required=False,
  352. help_text=_("Optional css class added to content belonging to this rank owner.")
  353. )
  354. is_tab = forms.BooleanField(
  355. label=_("Give rank dedicated tab on users list"),
  356. required=False,
  357. help_text=_(
  358. "Selecting this option will make users with this rank easily discoverable "
  359. "by others through dedicated page on forum users list."
  360. )
  361. )
  362. class Meta:
  363. model = Rank
  364. fields = [
  365. 'name',
  366. 'description',
  367. 'css_class',
  368. 'title',
  369. 'roles',
  370. 'is_tab',
  371. ]
  372. def clean_name(self):
  373. data = self.cleaned_data['name']
  374. self.instance.set_name(data)
  375. unique_qs = Rank.objects.filter(slug=self.instance.slug)
  376. if self.instance.pk:
  377. unique_qs = unique_qs.exclude(pk=self.instance.pk)
  378. if unique_qs.exists():
  379. raise forms.ValidationError(_("This name collides with other rank."))
  380. return data
  381. class BanUsersForm(forms.Form):
  382. ban_type = forms.MultipleChoiceField(
  383. label=_("Values to ban"),
  384. widget=forms.CheckboxSelectMultiple,
  385. choices=[]
  386. )
  387. user_message = forms.CharField(
  388. label=_("User message"),
  389. required=False,
  390. max_length=1000,
  391. help_text=_("Optional message displayed to users instead of default one."),
  392. widget=forms.Textarea(attrs={'rows': 3}),
  393. error_messages={
  394. 'max_length': _("Message can't be longer than 1000 characters."),
  395. }
  396. )
  397. staff_message = forms.CharField(
  398. label=_("Team message"),
  399. required=False,
  400. max_length=1000,
  401. help_text=_("Optional ban message for moderators and administrators."),
  402. widget=forms.Textarea(attrs={'rows': 3}),
  403. error_messages={
  404. 'max_length': _("Message can't be longer than 1000 characters."),
  405. }
  406. )
  407. expires_on = IsoDateTimeField(
  408. label=_("Expires on"),
  409. required=False,
  410. help_text=_("Leave this field empty for set bans to never expire.")
  411. )
  412. def __init__(self, *args, **kwargs):
  413. users = kwargs.pop('users')
  414. super().__init__(*args, **kwargs)
  415. self.fields['ban_type'].choices = [
  416. ('usernames', _('Usernames')),
  417. ('emails', _('E-mails')),
  418. ('domains', _('E-mail domains')),
  419. ]
  420. enable_ip_bans = list(filter(None, [u.joined_from_ip for u in users]))
  421. if enable_ip_bans:
  422. self.fields['ban_type'].choices += [
  423. ('ip', _('IP addresses')),
  424. ('ip_first', _('First segment of IP addresses')),
  425. ('ip_two', _('First two segments of IP addresses')),
  426. ]
  427. class BanForm(forms.ModelForm):
  428. check_type = forms.TypedChoiceField(
  429. label=_("Check type"),
  430. coerce=int,
  431. choices=Ban.CHOICES,
  432. )
  433. registration_only = YesNoSwitch(
  434. label=_("Restrict this ban to registrations"),
  435. help_text=_(
  436. "Changing this to yes will make this ban check be only performed on registration "
  437. "step. This is good if you want to block certain registrations like ones from "
  438. "recently comprimised e-mail providers, without harming existing users."
  439. ),
  440. )
  441. banned_value = forms.CharField(
  442. label=_("Banned value"),
  443. max_length=250,
  444. help_text=_(
  445. 'This value is case-insensitive and accepts asterisk (*) '
  446. 'for rought matches. For example, making IP ban for value '
  447. '"83.*" will ban all IP addresses beginning with "83.".'
  448. ),
  449. error_messages={
  450. 'max_length': _("Banned value can't be longer than 250 characters."),
  451. }
  452. )
  453. user_message = forms.CharField(
  454. label=_("User message"),
  455. required=False,
  456. max_length=1000,
  457. help_text=_("Optional message displayed to user instead of default one."),
  458. widget=forms.Textarea(attrs={'rows': 3}),
  459. error_messages={
  460. 'max_length': _("Message can't be longer than 1000 characters."),
  461. }
  462. )
  463. staff_message = forms.CharField(
  464. label=_("Team message"),
  465. required=False,
  466. max_length=1000,
  467. help_text=_("Optional ban message for moderators and administrators."),
  468. widget=forms.Textarea(attrs={'rows': 3}),
  469. error_messages={
  470. 'max_length': _("Message can't be longer than 1000 characters."),
  471. }
  472. )
  473. expires_on = IsoDateTimeField(
  474. label=_("Expires on"),
  475. required=False,
  476. help_text=_("Leave this field empty for this ban to never expire.")
  477. )
  478. class Meta:
  479. model = Ban
  480. fields = [
  481. 'check_type',
  482. 'registration_only',
  483. 'banned_value',
  484. 'user_message',
  485. 'staff_message',
  486. 'expires_on',
  487. ]
  488. def clean_banned_value(self):
  489. data = self.cleaned_data['banned_value']
  490. while '**' in data:
  491. data = data.replace('**', '*')
  492. if data == '*':
  493. raise forms.ValidationError(_("Banned value is too vague."))
  494. return data
  495. class SearchBansForm(forms.Form):
  496. check_type = forms.ChoiceField(
  497. label=_("Type"),
  498. required=False,
  499. choices=[
  500. ('', _('All bans')),
  501. ('names', _('Usernames')),
  502. ('emails', _('E-mails')),
  503. ('ips', _('IPs')),
  504. ],
  505. )
  506. value = forms.CharField(label=_("Banned value begins with"), required=False)
  507. registration_only = forms.ChoiceField(
  508. label=_("Registration only"),
  509. required=False,
  510. choices=[
  511. ('', _('Any')),
  512. ('only', _('Yes')),
  513. ('exclude', _('No')),
  514. ]
  515. )
  516. state = forms.ChoiceField(
  517. label=_("State"),
  518. required=False,
  519. choices=[
  520. ('', _('Any')),
  521. ('used', _('Active')),
  522. ('unused', _('Expired')),
  523. ]
  524. )
  525. def filter_queryset(self, search_criteria, queryset):
  526. criteria = search_criteria
  527. if criteria.get('check_type') == 'names':
  528. queryset = queryset.filter(check_type=0)
  529. if criteria.get('check_type') == 'emails':
  530. queryset = queryset.filter(check_type=1)
  531. if criteria.get('check_type') == 'ips':
  532. queryset = queryset.filter(check_type=2)
  533. if criteria.get('value'):
  534. queryset = queryset.filter(banned_value__startswith=criteria.get('value').lower())
  535. if criteria.get('state') == 'used':
  536. queryset = queryset.filter(is_checked=True)
  537. if criteria.get('state') == 'unused':
  538. queryset = queryset.filter(is_checked=False)
  539. if criteria.get('registration_only') == 'only':
  540. queryset = queryset.filter(registration_only=True)
  541. if criteria.get('registration_only') == 'exclude':
  542. queryset = queryset.filter(registration_only=False)
  543. return queryset
  544. class RequestDataDownloadsForm(forms.Form):
  545. user_identifiers = forms.CharField(
  546. label=_("Usernames or emails"),
  547. help_text=_(
  548. "Enter every item in new line. Duplicates will be ignored. "
  549. "This field is case insensitive. Depending on site configuration and amount of data "
  550. "to archive it may take up to few days for requests to complete. E-mail "
  551. "will notification will be sent to every user once their download is ready."
  552. ),
  553. widget=forms.Textarea,
  554. )
  555. def clean_user_identifiers(self):
  556. user_identifiers = self.cleaned_data['user_identifiers'].lower().splitlines()
  557. user_identifiers = list(filter(bool, user_identifiers))
  558. user_identifiers = list(set(user_identifiers))
  559. if len(user_identifiers) > 20:
  560. raise forms.ValidationError(
  561. _(
  562. "You may not enter more than 20 items at single time "
  563. "(You have entered %(show_value)s)."
  564. ) % {'show_value': len(user_identifiers)}
  565. )
  566. return user_identifiers
  567. def clean(self):
  568. data = super().clean()
  569. if data.get('user_identifiers'):
  570. username_match = Q(slug__in=data['user_identifiers'])
  571. email_match = Q(email_hash__in=map(hash_email, data['user_identifiers']))
  572. data['users'] = list(UserModel.objects.filter(username_match | email_match))
  573. if len(data['users']) != len(data['user_identifiers']):
  574. raise forms.ValidationError(_("One or more specified users could not be found."))
  575. return data
  576. class SearchDataDownloadsForm(forms.Form):
  577. status = forms.ChoiceField(
  578. label=_("Status"),
  579. required=False,
  580. choices=DataDownload.STATUS_CHOICES,
  581. )
  582. user = forms.CharField(
  583. label=_("User"),
  584. required=False,
  585. )
  586. requested_by = forms.CharField(
  587. label=_("Requested by"),
  588. required=False,
  589. )
  590. def filter_queryset(self, search_criteria, queryset):
  591. criteria = search_criteria
  592. if criteria.get('status') is not None:
  593. queryset = queryset.filter(status=criteria['status'])
  594. if criteria.get('user'):
  595. queryset = queryset.filter(user__slug__istartswith=criteria['user'])
  596. if criteria.get('requested_by'):
  597. queryset = queryset.filter(requester__slug__istartswith=criteria['requested_by'])
  598. return queryset