class GroupAdminForm(ModelForm): class Meta: model = Group exclude = [] # Add the users field users = ModelMultipleChoiceField( queryset=User.objects.all(), required=False, # Use the pretty ``filter_horizontal`` widget widget=FilteredSelectMultiple("users", False), label=_("Users", ), ) def __init__(self, *args, **kwargs): # Do the normal form initialisation super(GroupAdminForm, self).__init__(*args, **kwargs) # If it is an existing group (saved objects have a pk) if self.instance.pk: # Populate the users field with the current Group users self.fields["users"].initial = self.instance.user_set.all() def save_m2m(self): # Add the users to the Group self.instance.user_set.set(self.cleaned_data["users"]) def save(self, *args, **kwargs): # Default save instance = super(GroupAdminForm, self).save() # Save many-to-many data self.save_m2m() return instance
class ExtendedSiteAdminForm(add_bidirectional_m2m(registered_form(Site))): snippets = ModelMultipleChoiceField( queryset=SmartSnippet.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Snippets', is_stacked=False ) ) def _get_bidirectional_m2m_fields(self): return super(ExtendedSiteAdminForm, self).\ _get_bidirectional_m2m_fields() + [('snippets', 'smartsnippet_set')] def clean_snippets(self): assigned_snippets = self.cleaned_data['snippets'] if self.instance.pk is None or include_orphan: return assigned_snippets pks = [s.pk for s in assigned_snippets] # snippets that were previously assigned to this site, but got unassigned unassigned_snippets = self.instance.smartsnippet_set.exclude(pk__in=pks) snippets_with_no_sites = [] for snippet in unassigned_snippets: if snippet.sites.count() == 1: snippets_with_no_sites.append(snippet) if snippets_with_no_sites: raise ValidationError( "Following snippets will remain with no sites assigned: %s" % ", ".join(s.name for s in snippets_with_no_sites)) return assigned_snippets
class FlujoCreateForm(forms.ModelForm): actividades = ModelMultipleChoiceField(Actividad.objects.all(), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = Flujo fields = [ 'nombre', 'actividades']
class ProblemGroupForm(ModelForm): problems = ModelMultipleChoiceField( label=_('Included problems'), queryset=Problem.objects.all(), required=False, help_text=_('These problems are included in this group of problems'), widget=AdminHeavySelect2MultipleWidget(data_view='problem_select2'))
def test_modelchoicefield(self): # Create choices for the model choice field tests below. ChoiceModel.objects.create(pk=1, name='a') ChoiceModel.objects.create(pk=2, name='b') ChoiceModel.objects.create(pk=3, name='c') # ModelChoiceField e = { 'required': 'REQUIRED', 'invalid_choice': 'INVALID CHOICE', } f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['INVALID CHOICE'], f.clean, '4') # ModelMultipleChoiceField e = { 'required': 'REQUIRED', 'invalid_choice': '%(value)s IS INVALID CHOICE', 'invalid_list': 'NOT A LIST OF VALUES', } f = ModelMultipleChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['NOT A LIST OF VALUES'], f.clean, '3') self.assertFormErrors(['4 IS INVALID CHOICE'], f.clean, ['4'])
def __init__(self, *args, **kwargs): ModelForm.__init__(self, *args, **kwargs) self.fields['protected_class'] = ModelMultipleChoiceField( error_messages={'required': PROTECTED_CLASS_ERROR}, required=True, label="", queryset=ProtectedClass.objects.filter( protected_class__in=PROTECTED_CLASS_CHOICES).order_by( 'form_order'), widget=UsaCheckboxSelectMultiple( attrs={'aria-describedby': 'protected-class-help-text'}), ) self.fields['other_class'].help_text = _( 'Please describe "Other reason"') self.fields['other_class'].widget = TextInput( attrs={'class': 'usa-input word-count-10'}) self.question_groups = [ QuestionGroup( self, ('protected_class', ), group_name= _('Do you believe any of these personal characteristics influenced why you were treated this way?' ), help_text= _('Some civil rights laws protect people from discrimination, which include these protected classes. These are some of the most common classes that we see.' ), optional=False, ally_id="protected-class-help-text") ]
class GroupForm(ModelForm): class Meta: model = Group fields = '__all__' group_users = ModelMultipleChoiceField(label='使用者', queryset=User.objects.all(), required=False) def __init__(self, *args, **kwargs): super(GroupForm, self).__init__(*args, **kwargs) # 將使用者不需要的model排除 content_types = get_content_types(settings.MODELS) self.fields['permissions'].queryset = Permission.objects.filter(content_type__in=content_types) # 顯示群組裡的使用者 if self.instance.id: user_ids = [user.id for user in self.instance.user_set.all()] self.fields['group_users'].initial = user_ids def save(self, commit=True): group = super().save(commit=False) if commit: group.save() # 寫入多對多表 self.save_m2m() # 加入使用者 group_users = group.user_set.all() group_set_users = self.cleaned_data["group_users"] group_remove_users = group_users.exclude(id__in=group_set_users) group_add_users = group_set_users.exclude(id__in=group_users) for user in group_remove_users: group.user_set.remove(user) for user in group_add_users: group.user_set.add(user) return group
class ProjectGroupAdminForm(ModelForm): managers = ModelMultipleChoiceField(User.objects.all().order_by('full_name'), required=False, widget=FilteredSelectMultiple(verbose_name='Managers', is_stacked=False)) def __init__(self, *args, **kwargs): super(ProjectGroupAdminForm, self).__init__(*args, **kwargs) if self.instance and self.instance.pk: self.managers = self.instance.roles.get( role_type=models.ProjectGroupRole.MANAGER).permission_group.user_set.all() self.fields['managers'].initial = self.managers else: self.managers = User.objects.none() def save(self, commit=True): group = super(ProjectGroupAdminForm, self).save(commit=False) if not group.pk: group.save() new_managers = self.cleaned_data['managers'] added_managers = new_managers.exclude(pk__in=self.managers) removed_managers = self.managers.exclude(pk__in=new_managers) for user in added_managers: group.add_user(user, role_type=models.ProjectGroupRole.MANAGER) for user in removed_managers: group.remove_user(user, role_type=models.ProjectGroupRole.MANAGER) self.save_m2m() return group
class ContestTagForm(ModelForm): contests = ModelMultipleChoiceField( label=_('Included contests'), queryset=Contest.objects.all(), required=False, widget=HeavySelect2MultipleWidget(data_view='contest_select2') if use_select2 else FilteredSelectMultiple('contests', False))
class AddGroupSurveyForm(ModelForm): groups = ModelMultipleChoiceField( label=_('Survey'), queryset=Group.objects.all(), widget=FilteredSelectMultiple('Group', is_stacked=True), required=False ) def __init__(self, *args, **kwargs): instance = kwargs.get('instance') if instance: initial = kwargs.setdefault('initial', {}) initial['groups'] = [group.pk for group in instance.groups.all()] super().__init__(*args, **kwargs) class Meta: model = Survey fields = ( 'name_en', 'name_fr', 'name_nl', 'groups' ) def save(self, commit=True): instance = super().save(False) _save_m2m = self.save_m2m def save_m2m(): _save_m2m() instance.groups.clear() instance.groups.add(*self.cleaned_data['groups']) self.save_m2m = save_m2m if commit: instance.save() self.save_m2m() return instance
class Meta: model = gnuhealth_operational_sector fields = "__all__" operational_area = ModelMultipleChoiceField( queryset=gnuhealth_operational_area.objects.values_list('name', flat=True), widget=Select2MultipleWidget)
def __init__(self, *args, **kwargs): ModelForm.__init__(self, *args, **kwargs) self.fields['protected_class'] = ModelMultipleChoiceField( error_messages={'required': PROTECTED_CLASS_ERROR}, required=True, label="", queryset=ProtectedClass.objects.filter(protected_class__in=PROTECTED_CLASS_CHOICES).order_by('form_order'), widget=UsaCheckboxSelectMultiple(attrs={ 'aria-describedby': 'protected-class-help-text' }), ) self.fields['other_class'].help_text = _('Please describe "Other reason"') self.fields['other_class'].widget = TextInput( attrs={'class': 'usa-input word-count-10'} ) self.question_groups = [ QuestionGroup( self, ('protected_class',), group_name=PROTECTED_CLASS_QUESTION, help_text=_('There are federal and state laws that protect people from discrimination based on their personal characteristics. Here is a list of the most common characteristics that are legally protected. Select any that apply to your incident.'), optional=False, ally_id="protected-class-help-text" ) ]
class TgroupForm(forms.ModelForm): tgrname = forms.CharField(label=_("Tag group"), required=False, widget=forms.TextInput( attrs={ 'class': 'searching input-sm', 'placeholder': 'Tag group...', 'style': 'width: 100%;' })) tgrlist = ModelMultipleChoiceField(queryset=None, required=False) class Meta: model = Tgroup ATTRS_FOR_FORMS = { 'class': 'form-control' } fields = ['name'] widgets = { 'name': forms.TextInput( attrs={ 'class': 'searching input-sm', 'placeholder': 'Tag group...', 'style': 'width: 100%;' }) } def __init__(self, *args, **kwargs): # Start by executing the standard handling super(TgroupForm, self).__init__(*args, **kwargs) # Some fields are not required self.fields['name'].required = False self.fields['tgrname'].required = False self.fields['tgrlist'].queryset = Tgroup.objects.all().order_by('name')
class NetIfForm(ModelForm): nic = ModelMultipleChoiceField( queryset=NetworkInterfaceCard.objects.exclude(dev__in=[ 'lo0', 'lo1', 'lo2', 'lo3', 'lo4', 'lo5', 'lo6', 'pflog0', 'vm-public', 'tap0', 'tun0' ]), widget=SelectMultiple(attrs={'class': 'form-control select2'}), ) class Meta: model = NetworkAddress fields = ('name', 'nic', 'ip', 'prefix_or_netmask', 'carp_vhid') widgets = { 'name': TextInput(attrs={'class': 'form-control'}), 'ip': TextInput(attrs={'class': 'form-control'}), 'carp_vhid': NumberInput(attrs={'class': 'form-control'}), 'prefix_or_netmask': TextInput(attrs={'class': 'form-control'}), } def clean_prefix_or_netmask(self): value = self.cleaned_data.get('prefix_or_netmask') if value: if netmask2prefix(value) == 0: try: test = int(value.replace('/', '')) except: raise ValidationError( "Netmask/Prefix invalid. (ex: 255.255.255.0 or 24 or 64 (ipv6))" ) return value
class PostForm(ModelForm): class Meta: model = Post exclude = ['author'] tags = ModelMultipleChoiceField(queryset=Tag.objects)
def __init__(self, **kwargs): items = kwargs['items'] del kwargs['items'] instance = kwargs.get('instance', None) self.original_instance = copy.copy(instance) if instance else None super().__init__(**kwargs) if hasattr(self, 'instance') and self.instance.pk: active_items = set(self.instance.items.all()) active_variations = set(self.instance.variations.all()) else: active_items = set() active_variations = set() for item in items: if len(item.variations.all()) > 0: self.fields['item_%s' % item.id] = ModelMultipleChoiceField( label=_("Activate for"), required=False, initial=active_variations, queryset=item.variations.all(), widget=forms.CheckboxSelectMultiple ) else: self.fields['item_%s' % item.id] = BooleanField( label=_("Activate"), required=False, initial=(item in active_items) )
def __init__(self, *args, **kwargs): ModelForm.__init__(self, *args, **kwargs) self.fields['hatecrimes_trafficking'] = ModelMultipleChoiceField( queryset=HateCrimesandTrafficking.objects.filter( hatecrimes_trafficking_option__in= HATE_CRIMES_TRAFFICKING_CHOICES), widget=UsaCheckboxSelectMultiple( attrs={'aria-describedby': 'hatecrimes-help-text'}), required=False, label=_( 'Please select if any that apply to your situation (optional)') ) self.question_groups = [ QuestionGroup( self, ('hatecrimes_trafficking', ), group_name=_('Hate Crimes & Human Trafficking'), help_text= _('Hate crimes and human trafficking are considered criminal cases and go through a different process for investigation than other civil rights cases. If we determine your situation falls into these categories after submitting your concern, we will contact you with next steps.' ), optional=False, cls="text-bold", ally_id="hatecrimes-help-text") ]
class CustomerAdminForm(ModelForm): owners = ModelMultipleChoiceField(User.objects.all().order_by('full_name'), required=False, widget=FilteredSelectMultiple(verbose_name='Owners', is_stacked=False)) def __init__(self, *args, **kwargs): super(CustomerAdminForm, self).__init__(*args, **kwargs) if self.instance and self.instance.pk: self.owners = self.instance.roles.get( role_type=models.CustomerRole.OWNER).permission_group.user_set.all() self.fields['owners'].initial = self.owners else: self.owners = User.objects.none() def save(self, commit=True): customer = super(CustomerAdminForm, self).save(commit=False) if not customer.pk: customer.save() new_owners = self.cleaned_data['owners'] added_owners = new_owners.exclude(pk__in=self.owners) removed_owners = self.owners.exclude(pk__in=new_owners) for user in added_owners: customer.add_user(user, role_type=models.CustomerRole.OWNER) for user in removed_owners: customer.remove_user(user, role_type=models.CustomerRole.OWNER) self.save_m2m() return customer
class UploadRawImagesForm(SaveFormInitMixin, forms.ModelForm): user_uploads = ModelMultipleChoiceField( widget=UserUploadMultipleWidget, label="Image files", help_text=IMAGE_UPLOAD_HELP_TEXT, queryset=None, ) def __init__(self, *args, user, linked_task=None, **kwargs): super().__init__(*args, **kwargs) self.fields["user_uploads"].queryset = get_objects_for_user( user, "uploads.change_userupload", accept_global_perms=False).filter( status=UserUpload.StatusChoices.COMPLETED) self._linked_task = linked_task def clean_user_uploads(self): user_uploads = self.cleaned_data["user_uploads"] if len({f.filename for f in user_uploads}) != len(user_uploads): raise ValidationError("Filenames must be unique.") return user_uploads def save(self, *args, **kwargs): instance = super().save(*args, **kwargs) instance.process_images(linked_task=self._linked_task) return instance class Meta: model = RawImageUploadSession fields = ("user_uploads", )
class QuestionFlagForm(ModelForm): flag_reason = ModelMultipleChoiceField( queryset=QuestionFlagReason.objects.all()) class Meta: model = QuestionFlag fields = ["flag", "flag_reason", "comment"]
class EmailForm(ModelForm): """ Email Form =========== Email model form, extended to prefill initial values based on visitor lead id (optional). **LEAD ID** 1. *External attachments* Lead id is used to show appropriate External attachments along with the composer layout. Incase lead ID is not provided, no external attachments will appear. 2. *Templates* Email templates are mapped against the project, lead id is used to get the project id, and prefill (or in templates section) the available templates for the given project. """ ext_attachments = ModelMultipleChoiceField( widget=CheckboxSelectMultiple, queryset=ExternalAttachment.objects.all().exclude()) def __init__(self, *args, **kwargs): lead_idx = None print(kwargs) initial = kwargs.get("initial") if initial: lead_idx = initial.get("lead_id") if lead_idx: super(EmailForm, self).__init__(*args, **kwargs) try: lead_idx = int(lead_idx) except TypeError: pass lead = Lead.objects.filter(id=lead_idx).last() self.fields["mail_id"].queryset = \ Emailaddress.objects.filter(id__in=lead.email.all()) self.fields["ext_attachments"].queryset = \ ExternalAttachment.objects.filter( property_name=lead.project) self.fields['ext_attachments'].required = False # self.fields["lead_id"].widget = HiddenInput() else: super().__init__(*args, **kwargs) # def clean_message_content(self): # data = self.cleaned_data["message_content"] # return base64.b64decode(data) class Meta: model = Email fields = "__all__" exclude = ["tries", "status"]
class SongForm(ModelForm): """Song form""" categories = ModelMultipleChoiceField(widget=CheckboxSelectMultiple, queryset=Category.objects.all()) class Meta: model = Song # pylint: disable=modelform-uses-exclude exclude = ["prerendered_web", "prerendered_pdf"]
def __init__(self, *args, **kwargs): self.wealth = kwargs.pop('wealth', None) super(AssociateTagForm, self).__init__(*args, **kwargs) self.fields['associate'] = BooleanField(initial=False, required=False) self.fields['tag'] = ModelChoiceField(queryset=Tag.objects.filter( wealth=self.wealth)) self.fields['transactions'] = ModelMultipleChoiceField( queryset=Transaction.objects.filter(wealth=self.wealth))
def test_list_error_message_warning(self): msg = ("The 'list' error message key is deprecated in favor of " "'invalid_list'.") with self.assertRaisesMessage(RemovedInDjango40Warning, msg): ModelMultipleChoiceField( queryset=ChoiceModel.objects.all(), error_messages={'list': 'NOT A LIST OF VALUES'}, )
class UserForm(ModelForm): sub = ModelMultipleChoiceField(queryset=Board.objects.all(), required=False) class Meta: model = User fields = ('sub', )
class FilmOnChannelForm(ModelForm): class Meta: fields = ('key', 'title', 'year', 'directors', 'film', 'match', 'candidates', 'imdb_code') candidates = ModelMultipleChoiceField(Film.objects, widget=CandidatesWidget, required=False)
class LanguageForm(ModelForm): problems = ModelMultipleChoiceField( label=_('Disallowed problems'), queryset=Problem.objects.all(), required=False, help_text=_( 'These problems are NOT allowed to be submitted in this language'), widget=HeavySelect2MultipleWidget(data_view='problem_select2'))
class TodoForm(ModelForm): start_date = DateTimeField(initial=datetime.now(), required=False, help_text="Optional") stop_date = DateTimeField(initial=datetime.now(), required=False, help_text="Optional") categories = ModelMultipleChoiceField( Entry.objects.all().order_by('title'), required=False, widget=MultipleSelectWithPop, help_text= "The categories which this todo belongs to. It also be used to assign arbitrary kind of labels" ) executor = ModelMultipleChoiceField( User.objects.all().order_by('username'), required=False, help_text="The assigned user who should execute the todo (Optional).") def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( Fieldset( '', 'title', 'description', 'priority', 'value', 'difficulty', 'progress', 'start_date', 'stop_date', 'creator', 'executor', 'categories', 'onhold', 'done', ), FormActions(Submit('submit', 'Submit', css_class="btn-primary"), Submit('cancel', 'Cancel', css_class="btn-danger"))) super(TodoForm, self).__init__(*args, **kwargs) class Meta: model = Todo
def __init__(self, *args, **kwargs): ingredient = ModelMultipleChoiceField( queryset=Ingredient.objects.all(), widget=CheckboxSelectMultiple(), label="Ingredientes") super(ProductForm, self).__init__(*args, **kwargs) self.fields['description'].widget.attrs.update({'rows': 3, 'cols': 5}) self.fields['ingredient'] = ingredient
class SecretRoleInfoForm(SelectRoleForm): conference = ModelMultipleChoiceField( queryset=Conference.objects.all().order_by('conference_name'), widget=MultipleHiddenInput(), required=True) roles = MultipleChoiceField(widget=MultipleHiddenInput(), required=True, choices=role_options)