prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Bug: assignment form queryset may return duplicate results
  Introduced in v2.16, AssignmentForm contains a queryset that may yield duplicate results due to the filtering used.
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `amy/dashboard/forms.py`
  Content:
  ```
  1 from django import forms
  2 from django.core.exceptions import ValidationError
  3 from django.db.models import Q
  4 from django_countries.fields import CountryField
  5 
  6 from workshops.models import (
  7     Language,
  8     GenderMixin,
  9     Person,
  10     TrainingProgress,
  11     TrainingRequirement,
  12 )
  13 
  14 from workshops.forms import BootstrapHelper
  15 # this is used instead of Django Autocomplete Light widgets
  16 # see issue #1330: https://github.com/swcarpentry/amy/issues/1330
  17 from workshops.fields import (
  18     Select2Widget,
  19     ModelSelect2MultipleWidget,
  20     RadioSelectWithOther,
  21 )
  22 
  23 
  24 class AssignmentForm(forms.Form):
  25     assigned_to = forms.ModelChoiceField(
  26         label="Assigned to:",
  27         required=False,
  28         queryset=Person.objects.filter(
  29             Q(is_superuser=True) | Q(groups__name="administrators")
  30         ),
  31         widget=Select2Widget(),
  32     )
  33     helper = BootstrapHelper(
  34         add_submit_button=False,
  35         add_cancel_button=False,
  36         wider_labels=True,
  37         use_get_method=True,
  38         form_id="assignment-form"
  39     )
  40 
  41 
  42 class AutoUpdateProfileForm(forms.ModelForm):
  43     username = forms.CharField(disabled=True, required=False)
  44     email = forms.CharField(
  45         disabled=True, required=False,
  46         label=Person._meta.get_field('email').verbose_name,
  47         help_text=Person._meta.get_field('email').help_text,
  48     )
  49     github = forms.CharField(
  50         disabled=True, required=False,
  51         help_text='If you want to change your github username, please email '
  52                   'us at <a href="mailto:team@carpentries.org">'
  53                   'team@carpentries.org</a>.')
  54 
  55     country = CountryField().formfield(
  56         required=False,
  57         help_text='Your country of residence.',
  58         widget=Select2Widget,
  59     )
  60 
  61     languages = forms.ModelMultipleChoiceField(
  62         label='Languages',
  63         required=False,
  64         queryset=Language.objects.all(),
  65         widget=ModelSelect2MultipleWidget(data_view='language-lookup')
  66     )
  67 
  68     helper = BootstrapHelper(add_cancel_button=False)
  69 
  70     class Meta:
  71         model = Person
  72         fields = [
  73             'personal',
  74             'middle',
  75             'family',
  76             'email',
  77             'secondary_email',
  78             'gender',
  79             'gender_other',
  80             'may_contact',
  81             'publish_profile',
  82             'lesson_publication_consent',
  83             'country',
  84             'airport',
  85             'github',
  86             'twitter',
  87             'url',
  88             'username',
  89             'affiliation',
  90             'domains',
  91             'lessons',
  92             'languages',
  93             'occupation',
  94             'orcid',
  95         ]
  96         readonly_fields = (
  97             'username',
  98             'github',
  99         )
  100         widgets = {
  101             'gender': RadioSelectWithOther('gender_other'),
  102             'domains': forms.CheckboxSelectMultiple(),
  103             'lessons': forms.CheckboxSelectMultiple(),
  104             'airport': Select2Widget,
  105         }
  106 
  107     def __init__(self, *args, **kwargs):
  108         super().__init__(*args, **kwargs)
  109 
  110         # set up a layout object for the helper
  111         self.helper.layout = self.helper.build_default_layout(self)
  112 
  113         # set up `*WithOther` widgets so that they can display additional
  114         # fields inline
  115         self['gender'].field.widget.other_field = self['gender_other']
  116 
  117         # remove additional fields
  118         self.helper.layout.fields.remove('gender_other')
  119 
  120     def clean(self):
  121         super().clean()
  122         errors = dict()
  123 
  124         # 1: require "other gender" field if "other" was selected in
  125         # "gender" field
  126         gender = self.cleaned_data.get('gender', '')
  127         gender_other = self.cleaned_data.get('gender_other', '')
  128         if gender == GenderMixin.OTHER and not gender_other:
  129             errors['gender'] = ValidationError("This field is required.")
  130         elif gender != GenderMixin.OTHER and gender_other:
  131             errors['gender'] = ValidationError(
  132                 'If you entered data in "Other" field, please select that '
  133                 "option.")
  134 
  135         # raise errors if any present
  136         if errors:
  137             raise ValidationError(errors)
  138 
  139 
  140 class SendHomeworkForm(forms.ModelForm):
  141     url = forms.URLField(label='URL')
  142     requirement = forms.ModelChoiceField(
  143         queryset=TrainingRequirement.objects.filter(name__endswith="Homework"),
  144         label="Type", required=True,
  145     )
  146 
  147     helper = BootstrapHelper(add_cancel_button=False)
  148 
  149     class Meta:
  150         model = TrainingProgress
  151         fields = [
  152             'requirement',
  153             'url',
  154         ]
  155 
  156 
  157 class SearchForm(forms.Form):
  158     """Represent general searching form."""
  159 
  160     term = forms.CharField(label="Term", max_length=100)
  161     no_redirect = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)
  162     helper = BootstrapHelper(add_cancel_button=False, use_get_method=True)
  163
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/amy/dashboard/forms.py b/amy/dashboard/forms.py
  --- a/amy/dashboard/forms.py
  +++ b/amy/dashboard/forms.py
  @@ -27,7 +27,7 @@
           required=False,
           queryset=Person.objects.filter(
               Q(is_superuser=True) | Q(groups__name="administrators")
  -        ),
  +        ).distinct(),
           widget=Select2Widget(),
       )
       helper = BootstrapHelper(
  
verification_info: {"golden_diff": "diff --git a/amy/dashboard/forms.py b/amy/dashboard/forms.py\n--- a/amy/dashboard/forms.py\n+++ b/amy/dashboard/forms.py\n@@ -27,7 +27,7 @@\n         required=False,\n         queryset=Person.objects.filter(\n             Q(is_superuser=True) | Q(groups__name=\"administrators\")\n-        ),\n+        ).distinct(),\n         widget=Select2Widget(),\n     )\n     helper = BootstrapHelper(\n", "issue": "Bug: assignment form queryset may return duplicate results\nIntroduced in v2.16, AssignmentForm contains a queryset that may yield duplicate results due to the filtering used.\n", "before_files": [{"content": "from django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.db.models import Q\nfrom django_countries.fields import CountryField\n\nfrom workshops.models import (\n    Language,\n    GenderMixin,\n    Person,\n    TrainingProgress,\n    TrainingRequirement,\n)\n\nfrom workshops.forms import BootstrapHelper\n# this is used instead of Django Autocomplete Light widgets\n# see issue #1330: https://github.com/swcarpentry/amy/issues/1330\nfrom workshops.fields import (\n    Select2Widget,\n    ModelSelect2MultipleWidget,\n    RadioSelectWithOther,\n)\n\n\nclass AssignmentForm(forms.Form):\n    assigned_to = forms.ModelChoiceField(\n        label=\"Assigned to:\",\n        required=False,\n        queryset=Person.objects.filter(\n            Q(is_superuser=True) | Q(groups__name=\"administrators\")\n        ),\n        widget=Select2Widget(),\n    )\n    helper = BootstrapHelper(\n        add_submit_button=False,\n        add_cancel_button=False,\n        wider_labels=True,\n        use_get_method=True,\n        form_id=\"assignment-form\"\n    )\n\n\nclass AutoUpdateProfileForm(forms.ModelForm):\n    username = forms.CharField(disabled=True, required=False)\n    email = forms.CharField(\n        disabled=True, required=False,\n        label=Person._meta.get_field('email').verbose_name,\n        help_text=Person._meta.get_field('email').help_text,\n    )\n    github = forms.CharField(\n        disabled=True, required=False,\n        help_text='If you want to change your github username, please email '\n                  'us at <a href=\"mailto:team@carpentries.org\">'\n                  'team@carpentries.org</a>.')\n\n    country = CountryField().formfield(\n        required=False,\n        help_text='Your country of residence.',\n        widget=Select2Widget,\n    )\n\n    languages = forms.ModelMultipleChoiceField(\n        label='Languages',\n        required=False,\n        queryset=Language.objects.all(),\n        widget=ModelSelect2MultipleWidget(data_view='language-lookup')\n    )\n\n    helper = BootstrapHelper(add_cancel_button=False)\n\n    class Meta:\n        model = Person\n        fields = [\n            'personal',\n            'middle',\n            'family',\n            'email',\n            'secondary_email',\n            'gender',\n            'gender_other',\n            'may_contact',\n            'publish_profile',\n            'lesson_publication_consent',\n            'country',\n            'airport',\n            'github',\n            'twitter',\n            'url',\n            'username',\n            'affiliation',\n            'domains',\n            'lessons',\n            'languages',\n            'occupation',\n            'orcid',\n        ]\n        readonly_fields = (\n            'username',\n            'github',\n        )\n        widgets = {\n            'gender': RadioSelectWithOther('gender_other'),\n            'domains': forms.CheckboxSelectMultiple(),\n            'lessons': forms.CheckboxSelectMultiple(),\n            'airport': Select2Widget,\n        }\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        # set up a layout object for the helper\n        self.helper.layout = self.helper.build_default_layout(self)\n\n        # set up `*WithOther` widgets so that they can display additional\n        # fields inline\n        self['gender'].field.widget.other_field = self['gender_other']\n\n        # remove additional fields\n        self.helper.layout.fields.remove('gender_other')\n\n    def clean(self):\n        super().clean()\n        errors = dict()\n\n        # 1: require \"other gender\" field if \"other\" was selected in\n        # \"gender\" field\n        gender = self.cleaned_data.get('gender', '')\n        gender_other = self.cleaned_data.get('gender_other', '')\n        if gender == GenderMixin.OTHER and not gender_other:\n            errors['gender'] = ValidationError(\"This field is required.\")\n        elif gender != GenderMixin.OTHER and gender_other:\n            errors['gender'] = ValidationError(\n                'If you entered data in \"Other\" field, please select that '\n                \"option.\")\n\n        # raise errors if any present\n        if errors:\n            raise ValidationError(errors)\n\n\nclass SendHomeworkForm(forms.ModelForm):\n    url = forms.URLField(label='URL')\n    requirement = forms.ModelChoiceField(\n        queryset=TrainingRequirement.objects.filter(name__endswith=\"Homework\"),\n        label=\"Type\", required=True,\n    )\n\n    helper = BootstrapHelper(add_cancel_button=False)\n\n    class Meta:\n        model = TrainingProgress\n        fields = [\n            'requirement',\n            'url',\n        ]\n\n\nclass SearchForm(forms.Form):\n    \"\"\"Represent general searching form.\"\"\"\n\n    term = forms.CharField(label=\"Term\", max_length=100)\n    no_redirect = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)\n    helper = BootstrapHelper(add_cancel_button=False, use_get_method=True)\n", "path": "amy/dashboard/forms.py"}], "after_files": [{"content": "from django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.db.models import Q\nfrom django_countries.fields import CountryField\n\nfrom workshops.models import (\n    Language,\n    GenderMixin,\n    Person,\n    TrainingProgress,\n    TrainingRequirement,\n)\n\nfrom workshops.forms import BootstrapHelper\n# this is used instead of Django Autocomplete Light widgets\n# see issue #1330: https://github.com/swcarpentry/amy/issues/1330\nfrom workshops.fields import (\n    Select2Widget,\n    ModelSelect2MultipleWidget,\n    RadioSelectWithOther,\n)\n\n\nclass AssignmentForm(forms.Form):\n    assigned_to = forms.ModelChoiceField(\n        label=\"Assigned to:\",\n        required=False,\n        queryset=Person.objects.filter(\n            Q(is_superuser=True) | Q(groups__name=\"administrators\")\n        ).distinct(),\n        widget=Select2Widget(),\n    )\n    helper = BootstrapHelper(\n        add_submit_button=False,\n        add_cancel_button=False,\n        wider_labels=True,\n        use_get_method=True,\n        form_id=\"assignment-form\"\n    )\n\n\nclass AutoUpdateProfileForm(forms.ModelForm):\n    username = forms.CharField(disabled=True, required=False)\n    email = forms.CharField(\n        disabled=True, required=False,\n        label=Person._meta.get_field('email').verbose_name,\n        help_text=Person._meta.get_field('email').help_text,\n    )\n    github = forms.CharField(\n        disabled=True, required=False,\n        help_text='If you want to change your github username, please email '\n                  'us at <a href=\"mailto:team@carpentries.org\">'\n                  'team@carpentries.org</a>.')\n\n    country = CountryField().formfield(\n        required=False,\n        help_text='Your country of residence.',\n        widget=Select2Widget,\n    )\n\n    languages = forms.ModelMultipleChoiceField(\n        label='Languages',\n        required=False,\n        queryset=Language.objects.all(),\n        widget=ModelSelect2MultipleWidget(data_view='language-lookup')\n    )\n\n    helper = BootstrapHelper(add_cancel_button=False)\n\n    class Meta:\n        model = Person\n        fields = [\n            'personal',\n            'middle',\n            'family',\n            'email',\n            'secondary_email',\n            'gender',\n            'gender_other',\n            'may_contact',\n            'publish_profile',\n            'lesson_publication_consent',\n            'country',\n            'airport',\n            'github',\n            'twitter',\n            'url',\n            'username',\n            'affiliation',\n            'domains',\n            'lessons',\n            'languages',\n            'occupation',\n            'orcid',\n        ]\n        readonly_fields = (\n            'username',\n            'github',\n        )\n        widgets = {\n            'gender': RadioSelectWithOther('gender_other'),\n            'domains': forms.CheckboxSelectMultiple(),\n            'lessons': forms.CheckboxSelectMultiple(),\n            'airport': Select2Widget,\n        }\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n\n        # set up a layout object for the helper\n        self.helper.layout = self.helper.build_default_layout(self)\n\n        # set up `*WithOther` widgets so that they can display additional\n        # fields inline\n        self['gender'].field.widget.other_field = self['gender_other']\n\n        # remove additional fields\n        self.helper.layout.fields.remove('gender_other')\n\n    def clean(self):\n        super().clean()\n        errors = dict()\n\n        # 1: require \"other gender\" field if \"other\" was selected in\n        # \"gender\" field\n        gender = self.cleaned_data.get('gender', '')\n        gender_other = self.cleaned_data.get('gender_other', '')\n        if gender == GenderMixin.OTHER and not gender_other:\n            errors['gender'] = ValidationError(\"This field is required.\")\n        elif gender != GenderMixin.OTHER and gender_other:\n            errors['gender'] = ValidationError(\n                'If you entered data in \"Other\" field, please select that '\n                \"option.\")\n\n        # raise errors if any present\n        if errors:\n            raise ValidationError(errors)\n\n\nclass SendHomeworkForm(forms.ModelForm):\n    url = forms.URLField(label='URL')\n    requirement = forms.ModelChoiceField(\n        queryset=TrainingRequirement.objects.filter(name__endswith=\"Homework\"),\n        label=\"Type\", required=True,\n    )\n\n    helper = BootstrapHelper(add_cancel_button=False)\n\n    class Meta:\n        model = TrainingProgress\n        fields = [\n            'requirement',\n            'url',\n        ]\n\n\nclass SearchForm(forms.Form):\n    \"\"\"Represent general searching form.\"\"\"\n\n    term = forms.CharField(label=\"Term\", max_length=100)\n    no_redirect = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)\n    helper = BootstrapHelper(add_cancel_button=False, use_get_method=True)\n", "path": "amy/dashboard/forms.py"}]}