def __init__(self, site, queryset, yaaac_opts, limit_choices_to=None, empty_label="---------", cache_choices=None, required=True, widget=None, label=None, initial=None, help_text='', to_field_name=None, *args, **kwargs): # the `limit_choices_to' parameter allows us to enable the filtering in # the ajax autocomplete and the related lookup. # It may seems redundant with `ForeignKey.limit_choices_to' but we don't # have access to a `rel' object here. model = queryset.model app_label = model._meta.app_label model_name = model._meta.model_name queryset_id = autocomplete.register_queryset(app_label=app_label, model_name=model_name, queryset=queryset) if not widget: widget = AutocompleteWidget() widget.queryset_id = queryset_id widget.site = site widget.model = model widget.opts = { "min_chars": 1, "max_height": 300, "width": 300, "suggest_by": "__str__", "allow_lookup": True, } widget.opts.update(yaaac_opts or {}) widget.limit_choices_to = limit_choices_to or {} ModelChoiceField.__init__(self, queryset, empty_label, required, widget, label, initial, help_text, to_field_name, *args, **kwargs)
class ResumeForm(forms.ModelForm): """ Form for input resume """ class Meta: model = Resume exclude = ('resume_name', 'views') industry = ModelChoiceField(Industry.objects.all(), empty_label=_(u'请选择')) location = ModelChoiceField(Location.objects.all(), empty_label=None) self_desc = forms.CharField(widget=Textarea(attrs={'rows': 3, 'class': 'input-xxlarge char_area'}), max_length=2000) positions = forms.CharField(required=False) # Add some custom validation to our image field def clean_avatar(self): avatar = self.cleaned_data.get('avatar', False) if avatar: if avatar.size > AVATAR_SIZE_LIMIT: raise forms.ValidationError(_(u'上传图片尺寸过大( 大于2M )')) return avatar def save(self, **new_data): instance = self.instance instance.save() # Saving positions position_list = [strip(position_id) for position_id in new_data['positions'].split(',')] models.ResumePositionR.objects.filter(resume=instance).delete() for position_id in position_list: if position_id != '': position_obj = models.Position.objects.get(id=position_id) resume_position_r = models.ResumePositionR(resume=instance, position=position_obj) resume_position_r.save()
class BadgeRequestForm(ModelForm): badge = ModelChoiceField(Badge.objects.all(),widget=HiddenInput) issuer = ModelChoiceField(Issuer.objects.all(),widget=HiddenInput) class Meta: model = BadgeRequest exclude = ['expires','user',]
class DesafioLadderLutaForm(ModelForm): """Formulário para uma luta de desafio de ladder""" personagem_desafiante = ModelChoiceField(queryset=Personagem.objects.all(), required=False) personagem_desafiado = ModelChoiceField(queryset=Personagem.objects.all(), required=False) class Meta: model = Luta fields = ('ganhador', 'stage') def __init__(self, *args, **kwargs): super(DesafioLadderLutaForm, self).__init__(*args, **kwargs) preparar_classes_form(self) # Diminuir tamanho de campo de escolha de personagens classes_atuais = self.fields['personagem_desafiante'].widget.attrs[ 'class'] self.fields['personagem_desafiante'].widget.attrs.update( {'class': ' '.join([classes_atuais, 'col-8'])}) classes_atuais = self.fields['personagem_desafiado'].widget.attrs[ 'class'] self.fields['personagem_desafiado'].widget.attrs.update( {'class': ' '.join([classes_atuais, 'col-8'])}) if 'id' in self.initial and self.instance.id == None: self.instance = Luta.objects.get(id=self.initial['id']) self.fields['stage'].queryset = Stage.objects.all().exclude(stagevalidaladder__isnull=True, modelo=Stage.TIPO_NORMAL) \ .order_by('stagevalidaladder', 'nome', 'modelo')
class tutorsForm(forms.Form): grup = forms.CharField(widget=forms.TextInput(attrs={'readonly': True})) tutor1 = ModelChoiceField(widget=ModelSelect2Widget( queryset=Professor.objects.all(), search_fields=( 'last_name__icontains', 'first_name__icontains', ), attrs={'style': "'width': '100%'"}), queryset=Professor.objects.all(), required=False) tutor2 = ModelChoiceField(widget=ModelSelect2Widget( queryset=Professor.objects.all(), search_fields=( 'last_name__icontains', 'first_name__icontains', ), attrs={'style': "'width': '100%'"}), queryset=Professor.objects.all(), required=False) tutor3 = ModelChoiceField(widget=ModelSelect2Widget( queryset=Professor.objects.all(), search_fields=( 'last_name__icontains', 'first_name__icontains', ), attrs={'style': "'width': '100%'"}), queryset=Professor.objects.all(), required=False)
class Form_ventas_buscar_paquete(forms.Form): agencia = ModelChoiceField(Agencias_de_viajes.objects.all(), label='Agencia de Viajes', required=False) ciudad = ModelChoiceField(Ciudades.objects.all(), label='Ciudades', required=False) personas = forms.IntegerField(label='Nro Personas', required=False) agente = forms.IntegerField(label='') cliente = forms.IntegerField(label='') fecha = forms.DateField(label='Fecha Aproximada', required=False , widget=DateInput(attrs={'type': 'date'})) area = ModelChoiceField(Areas_de_interes.objects.all(), label='Area de interes', required=False)
def add_fields(self, form, index): super(BillDetailInlineFormset, self).add_fields(form, index) form.fields["mission"] = ModelChoiceField( widget=LeadMissionChoices(lead=self.instance.lead), queryset=Mission.objects) form.fields["consultant"] = ModelChoiceField( widget=ConsultantChoices, queryset=Consultant.objects, required=False) form.fields["month"] = BillingDateChoicesField(required=False)
class SearchJobForm(forms.Form): """ Form for input search job condition """ industry = ModelChoiceField(Industry.objects.all(), empty_label=_(u'不限'), required=False) location = ModelChoiceField(Location.objects.all(), empty_label=_(u'请选择'), required=False) type = ChoiceField(widget=RadioSelect(attrs={'style': 'width:auto;'}), initial=0, choices=SEARCH_TYPE) filter_str = forms.CharField(widget=forms.TextInput( attrs={'style': 'width: 200px; height: 20px; border-color: rgb(238, 95, 91);', 'size': 16}), max_length=255, required=False) is_vip = forms.CharField(widget=forms.HiddenInput(), required=False)
class SearchResumeForm(forms.Form): """ Form for input search person condition """ industry = ModelChoiceField(Industry.objects.all(), empty_label=_(u'不限'), required=False) location = ModelChoiceField(Location.objects.all(), empty_label=_(u'请选择'), required=False) attendance_time = ChoiceField(choices=ATTENDANCE_TIME_SEARCH_JOB, required=False) job_type = ChoiceField(choices=JOB_TYPE, required=False) type = ChoiceField(widget=RadioSelect(attrs={'style': 'width:auto;'}), initial=0, choices=SEARCH_PERSON_TYPE) filter_str = forms.CharField(widget=forms.TextInput( attrs={'style': 'width: 200px; height: 20px; border-color: rgb(238, 95, 91);', 'size': 16}), max_length=255, required=False)
class SubmissionForm(ModelForm): request = ModelChoiceField(Request.objects.all(), widget=HiddenInput, to_field_name="slug") term = ModelChoiceField(Term.objects.all(), widget=HiddenInput, to_field_name="body") valence = FloatField(initial="0", widget=HiddenInput(attrs={"class": "valence-input"})) class Meta: model = Submission
class ActivityForm(forms.ModelForm): # club = ModelChoiceField(label='舉辦單位', queryset=None) begin = forms.DateTimeField(label="活動起始日", input_formats=[ '%Y/%m/%d %H:%M'], widget=XDSoftDateTimePickerInput()) end = forms.DateTimeField(label="活動終止日", input_formats=[ '%Y/%m/%d %H:%M'], widget=XDSoftDateTimePickerInput()) deadline = forms.DateTimeField(label='報名截止時日', input_formats=[ '%Y/%m/%d %H:%M'], widget=XDSoftDateTimePickerInput()) principal = ModelChoiceField(label='活動負責人', queryset=None) content = forms.CharField(label='內容', widget=RichTextWidget()) site = forms.CharField(label='場地') contact = forms.CharField(label='聯絡方式', widget=RichTextWidget()) fee = forms.IntegerField(label='參加費用',) meal = forms.BooleanField(label='是否供餐',) insure = forms.BooleanField(label='是否有保險',) note = forms.CharField(label='備註', widget=RichTextWidget()) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(ActivityForm, self).__init__(*args, **kwargs) def get_all_member(self): membersets = Member.objects.filter(user=self.request.user) return membersets def get_all_club(self): clubsets = Club.objects.filter(member__in=get_all_member(self)) return clubsets try: self.fields['club'].queryset = get_all_club(self) self.fields['principal'].queryset = get_all_member(self) except: # print(get_all_club(self)) raise ValueError('activity_mgt.forms.py crash: choice club') class Meta: model = Activity fields = ['club', 'begin', 'end', 'deadline', 'principal', 'content', 'site', 'contact', 'fee', 'meal', 'insure', 'note',] exclude = ('author',)
def __init__(self, settings, data=None): super(SettingsForm, self).__init__(data=data) self.settings = settings for setting in settings: if setting.type == SettingTypes.STRING: self.fields[self.field(setting)] = fields.CharField( label=setting.display_name, initial=setting.value) elif setting.type == SettingTypes.INT: self.fields[self.field(setting)] = fields.IntegerField( label=setting.display_name, initial=setting.value) elif setting.type == SettingTypes.FLOAT: self.fields[self.field(setting)] = fields.CharField( label=setting.display_name, widget=fields.NumberInput(), initial=setting.value) elif setting.type == SettingTypes.FOREIGN: model = get_model(*setting.foreign_model.split(".")) self.fields[self.field(setting)] = ModelChoiceField( label=setting.display_name, queryset=model.objects.all(), initial=setting.value) elif setting.type == SettingTypes.CHOICES: options = settings_py.MASTER_SETTINGS[setting.name]['options'] choices = [] for option in options: choices.append((option, option)) self.fields[self.field(setting)] = fields.ChoiceField( label=setting.display_name, choices=choices, initial=setting.value)
class AnnouncementForm(forms.ModelForm): # 社團公告發布 club = ModelChoiceField(label='公告單位', queryset=None) title = forms.CharField(label='標題') contents = forms.CharField(label='內容', widget=RichTextWidget()) due = forms.DateTimeField(label="到期日", input_formats=['%Y/%m/%d %H:%M'], widget=XDSoftDateTimePickerInput()) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(AnnouncementForm, self).__init__(*args, **kwargs) def get_all_club(self): membersets = Member.objects.filter(user=self.request.user) clubsets = Club.objects.filter(member__in=membersets) return clubsets try: self.fields['club'].queryset = get_all_club(self) except: # print(get_all_club(self)) raise ValueError('announcement_mgt.forms.py crash: choice club') class Meta: model = Announcement fields = ['club', 'title', 'contents', 'due'] exclude = ('author', )
class ProductForm(EntangledModelForm): name = fields.CharField() tenant = ModelChoiceField(queryset=get_user_model().objects.all(), empty_label=None) active = fields.BooleanField() color = fields.CharField() size = fields.ChoiceField(choices=[ ('s', "Small"), ('m', "Medium"), ('l', "Large"), ]) categories = ModelMultipleChoiceField(queryset=Category.objects.all(), required=False) class Meta: model = Product untangled_fields = ['name'] entangled_fields = { 'properties': ['tenant', 'active', 'color', 'size', 'categories'] } retangled_fields = { 'color': 'extra.variants.color', 'size': 'extra.variants.size', 'tenant': 'ownership.tenant', 'categories': 'extra.categories' }
class PartsRequestForm(Form): # Ticket info priority = ChoiceField(label='Request Priority', error_messages={'required': 'Please select a priority'}) # Request info printer = ModelChoiceField(queryset=None, empty_label="-------------", label='Printer', error_messages={'required': 'Please select a printer'}) part = ChainedModelChoiceField('printer', reverse_lazy('printerrequests:chained_part'), Part, label='Part', error_messages={'required': 'Please select a part'}) address = CharField(label='Location') def __init__(self, *args, **kwargs): super(PartsRequestForm, self).__init__(*args, **kwargs) self.fields['printer'].queryset = PrinterType.objects.filter(id__in=set(Part.objects.values_list('printer', flat=True))) self.fields["priority"].choices = PRIORITY_CHOICES self.helper = FormHelper() self.helper.form_method = 'post' self.helper.html5_required = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-2' self.helper.field_class = 'col-sm-8 col-md-6' self.helper.layout = Layout( Fieldset( 'Create a parts request', *self.fields ), FormActions( Submit('submit', 'Submit'), ) )
def __init__(self, *args, **kwargs): self.instance = kwargs.pop('instance') Form.__init__(self, *args, **kwargs) self.fields['account'] = ModelChoiceField( self.instance.domain.account_set.exclude( mailinglists=self.instance), empty_label='')
def optgroups(self, name, value, attrs=None): """Return only selected options and set QuerySet from `ModelChoicesIterator`.""" default = (None, [], 0) groups = [default] has_selected = False selected_choices = {str(v) for v in value} if not self.is_required and not self.allow_multiple_selected: default[1].append(self.create_option(name, '', '', False, 0)) if not isinstance(self.choices, ModelChoiceIterator): modelchoise_query = self.model.objects.all() modelchoise_field = ModelChoiceField(modelchoise_query) modelchoise_iter = ModelChoiceIterator(modelchoise_field) self.choices = modelchoise_iter selected_choices = { c for c in selected_choices if c not in self.choices.field.empty_values } field_name = self.choices.field.to_field_name or 'pk' query = Q(**{'%s__in' % field_name: selected_choices}) for obj in self.choices.queryset.filter(query): option_value = self.choices.choice(obj)[0] option_label = self.label_from_instance(obj) selected = (str(option_value) in value and (has_selected is False or self.allow_multiple_selected)) if selected is True and has_selected is False: has_selected = True index = len(default[1]) subgroup = default[1] subgroup.append( self.create_option(name, option_value, option_label, selected_choices, index)) return groups
class PlayedInGameForm(ModelForm): player = ModelChoiceField(queryset=Player.objects.order_by('first_name')) #game_date=forms.DateField() class Meta: model = PlayedInGame exclude = ('game', 'table_position', 'rank', 'rating', 'rating_change')
class Form_ventas_descuneto_forma_post(forms.Form): TRAMITES = { ('parcial', 'Parcial'), ('cuotas', 'Cuotas'), } tipo = forms.ChoiceField(choices=TRAMITES, label='Forma de pago') descuento = ModelChoiceField(Descuentos.objects.all(), label='Descuentos disponibles', required=False)
class addPlaceForm(ModelForm): lat= forms.FloatField(widget=forms.HiddenInput()) lon= forms.FloatField(widget=forms.HiddenInput()) currency = ModelChoiceField(Currency.objects.filter(active=True), empty_label=None) phone = forms.CharField(label=_('Your phone')) # neighborhood= forms.FloatField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): req_phone = kwargs.pop('req_phone',False) super(addPlaceForm, self).__init__(*args, **kwargs) self.fields['tags'].widget = forms.CheckboxSelectMultiple() self.fields["tags"].queryset = Tag.objects.all() if not req_phone: del self.fields['phone'] # self.fields['currency'].queryset = Currency.objects.filter(active=True) class Meta: model=Place fields = ('title','type','capacity','space','description','price','currency', 'city','country','district','street','address','lat','lon','neighborhood','state', 'postcode','tags', 'min_stay', 'max_stay', 'cancellation','manual','rules','size','size', 'size_type', 'bedroom' )
class Form_nuevo_socio_proveedor(forms.Form): CATEGORIA = ( ('exclusivo', 'Exclusivo'), ('multiagencias', 'Multiagencias'), ) nombre = forms.CharField(label='Nombre de Proveedor', max_length=30) tipo = forms.ChoiceField(choices=CATEGORIA, label='Tipo de Proveedor') alojamiento = ModelChoiceField(Alojamientos.objects.all(), label='Alojamiento') agencia = ModelChoiceField(Agencias_de_viajes.objects.all(), label='Agencia de Viajes') f_inicio = forms.DateField(label='Inicio de asociacion', widget=DateInput(attrs={'type': 'date'})) f_fin = forms.DateField(label='Fin de asociacion', required=False, widget=DateInput(attrs={'type': 'date'}))
class EmailSelectForm(Form): """ Form for selecting email addresses """ SERVICETYPECHOICES = (('saml', _('SAML / Shibboleth')), ('ldap', _('LDAP')), ('oidc', _('OIDC'))) service_type = MultipleChoiceField(required=True, widget=CheckboxSelectMultiple, choices=SERVICETYPECHOICES) production_sp = BooleanField(required=False, help_text=_("Select production SPs.")) test_sp = BooleanField(required=False, help_text=_("Select test SPs")) individual_sp = ModelMultipleChoiceField( queryset=ServiceProvider.objects.filter( end_at=None, history=None).order_by('entity_id'), required=False, help_text=_("Select individual SPs")) admin_emails = BooleanField(required=False, help_text=_("Select admin emails")) technical_contacts = BooleanField(required=False, help_text=_("Select technical contacts")) support_contacts = BooleanField(required=False, help_text=_("Select support contacts")) administrative_contacts = BooleanField( required=False, help_text=_("Select administrative contacts")) template = ModelChoiceField( queryset=Template.objects.all(), required=False, help_text=_('Select template if you want to send email'))
class JobForm(forms.ModelForm): """ Form for add a new job """ class Meta: model = Job exclude = ('company', ) widgets = { 'name': TextInput(attrs={'size': 20}), 'number': TextInput(attrs={'size': 3}), 'description': Textarea(attrs={'rows': 10, 'class': 'input-xxlarge char_area'}) } #Override department = forms.CharField(widget=TextInput(attrs={'size': 15}), required=False) end_date = forms.DateField(label=_(u'截至日期'), widget=TextInput(attrs={'readonly': 'true'}), required=False) location = ModelChoiceField(Location.objects.all(), empty_label=_(u'请选择')) def save(self, company, **new_data): ''' Create job ''' job = Job(**new_data) job.company = company job.save() company.cp_job_last_updated = datetime.datetime.now() company.save() return job
class UserInfoForm(forms.Form): user = fields.CharField(required=False, widget=widgets.Textarea(attrs={'class': 'c1'})) pwd = fields.CharField(max_length=12, widget=widgets.PasswordInput(attrs={'class': 'c1'})) # 针对两种select框创建方式分别实现动态select user_type = fields.ChoiceField( # choices=models.UserType.objects.values_list('id', 'name'), # 构造方法中定义choices后,这里取的值没用了 choices=[]) user_type2 = fields.CharField(widget=widgets.Select(choices=[])) user_type3 = ModelChoiceField( queryset=models.UserType.objects.all(), empty_label='请选择用户类型', to_field_name='id' # HTML中select标签下option标签的value的值对应的字段 ) def __init__(self, *args, **kwargs): """ 重写父类构造方法,构造方法只有在创建类的实例的时候才会执行, 利用构造方法的特性,实例化为对象时去数据库select可实现动态select获取,之后封装到对象中 """ super(UserInfoForm, self).__init__(*args, **kwargs) self.fields['user_type'].choices = models.UserType.objects.values_list( 'id', 'name') # 每次实例化为对象时都会去数据库中取数据 self.fields[ 'user_type2'].widget.choices = models.UserType.objects.values_list( 'id', 'name') # 针对两种select框创建方式分别实现动态select
class UserInfoForms(forms.Form): user = Fields.CharField( required=True, widget=widgets.TextInput(attrs={"placeholder": "请输入用户名"})) pwd = Fields.CharField( max_length=12, min_length=6, widget=widgets.PasswordInput(attrs={"placeholder": "请输入密码"})) email = Fields.EmailField( widget=widgets.TextInput(attrs={"placeholder": "请输入邮箱"}), error_messages={ "required": "邮箱不能为空", "invalid": "邮箱格式不对" }) user_type = Fields.ChoiceField(choices=[]) from django.forms.models import ModelChoiceField user_type2 = ModelChoiceField(to_field_name="id", empty_label="请选择用户类型", queryset=models.UserType.objects.all()) def __init__(self, *args, **kwargs): super(UserInfoForms, self).__init__(*args, **kwargs) self.Fields["user_type"].choices = models.UserType.objects.values_list( "id", "name")
def add_fields(self, form, index): """Add a hidden field for the object's primary key.""" from django.db.models import AutoField, OneToOneField, ForeignKey self._pk_field = pk = self.model._meta.pk # If a pk isn't editable, then it won't be on the form, so we need to # add it here so we can tell which object is which when we get the # data back. Generally, pk.editable should be false, but for some # reason, auto_created pk fields and AutoField's editable attribute is # True, so check for that as well. def pk_is_not_editable(pk): return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or (pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk))) if pk_is_not_editable(pk) or pk.name not in form.fields: if form.is_bound: pk_value = form.instance.pk else: try: if index is not None: pk_value = self.get_queryset()[index].pk else: pk_value = None except IndexError: pk_value = None if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey): qs = pk.rel.to._default_manager.get_query_set() else: qs = self.model._default_manager.get_query_set() qs = qs.using(form.instance._state.db) form.fields[self._pk_field.name] = ModelChoiceField( qs, initial=pk_value, required=False, widget=HiddenInput) super(BaseModelFormSet, self).add_fields(form, index)
class UserInfoForm(forms.Form): user = fields.CharField( required=False, widget=widgets.Textarea(attrs={'class':'c1'}) ) pwd = fields.CharField( max_length=12, widget=widgets.PasswordInput(attrs={'class':'c1'}) ) user_type=fields.ChoiceField( # choices=[(1,'普通用户'),(2,'超级用户'),], # choices=models.UserType.objects.values_list('id','name'), choices=[], widget=widgets.Select, ) user_type2 = fields.CharField( widget=widgets.Select(choices=[]) ) user_type3 = ModelChoiceField( empty_label='请选择用户', queryset=models.UserType.objects.all(), to_field_name='name', ) def __init__(self,*args,**kwargs): super(UserInfoForm,self).__init__(*args,**kwargs) self.fields['user_type'].choices = models.UserType.objects.values_list('id', 'name') self.fields['user_type2'].widget.choices = models.UserType.objects.values_list('id', 'name')
class CreateForm(CustomModelForm): class Meta: model = Guild fields = ['owner', 'name'] owner = ModelChoiceField( label=_('Guild owner'), help_text=_('Guild owner must have at least {min} level.').format( min=GuildOwnerMinLevel), queryset=None, widget=Select(attrs={'class': 'form-control'}), ) name = CharField( label=_('Guild name'), help_text=GuildNameHelpText, min_length=GuildNameMinLength, max_length=GuildNameMaxLength, validators=[GuildNameValidator], ) def __init__(self, account, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields['owner'].queryset = account.players def clean_owner(self): owner = self.cleaned_data.get('owner') if owner.level < GuildOwnerMinLevel: self.add_error( 'owner', _('Player must have {min} level to create guild.').format( min=GuildOwnerMinLevel)) return owner
class WorkExperienceForm(forms.ModelForm): """ Form for work experience """ class Meta: model = WorkExperience exclude = ('resume', 'start_date', 'end_date') def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,\ initial=None, error_class=ErrorList, label_suffix=':',\ empty_permitted=False, instance=None): super(WorkExperienceForm, self).__init__(data, files, auto_id, prefix, initial,\ error_class, label_suffix, empty_permitted, instance) if instance: self.fields['work_from_year'].initial = str(instance.start_date.year if instance.start_date else 0) self.fields['work_from_month'].initial = str(instance.start_date.month if instance.start_date else 0) self.fields['work_to_year'].initial = str(instance.end_date.year if instance.end_date else 0) self.fields['work_to_month'].initial = str(instance.end_date.month if instance.end_date else 0) industry = ModelChoiceField(Industry.objects.all(), empty_label=_(u'请选择')) work_from_year = forms.ChoiceField(choices=constant.YEAR_SCOPE) work_from_month = forms.ChoiceField(choices=constant.MONTH_SCOPE) work_to_year = forms.ChoiceField(choices=constant.YEAR_SCOPE) work_to_month = forms.ChoiceField(choices=constant.MONTH_SCOPE) work_desc = forms.CharField(widget=forms.Textarea(attrs={'rows': 3, 'class': 'input-xxlarge char_area'}), max_length=2000) def clean_work_from_year(self): """ Validate that the work experience time period """ work_from_year = str(self.prefix) + '-' + 'work_from_year' work_from_month = str(self.prefix) + '-' + 'work_from_month' work_to_year = str(self.prefix) + '-' + 'work_to_year' work_to_month = str(self.prefix) + '-' + 'work_to_month' if self.data.get(work_from_year) == '0' or self.data.get(work_from_month) == '0': raise forms.ValidationError(_(u'开始时间是必填项。')) if self.data.get(work_to_year) != '0' and int(self.data.get(work_from_year)) > int( self.data.get(work_to_year)): raise forms.ValidationError(_(u'开始时间必须小于结束时间。')) if self.data.get(work_to_year) != '0' and int(self.data.get(work_to_year)) == int(self.data.get(work_from_year))\ and self.data[work_to_month] != '0' and int(self.data[work_from_month]) > int(self.data[work_to_month]): raise forms.ValidationError(_(u'开始时间必须小于结束时间。')) self.cleaned_data['start_date'] = datetime.date(int(self.data[work_from_year]), int(self.data[work_from_month]), 1) if self.data[work_to_year] == '0' or self.data[work_to_month] == '0': self.cleaned_data['end_date'] = None else: self.cleaned_data['end_date'] = datetime.date(int(self.data[work_to_year]), int(self.data[work_to_month]), 1) return self.cleaned_data['work_from_year'] def save(self, **new_data): instance = self.instance instance.start_date = new_data['start_date'] instance.end_date = new_data['end_date'] instance.save()
def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'submitted_by': kwargs['initial'] = request.user queryset = User.objects.filter(id=request.user.id) return ModelChoiceField(queryset, initial=request.user) return super(FilterUserAdmin, self).formfield_for_foreignkey( db_field, request, **kwargs )
class ResponseForm(ModelForm): term = ModelChoiceField(Term.objects.all(), widget=HiddenInput) valence = FloatField(initial="0", widget=HiddenInput(attrs={"class": "valence-input"})) request = SlugField() class Meta: model = Response
def __init__(self, site, queryset, yaaac_opts, limit_choices_to=None, empty_label="---------", cache_choices=False, required=True, widget=None, label=None, initial=None, help_text='', to_field_name=None, *args, **kwargs): # the `limit_choices_to' parameter allows us to enable the filtering in # the ajax autocomplete and the related lookup. # It may seems redundant with `ForeignKey.limit_choices_to' but we don't # have access to a `rel' object here. model = queryset.model app_label = model._meta.app_label if DJ_VERSION < (1, 6): model_name = model._meta.module_name else: model_name = model._meta.model_name queryset_id = autocomplete.register_queryset(app_label=app_label, model_name=model_name, queryset=queryset) widget = AutocompleteWidget(site, model, limit_choices_to, yaaac_opts, queryset_id=queryset_id) ModelChoiceField.__init__(self, queryset, empty_label, cache_choices, required, widget, label, initial, help_text, to_field_name, *args, **kwargs)