本文整理汇总了Python中django.forms.ModelForm类的典型用法代码示例。如果您正苦于以下问题:Python ModelForm类的具体用法?Python ModelForm怎么用?Python ModelForm使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ModelForm类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: full_clean
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")
示例2: __init__
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))
示例3: __init__
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()
示例4: __init__
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)
示例5: register_view
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)
示例6: __init__
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
示例7: __init__
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
示例8: save
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)
示例9: __init__
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"})
示例10: __init__
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))
示例11: _save_related
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)]
示例12: is_valid
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
示例13: __new__
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)
示例14: __init__
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
示例15: __init__
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)