Пример #1
0
 def __init__(self, *args, **kwargs):
     ModelForm.__init__(self, *args, **kwargs)
     if self.instance:
         try:
             self.fields["custom_operation"].initial = self.instance.operation.operation_id
         except:
             pass
Пример #2
0
 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, usuario=None):
     ModelForm.__init__(self, data=data, files=files, auto_id=auto_id, prefix=prefix, initial=initial, error_class=error_class, label_suffix=label_suffix, empty_permitted=empty_permitted, instance=instance)
     unidades = [(0, "------------")]
     for unidad in usuario.unidades_responsable.all():
         unidades.append( (unidad.id,unidad.nombre) )
     self.fields['unidad'].choices = unidades
Пример #3
0
 def form_valid_formset(self, form: ModelForm,
                        formset: ProfileFormSet) -> HttpResponseRedirect:
     if formset.is_valid():
         formset.save(commit=False)
         formset.save()
     else:
         return HttpResponseRedirect(self.get_success_url())
     form.save()
     return HttpResponseRedirect(self.get_success_url())
Пример #4
0
    def __init__(self, *args, **kwargs):
        """

        Arguments:
        - `self`:
        - `*args`:
        - `**kwargs`:

        Return:
        Exceptions:
        """
        ModelForm.__init__(self, *args, **kwargs)
Пример #5
0
    def __init__(self, *args, **kwargs):
        """

        Arguments:
        - `self`:
        - `*args`:
        - `**kwargs`:

        Return:
        Exceptions:
        """
        ModelForm.__init__(self, *args, **kwargs)
Пример #6
0
def __new__(cls, *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)

        if hasattr(cls.Meta.admin, "clean_%s" % field_name):
            clean_field_func = getattr(cls.Meta.admin, "clean_%s" % field_name)
            setattr(cls, "clean_%s" % field_name, clean_field_func)
    else:
        if hasattr(cls.Meta.model,
                   "clean2"):  # clean2 is kingadmin's own clean method
            clean_func = getattr(cls.Meta.model, "clean")
            setattr(cls, "clean", clean_func)
        else:  # use default clean method
            setattr(cls, "clean", default_clean)

    return ModelForm.__new__(cls)
Пример #7
0
 def save_existing(self, form: ModelForm, instance: Page,
                   commit: bool = True) -> Page:
     """Replace an existing chapter page."""
     with form.instance.image.open('rb') as img:
         dgst = blake2b(img.read(), digest_size=16)
         ext = form.instance.image.name.split(".")[-1]
         path = form.instance.chapter.get_directory()
         name = str(path / f'{dgst.hexdigest()}.{ext}')
         form.instance.image.name = name
         return form.save(commit=commit)
Пример #8
0
def form_init(self, *args, **kwargs):

    # call class super initialisation
    ModelForm.__init__(self, *args, **kwargs)

    # check model is in dictionary
    if self.Meta.model in absFields:

        # get fields specific to this model
        fieldsDict = absFields[self.Meta.model]

        # if field is in required list of absolutes set absolute value in dict
        newValues = {
            f: abs(getattr(self.instance, f))
            for f in self.Meta.fields if f in fieldsDict
        }

        # update initial dict
        self.initial.update(newValues)
Пример #9
0
 def clean(self):
     cd = self.cleaned_data
     inst = self.instance
     try:
         inst.content_object = cd['content_type'].get_object_for_this_type(
             numero=cd['numero'], ano=cd['ano'], tipo_id=cd['tipo'])
     except:
         raise ValidationError('Registro não encontrado!')
     cd['object_id'] = inst.object_id
     cd['diario'] = inst.diario
     return ModelForm.clean(self)
Пример #10
0
 def __new__(cls, *args, **kwargs):
     for field_name, field_obj in cls.base_fields.items():
         field_obj.widget.attrs['class'] = 'form-control'
         try:
             if field_obj.widget.input_type == 'checkbox':
                 field_obj.widget.attrs['class'] = 'checkbox'
         except AttributeError:
             pass
         if not form_add:
             if field_name in admin_class.readonly_fields:
                 field_obj.widget.attrs['disabled'] = 'disabled'
     return ModelForm.__new__(cls)
Пример #11
0
    def _changeform_view(self, request, object_id, form_url, extra_context):
        if request.method == "POST":
            data = json.loads(request.body)
            action = data.get("_cms_action")
            change = bool(object_id)
            if change:
                obj = self.get_object(request, object_id)
            else:
                if not self.has_add_permission(request):
                    raise PermissionDenied
                obj = None
            if action:
                del data["_cms_action"]
            if action == "save":
                ModelForm = self.get_form(request, change=change)
                form = ModelForm(data, request.FILES, instance=obj)
                return handle_save(change, data, form, request)
            elif action == "revert":
                return handle_revert(data, object_id, request)
            elif action == "publish":
                ModelForm = self.get_form(request, change=change)
                form = ModelForm(data, request.FILES, instance=obj)
                return handle_publication(data, form, request)
            elif action == "unpublish":
                return handle_unpublication(obj)

        elif request.method == "GET" and request.GET.get("format") == "json":
            content_type = ContentType.objects.get_for_model(self.model)
            latest = (Revision.objects.filter(
                object_id=object_id,
                content_type=content_type).order_by("-date_created").first())
            if not latest:
                return no_revision_found()

            return JsonResponse(latest.data)

        extra_context = extra_context or {}
        extra_context["INK_DEV"] = INK_CONFIG["DEV"]
        return super()._changeform_view(request, object_id, form_url,
                                        extra_context)
Пример #12
0
 def clean(self):
     ''' check for valid service version '''
     cleaned_data = ModelForm.clean(self)
     service = cleaned_data['service_type']
     versions = map(lambda x: x[0], dict(VERSIONS).get(service))
     version = cleaned_data['version']
     if version not in versions:
         raise ValidationError(
             _('Invalid version (%(version)s) for %(service)s server'),
             code='invalid',
             params={
                 'version': version,
                 'service': service
             })
     return cleaned_data
Пример #13
0
	def change_view(self, request, object_id, extra_context=None):
		"""Add a hidden field for the object's primary key."""
		model = self.model
		opts = model._meta

		obj = self.get_object(request, unquote(object_id))

		if not self.has_change_permission(request, obj):
			raise PermissionDenied

		if obj is None:
			raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})

		if request.method == 'POST' and "_saveasnew" in request.POST:
			return self.add_view(request, form_url='../add/')

		ModelForm = self.get_form(request, obj)
		formsets = []
		if request.method == 'POST':
			form = ModelForm(request.POST, request.FILES, instance=obj)
			if form.is_valid():
				form_validated = True
				new_object = self.save_form(request, form, change=True)
			else:
				form_validated = False
				new_object = obj
			prefixes = {}
			for FormSet, inline in zip(self.get_formsets(request, new_object),
									   self.inline_instances):
				prefix = FormSet.get_default_prefix()
				prefixes[prefix] = prefixes.get(prefix, 0) + 1
				if prefixes[prefix] != 1:
					prefix = "%s-%s" % (prefix, prefixes[prefix])
				formset = FormSet(request.POST, request.FILES,
								  instance=new_object, prefix=prefix,
								  queryset=inline.queryset(request))

				formsets.append(formset)

			embedded_formsets=[]
			for FormSet, embedded in zip(self.get_embedded_formsets(request, new_object),
									   self.embedded_instances):
				prefix = FormSet.model._meta.object_name.lower()
				prefixes[prefix] = prefixes.get(prefix, 0) + 1
				if prefixes[prefix] != 1:
					prefix = "%s-%s" % (prefix, prefixes[prefix])
				try:
					formset = FormSet(request.POST, request.FILES, prefix=prefix,
									  queryset=embedded.queryset(request, obj))

					embedded_formsets.append(formset) # this is only to get a complete history messaging
				except:
					pass
				
			if all_valid(formsets) and all_valid(embedded_formsets) and form_validated:
				# we have to update embedded formsets first because we modify the new_object
				for formset in embedded_formsets:
					embedded_data = self.save_embedded_formset(formset, change=True)
					setattr(new_object, formset.model._meta.object_name.lower(), embedded_data)				
				self.save_model(request, new_object, form, change=True)
				form.save_m2m()
				for formset in formsets:
					self.save_formset(request, form, formset, change=True)
					
				change_message = self.construct_change_message(request, form, formsets+embedded_formsets)
				self.log_change(request, new_object, change_message)
				return self.response_change(request, new_object)

		else:
			form = ModelForm(instance=obj)
			prefixes = {}
			for FormSet, inline in zip(self.get_formsets(request, obj), self.inline_instances):
				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=obj, prefix=prefix,
								  queryset=inline.queryset(request))
				formsets.append(formset)
			
			for FormSet, embedded in zip(self.get_embedded_formsets(request, obj), self.embedded_instances):
				prefix = FormSet.model._meta.object_name.lower()
				prefixes[prefix] = prefixes.get(prefix, 0) + 1
				if prefixes[prefix] != 1:
					prefix = "%s-%s" % (prefix, prefixes[prefix])
				formset = FormSet(instance=embedded.model, prefix=prefix,
								  queryset=embedded.queryset(request, obj))
				formsets.append(formset)
				
		adminForm = admin.helpers.AdminForm(form, self.get_fieldsets(request, obj),
			self.prepopulated_fields, self.get_readonly_fields(request, obj),
			model_admin=self)
		media = self.media + adminForm.media

		inline_admin_formsets = []
		for inline, formset in zip(self.inline_instances, formsets):
			fieldsets = list(inline.get_fieldsets(request, obj))
			readonly = list(inline.get_readonly_fields(request, obj))
			inline_admin_formset = admin.helpers.InlineAdminFormSet(inline, formset,
				fieldsets, readonly, model_admin=self)
			inline_admin_formsets.append(inline_admin_formset)
			media = media + inline_admin_formset.media
			
		embedded_admin_formsets=[]
		for embedded, formset in zip(self.embedded_instances, formsets):
			fieldsets = list(embedded.get_fieldsets(request, obj))
			readonly = list(embedded.get_readonly_fields(request, obj))
			embedded_admin_formset = EmbeddedAdminFormSet(embedded, formset,
				fieldsets, readonly, model_admin=self)
			embedded_admin_formsets.append(embedded_admin_formset)
			media = media + embedded_admin_formset.media

		context = {
			'title': _('Change %s') % force_unicode(opts.verbose_name),
			'adminform': adminForm,
			'object_id': object_id,
			'original': obj,
			'is_popup': "_popup" in request.REQUEST,
			'media': mark_safe(media),
			'inline_admin_formsets': inline_admin_formsets,
			'embedded_admin_formsets': embedded_admin_formsets,
			'errors': admin.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, change=True, obj=obj)
Пример #14
0
 def has_changed(self):
     has_changed = ModelForm.has_changed(self)
     return bool(self.initial or has_changed)
Пример #15
0
	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():
				new_object = self.save_form(request, form, change=False)
				form_validated = True
			else:
				form_validated = False
				new_object = self.model()
			prefixes = {}
			for FormSet, inline in zip(self.get_formsets(request), self.inline_instances):
				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="_saveasnew" in request.POST,
								  prefix=prefix, queryset=inline.queryset(request))
				formsets.append(formset)

			embedded_formsets = []
			for FormSet, embedded in zip(self.get_embedded_formsets(request, new_object),
									   self.embedded_instances):
				prefix = FormSet.model._meta.object_name.lower()
				prefixes[prefix] = prefixes.get(prefix, 0) + 1
				if prefixes[prefix] != 1:
					prefix = "%s-%s" % (prefix, prefixes[prefix])
				try:
					formset = FormSet(request.POST, request.FILES, prefix=prefix,
									  instance=embedded.model,
									  queryset=embedded.queryset(request))
					embedded_formsets.append(formset) # this is only to get a complete log messaging
				except:
					pass

			if all_valid(formsets) and all_valid(embedded_formsets) and form_validated:
				# we have to update embedded formsets first because we modify the new_object
				for formset in embedded_formsets:
					embedded_data = self.save_embedded_formset(formset, change=False)
					setattr(new_object, formset.model._meta.object_name.lower(), embedded_data)
				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, inline in zip(self.get_formsets(request),
									   self.inline_instances):
				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,
								  queryset=inline.queryset(request))
				formsets.append(formset)

			for FormSet, embedded in zip(self.get_embedded_formsets(request, ), self.embedded_instances):
				prefix = FormSet.model._meta.object_name.lower()
				prefixes[prefix] = prefixes.get(prefix, 0) + 1
				if prefixes[prefix] != 1:
					prefix = "%s-%s" % (prefix, prefixes[prefix])
				formset = FormSet(instance=embedded.model, prefix=prefix,
								  queryset=embedded.queryset(request))
				formsets.append(formset)
				
		adminForm = admin.helpers.AdminForm(form, list(self.get_fieldsets(request)),
			self.prepopulated_fields, self.get_readonly_fields(request),
			model_admin=self)
		media = self.media + adminForm.media

		inline_admin_formsets = []
		for inline, formset in zip(self.inline_instances, formsets):
			fieldsets = list(inline.get_fieldsets(request))
			readonly = list(inline.get_readonly_fields(request))
			inline_admin_formset = admin.helpers.InlineAdminFormSet(inline, formset,
				fieldsets, readonly, model_admin=self)
			inline_admin_formsets.append(inline_admin_formset)
			media = media + inline_admin_formset.media

		embedded_admin_formsets=[]
		for embedded, formset in zip(self.embedded_instances, formsets):
			fieldsets = list(embedded.get_fieldsets(request))
			readonly = list(embedded.get_readonly_fields(request))
			embedded_admin_formset = EmbeddedAdminFormSet(embedded, formset,
				fieldsets, readonly, model_admin=self)
			embedded_admin_formsets.append(embedded_admin_formset)
			media = media + embedded_admin_formset.media

		context = {
			'title': _('Add %s') % force_unicode(opts.verbose_name),
			'adminform': adminForm,
			'is_popup': "_popup" in request.REQUEST,
			'show_delete': False,
			'media': mark_safe(media),
			'inline_admin_formsets': inline_admin_formsets,
			'embedded_admin_formsets': embedded_admin_formsets,
			'errors': admin.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)
Пример #16
0
    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 = []
        inline_instances = self.get_inline_instances(request, None)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                new_object = self.save_form(request, form, change=False)
                form_validated = True
            else:
                form_validated = False
                new_object = self.model()
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request), inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST, files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix, queryset=inline.queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)
            if self.all_valid_with_nesting(formsets) and form_validated:
                self.save_model(request, new_object, form, False)
                self.save_related(request, form, formsets, 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, inline in zip(self.get_formsets(request), inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=self.model(), prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

        adminForm = AdminForm(form, list(self.get_fieldsets(request)),
            self.get_prepopulated_fields(request),
            self.get_readonly_fields(request),
            model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            prepopulated = dict(inline.get_prepopulated_fields(request))
            inline_admin_formset = InlineAdminFormSet(inline, formset,
                fieldsets, prepopulated, readonly, model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if inline.inlines:
                media = media + self.wrap_nested_inline_formsets(request, inline, formset)

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.REQUEST,
            'show_delete': False,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': AdminErrorList(form, formsets),
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, form_url=form_url, add=True)
Пример #17
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        "The 'change' admin view for this model."
        model = self.model
        opts = model._meta

        obj = self.get_object(request, unquote(object_id))

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})

        if request.method == 'POST' and "_saveasnew" in request.POST:
            return self.add_view(request, form_url=reverse('admin:%s_%s_add' %
                                    (opts.app_label, opts.module_name),
                                    current_app=self.admin_site.name))

        ModelForm = self.get_form(request, obj)
        formsets = []
        inline_instances = self.get_inline_instances(request, obj)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, new_object), inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST, request.FILES,
                                  instance=new_object, prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

            if self.all_valid_with_nesting(formsets) and form_validated:
                self.save_model(request, new_object, form, True)
                self.save_related(request, form, formsets, True)
                change_message = self.construct_change_message(request, form, formsets)
                self.log_change(request, new_object, change_message)
                return self.response_change(request, new_object)

        else:
            form = ModelForm(instance=obj)
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, obj), inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj, prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

        adminForm = AdminForm(form, self.get_fieldsets(request, obj),
            self.get_prepopulated_fields(request, obj),
            self.get_readonly_fields(request, obj),
            model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            prepopulated = dict(inline.get_prepopulated_fields(request, obj))
            inline_admin_formset = InlineAdminFormSet(inline, formset,
                fieldsets, prepopulated, readonly, model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if inline.inlines:
                media = media + self.wrap_nested_inline_formsets(request, inline, formset)

        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': "_popup" in request.REQUEST,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': AdminErrorList(form, formsets),
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request, context, change=True, obj=obj, form_url=form_url)
Пример #18
0
 def has_changed(self):
     has_changed = ModelForm.has_changed(self)
     return bool(self.initial or has_changed)
Пример #19
0
 def save(self, user, commit=True):
     self.instance.user = user        
     return ModelForm.save(self, commit=commit)
Пример #20
0
    def save(self, commit=True):

        instance = ModelForm.save(self, commit=False)
        return UrlShortener.objects.get_or_create_short(
            url_long=instance.url_long, automatico=False, link_absoluto=True)
Пример #21
0
 def has_changed(self):
     """
     Returns True if we have initial data.
     """
     has_changed = ModelForm.has_changed(self)
     return bool(self.initial or has_changed)
Пример #22
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        "The 'change' admin view for this model."
        model = self.model
        opts = model._meta

        obj = self.get_object(request, unquote(object_id))

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if obj is None:
            raise Http404(
                _('%(name)s object with primary key %(key)r does not exist.') %
                {
                    'name': force_unicode(opts.verbose_name),
                    'key': escape(object_id)
                })

        if request.method == 'POST' and "_saveasnew" in request.POST:
            return self.add_view(
                request,
                form_url=reverse('admin:%s_%s_add' %
                                 (opts.app_label, opts.module_name),
                                 current_app=self.admin_site.name))

        ModelForm = self.get_form(request, obj)
        formsets = []
        inline_instances = self.get_inline_instances(request, obj)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, new_object),
                                       inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST,
                                  request.FILES,
                                  instance=new_object,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

            if self.all_valid_with_nesting(formsets) and form_validated:
                self.save_model(request, new_object, form, True)
                self.save_related(request, form, formsets, True)
                change_message = self.construct_change_message(
                    request, form, formsets)
                self.log_change(request, new_object, change_message)
                return self.response_change(request, new_object)

        else:
            form = ModelForm(instance=obj)
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, obj),
                                       inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

        adminForm = AdminForm(form,
                              self.get_fieldsets(request, obj),
                              self.get_prepopulated_fields(request, obj),
                              self.get_readonly_fields(request, obj),
                              model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            prepopulated = dict(inline.get_prepopulated_fields(request, obj))
            inline_admin_formset = InlineAdminFormSet(inline,
                                                      formset,
                                                      fieldsets,
                                                      prepopulated,
                                                      readonly,
                                                      model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if inline.inlines:
                media = media + self.wrap_nested_inline_formsets(
                    request, inline, formset)

        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': "_popup" in request.REQUEST,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': AdminErrorList(form, formsets),
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       change=True,
                                       obj=obj,
                                       form_url=form_url)
Пример #23
0
 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, paso = None):
     ModelForm.__init__(self, data=data, files=files, auto_id=auto_id, prefix=prefix, initial=initial, error_class=error_class, label_suffix=label_suffix, empty_permitted=empty_permitted, instance=instance)
     self.fields['paso'].choices = (paso.id, paso.nombre)
     self.fields['paso'].initial = paso.id
Пример #24
0
 def is_valid(self):
     return ModelForm.is_valid(self)
Пример #25
0
 def save(self):
     return ModelForm.save(self)
Пример #26
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        tab_language = get_language_from_request(request, None)
        to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
                                   
        "The 'change' admin view for this model."
        model = self.model
        opts = model._meta

        obj = self.get_object(request, unquote(object_id))

        if not self.has_change_permission(request, obj):
            messages.warning(request, _("You have no permissions to change %(name)s") % {"name": obj})
            if request.GET.get('destination'):
                dest_url = self.parse_destination(request, obj)
            else:
                dest_url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name),  current_app=self.admin_site.name)
            return HttpResponseRedirect(dest_url)
        
        if obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})

        request.scms['page_type'] = obj.type
        request.scms['page'] = obj
        #if request.method == 'POST' and "_saveasnew" in request.POST:
            #raise PermissionDenied
            # Не реализовано
            #if not request.user.is_superuser and 'create' in scms.site.get_content_type(obj.type).permissions:
            #    return self.add_view(request, form_url='../add/%s' %  obj.type, current_app=self.admin_site.name)
            #else:
            #    raise PermissionDenied

        ModelForm = self.get_form(request, obj)
        formsets = []
        inline_instances = scms.site.get_content_type(obj.type).get_fields(obj)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj, language=tab_language)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
                 # Возвращается просто объект страницы, но запись в БД еще не происходила
                 # тк еще надо проверь корректность inline ов
            else:
                form_validated = False
                new_object = obj
            
            for inline in inline_instances:
                inline.init(self.model, self.admin_site)
                formset = inline.get_plugin_formset(request, obj, instance=new_object)
                formsets.append(formset)

            if all_valid(formsets) and form_validated:
                if "_saveasnew" in request.POST:
                    new_object = self.copy_page(new_object)

                self.save_related(request, form, formsets, True)
                self.save_model(request, new_object, form, True)
                change_message = self.construct_change_message(request, form, formsets)
                self.log_change(request, new_object, change_message)
                response = self.response_change(request, new_object) # стандартный обработчик
                if tab_language and response.status_code == 302 and response._headers['location'][1] == request.path:
                    location = response._headers['location']
                    response._headers['location'] = (location[0], "%s?language=%s" % (location[1], tab_language))
                return response

        else:
            form = ModelForm(instance=obj, language=tab_language)
      
            for inline in inline_instances:
                inline.init(self.model, self.admin_site)
                formset = inline.get_plugin_formset(request, None, instance=obj)
                formsets.append(formset)

        fieldsets = self.get_fieldsets(request, obj) 
                
        adminForm = helpers.AdminForm(
            form,
            list(self.get_fieldsets(request, obj)),
            self.get_prepopulated_fields(request, obj),
            self.get_readonly_fields(request, obj),
            model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            prepopulated = dict(inline.get_prepopulated_fields(request, obj))
            inline_formset = helpers.InlineAdminFormSet(inline, formset,
                fieldsets, prepopulated, readonly, model_admin=self)
            inline_admin_formsets.append(inline_formset)
            media = media + inline_formset.media
        
        fullobj = form.instance.full_load(language=tab_language)
        
        # context = {
        #     'title': _('Change %s') % force_text(opts.verbose_name), #TODO: указывать тип создаваемой страницы
        #     'adminform': adminForm,
        #     'object_id': object_id,
        #     'original': obj,
        #     'is_popup': "_popup" in request.GET or "_popup" in request.POST,
        #     'media': media,
        #     'inline_admin_formsets': inline_admin_formsets,
        #     'errors': helpers.AdminErrorList(form, formsets),
        #     'app_label': opts.app_label,
        #     #TODO!!!'root_path': self.admin_site.root_path,
        #     'view_path': fullobj and fullobj.link or None ,
        #     'destination': self.parse_destination(request, obj),
        #     'has_permission': True,
        #     'breadcrumbs': self.model(id=obj.parent_id).full_load().parents + [obj.full_load()],
        # }

        context = dict(
            self.admin_site.each_context(request),
            title=_('Change %s') % opts.verbose_name,
            adminform=adminForm,
            object_id=object_id,
            original=obj,
            is_popup=(IS_POPUP_VAR in request.POST or
                      IS_POPUP_VAR in request.GET),
            to_field=to_field,
            media=media,
            inline_admin_formsets=inline_admin_formsets,
            errors=helpers.AdminErrorList(form, formsets),
            preserved_filters=self.get_preserved_filters(request),
            view_path=fullobj and fullobj.link or None ,
            breadcrumbs=list(obj.get_parents()) + [obj.full_load(tab_language)],
            has_permission=True,            
            destination=self.parse_destination(request, obj),
        )

        context = self.update_language_tab_context(request, None, context)

        extra_context = self.update_language_tab_context(request, None, extra_context)
        extra_context['destination'] = request.GET.get('destination', None)
        form_url = form_url
        # extra_context['breadcrumbs'] = self.model(id=parent_id).full_load(tab_language).parents

        context.update(extra_context or {})

        return self.render_change_form(request, context, change=True, obj=obj, form_url=form_url)
Пример #27
0
 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'] = 'disabled'
     return ModelForm.__new__(cls)
Пример #28
0
    def change_view(self, request, object_id, extra_context=None):
        "The 'change' admin view for this model."
        model = self.model
        opts = model._meta

        try:
            obj = self.queryset(request).get(pk=unquote(object_id))
        except model.DoesNotExist:
            # Don't raise Http404 just yet, because we haven't checked
            # permissions yet. We don't want an unauthenticated user to be able
            # to determine whether a given object exists.
            obj = None

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        if obj is None:
            raise Http404(
                _('%(name)s object with primary key %(key)r does not exist.') %
                {
                    'name': force_unicode(opts.verbose_name),
                    'key': escape(object_id)
                })

        if request.method == 'POST' and request.POST.has_key("_saveasnew"):
            return self.add_view(request, form_url='../add/')

        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == 'POST':
            # on précise l'utilisateur dans le formulaire
            form = ModelForm(request.POST,
                             request.FILES,
                             instance=obj,
                             user=request.user)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet in self.get_formsets(request, new_object):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST,
                                  request.FILES,
                                  instance=new_object,
                                  prefix=prefix)
                formsets.append(formset)

            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=True)

                change_message = self.construct_change_message(
                    request, form, formsets)
                self.log_change(request, new_object, change_message)
                return self.response_change(request, new_object)

        else:
            # on précise l'utilisateur dans le formulaire
            form = ModelForm(instance=obj, user=request.user)
            prefixes = {}
            for FormSet in self.get_formsets(request, obj):
                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=obj, prefix=prefix)
                formsets.append(formset)

        adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
                                      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, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(
                inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': request.REQUEST.has_key('_popup'),
            '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, change=True, obj=obj)
Пример #29
0
 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)
Пример #30
0
 def save(self, commit=True):
     inst = ModelForm.save(self, commit=True)
     return inst
Пример #31
0
 def __init__(self, data=None, files=None, initial=None):
     data = self.remove_initial_values(data)
     ModelForm.__init__(self, data=data, files=files, initial=initial)
     self.set_initial_values()
Пример #32
0
 def save_model(self, commit=True):
     value = self.cleaned_data["custom_operation"]
     self.instance.operation = Operation.objects.get(operation_id=value)
     ModelForm.save_model(self, commit)
Пример #33
0
    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 = []
        inline_instances = self.get_inline_instances(request, None)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                new_object = self.save_form(request, form, change=False)
                form_validated = True
            else:
                form_validated = False
                new_object = self.model()
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request),
                                       inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(data=request.POST,
                                  files=request.FILES,
                                  instance=new_object,
                                  save_as_new="_saveasnew" in request.POST,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)
            if self.all_valid_with_nesting(formsets) and form_validated:
                self.save_model(request, new_object, form, False)
                self.save_related(request, form, formsets, 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, inline in zip(self.get_formsets(request),
                                       inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=self.model(),
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)
                if inline.inlines:
                    self.add_nested_inline_formsets(request, inline, formset)

        adminForm = AdminForm(form,
                              list(self.get_fieldsets(request)),
                              self.get_prepopulated_fields(request),
                              self.get_readonly_fields(request),
                              model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request))
            readonly = list(inline.get_readonly_fields(request))
            prepopulated = dict(inline.get_prepopulated_fields(request))
            inline_admin_formset = InlineAdminFormSet(inline,
                                                      formset,
                                                      fieldsets,
                                                      prepopulated,
                                                      readonly,
                                                      model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
            if inline.inlines:
                media = media + self.wrap_nested_inline_formsets(
                    request, inline, formset)

        context = {
            'title': _('Add %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'is_popup': "_popup" in request.REQUEST,
            'show_delete': False,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': AdminErrorList(form, formsets),
            'app_label': opts.app_label,
        }
        context.update(extra_context or {})
        return self.render_change_form(request,
                                       context,
                                       form_url=form_url,
                                       add=True)
Пример #34
0
    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':
            # on précise l'utilisateur dans le formulaire
            form = ModelForm(request.POST, request.FILES, user=request.user)
            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:
                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(",")
            # on précise l'utilisateur dans le formulaire
            form = ModelForm(initial=initial, user=request.user)
            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)