Пример #1
0
  def register(self, request, **kwargs):
    """
    Register a new user account, which will initially be inactive.

    It also creates corresponding user profile.
    """
    
    user = super(ProfileBackend, self).register(request, **kwargs)
    profile, created = utils.get_profile_model().objects.get_or_create(user=user)
    
    # lambda-object to the rescue
    form = lambda: None
    form.cleaned_data = kwargs
    
    # First name, last name and e-mail address are stored in user object
    forms_models.construct_instance(form, user)
    user.save()
    
    # Other fields are stored in user profile object
    forms_models.construct_instance(form, profile)
    profile.save()
    
    user_profile_registered.send(sender=self.__class__, user=user, profile=profile, request=request)
    
    return user
Пример #2
0
    def register(self, request, **kwargs):
        """
    Register a new user account, which will initially be inactive.

    It also creates corresponding user profile.
    """

        user = super(ProfileBackend, self).register(request, **kwargs)
        profile, created = utils.get_profile_model().objects.get_or_create(
            user=user)

        # lambda-object to the rescue
        form = lambda: None
        form.cleaned_data = kwargs

        # First name, last name and e-mail address are stored in user object
        forms_models.construct_instance(form, user)
        user.save()

        # Other fields are stored in user profile object
        forms_models.construct_instance(form, profile)
        profile.save()

        user_profile_registered.send(sender=self.__class__,
                                     user=user,
                                     profile=profile,
                                     request=request)

        return user
Пример #3
0
 def _post_clean(self):
     """
     Stores translation data into translation instance
     """
     opts = self._meta
     translation = self.instance._get_translation(get_active(), can_create=True)
     if opts.exclude is None:
         exclude = ('id', 'language_code', 'master')
     else:
         exclude = list(opts.exclude) + ['id', 'language_code', 'master']
     # Update instance translation
     construct_instance(self, translation, opts.fields, exclude)
     super(BaseMultilingualModelForm, self)._post_clean()
Пример #4
0
    def _post_clean(self):
        opts = self._meta
        # Update the model instance with self.cleaned_data.
        self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)

        exclude = self._get_validation_exclusions()

        # Foreign Keys being used to represent inline relationships
        # are excluded from basic field value validation. This is for two
        # reasons: firstly, the value may not be supplied (#12507; the
        # case of providing new values to the admin); secondly the
        # object being referred to may not yet fully exist (#12749).
        # However, these fields *must* be included in uniqueness checks,
        # so this can't be part of _get_validation_exclusions().
        for f_name, field in self.fields.items():
            if isinstance(field, InlineForeignKeyField):
                exclude.append(f_name)

        # Clean the model instance's fields.
        try:
            if isinstance(self.instance, models.ModelWithRequest):
                self.instance.clean_fields(request=self.request, exclude=exclude)
            else:
                self.instance.clean_fields(exclude=exclude)
        except ValidationError, e:
            self._update_errors(e.message_dict)
Пример #5
0
def post_clean_with_simpler_validation(original_function, self):
    """
    Until https://code.djangoproject.com/ticket/16423#comment:3 is implemented,
    patch it in ourselves: do the same validation on objects when called
    from the form, as the object would do on itself.
    """
    
    opts = self._meta
    # Update the model instance with self.cleaned_data.
    # print "construct_instance with password = %s" % self.cleaned_data.get('password')
    self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
    # print "constructed instance with password = %s" % self.instance.password

    exclude = self._get_validation_exclusions()

    # Foreign Keys being used to represent inline relationships
    # are excluded from basic field value validation. This is for two
    # reasons: firstly, the value may not be supplied (#12507; the
    # case of providing new values to the admin); secondly the
    # object being referred to may not yet fully exist (#12749).
    # However, these fields *must* be included in uniqueness checks,
    # so this can't be part of _get_validation_exclusions().
    for f_name, field in self.fields.items():
        if isinstance(field, InlineForeignKeyField):
            exclude.append(f_name)

    from django.core.exceptions import ValidationError
    # Clean the model instance's fields.
    try:
        self.instance.full_clean(exclude)
    except ValidationError, e:
        self._update_errors(e.update_error_dict(None))
Пример #6
0
    def save(self, commit=True):
        if self.instance.pk is None:
            fail_message = 'created'
            new = True
        else:
            fail_message = 'changed'
            new = False

        if self.errors:
            opts = instance._meta
            raise ValueError("The %s could not be %s because the data didn't"
                             " validate." % (opts.object_name, fail_message))

        trans_model = self.instance._meta.translations_model
        language_code = self.cleaned_data.get('language_code', get_language())

        if not new:
            trans = get_cached_translation(self.instance)
            if not trans or trans.language_code != language_code:
                try:
                    trans = get_translation(self.instance, language_code)
                except trans_model.DoesNotExist:
                    trans = trans_model()
        else:
            trans = trans_model()

        trans = construct_instance(self, trans, self._meta.fields)
        trans.language_code = language_code
        trans.master = self.instance
        self.instance = combine(trans, self.Meta.model)

        super(TranslatableModelForm, self).save(commit=commit)
        return self.instance
Пример #7
0
    def done(self, form_list, **kwargs):
        
        # Save patient
        patient = Patient()
        for form in form_list:
            patient = construct_instance(form, patient)
        patient.created_by = self.request.user
        patient.updated_by = self.request.user
        patient.save()

        # Save management records
        for management_record in form_list[1].save(commit=False):
            management_record.patient = patient
            management_record.created_by = self.request.user
            management_record.updated_by = self.request.user
            management_record.save()

        # Save outcome records
        for outcome_record in form_list[2].save(commit=False):
            outcome_record.patient = patient
            outcome_record.created_by = self.request.user
            outcome_record.updated_by = self.request.user
            outcome_record.save()

        return render(self.request, 'thanks.html', { "patient": patient })
Пример #8
0
    def _post_clean(self):
        opts = self._meta

        exclude = self._get_validation_exclusions()

        try:
            self.instance = construct_instance(self, self.instance,
                                               opts.fields, exclude)
        except ValidationError as e:
            self._update_errors(e)

        self.instance.problem = self.cleaned_data["problem"]

        # Foreign Keys being used to represent inline relationships
        # are excluded from basic field value validation. This is for two
        # reasons: firstly, the value may not be supplied (#12507; the
        # case of providing new values to the admin); secondly the
        # object being referred to may not yet fully exist (#12749).
        # However, these fields *must* be included in uniqueness checks,
        # so this can't be part of _get_validation_exclusions().
        for name, field in self.fields.items():
            if isinstance(field, InlineForeignKeyField):
                exclude.append(name)

        try:
            self.instance.full_clean(exclude=exclude, validate_unique=False)
        except ValidationError as e:
            self._update_errors(e)

        # Validate uniqueness if needed.
        if self._validate_unique:
            self.validate_unique()
Пример #9
0
    def save(self, commit=True):
        ''' Saves the model
            If will always use the language specified in self.cleaned_data, with
            the usual None meaning 'call get_language()'. If instance has
            another language loaded, it gets reloaded with the new language.

            If no language is specified in self.cleaned_data, assume the instance
            is preloaded with correct language.
        '''
        assert self.is_valid(), (
            'Method save() must not be called on an invalid '
            'form. Check the result of .is_valid() before '
            'calling save().')

        # Get the right translation for object and language
        # It should have been done in _post_clean, but instance may have been
        # changed since.
        enforce = 'language_code' in self.cleaned_data
        language = self.cleaned_data.get('language_code') or get_language()
        translation = load_translation(self.instance, language, enforce)

        # Fill the translated fields with values from the form
        excludes = list(self._meta.exclude) + ['master', 'language_code']
        translation = construct_instance(self, translation, self._meta.fields,
                                         excludes)
        set_cached_translation(self.instance, translation)

        # Delegate shared fields to super()
        return super(BaseTranslatableModelForm, self).save(commit=commit)
Пример #10
0
    def save(self, commit=True):
        if self.instance.pk is None:
            fail_message = 'created'
            new = True
        else:
            fail_message = 'changed'
            new = False

        if self.errors:
            opts = self.instance._meta
            raise ValueError("The %s could not be %s because the data didn't"
                             " validate." % (opts.object_name, fail_message))

        trans_model = self.instance._meta.translations_model
        language_code = self.cleaned_data.get('language_code', get_language())

        if not new:
            trans = get_cached_translation(self.instance)
            if not trans or trans.language_code != language_code:
                try:
                    trans = get_translation(self.instance, language_code)
                except trans_model.DoesNotExist:
                    trans = trans_model()
        else:
            trans = trans_model()

        trans = construct_instance(self, trans, self._meta.fields)
        trans.language_code = language_code
        trans.master = self.instance
        self.instance = combine(trans, self.Meta.model)

        super(TranslatableModelForm, self).save(commit=commit)
        return self.instance
Пример #11
0
 def form_valid(self, form):
     form.instance.operator = self.request.user
     if 'onidc' not in form.cleaned_data:
         form.instance.onidc = self.request.user.onidc
     d1 = form.initial
     message = json.dumps(form.changed_data)
     response = super(EditModelView, self).form_valid(form)
     d2 = model_to_dict(construct_instance(form, self.object))
     diffs = diff_dict(make_dict(d1), make_dict(d2))
     content = json.dumps(diffs)
     log_action(user_id=self.request.user.pk,
                content_type_id=get_content_type_for_model(
                    self.object, True).pk,
                object_id=self.object.pk,
                action_flag="修改",
                message=message,
                content=content)
     # if self.model_name == 'online':
     #     verify = Thread(target=device_post_save, args=(self.object.pk,))
     #     verify.start()
     if self.request.is_ajax():
         data = {
             'message': "Successfully submitted form data.",
             'data': form.cleaned_data
         }
         return JsonResponse(data)
     else:
         return response
Пример #12
0
    def done(self, form_list, **kwargs):

        # Save patient
        patient = Patient()
        for form in form_list:
            patient = construct_instance(form, patient)
        patient.created_by = self.request.user
        patient.updated_by = self.request.user
        patient.save()

        # Save management records
        for management_record in form_list[1].save(commit=False):
            management_record.patient = patient
            management_record.created_by = self.request.user
            management_record.updated_by = self.request.user
            management_record.save()

        # Save outcome records
        for outcome_record in form_list[2].save(commit=False):
            outcome_record.patient = patient
            outcome_record.created_by = self.request.user
            outcome_record.updated_by = self.request.user
            outcome_record.save()

        return render(self.request, 'thanks.html', {"patient": patient})
Пример #13
0
def process_form_data(form_list):
    form_data = [form.cleaned_data for form in form_list]
    new = Person()
    for form in form_list:
        new = construct_instance(form, new, form._meta.fields, form._meta.exclude)
    new.save()
    return new.id
Пример #14
0
    def _post_clean(self):
        # TODO: find a way to not copy-paste and override private method...
        # the only we change is excluding pointer-fields from validation
        opts = self._meta

        exclude = self._get_validation_exclusions() + [
            f.name for f in self._pointer_fields
        ]

        # Foreign Keys being used to represent inline relationships
        # are excluded from basic field value validation. This is for two
        # reasons: firstly, the value may not be supplied (#12507; the
        # case of providing new values to the admin); secondly the
        # object being referred to may not yet fully exist (#12749).
        # However, these fields *must* be included in uniqueness checks,
        # so this can't be part of _get_validation_exclusions().
        for name, field in self.fields.items():
            if isinstance(field, InlineForeignKeyField):
                exclude.append(name)

        try:
            construct_excludes = opts.exclude + exclude if opts.exclude else exclude
            self.instance = construct_instance(self, self.instance,
                                               opts.fields, construct_excludes)
        except ValidationError as e:
            self._update_errors(e)

        try:
            self.instance.full_clean(exclude=exclude, validate_unique=False)
        except ValidationError as e:
            self._update_errors(e)

        # Validate uniqueness if needed.
        if self._validate_unique:
            self.validate_unique()
Пример #15
0
    def save(self, commit=True):
        ''' Saves the model
            If will always use the language specified in self.cleaned_data, with
            the usual None meaning 'call get_language()'. If instance has
            another language loaded, it gets reloaded with the new language.

            If no language is specified in self.cleaned_data, assume the instance
            is preloaded with correct language.
        '''
        assert self.is_valid(), ('Method save() must not be called on an invalid '
                                 'form. Check the result of .is_valid() before '
                                 'calling save().')

        # Get the right translation for object and language
        # It should have been done in _post_clean, but instance may have been
        # changed since.
        enforce = 'language_code' in self.cleaned_data
        if getattr(self, 'is_edit', False):
            language = self.language or get_language()
        else:
            language = self.cleaned_data.get('language_code') or get_language()
        translation = load_translation(self.instance, language, enforce)

        # Fill the translated fields with values from the form
        excludes = list(self._meta.exclude) + ['master', 'language_code']
        translation = construct_instance(self, translation,
                                         self._meta.fields, excludes)
        if getattr(self, 'is_edit', False):
            translation.language_code = \
                self.cleaned_data.get('language_code', None) or self.new_lang
        set_cached_translation(self.instance, translation)

        # Delegate shared fields to super()
        return super(BaseTranslatableModelForm, self).save(commit=commit)
Пример #16
0
 def save_new(self, form, commit=True):
     kwargs = {
         self.ct_field.get_attname(): ContentType.objects.get_for_model(
             self.instance, for_concrete_model=self.for_concrete_model).pk,
         self.ct_fk_field.get_attname(): self.instance.pk,
     }
     form.instance = construct_instance(form, self.model(**kwargs))
     return form.save(commit=commit)
Пример #17
0
 def test_empty_fields_to_construct_instance(self):
     "No fields should be set on a model instance if construct_instance receives fields=()"
     form = modelform_factory(Person, fields="__all__")({
         'name': 'John Doe'
     })
     self.assertTrue(form.is_valid())
     instance = construct_instance(form, Person(), fields=())
     self.assertEqual(instance.name, '')
Пример #18
0
    def save_instance(self,
                      instance,
                      fields=None,
                      fail_message='saved',
                      commit=True,
                      exclude=None,
                      construct=True):
        """
        Saves bound Form ``form``'s cleaned_data into model instance
        ``instance``.

        If commit=True, then the changes to ``instance`` will be saved to the
        database. Returns ``instance``.

        If construct=False, assume ``instance`` has already been constructed
        and just needs to be saved.
        """
        if construct:
            instance = construct_instance(self, instance, fields, exclude)
        opts = instance._meta
        if self.errors:
            raise ValueError("the %s could not be %s because the data didn't"
                             " validate." % (opts.object_name, fail_message))

        # wrap up the saving of m2m data as a function.
        def save_m2m(instance):
            cleaned_data = self.cleaned_data
            for f in opts.many_to_many:
                if fields and f.name not in fields:
                    continue
                if f.name in cleaned_data:
                    for validator in f.validators:
                        validator(instance, cleaned_data[f.name])
                    f.save_form_data(instance, cleaned_data[f.name])

        if commit:
            # TODO XXX, why are we not using transactions?
            # if we are committing, save the instance and the m2m data
            # immediately.
            if not instance.pk:
                rollback = True
            else:
                rollback = False
            instance.save()
            try:
                save_m2m(instance)
                # ^-- pass instance so we can validate it's views
            except ValidationError:
                if rollback:
                    self.delete_instance(instance)
                    # we didn't call ensure_label_domain so it's not our
                    # responsibility to call prune_tree
                raise
        else:
            # we're not committing. add a method to the form to allow deferred
            # saving of m2m data.
            self.save_m2m = save_m2m
        return instance
Пример #19
0
    def done(self, form_list, form_dict, **kwargs):

        try:
            client = Client.objects.get(
                mail=self.request.POST.get('step2-mail', False))

        except Client.DoesNotExist:
            client = Client()
            form_client_step_2 = form_dict['step2']
            client = construct_instance(form_client_step_2, client,
                                        form_client_step_2.fields)
            client.save()

        order = Order()
        template_options = form_dict['step1']

        order = construct_instance(template_options, order,
                                   template_options.fields)
        order.client = Client.objects.get(id=client.pk)

        order.save()

        for i in template_options.cleaned_data['packages']:
            order.packages.add(i)

        m = client.mail

        send_templated_mail(
            template_name='lol',
            from_email='*****@*****.**',
            recipient_list=[m],
            context={
                "order": order,
                "client": client,
            },
            # Optional:
            # cc=['*****@*****.**'],
            # bcc=['*****@*****.**'],
            # headers={'My-Custom-Header':'Custom Value'},
            # template_prefix="my_emails/",
            # template_suffix="email",
        )

        return render(self.request, 'step_final.html', {'mail': m})
Пример #20
0
def clean_join_form(form):
    from foundry.forms import JoinForm
    from django.forms.models import construct_instance
    cleaned_data = super(JoinForm, form).clean()
    opts = form._meta
    # Update the model instance with cleaned_data.
    member = construct_instance(form, form.instance, opts.fields, opts.exclude)
    member.set_password(form.cleaned_data["password1"])
    member.full_clean()
    return cleaned_data
Пример #21
0
    def save_instance(self, instance, fields=None, fail_message='saved',
                      commit=True, exclude=None, construct=True):
        """
        Saves bound Form ``form``'s cleaned_data into model instance
        ``instance``.

        If commit=True, then the changes to ``instance`` will be saved to the
        database. Returns ``instance``.

        If construct=False, assume ``instance`` has already been constructed
        and just needs to be saved.
        """
        if construct:
            instance = construct_instance(self, instance, fields, exclude)
        opts = instance._meta
        if self.errors:
            raise ValueError("the %s could not be %s because the data didn't"
                             " validate." % (opts.object_name, fail_message))

        # wrap up the saving of m2m data as a function.
        def save_m2m(instance):
            cleaned_data = self.cleaned_data
            for f in opts.many_to_many:
                if fields and f.name not in fields:
                    continue
                if f.name in cleaned_data:
                    for validator in f.validators:
                        validator(instance, cleaned_data[f.name])
                    f.save_form_data(instance, cleaned_data[f.name])
        if commit:
            # TODO XXX, why are we not using transactions?
            # if we are committing, save the instance and the m2m data
            # immediately.
            if not instance.pk:
                rollback = True
            else:
                rollback = False
            instance.save()
            try:
                save_m2m(instance)
                # ^-- pass instance so we can validate it's views
            except ValidationError:
                if rollback:
                    self.delete_instance(instance)
                    # we didn't call ensure_label_domain so it's not our
                    # responsibility to call prune_tree
                raise
        else:
            # we're not committing. add a method to the form to allow deferred
            # saving of m2m data.
            self.save_m2m = save_m2m
        return instance
Пример #22
0
 def clean_join_form(form):
     cleaned_data = original_clean(form)
     if not form._errors and not form.non_field_errors():
         opts = form._meta
         # Update the model instance with cleaned_data.
         member = construct_instance(form, form.instance, opts.fields, opts.exclude)
         member.set_password(form.cleaned_data["password1"])
         member.full_clean()
         try:
             form.neoprofile = member.neoprofile
         except NeoProfile.DoesNotExist:
             pass
     return cleaned_data
 def _post_clean(self):
     # must be overriden to bypass instance.clean()
     if self.cleaned_data.get('_clean', False):
         opts = self._meta
         self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
         exclude = self._get_validation_exclusions()
         for f_name, field in self.fields.items():
             if isinstance(field, InlineForeignKeyField):
                 exclude.append(f_name)
                 # Clean the model instance's fields.
         try:
             self.instance.clean_fields(exclude=exclude)
         except ValidationError, e:
             self._update_errors(e.message_dict)
Пример #24
0
 def _post_clean(self):
     # must be overriden to bypass instance.clean()
     if self.cleaned_data.get('_clean', False):
         opts = self._meta
         self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
         exclude = self._get_validation_exclusions()
         for f_name, field in list(self.fields.items()):
             if isinstance(field, InlineForeignKeyField):
                 exclude.append(f_name)
                 # Clean the model instance's fields.
         try:
             self.instance.clean_fields(exclude=exclude)
         except ValidationError as e:
             self._update_errors(e.message_dict)
Пример #25
0
def save_instance(form,
                  instance,
                  fields=None,
                  fail_message='saved',
                  commit=True,
                  exclude=None,
                  construct=True,
                  user=None):
    """
    Saves bound Form ``form``'s cleaned_data into model instance ``instance``.

    If commit=True, then the changes to ``instance`` will be saved to the
    database. Returns ``instance``.

    If construct=False, assume ``instance`` has already been constructed and
    just needs to be saved.
    """
    if construct:
        instance = construct_instance(form, instance, fields, exclude)
    opts = instance._meta
    if form.errors:
        raise ValueError("The %s could not be %s because the data didn't"
                         " validate." % (opts.object_name, fail_message))

    # Wrap up the saving of m2m data as a function.
    def save_m2m():
        cleaned_data = form.cleaned_data
        # Note that for historical reasons we want to include also
        # virtual_fields here. (GenericRelation was previously a fake
        # m2m field).

        for f in list(opts.many_to_many) + opts.private_fields:
            if not hasattr(f, 'save_form_data'):
                continue
            if fields and f.name not in fields:
                continue
            if exclude and f.name in exclude:
                continue
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

    if commit:
        # If we are committing, save the instance and the m2m data immediately.
        instance.save(user=user)
        save_m2m()
    else:
        # We're not committing. Add a method to the form to allow deferred
        # saving of m2m data.
        form.save_m2m = save_m2m
    return instance
Пример #26
0
    def _post_clean(self):
        ''' Switch the translation on self.instance
            This cannot (and should not) be done in clean() because it could be
            overriden to change the language. Yet it should be done before save()
            to allow an overriden save to set some translated field values before
            invoking super().
        '''
        enforce = 'language_code' in self.cleaned_data
        language = self.cleaned_data.get('language_code') or get_language()
        translation = load_translation(self.instance, language, enforce)

        exclude = self._get_validation_exclusions()
        translation = construct_instance(self, translation, self._meta.fields, exclude)
        set_cached_translation(self.instance, translation)
        result = super(BaseTranslatableModelForm, self)._post_clean()
        return result
Пример #27
0
    def _post_clean(self):
        ''' Switch the translation on self.instance
            This cannot (and should not) be done in clean() because it could be
            overriden to change the language. Yet it should be done before save()
            to allow an overriden save to set some translated field values before
            invoking super().
        '''
        enforce = 'language_code' in self.cleaned_data
        language = self.cleaned_data.get('language_code') or get_language()
        translation = load_translation(self.instance, language, enforce)

        exclude = self._get_validation_exclusions()
        translation = construct_instance(self, translation, self._meta.fields, exclude)
        set_cached_translation(self.instance, translation)
        result = super(BaseTranslatableModelForm, self)._post_clean()
        return result
Пример #28
0
 def form_valid(self, form):
     form.instance.updated_by = self.request.user
     context = self.get_context_data()
     baseline_form = context['baseline_form']
     management_formset = context['formsets']['Management']
     outcome_formset = context['formsets']['Outcome']
     if baseline_form.is_valid() and management_formset.is_valid() and outcome_formset.is_valid():
         form.instance = construct_instance(baseline_form, form.instance)
         management_formset.instance = self.object
         for management_instance in management_formset.save(commit=False):
             management_instance.updated_by = self.request.user
             management_instance.save()
         outcome_formset.instance = self.object
         for outcome_instance in outcome_formset.save(commit=False):
             outcome_instance.updated_by = self.request.user
             outcome_instance.save()
         return super(PatientUpdateView, self).form_valid(form)
     else:
         return self.render_to_response(self.get_context_data(form=form))
Пример #29
0
 def clean(self):
     bulk_edits = self.extra_forms[0].cleaned_data
     for key in list(bulk_edits.keys()):  # get the list because we'll be
         # changing the dictionary
         if bulk_edits[key] in ['', None] or key == 'id':
             del bulk_edits[key]
     if bulk_edits:
         for form in self.bulk_forms:
             for key, value in bulk_edits.items():
                 if key == 'auto_categories':
                     # categories append, not replace
                     form.cleaned_data[key] = (
                         list(form.cleaned_data[key]) + list(value))
                 else:
                     form.cleaned_data[key] = value
             form.instance = construct_instance(form, form.instance,
                                                form._meta.fields,
                                                form._meta.exclude)
     return BaseModelFormSet.clean(self)
Пример #30
0
def save_instance(form, instance, fields=None, fail_message='saved',
                  commit=True, exclude=None, construct=True, user=None):
    """
    Saves bound Form ``form``'s cleaned_data into model instance ``instance``.

    If commit=True, then the changes to ``instance`` will be saved to the
    database. Returns ``instance``.

    If construct=False, assume ``instance`` has already been constructed and
    just needs to be saved.
    """
    if construct:
        instance = construct_instance(form, instance, fields, exclude)
    opts = instance._meta
    if form.errors:
        raise ValueError("The %s could not be %s because the data didn't"
                         " validate." % (opts.object_name, fail_message))

    # Wrap up the saving of m2m data as a function.
    def save_m2m():
        cleaned_data = form.cleaned_data
        # Note that for historical reasons we want to include also
        # virtual_fields here. (GenericRelation was previously a fake
        # m2m field).

        for f in list(opts.many_to_many) + opts.virtual_fields:
            if not hasattr(f, 'save_form_data'):
                continue
            if fields and f.name not in fields:
                continue
            if exclude and f.name in exclude:
                continue
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])
    if commit:
        # If we are committing, save the instance and the m2m data immediately.
        instance.save(user=user)
        save_m2m()
    else:
        # We're not committing. Add a method to the form to allow deferred
        # saving of m2m data.
        form.save_m2m = save_m2m
    return instance
Пример #31
0
 def clean(self):
     bulk_edits = self.extra_forms[0].cleaned_data
     for key in list(bulk_edits.keys()): # get the list because we'll be
                                         # changing the dictionary
         if bulk_edits[key] in ['', None] or key == 'id':
             del bulk_edits[key]
     if bulk_edits:
         for form in self.bulk_forms:
             for key, value in bulk_edits.items():
                 if key == 'auto_categories':
                     # categories append, not replace
                     form.cleaned_data[key] = (
                         list(form.cleaned_data[key]) +
                         list(value))
                 else:
                     form.cleaned_data[key] = value
             form.instance = construct_instance(form, form.instance,
                                                form._meta.fields,
                                                form._meta.exclude)
     return BaseModelFormSet.clean(self)
Пример #32
0
 def form_valid(self, form):
     form.instance.updated_by = self.request.user
     context = self.get_context_data()
     baseline_form = context['baseline_form']
     management_formset = context['formsets']['Management']
     outcome_formset = context['formsets']['Outcome']
     if baseline_form.is_valid() and management_formset.is_valid(
     ) and outcome_formset.is_valid():
         form.instance = construct_instance(baseline_form, form.instance)
         management_formset.instance = self.object
         for management_instance in management_formset.save(commit=False):
             management_instance.updated_by = self.request.user
             management_instance.save()
         outcome_formset.instance = self.object
         for outcome_instance in outcome_formset.save(commit=False):
             outcome_instance.updated_by = self.request.user
             outcome_instance.save()
         return super(PatientUpdateView, self).form_valid(form)
     else:
         return self.render_to_response(self.get_context_data(form=form))
Пример #33
0
def save_instance(form,
                  instance,
                  fields=None,
                  fail_message='saved',
                  commit=True,
                  exclude=None,
                  construct=True):
    """
    Saves bound Form ``form``'s cleaned_data into model instance ``instance``.

    If commit=True, then the changes to ``instance`` will be saved to the
    database. Returns ``instance``.

    If construct=False, assume ``instance`` has already been constructed and
    just needs to be saved.
    """
    if construct:
        instance = construct_instance(form, instance, fields, exclude)
    opts = instance._meta
    if form.errors:
        raise ValueError("The %s could not be %s because the data didn't"
                         " validate." % (opts.object_name, fail_message))

    # Wrap up the saving of m2m data as a function.
    def save_m2m():
        cleaned_data = form.cleaned_data
        for f in opts.many_to_many:
            if fields and f.name not in fields:
                continue
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])

    if commit:
        # If we are committing, save the instance and the m2m data immediately.
        instance.save()
        save_m2m()
    else:
        # We're not committing. Add a method to the form to allow deferred
        # saving of m2m data.
        form.save_m2m = save_m2m
    return instance
Пример #34
0
    def save(self, commit=True):
        ''' Saves the model
            If will always use the language specified in self.cleaned_data, with
            the usual None meaning 'call get_language()'. If instance has
            another language loaded, it gets reloaded with the new language.

            If no language is specified in self.cleaned_data, assume the instance
            is preloaded with correct language.
        '''
        if not self.is_valid():
            # raise in 1.3, remove in 1.5
            warnings.warn(
                'Calling save() on an invalid form is deprecated and '
                'will fail in the future. Check the result of .is_valid() '
                'before calling save().',
                DeprecationWarning,
                stacklevel=2)
            raise ValueError((_(
                "The %s could not be created because the data didn't validate."
            ) if self.instance.pk is None else _(
                "The %s could not be changed because the data didn't validate."
            )) % self.instance._meta.object_name)

        # Get the right translation for object and language
        # It should have been done in _post_clean, but instance may have been
        # changed since.
        enforce = 'language_code' in self.cleaned_data
        language = self.cleaned_data.get('language_code') or get_language()
        translation = load_translation(self.instance, language, enforce)

        # Fill the translated fields with values from the form
        excludes = list(self._meta.exclude) + ['master', 'language_code']
        translation = construct_instance(self, translation, self._meta.fields,
                                         excludes)
        set_cached_translation(self.instance, translation)

        # Delegate shared fields to super()
        return super(BaseTranslatableModelForm, self).save(commit=commit)
Пример #35
0
    def save(self, commit=True):
        ''' Saves the model
            If will always use the language specified in self.cleaned_data, with
            the usual None meaning 'call get_language()'. If instance has
            another language loaded, it gets reloaded with the new language.

            If no language is specified in self.cleaned_data, assume the instance
            is preloaded with correct language.
        '''
        if not self.is_valid():
            # raise in 1.3, remove in 1.5
            warnings.warn('Calling save() on an invalid form is deprecated and '
                          'will fail in the future. Check the result of .is_valid() '
                          'before calling save().', DeprecationWarning, stacklevel=2)
            raise ValueError((
                _("The %s could not be created because the data didn't validate.")
                if self.instance.pk is None else
                _("The %s could not be changed because the data didn't validate.")
                ) % self.instance._meta.object_name
            )

        # Get the right translation for object and language
        # It should have been done in _post_clean, but instance may have been
        # changed since.
        enforce = 'language_code' in self.cleaned_data
        language = self.cleaned_data.get('language_code') or get_language()
        translation = load_translation(self.instance, language, enforce)

        # Fill the translated fields with values from the form
        excludes = list(self._meta.exclude) + ['master', 'language_code']
        translation = construct_instance(self, translation,
                                         self._meta.fields, excludes)
        set_cached_translation(self.instance, translation)

        # Delegate shared fields to super()
        return super(BaseTranslatableModelForm, self).save(commit=commit)
Пример #36
0
def add_feed(request):
    add_form = forms.AddFeedForm(request.GET)

    if not add_form.is_valid():
        return HttpResponseBadRequest(add_form['feed_url'].errors.as_text())

    feed_url = add_form.cleaned_data['feed_url']
    scraped_feed = add_form.cleaned_data['scraped_feed']

    try:
        scraped_feed.load()
    except vidscraper.errors.CantIdentifyUrl:
        return HttpResponseBadRequest(
            '* It does not appear that %s is an RSS/Atom feed URL.' %
            (scraped_feed.url, ))
    except Exception:
        logging.error('unknown error loading scraped feed: %r',
                      feed_url,
                      exc_info=None)
        return HttpResponseBadRequest(
            '* There was an unknown error loading %s' % (feed_url, ))
    title = scraped_feed.title or ''

    for regexp in VIDEO_SERVICE_TITLES:
        match = regexp.match(title)
        if match:
            title = match.group(1)
            break

    defaults = {
        'name': title,
        'feed_url': feed_url,
        'webpage': scraped_feed.webpage or '',
        'description': scraped_feed.description or '',
        'etag': scraped_feed.etag or '',
        'when_submitted': datetime.datetime.now(),
        'last_updated': datetime.datetime.now(),
        'status': Feed.INACTIVE,
        'user': request.user,
        'auto_approve': bool(request.POST.get('auto_approve', False))
    }

    video_count = scraped_feed.entry_count

    if request.method == 'POST':
        if 'cancel' in request.POST:
            return HttpResponseRedirect(reverse('localtv_admin_manage_page'))

        form = forms.SourceForm(request.POST, instance=Feed(**defaults))
        if form.is_valid():
            feed, created = Feed.objects.get_or_create(
                feed_url=defaults['feed_url'],
                site=SiteSettings.objects.get_current().site,
                defaults=defaults)

            if not created:
                for key, value in defaults.items():
                    setattr(feed, key, value)

            construct_instance(form, feed)

            thumbnail_url = scraped_feed.thumbnail_url

            if thumbnail_url:
                try:
                    thumbnail_file = ContentFile(
                        urllib2.urlopen(
                            utils.quote_unicode_url(thumbnail_url)).read())
                except IOError:
                    # couldn't get the thumbnail
                    pass
                else:
                    try:
                        feed.save_thumbnail_from_file(thumbnail_file,
                                                      update=False)
                    except CannotOpenImageUrl:
                        # couldn't parse the thumbnail. Not sure why this
                        # raises CannotOpenImageUrl, tbh.
                        pass
            if feed.video_service():
                user, created = User.objects.get_or_create(
                    username=feed.name[:30], defaults={'email': ''})
                if created:
                    user.set_unusable_password()
                    Profile.objects.create(user=user,
                                           website=defaults['webpage'])
                    user.save()
                feed.auto_authors.add(user)
            feed.save()

            tasks.feed_update.delay(feed.pk,
                                    using=tasks.CELERY_USING,
                                    clear_rejected=True)

            return HttpResponseRedirect(reverse('localtv_admin_manage_page'))

    else:
        form = forms.SourceForm(instance=Feed(**defaults))
    return render_to_response('localtv/admin/add_feed.html', {
        'form': form,
        'video_count': video_count
    },
                              context_instance=RequestContext(request))
Пример #37
0
def add_feed(request):
    add_form = forms.AddFeedForm(request.GET)

    if not add_form.is_valid():
        return HttpResponseBadRequest(
            add_form['feed_url'].errors.as_text())

    feed_url = add_form.cleaned_data['feed_url']
    scraped_feed = add_form.cleaned_data['scraped_feed']

    try:
        scraped_feed.load()
    except vidscraper.errors.CantIdentifyUrl:
        return HttpResponseBadRequest(
            '* It does not appear that %s is an RSS/Atom feed URL.' % (
                scraped_feed.url,))
    except Exception:
        logging.error('unknown error loading scraped feed: %r',
                      feed_url,
                      exc_info=None)
        return HttpResponseBadRequest(
            '* There was an unknown error loading %s' % (
                feed_url,))
    title = scraped_feed.title or ''

    for regexp in VIDEO_SERVICE_TITLES:
        match = regexp.match(title)
        if match:
            title = match.group(1)
            break
        
    defaults = {
        'name': title,
        'feed_url': feed_url,
        'webpage': scraped_feed.webpage or '',
        'description': scraped_feed.description or '',
        'etag': scraped_feed.etag or '',
        'when_submitted': datetime.datetime.now(),
        'last_updated': datetime.datetime.now(),
        'status': Feed.INACTIVE,
        'user': request.user,

        'auto_approve': bool(request.POST.get('auto_approve', False))}

    video_count = scraped_feed.entry_count

    if request.method == 'POST':
        if 'cancel' in request.POST:
            return HttpResponseRedirect(reverse('localtv_admin_manage_page'))

        form = forms.SourceForm(request.POST, instance=Feed(**defaults))
        if form.is_valid():
            feed, created = Feed.objects.get_or_create(
                feed_url=defaults['feed_url'],
                site=SiteSettings.objects.get_current().site,
                defaults=defaults)

            if not created:
                for key, value in defaults.items():
                    setattr(feed, key, value)

            construct_instance(form, feed)

            thumbnail_url = scraped_feed.thumbnail_url

            if thumbnail_url:
                try:
                    thumbnail_file = ContentFile(
                        urllib2.urlopen(
                            utils.quote_unicode_url(thumbnail_url)).read())
                except IOError:
                    # couldn't get the thumbnail
                    pass
                else:
                    try:
                        feed.save_thumbnail_from_file(thumbnail_file,
                                                      update=False)
                    except CannotOpenImageUrl:
                        # couldn't parse the thumbnail. Not sure why this
                        # raises CannotOpenImageUrl, tbh.
                        pass
            if feed.video_service():
                user, created = User.objects.get_or_create(
                    username=feed.name[:30],
                    defaults={'email': ''})
                if created:
                    user.set_unusable_password()
                    Profile.objects.create(
                        user=user,
                        website=defaults['webpage'])
                    user.save()
                feed.auto_authors.add(user)
            feed.save()

            tasks.feed_update.delay(
                feed.pk,
                using=tasks.CELERY_USING,
                clear_rejected=True)

            return HttpResponseRedirect(reverse('localtv_admin_manage_page'))

    else:
        form = forms.SourceForm(instance=Feed(**defaults))
    return render_to_response('localtv/admin/add_feed.html',
                              {'form': form,
                               'video_count': video_count},
                              context_instance=RequestContext(request))
Пример #38
0
    def done(self, form_list, **kwargs):

        personal_details_instance = PersonalDetails()
        personal_contact_instance = PersonalContactDetail()
        transport_allocation_instance = TransportAllocation()
        hostel_allocation_instance = HostelAllocation()
        qualification_instance = Qualification()
        fee_collection_instance = FeeCollection()
        student_registration_instance = StudentRegistration()

        student_registration_instance.created_by = self.request.user

        student_registration_instance.personal_details = personal_details_instance

        student_registration_instance.personal_contact_detail = personal_contact_instance

        student_registration_instance.transport_allocation = transport_allocation_instance

        student_registration_instance.hostel_allocation = hostel_allocation_instance

        student_registration_instance.qualification = qualification_instance

        student_registration_instance.feecollection = fee_collection_instance

        for form in form_list:

            personal_details_instance = construct_instance(
                form, personal_details_instance, form._meta.fields,
                form._meta.exclude)

            personal_contact_instance = construct_instance(
                form, personal_contact_instance, form._meta.fields,
                form._meta.exclude)

            transport_allocation_instance = construct_instance(
                form, transport_allocation_instance, form._meta.fields,
                form._meta.exclude)

            hostel_allocation_instance = construct_instance(
                form, hostel_allocation_instance, form._meta.fields,
                form._meta.exclude)

            qualification_instance = construct_instance(
                form, qualification_instance, form._meta.fields,
                form._meta.exclude)

            fee_collection_instance = construct_instance(
                form, fee_collection_instance, form._meta.fields,
                form._meta.exclude)

            student_registration_instance = construct_instance(
                form, student_registration_instance, form._meta.fields,
                form._meta.exclude)

        personal_details_instance.save()
        personal_contact_instance.save()
        transport_allocation_instance.save()
        hostel_allocation_instance.save()
        qualification_instance.save()
        fee_collection_instance.save()
        student_registration_instance.save()

        return render(self.request, 'students/done.html', {
            'form_data': [form.cleaned_data for form in form_list],
        })
Пример #39
0
 def data_valid(self,sendtype):        
         obj= construct_instance(self, instance, fields)
         if hasattr(obj,"data_valid"):
             return obj.data_valid(sendtype)
         else:
             pass
Пример #40
0
def save_instance(form, instance, fields=None, fail_message='saved',
                  commit=True, exclude=None, construct=True):
    """
    Saves bound Form ``form``'s cleaned_data into model instance ``instance``.

    If commit=True, then the changes to ``instance`` will be saved to the
    database. Returns ``instance``.

    If construct=False, assume ``instance`` has already been constructed and
    just needs to be saved.

    This is almost identical to django's default ``save_instance``, except
    we add ``save_fk`` method which needs to be called before saving the
    instance in order to save those objects pointed to with a foreign key.

    """
    if construct:
        instance = construct_instance(form, instance, fields, exclude)
    opts = instance._meta
    if form.errors:
        raise ValueError("The %s could not be %s because the data didn't"
                         " validate." % (opts.object_name, fail_message))

    self_save_fk = getattr(form, 'save_fk', None)

    def save_fk():
        if self_save_fk:
            self_save_fk()

        cleaned_data = form.cleaned_data
        for f in opts.fields:
            if not isinstance(f, ForeignKey):
                continue
            if fields is not None and f.name not in fields:
                continue
            if exclude and f.name in exclude:
                continue
            if f.name in cleaned_data:
                data = cleaned_data[f.name]
                data.save()
                f.save_form_data(instance, data)

    # Wrap up the saving of m2m data as a function.
    self_save_m2m = getattr(form, 'save_m2m', None)

    def save_m2m():
        if self_save_m2m:
            self_save_m2m()

        cleaned_data = form.cleaned_data
        for f in opts.many_to_many:
            if fields is not None and f.name not in fields:
                continue
            if exclude and f.name in exclude:
                continue
            if f.name in cleaned_data:
                f.save_form_data(instance, cleaned_data[f.name])
        for f in form.fields.values():
            if isinstance(f, InlineFormSetField):
                if not f.widget.instance.pk:
                    f.widget.instance = instance
                f.widget.save()

    if commit:
        # If we are committing, save the instance and the m2m data immediately.
        save_fk()
        instance.save()
        save_m2m()
    else:
        # We're not committing. Add a method to the form to allow deferred
        # saving of m2m data.
        form.save_fk = save_fk
        form.save_m2m = save_m2m

    return instance
Пример #41
0
def modify_event_view(request, event_id=None, *args, **kwargs):
    active_link_id = "event"
    
    hash = 'event-tab'   
    main_person_form = PersonForm(auto_id='%s', prefix="main")
    person_form_prefix = 'person_from'
    person_form_number = 1    
    
    if event_id:
        action = reverse('edit_event', args=[event_id])
        event_instance = get_object_or_404(Event, pk=int(event_id))
    else:
        action = reverse('add_event')
        event_instance = None
        
    if request.method == 'POST': 
        event_form = EventForm(request.POST, request.FILES, instance=event_instance, auto_id='%s')
        if request.user.is_authenticated(): del event_form.fields['captcha']
        existing_persons_form = ExistingPersonsForm(request.POST, request.FILES, instance=event_instance, auto_id='%s')
        
        person_forms = []
        person_form_prefixes = filter(lambda p: p, request.POST['new_persons'].split(","))    
        existing_persons_form.fields['new_persons'].initial = ",".join(person_form_prefixes)
        for prefix in person_form_prefixes:
            person_forms.append(PersonForm(request.POST, request.FILES, auto_id='%s', prefix=prefix))
        person_form_number = max(map(lambda p: int(p.replace(person_form_prefix, "")), person_form_prefixes) or [0]) + 1
                
        error = False
        if not event_form.is_valid():
            error = True
            hash = 'event-tab'
        for person_form in person_forms:
            if not person_form.is_valid():
                error = True
                hash = 'person-tab'
                        
        if not error:  
            # Save event
            event = construct_instance(event_form, event_form.instance, ['subject', 'date_happened', 'date_ended', 'location', 'description', 'actions_taken', 'related_events'])
            
            if 'photo' in request.FILES:
                try: os.remove("%s/%s" % (settings.EVENT_IMAGES_DIR , request.POST['photo_path']))
                except: pass
                event.photo = save_request_file(settings.EVENT_IMAGES_DIR, request.FILES['photo'])
            elif event_instance:
                if 'remove_photo' not in request.POST:
                    event.photo = request.POST.get('photo_path', None)
                else:
                    try: os.remove("%s/%s" % (settings.EVENT_IMAGES_DIR , event.photo))
                    except: pass
                    event.photo = None
            if not request.user.is_authenticated(): event.status = 'unconfirmed'
            if request.user.is_authenticated(): event.modified_by = request.user
            event.save()
                
            # Save tags
            if event_instance:
                for i in event.tags.all():
                    event.tags.remove(i)
            for i in request.POST.getlist('tags'):      
                tag = Tag.objects.get(id=int(i))
                event.tags.add(tag)
                
            # Save related events
            if event_instance:
                for i in event.related_events.all():
                    event.related_events.remove(i)
            for i in request.POST.getlist('related_events'):      
                related_event = Event.objects.get(id=int(i))
                if related_event != event:
                    event.related_events.add(related_event)
                
            # Save attachments
            for attachment in request.POST.getlist('remove_attachments'):
                attachment = Attachment.objects.get(id=int(attachment))
                try: os.remove("%s/%s" % (settings.EVENT_ATTACHMENTS_DIR , attachment.filename))
                except: pass
                attachment.delete()
            for attachment in request.FILES.getlist('attachments'):
                filename = save_request_file(settings.EVENT_ATTACHMENTS_DIR, attachment)
                Attachment.objects.create(name=attachment.name, filename=filename, event=event)
                
            # Save persons
            if event_instance:
                for i in event.persons.all():
                    event.persons.remove(i)
            for i in request.POST.getlist('persons'):      
                person = Person.objects.get(id=int(i))
                event.persons.add(person)
            for person_form in person_forms:                
                person = person_form.save() 
                if not request.user.is_authenticated(): person.status = 'unconfirmed'
                if request.user.is_authenticated(): person.modified_by = request.user
                person.save()
                person_photo = '%s-person_photo' % person_form.prefix
                if person_photo in request.FILES:
                    person.person_photo = save_request_file(settings.PERSON_IMAGES_DIR, request.FILES[person_photo])
                    person.save()
                event.persons.add(person)
          
            return redirect(reverse('detail_event', args=[event.id]))
        else:
            event_form.fields['date_happened'].widget.attrs.update({'data-ignore-convert':'1'})
            event_form.fields['date_ended'].widget.attrs.update({'data-ignore-convert':'1'})
            for person_form in person_forms:
                person_form.fields['birth_date'].widget.attrs.update({'data-ignore-convert':'1'})
                person_form.fields['death_date'].widget.attrs.update({'data-ignore-convert':'1'})
    else:
        event_form = EventForm(instance=event_instance, auto_id='%s')
        if request.user.is_authenticated(): del event_form.fields['captcha']
        existing_persons_form = ExistingPersonsForm(instance=event_instance, auto_id='%s')
        person_forms = []
        
    title = 'ارسال رویداد جدید' if not request.user.is_authenticated() else ('ایجاد رویداد جدید' if not event_id else 'ویرایش رویداد')
    event_photo = event_instance and event_instance.photo or ''
    attachments = event_instance.attachments.all() if event_instance else []
      
    return render_to_response('event/modify.html', locals(), context_instance = RequestContext(request))
Пример #42
0
 def data_valid(self, sendtype):
     obj = construct_instance(self, instance, fields)
     if hasattr(obj, "data_valid"):
         return obj.data_valid(sendtype)
     else:
         pass
Пример #43
0
 def test_empty_fields_to_construct_instance(self):
     "No fields should be set on a model instance if construct_instance receives fields=()"
     form = modelform_factory(Person, fields="__all__")({'name': 'John Doe'})
     self.assertTrue(form.is_valid())
     instance = construct_instance(form, Person(), fields=())
     self.assertEqual(instance.name, '')