class Meta: fields = ('name', 'specialty', 'image', 'sub_categories', 'parent') model = Category widgets = { 'parent': apply_select2(forms.Select), 'specialty': apply_select2(forms.Select), }
class RepCaseForm(forms.ModelForm): owners = forms.ModelMultipleChoiceField( widget=apply_select2(forms.SelectMultiple), queryset=Account.objects.all().prefetch_related('role', 'user')) physician = forms.ModelChoiceField( widget=apply_select2(forms.Select), queryset=Account.objects.all().prefetch_related('role', 'user')) class Meta: model = RepCase fields = ('client', 'owners', 'procedure_date', 'status') widgets = { 'client': apply_select2(forms.Select), 'client_id': forms.HiddenInput() } def clean(self): data = self.cleaned_data client = data.get('client') if client: owners = data.get('owners', []) for owner in owners: try: client.account_set.get(pk=owner.pk) except ObjectDoesNotExist: raise ValidationError(f'Invalid {owner} for {client}')
class Meta: model = Account fields = ('user', 'role', 'client', 'specialties') widgets = { 'user': apply_select2(forms.Select), 'role': apply_select2(forms.Select), 'client': apply_select2(forms.Select), }
class Meta: model = models.UserFenRun fields = ["user", "point", "rmb", "message"] widgets = { 'user': apply_select2(forms.Select), 'point': apply_select2(forms.Select), 'rmb': apply_select2(forms.Select), }
class Meta: model = Rebate fields = ('name', 'manufacturer', 'client', 'start_date', 'end_date') widgets = { 'eligible_items': apply_select2(forms.SelectMultiple), 'rebated_items': apply_select2(forms.SelectMultiple), 'client': apply_select2(forms.Select), 'manufacturer': apply_select2(forms.Select), }
class Meta: model = RepCase fields = ('client', 'owners', 'procedure_date', 'status') widgets = { 'client': apply_select2(forms.Select), 'client_id': forms.HiddenInput() }
class CustomerWithUserDataForm(UserDataForm): delivery_point = forms.ModelChoiceField( LUT_DeliveryPoint.objects.filter(customer_responsible__isnull=False), label=_("Group"), widget=apply_select2(forms.Select), required=False) def __init__(self, *args, **kwargs): super(CustomerWithUserDataForm, self).__init__(*args, **kwargs) self.fields["delivery_point"].widget.can_add_related = False self.fields["delivery_point"].widget.can_delete_related = False class Meta: widgets = { 'address': Textarea(attrs={ 'rows': 4, 'cols': 80, 'style': 'height: 5em; width: 30em;' }), 'memo': Textarea(attrs={ 'rows': 4, 'cols': 160, 'style': 'height: 5em; width: 60em;' }), } model = Customer fields = "__all__"
class Meta: model = Recording fields = ("name", "ip_address", "port", "snmp_read_community", "recording_file", "autodiscover_sys_desc", "sys_description", "comment") widgets = { 'ip_address': apply_select2(forms.Select), }
class Meta: model = Product fields = "__all__" widgets = { 'long_name': forms.TextInput(attrs={'style': "width:450px !important"}), 'order_unit': SelectAdminOrderUnitWidget(attrs={'style': "width:700px !important"}), 'department_for_customer': apply_select2(forms.Select), }
class Meta: fields = [ 'name', 'owner_type', 'owners', ] widgets = { 'owners': apply_select2(SelectMultiple), }
class PreferenceForm(forms.ModelForm): content_type = forms.ModelChoiceField(queryset=ContentType.objects.filter( app_label='device', model__in=['category', 'specialty']), widget=forms.HiddenInput(), required=False) object_id = forms.ChoiceField(widget=apply_select2(forms.Select), label='Specialty/Category name') class Meta: model = Preference fields = ('name', 'client', 'content_type', 'object_id') widgets = { 'client': apply_select2(forms.Select), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) choices = [('_0', '-------')] for id, name in Specialty.objects.values_list('id', 'name'): choices.append((f'specialty_{id}', f'Specialty: {name}')) for category in Category.objects.all(): if not category.sub_categories.exists(): choices.append( (f'category_{category.id}', f'Category: {category.name}')) self.fields['object_id'].choices = choices try: model = ContentType.objects.get( id=self.initial.get('content_type')).model self.initial[ 'object_id'] = f"{model}_{self.initial.get('object_id')}" except ObjectDoesNotExist: pass def clean_object_id(self): content_object_id = self.cleaned_data.get('object_id') content_type_model, cleaned_object_id = content_object_id.split('_') if cleaned_object_id != '0': self.cleaned_data['content_type'] = ContentType.objects.get( app_label='device', model=content_type_model) return cleaned_object_id else: return None def clean(self): preferences = Preference.objects.filter(client_id=self.cleaned_data.get('client'), content_type=self.cleaned_data.get('content_type'), object_id=self.cleaned_data.get('object_id')) \ .exclude(pk=self.instance.id) if preferences.exists(): raise ValidationError( 'Preference for client, specialty/category exists') return self.cleaned_data
class Meta: model = Product fields = "__all__" widgets = { "long_name": forms.TextInput(attrs={"style": "width:450px !important"}), "order_unit": SelectAdminOrderUnitWidget( attrs={"style": "width:100% !important"} ), "department_for_customer": apply_select2(forms.Select), }
class Meta: model = Lesson fields = [ 'name', 'short_name', 'topic', 'tags', #'position', ] widgets = { 'position': forms.HiddenInput(), 'topic': apply_select2(forms.Select), } # hide the position field as it is determined by the sortable
class AccountForm(forms.ModelForm): specialties = forms.ModelMultipleChoiceField( queryset=Specialty.objects.all(), required=False, widget=apply_select2(forms.SelectMultiple)) class Meta: model = Account fields = ('user', 'role', 'client', 'specialties') widgets = { 'user': apply_select2(forms.Select), 'role': apply_select2(forms.Select), 'client': apply_select2(forms.Select), }
def formfield_for_manytomany(self, db_field, request=None, **kwargs): user = CuserMiddleware.get_user() if user.groups.all().first(): if user.groups.all().first().configuration_set.all().first(): configuration = user.groups.all().first( ).configuration_set.all().first() if db_field.name == 'trucks': kwargs['widget'] = apply_select2( forms.SelectMultiple ) if configuration.activity_filter_two == 2 else SortedFilteredSelectMultiple( ) elif 'employees' == db_field.name: kwargs['widget'] = apply_select2( forms.SelectMultiple ) if configuration.employees_filter_two == 2 else SortedFilteredSelectMultiple( ) return super(AdminActivity2, self).formfield_for_manytomany( db_field, request, **kwargs) else: if db_field.name in ['trucks', 'employees']: kwargs['widget'] = apply_select2(forms.SelectMultiple) return super(AdminActivity2, self).formfield_for_manytomany( db_field, request, **kwargs)
class Meta: model = ActivitySection # fields = ['name', 'section_type','position',] fields = [ 'name', 'short_name', 'lesson', 'duration', 'tags', # 'content', # 'position', ] widgets = { # 'content': TextEditorWidget(), 'position': forms.HiddenInput(), 'topic': apply_select2(forms.Select), } readonly_fields = ['topic']
class CategoryForm(FixedModelForm): sub_categories = forms.MultipleChoiceField(widget=apply_select2(forms.SelectMultiple), required=False) class Meta: fields = ('name', 'specialty', 'image', 'sub_categories', 'parent') model = Category widgets = { 'parent': apply_select2(forms.Select), 'specialty': apply_select2(forms.Select), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) changelist_filters = get_changelist_filters(kwargs) current_choices = list(self.instance.sub_categories.values_list('id', 'name')) other_choices = list(Category.objects.filter(parent=None) .exclude(id=self.instance.id) .values_list('id', 'name')) self.fields['sub_categories'].choices = current_choices + other_choices self.fields['sub_categories'].widget.template_name = 'admin/device/category/sub_categories.html' self.initial['sub_categories'] = list(self.instance.sub_categories.values_list('id', flat=True)) if not self.instance.id: self.initial['specialty'] = changelist_filters.get('specialty__id', [0])[0] self.initial['parent'] = changelist_filters.get('parent__id', [0])[0] def clean(self): cleaned_data = self.cleaned_data parent_category = cleaned_data.get('parent') if parent_category: new_sub_categories = Category.objects.filter(id__in=cleaned_data['sub_categories']) new_grandparent_categories = Category.get_all_parent_categories([parent_category.id]) new_parent_category_ids = ([parent_category.id] + list(new_grandparent_categories.values_list('id', flat=True))) if new_sub_categories.filter(id__in=new_parent_category_ids).exists(): raise ValidationError('Circular sub categories assigned.') return cleaned_data
class ClientForm(FixedModelForm): children = forms.MultipleChoiceField(widget=apply_select2( forms.SelectMultiple), required=False, label='Affiliate hospitals') class Meta: widgets = { 'country': apply_select2(forms.Select), } def __init__(self, *args, **kwargs): super(ClientForm, self).__init__(*args, **kwargs) current_choices = list(self.instance.children.values_list( 'id', 'name')) other_choices = list( Client.objects.filter(parent=None).exclude( id=self.instance.id).exclude( id=self.instance.root_parent_id).values_list('id', 'name')) self.fields['children'].choices = current_choices + other_choices self.fields[ 'children'].widget.template_name = 'admin/hospital/client/children.html' self.initial['children'] = list( self.instance.children.values_list('id', flat=True))
class FeaturesInline(admin.TabularInline): model = Feature fields = ('name', 'value', 'icon', 'shared_image') readonly_fields = ('icon', ) formfield_overrides = { models.ForeignKey: { 'widget': apply_select2(forms.Select) } } def get_extra(self, request, product=None, **kwargs): if product: return product.missing_category_features.count() return 0 def get_formset(self, request, product=None, **kwargs): initial = [] if request.method == 'GET' and product: for category_feature in product.missing_category_features: initial.append({ 'shared_image': category_feature.shared_image, 'name': category_feature.name, }) formset = super().get_formset(request, product, **kwargs) formset.__init__ = curry(formset.__init__, initial=initial) return formset def get_queryset(self, request): return super().get_queryset(request).select_related( 'category_feature', 'shared_image', 'category_feature__shared_image') def icon(self, feature): return feature.icon
class Meta: model = models.JKUserRMB fields = ["user", "rmb", "is_auto"] widgets = {'user': apply_select2(forms.Select)}
class Meta: model = models.JKFenRun fields = ["user", "point", "message"] widgets = {'user': apply_select2(forms.Select)}
class Meta: model = models.JKPos fields = ["user", "sn_code", "terminal", "is_activate"] widgets = {'user': apply_select2(forms.Select)}
class Meta: widgets = { 'permanence': apply_select2(forms.Select), 'customer': apply_select2(forms.Select), }
class Meta: model = models.SDBPos fields = ["user", "terminal"] widgets = { 'user': apply_select2(forms.Select), }
class Meta: model = Staff fields = "__all__" widgets = { 'customer_responsible': apply_select2(forms.Select), }
class Meta: model = RebatableItem fields = ('content_type', 'object_id', 'item_type') widgets = {'content_type': apply_select2(forms.Select)}
class Meta: widgets = { 'category': apply_select2(forms.Select), 'manufacturer': apply_select2(forms.Select), 'level': apply_select2(forms.Select), }
class Meta: model = Preference fields = ('name', 'client', 'content_type', 'object_id') widgets = { 'client': apply_select2(forms.Select), }
class BankAccountDataForm(forms.ModelForm): customer = CustomerModelChoiceField( queryset=Customer.objects.filter(is_active=True), label=_("customer"), required=False, widget=apply_select2(forms.Select) ) producer = ProducerModelChoiceField( queryset=Producer.objects.filter( represent_this_buyinggroup=False, is_active=True ), label=_("producer"), required=False, widget=apply_select2(forms.Select) ) bank_amount_in = FormMoneyField( label=_("bank_amount_in"), help_text=_('payment_on_the_account'), max_digits=8, decimal_places=2, required=False, initial=REPANIER_MONEY_ZERO) bank_amount_out = FormMoneyField( label=_("bank_amount_out"), help_text=_('payment_from_the_account'), max_digits=8, decimal_places=2, required=False, initial=REPANIER_MONEY_ZERO) def __init__(self, *args, **kwargs): super(BankAccountDataForm, self).__init__(*args, **kwargs) bank_account = self.instance if bank_account.id is not None: self.fields["bank_amount_in"].initial = bank_account.bank_amount_in self.fields["bank_amount_out"].initial = bank_account.bank_amount_out self.fields["customer"].widget.attrs['readonly'] = True self.fields["customer"].disabled = True self.fields["producer"].widget.attrs['readonly'] = True self.fields["producer"].disabled = True if bank_account.customer is None: self.fields["customer"].choices = [('', _("---------"))] else: self.fields["customer"].empty_label = None self.fields["customer"].queryset = Customer.objects.filter(id=bank_account.customer_id) if bank_account.producer is None: self.fields["producer"].choices = [('', _("---------"))] else: self.fields["producer"].empty_label = None self.fields["producer"].queryset = Producer.objects.filter(id=bank_account.producer_id) if (bank_account.customer_invoice is not None or bank_account.producer_invoice is not None) or ( bank_account.customer is None and bank_account.producer is None): self.fields["operation_date"].widget.attrs['readonly'] = True self.fields["operation_date"].disabled = True self.fields["bank_amount_in"].widget.attrs['readonly'] = True self.fields["bank_amount_in"].disabled = True self.fields["bank_amount_out"].widget.attrs['readonly'] = True self.fields["bank_amount_out"].disabled = True if bank_account.customer is None and bank_account.producer is None: self.fields["operation_comment"].widget.attrs['readonly'] = True self.fields["operation_comment"].disabled = True else: self.fields["producer"].queryset = Producer.objects.filter( represent_this_buyinggroup=False, is_active=True ) self.fields["customer"].queryset = Customer.objects.filter( is_active=True ) def clean(self): if any(self.errors): # Don't bother validating the formset unless each form is valid on its own return customer = self.cleaned_data.get("customer") producer = self.cleaned_data.get("producer") initial_id = self.instance.id initial_customer = self.instance.customer initial_producer = self.instance.producer if customer is None and producer is None: if initial_id is not None: if initial_customer is None and initial_producer is None: raise forms.ValidationError( _('You may not update a balance.') ) else: self.add_error('customer', _('Either a customer or a producer must be given.')) self.add_error('producer', _('Either a customer or a producer must be given.')) else: bank_account = BankAccount.objects.filter(operation_status=BANK_LATEST_TOTAL).order_by('?').first() if bank_account: # You may only insert the first latest bank total at initialisation of the website self.add_error('customer', _('Either a customer or a producer must be given.')) self.add_error('producer', _('Either a customer or a producer must be given.')) else: if self.instance.customer_invoice is not None or self.instance.producer_invoice is not None: raise forms.ValidationError( _('You may not update a bank operation linked to an invoice.') ) if customer is not None and producer is not None: self.add_error('customer', _('Only one customer or one producer must be given.')) self.add_error('producer', _('Only one customer or one producer must be given.')) latest_total = BankAccount.objects.filter(operation_status=BANK_LATEST_TOTAL).order_by('?').first() if latest_total is not None: operation_date = self.cleaned_data.get("operation_date") if operation_date < latest_total.operation_date: self.add_error('operation_date', _('The operation date must be greater or equal to the latest total operation date.')) class Meta: model = BankAccount fields = "__all__"
class Meta: fields = ["user", "terminals"] widgets = { 'user': apply_select2(forms.Select), }