def full_clean(self): ModelForm.full_clean(self) max_cost_errors = self._errors.get('max_cost') if not max_cost_errors: if 'warranty' in self.data and self.data['warranty'] == Product.N and float(self.data['max_cost']) <= 0.00: max_cost_errors = self._errors.setdefault("max_cost", ErrorList()) max_cost_errors.append("Podaj maksymalny koszt naprawy")
def __init__(self,*args,**kwargs): ModelForm.__init__(self,*args,**kwargs) #first argument, index is the position of the field you want it to come before self.fields.insert(6,'time_added',forms.TimeField(widget=JSDateTimePickerWidget(), input_formats=('%H:%M',), required=True)) if not self.instance.id: self.instance.date_added = utc.localize(datetime.datetime.today()) self.fields['time_added'].initial = self.instance.date_added.time()
def __init__ (self, *args, **kw): ModelForm.__init__ (self, *args, **kw) if self.instance and isinstance (self.instance, Prodopt): inst=self.instance dc=self.fields.get('defaultchoice') if trace: print inst.all_choices # option_id # dir (inst) if inst.pk and inst.all_choices().count(): dc.queryset = inst.all_choices() #Choice.objects.filter (id__in = inst.choices.values_list('id', flat=True))
def __init__(self, division=None, *args, **kwargs): ModelForm.__init__(self, *args, **kwargs) self.fields['municipio'].choices = cargar_municipio() if division: # Evalúa si se estableció el tipo de novedad a registrar de acuerdo a la división indicada, en caso # contrario muestra un listado con todos los tipos de procedimientos registrados self.fields['tipo_procedimiento'].choices = cargar_tipo_procedimiento(division)
def register_view(self, request, form_url='', extra_context=None): request.user = STAFF_REGISTER ModelForm = self.get_form(request, None) if request.method == 'POST': form = ModelForm(request.POST, request.FILES, instance=None) if form.is_valid(): form_validated = True new_object = self.save_form(request, form, change=False) else: form_validated = False new_object = form.instance formsets, inline_instances = self._create_formsets(request, new_object) if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, False) self.log_addition(request, new_object) return self.response_add(request, new_object, post_url_continue='/management/login/') else: initial = self.get_changeform_initial_data(request) form = ModelForm(initial=initial) formsets, inline_instances = self._create_formsets(request, self.model()) adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request, None)), self.get_prepopulated_fields(request, None), self.get_readonly_fields(request, None), model_admin=self) media = self.media + adminForm.media inline_formsets = self.get_inline_formsets(request, formsets, inline_instances, None) for inline_formset in inline_formsets: media = media + inline_formset.media context = dict(self.admin_site.each_context(), title=u'注册%s' % force_text(self.model._meta.verbose_name), adminform=adminForm, object_id=None, original=None, is_popup=(IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), to_field=None, media=media, # formsets=formsets, inline_admin_formsets=inline_formsets, errors=helpers.AdminErrorList(form, formsets), preserved_filters=self.get_preserved_filters(request)) context.update(extra_context or {}) return self.render_change_form(request, context, add=True, change=False, obj=None, form_url=form_url)
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): ModelForm.__init__(self, data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) # override manually role_field = self.fields['role'] role_field.required = False role_field.choices = [(u'', u'---------')] + [(r.id, str(r)) for r in Role.objects.filter(anon=True)] # limit anon choices self.fields['role'] = role_field
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): ModelForm.__init__(self, data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) # override manually to disabled format_field = self.fields['format'] format_field.widget.attrs = {'disabled':'disabled'} format_field.required = False self.fields['format'] = format_field
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): ModelForm.__init__(self, data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) # override manually role_field = self.fields['role'] #role_field.required = True role_field.label = _(u'Workspace level role') role_field.help_text = _(u'This role will apply to every text in the workspace. To share only a (few) texts with this user, you can leave this blank and delegate roles on texts once the user is created.') self.fields['role'] = role_field
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): ModelForm.__init__(self, data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance) # override manually role_field = self.fields['role'] #role_field.required = True role_field.label = _(u'Text level role') role_field.help_text = _(u'This role will apply only to this text.') self.fields['role'] = role_field
def save(self): if self.is_valid(): au = auth.models.User.objects.create_user( username=self.cleaned_data["email"], email=self.cleaned_data["email"], password=self.cleaned_data["password"], ) self.instance.user = au self.instance.user.first_name = self.cleaned_data["first_name"] self.instance.user.last_name = self.cleaned_data["last_name"] self.instance.user.save() ModelForm.save(self)
def __init__(self, *args, **kwargs): if "instance" in kwargs: initial = kwargs.setdefault("initial", {}) initial["teams"] = [team.pk for team in kwargs["instance"].team_set.all()] ModelForm.__init__(self, *args, **kwargs) super(PersonForm, self).__init__(*args, **kwargs) for field in iter(self.fields): if field != "person_pic": self.fields[field].widget.attrs.update({"class": "form-control"})
def __init__ (self, *args, **kw): ModelForm.__init__ (self, *args, **kw) #self.fields ['choices'].queryset = Choice.objects.published() # so only published appear in slider cf = self.fields.get ('choices', '') if cf: cf.queryset = Choice.objects.published() # so only published appear in slider if self.instance and isinstance (self.instance, Prodopt): inst=self.instance dc=self.fields.get('defaultchoice') if trace: print inst.all_choices # option_id # dir (inst) if inst.pk and inst.all_choices().count(): dc.queryset = inst.all_choices() #Choice.objects.filter (id__in = inst.choices.values_list('id', flat=True))
def _save_related(self, template): """ Call SnippetTemplateAdmin.save_related for the given template instance. :returns: A list of the new template variables after save_related was called. """ request = self.factory.post('/url', {}) ModelForm = self.model_admin.get_form(request) form = ModelForm(instance=template) form.save_m2m = Mock() # Called by save_related but unnecessary here. self.model_admin.save_related(request, form, [], True) return [variable.name for variable in SnippetTemplateVariable.objects.filter(template=template)]
def is_valid(self): if ModelForm.is_valid(self): programm = L_get_left_programm(self.instance.year, self.instance.semester, self.instance.id) if programm[self.instance.course][self.instance.course_number][self.instance.course_type] < self.instance.num_of_groups: return False else: return False return True
def is_valid(self): result = ModelForm.is_valid(self) if self.data["required_hours_from"] != "" and self.data["required_hours_to"] != "": if int(self.data["required_hours_from"]) > int(self.data["required_hours_to"]): self._errors["required_hours_to"] = '1' self._errors['required_hours_from'] = '2' result = False return result
def __new__(cls, *args, **kwargs): for field_name in cls.base_fields: print(field_name) field = cls.base_fields[field_name] attr_dic = {'class':'form-control', 'placeholder':field.help_text, } field.widget.attrs.update(attr_dic) return ModelForm.__new__(cls)
def __init__(self, *args, **kwargs): instance = kwargs.get('instance', None) if instance: book = instance.book else: book = Word.objects.order_by('-create_dt')[0].book kwargs['initial'] = {'book': book} ModelForm.__init__(self, *args, **kwargs) queryset = Word.objects.filter(book=book) if instance: queryset = queryset.exclude(pk=instance.pk) self.fields['related'].queryset = queryset self.fields['synonym'].queryset = queryset self.fields['antonym'].queryset = queryset
def __new__(cls, *args, **kwargs): #cls.base_fields是一个元祖,里面是 所有的 【(字段名,字段的对象),(),()】 for field_name in cls.base_fields: field_obj = cls.base_fields[field_name] #添加属性 field_obj.widget.attrs.update({'class':'form-control'}) if field_name in cls.Meta.readonly_fields: field_obj.widget.attrs.update({'disabled':'true'}) return ModelForm.__new__(cls)
def __init__(self, *args, **kwargs): # Only in case we build the form from an instance # (otherwise, 'groups' list should be empty) if 'instance' in kwargs: # We get the 'initial' keyword argument or initialize it # as a dict if it didn't exist. initial = kwargs.setdefault('initial', {}) # The widget for a ModelMultipleChoiceField expects # a list of primary key for the selected data. initial['groups'] = [grp.pk for grp in kwargs['instance'].wishlistgroup_set.all()] if 'group' in kwargs: initial = kwargs.setdefault('initial', {}) groups = initial.setdefault('groups', []) groups.append(kwargs['group'].pk) del kwargs['group'] user = kwargs.pop('user') ModelForm.__init__(self, *args, **kwargs) self.fields['groups'].queryset = WishlistGroup.get_groups_by_user(user=user)
def save(self, commit=True): # we want to bypass UserCreationForm's save. user = ModelForm.save(self, commit=False) # only set a pass if the form is filled if self.cleaned_data['password1']: user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user
def save(self, commit=True): # Get the saved Group instance group = ModelForm.save(self, True) GroupItem.objects.filter(group=group, item__wisher=self.user).delete() group_items = [] for item in self.cleaned_data['items']: print "creating intermediate groupitems[item] for %s" % item group_items.append(GroupItem(group=group, item=item).save()) return group_items
def save(self, commit=True): added_sites = set() msc = ModelForm.save(self, commit) for site in self.cleaned_data['active_sites']: added_sites.add(site) if msc.pk: if set(added_sites) != set(msc.seosite_set.all()): msc.seosite_set = added_sites else: msc.save() msc.seosite_set = added_sites return msc
def save(self, **args): res = ModelForm.save(self, **args) for f in FlagType.objects.all(): fv = self.data[f.name] d = {'item': self.instance.id, 'type': f.id, 'value': fv} try: fg = Flag.objects.get(item=self.instance.id, type=f.id) except Flag.DoesNotExist: fg = Flag() ff = FlagForm(d, instance=fg) fv = ff.save() setattr(res, f.name, fv) return res
def clean(self): self.cleaned_data = ModelForm.clean(self) self.instance.clear_fields() for input in self.cleaned_data['layout'].inputs.all(): all_data = self.data.copy() all_data.update(self.files) data = get_data_with_prefix(all_data, make_safe_input_name(input.name)) field = input.field_model(input=input, **data) # field.page = self.instance try: field.full_clean() except ValidationError, e: # we should handle this raise e #field.save() self.layout_fields.setdefault('%s_%s' %(input.field_model._meta.app_label, input.field_model.__name__.lower()),[]).append(field)
def _is_valid(self): res = ModelForm.is_valid(self) if self.instance.id is None: return res for f in FlagType.objects.all(): fv = self.data[f.name] d = {'item': self.instance.id, 'type': f.id, 'value': fv} try: fg = Flag.objects.get(item=self.instance.id, type=f.id) except Flag.DoesNotExist: continue ff = FlagForm(d, instance=fg) if not ff.is_valid(): res = False self.errors[f.name] = ff.errors return res
def save(self, commit=True): # Get the unsaved Item instance instance = ModelForm.save(self, False) # Prepare a 'save_m2m' method for the form, old_save_m2m = self.save_m2m def new_save_m2m(): old_save_m2m() # This is where we actually link the item with groups instance.wishlistgroup_set.clear() for group in self.cleaned_data['groups']: print "creating intermediate groupitems for %s" % group GroupItem(item=instance, group=group).save() # instance.wishlistgroup_set.add(group) self.save_m2m = new_save_m2m # Do we need to save all changes now? if commit: instance.save() self.save_m2m() return instance
def __new__(cls, *args, **kwargs): # super(CustomerForm, self).__new__(*args, **kwargs) # self.fields['customer_note'].widget.attrs['class'] = 'form-control' #disabled_fields = ['qq', 'consultant'] for field_name in cls.base_fields: field = cls.base_fields[field_name] #print("field repr",field_name,field.__repr__()) attr_dic = {'placeholder': field.help_text} if 'BooleanField' not in field.__repr__(): attr_dic.update({'class': 'form-control'}) #print("-->field",field) if 'ModelChoiceField' in field.__repr__(): #fk field attr_dic.update({'data-tag':field_name}) # if 'DateTimeField' in field.__repr__(): # attr_dic.update({'placeholder': field_name}) if cls.Meta.form_create is False: if field_name in cls.Meta.admin.readonly_fields: attr_dic['disabled'] = True #print('----read only:',field_name) field.widget.attrs.update(attr_dic) print("modelf form admin class:",dir(cls.Meta)) return ModelForm.__new__(cls)
def save(self, *args, **kwargs): inst = ModelForm.save(self, *args, **kwargs) return inst
def __init__(self, *args, **kwargs): ImageValidationMixin.__init__(self, *args, **kwargs) ModelForm.__init__(self, *args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.form_tag = False
def __new__(cls, *args, **kwargs): for field_name, field_obj in cls.base_fields.items(): field_obj.widget.attrs['class'] = 'form-control' ## 前端的样式 if field_name in cls.Meta.readonly_fields: #如果不可修改 field_obj.widget.attrs['disabled'] = True ## 前端的样式 灰色 return ModelForm.__new__(cls)
def save(self, *args, **kw): invoice_num = self.cleaned_data['invoice_num'] invoice = Invoice.objects.get(num=invoice_num) self.instance.invoice = invoice return ModelForm.save(self, *args, **kw)
def __init__(self, *args, **kw): ModelForm.__init__(self, *args, **kw) self.fields['publish_date'].widget.attrs = {'class': 'vDateField'}
def save(cls, info: ResolveInfo, input: dict, form: forms.ModelForm): form.save()
def __init__(self, *args, **kw): ModelForm.__init__(self, *args, **kw) self.fields['options'].queryset = Option.objects.published( ) # so only published appear in slider
def __new__(cls, *args, **kwargs): # print("__new__",cls,args,kwargs) for field_name in cls.base_fields: filed_obj = cls.base_fields[field_name] filed_obj.widget.attrs.update({'class': 'form-control'}) return ModelForm.__new__(cls)
def __new__(cls, *args, **kwargs): return ModelForm.__new__(cls)
def save(self, commit=True): # save user self.instance.set_password(User.objects.make_random_password(length=20)) user = ModelForm.save(self, True) send_verification_email(self.request, user) return user
def save(self): """Hash password before saving.""" user = ModelForm.save(self, commit=False) user.set_password(self.cleaned_data.get("password")) user.save()
def __new__(cls, *args, **kwargs): for field_name, field_obj in cls.base_fields.items(): field_obj.widget.attrs['class'] = 'form-control' return ModelForm.__new__(cls)
def __init__(self, *args, **kwargs): ModelForm.__init__(self, *args, **kwargs) self.fields['patient_id'].widget = HiddenInput()
def __init__(self, *args, **kw): ModelForm.__init__(self, *args, **kw) self.fields['choices'].queryset = Choice.objects.published( ) # so only published appear in slider
def add_view(self, request, form_url='', extra_context=None): "The 'add' admin view for this model." model = self.model opts = model._meta if not self.has_add_permission(request): raise PermissionDenied ModelForm = self.get_form(request) formsets = [] if request.method == 'POST': form = ModelForm(request.POST, request.FILES) if form.is_valid(): form_validated = True new_object = self.save_form(request, form, change=False) else: form_validated = False new_object = self.model() prefixes = {} for FormSet in self.get_formsets(request): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(data=request.POST, files=request.FILES, instance=new_object, save_as_new=request.POST.has_key("_saveasnew"), prefix=prefix) formsets.append(formset) if all_valid(formsets) and form_validated: # Here is the modified code. for formset, inline in zip(formsets, self.inline_instances): if not isinstance(inline, ReverseInlineModelAdmin): continue obj = formset.save()[0] setattr(new_object, inline.parent_fk_name, obj) self.save_model(request, new_object, form, change=False) form.save_m2m() for formset in formsets: self.save_formset(request, form, formset, change=False) self.log_addition(request, new_object) return self.response_add(request, new_object) else: # Prepare the dict of initial data from the request. # We have to special-case M2Ms as a list of comma-separated PKs. initial = dict(request.GET.items()) for k in initial: try: f = opts.get_field(k) except models.FieldDoesNotExist: continue if isinstance(f, models.ManyToManyField): initial[k] = initial[k].split(",") form = ModelForm(initial=initial) prefixes = {} for FormSet in self.get_formsets(request): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset = FormSet(instance=self.model(), prefix=prefix) formsets.append(formset) adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)), self.prepopulated_fields) media = self.media + adminForm.media inline_admin_formsets = [] for inline, formset in zip(self.inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request)) inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets) inline_admin_formsets.append(inline_admin_formset) media = media + inline_admin_formset.media context = { 'title': _('Add %s') % force_unicode(opts.verbose_name), 'adminform': adminForm, 'is_popup': request.REQUEST.has_key('_popup'), 'show_delete': False, 'media': mark_safe(media), 'inline_admin_formsets': inline_admin_formsets, 'errors': helpers.AdminErrorList(form, formsets), #'root_path': self.admin_site.root_path, 'app_label': opts.app_label, } context.update(extra_context or {}) return self.render_change_form(request, context, form_url=form_url, add=True)
def form_valid(self, form: ModelForm): form.save() messages.success(self.request, "اطلاعات پروفایل شما با موفقیت ویرایش شد") return redirect(self.get_success_url())
def __new__(cls, *args, **kwargs): # 动态的给生成的form元素加上css {'class': 'form-control'} for field_name, field_obj in cls.base_fields.items(): field_obj.widget.attrs.update({'class': 'form-control'}) return ModelForm.__new__(cls)
def save(self, form: ModelForm) -> models.Model: """Save the data from the form""" return form.save()