コード例 #1
0
ファイル: views.py プロジェクト: Karlamon/roundware-server
    def valid_all(self, valid_forms):
        """ handle case all forms valid
        """
        select = valid_forms['master_ui_select']  # don't save anything
        select  # pyflakes
        form = valid_forms['master_ui_edit']
        mui_id = form.cleaned_data.get('id')
        formtags = form.cleaned_data['ui_mappings_tags']

        defaults = form.data['master_ui_edit-ui_mappings_tag_order'].split(',')
        if form.cleaned_data['ui_mappings_tags_indexes']:
            indexes = form.cleaned_data['ui_mappings_tags_indexes'].split(',')
            indexes = [el.startswith('t') and el.replace('t', '') or
                       UIMapping.objects.select_related('tag').filter(
                       pk=el)[0].tag.pk for el in indexes]
        else:
            indexes = []
        if mui_id:
            mui = MasterUI.objects.filter(pk=mui_id)[0]
            uimaps = UIMapping.objects.select_related(
                'tag').filter(master_ui=mui)
            # instance isn't constructed yet with data from form so we can't
            # use form.save() but have to do the following with construct=True
            save_instance(form, mui, form._meta.fields, 'form changed', True,
                          form._meta.exclude, True)
            self.update_ui_mappings(uimaps, formtags, defaults, indexes, mui)

        else:
            mui = form.save()
            self.update_ui_mappings([], formtags, defaults, indexes, mui)
コード例 #2
0
    def save(self, commit=True):
        if self.instance.pk is None:
            fail_message = 'created'
            new = True
        else:
            fail_message = 'changed'
            new = False
        super(TranslatableModelForm, self).save(True)
        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.language_code = language_code
        trans.master = self.instance
        trans = save_instance(self, trans, self._meta.fields, fail_message,
                              commit, construct=True)
        return combine(trans, self.Meta.model)
コード例 #3
0
ファイル: forms.py プロジェクト: failedguidedog/django-nani
    def save(self, commit=True):
        if self.instance.pk is None:
            fail_message = 'created'
            new = True
        else:
            fail_message = 'changed'
            new = False
        super(TranslatableModelForm, self).save(True)
        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:
                try:
                    trans = get_translation(self.instance, language_code)
                except trans_model.DoesNotExist:
                    trans = trans_model()
        else:
            trans = trans_model()

        trans.language_code = language_code
        trans.master = self.instance
        trans = save_instance(self, trans, self._meta.fields, fail_message,
                              commit, construct=True)
        return combine(trans)
コード例 #4
0
ファイル: shed.py プロジェクト: nuthanmunaiah/toolshare
 def save(self, owner, address, commit=True):
     shed = Shed.objects.create(owner=owner, address=address, **self.cleaned_data)
     self.instance = shed
     fail_message = 'created'
     return save_instance(self, self.instance, self._meta.fields,
                          fail_message, commit, self._meta.exclude,
                          construct=False)
コード例 #5
0
ファイル: newman_admin.py プロジェクト: strogo/ella
 def save_new(self, form, commit=True):
     kwargs = {
         self.ct_field.get_attname(): CT_PUBLISHABLE.pk,
         self.ct_fk_field.get_attname(): self.instance.pk,
     }
     new_obj = self.model(**kwargs)
     return save_instance(form, new_obj, commit=commit)
コード例 #6
0
 def save_new(self, form, commit=True):
     kwargs = {
         self.ct_field.get_attname(): CT_PUBLISHABLE.pk,
         self.ct_fk_field.get_attname(): self.instance.pk,
     }
     new_obj = self.model(**kwargs)
     return save_instance(form, new_obj, commit=commit)
コード例 #7
0
ファイル: forms.py プロジェクト: jordic/django_tiny_shop
 def create_order(self, request, form=None):
     if request.session.get(settings.ORDER_KEY):
         uid = request.session[settings.ORDER_KEY]
         try:
             order = Order.objects.get(uid=uid)
             order.delete()
         except:
             pass
     
     #try to search if contact already exists in database
     try:
         contact = get_object_or_404(Client, email=self.cleaned_data['email'])
         self.instance = contact
         #print "he trobat instancia %s" % self.instance
     except:
         contact = None;
 
     #contact = save_instance(self, contact)
     if self.instance:
         contact = save_instance(self, self.instance, construct=True)
     else:
         self.save()
             
     c = cart_from_session(request)
     pay_type = self.cleaned_data['pago']
     
     order = order_from_cart(c, contact, pay_type, form)
     return order    
コード例 #8
0
ファイル: main.py プロジェクト: CARocha/albastryde
 def save_new(self, form, commit=True):
     """Saves and returns a new model instance for the given form."""
     kwargs = {self.fk.get_attname(): self.instance.pk}
     new_obj = self.model(**kwargs)
     for field, func in form._meta.autopopulate.iteritems():
         setattr(new_obj, field, func(form.request))
     return save_instance(form, new_obj, exclude=[self._pk_field.name], commit=commit)
コード例 #9
0
    def test_articleadminbase_save_related(self):
        form = self.article_admin.get_form(self.request, obj=self.article)({
            'date': self.date,
            'news_feed': self.feed.pk,
            'slug': 'bar',
            'title': 'Bar'
        })
        self.assertTrue(form.is_valid())

        save_instance(form, self.article, commit=False)
        formsets = self.article_admin.get_formsets_with_inlines(self.request)
        self.article_admin.save_related(self.request, form, formsets, True)

        form.save()
        self.request.user = MockSuperUser().pk
        self.article_admin.save_related(self.request, form, formsets, False)
コード例 #10
0
ファイル: generic.py プロジェクト: FredericoAndrade/django
 def save_new(self, form, commit=True):
     kwargs = {
         self.ct_field.get_attname(): ContentType.objects.get_for_model(self.instance).pk,
         self.ct_fk_field.get_attname(): self.instance.pk,
     }
     new_obj = self.model(**kwargs)
     return save_instance(form, new_obj, commit=commit)
コード例 #11
0
 def save_existing(self, form, instance, commit=True):
     """Saves and returns an existing model instance for the given form."""
     for field, func in form._meta.autopopulate.iteritems():
         setattr(instance, field, func(form.request))
     return save_instance(form,
                          instance,
                          exclude=[self._pk_field.name],
                          commit=commit)
コード例 #12
0
 def save_new(self, form, commit=True):
     kwargs = {
         self.ct_fk_field.get_attname(): self.instance.pk,
     }
     if self.ct_field:
         kwargs[self.ct_field.get_attname()] = get_id_for_instance(self.instance, for_concrete_model=self.for_concrete_model)
     new_obj = self.model(**kwargs)
     return save_instance(form, new_obj, commit=commit)
コード例 #13
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,
     }
     new_obj = self.model(**kwargs)
     return save_instance(form, new_obj, commit=commit)
コード例 #14
0
 def save(self, commit=True):
     if self.instance.pk is None:
         fail_message = 'created'
     else:
         fail_message = 'changed'
     transmeta_field_names = [f.lang_name for f in self.transmeta_fields.values()]
     default_fields = (self._meta.fields and list(self._meta.fields)) or []
     return save_instance(self, self.instance, default_fields + transmeta_field_names, fail_message, commit)
コード例 #15
0
ファイル: views.py プロジェクト: dragshare/test1
def upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            logging.info("Upload form is valid: %s" % form)
            upload = Upload()
            upload.uploaded_by = request.user
            upload.timestamp = datetime.datetime.now()
            
            save_instance(form, upload)
            logging.info("Saved upload: %s" % upload)
            request.user.message_set.create(message=_('Your file has been received.'))
        else:
            logging.error("invalid form: %s" % form)
            logging.error("form errors: %s" % form.errors)

    return HttpResponseRedirect(reverse('uploads'))
コード例 #16
0
ファイル: generic.py プロジェクト: dchang00/keekaa-back-end
 def save_new(self, form, commit=True):
     # Avoid a circular import.
     from django.contrib.contenttypes.models import ContentType
     kwargs = {
         self.ct_field.get_attname(): ContentType.objects.get_for_model(self.instance).pk,
         self.ct_fk_field.get_attname(): self.instance.pk,
     }
     new_obj = self.model(**kwargs)
     return save_instance(form, new_obj, commit=commit)
コード例 #17
0
ファイル: generic.py プロジェクト: becomingGuru/django
 def save_new(self, form, commit=True):
     # Avoid a circular import.
     from django.contrib.contenttypes.models import ContentType
     kwargs = {
         self.ct_field.get_attname(): ContentType.objects.get_for_model(self.instance).pk,
         self.ct_fk_field.get_attname(): self.instance.pk,
     }
     new_obj = self.model(**kwargs)
     return save_instance(form, new_obj, commit=commit)
コード例 #18
0
 def save_new(self, form, commit=True):
     """Saves and returns a new model instance for the given form."""
     kwargs = {self.fk.get_attname(): self.instance.pk}
     new_obj = self.model(**kwargs)
     for field, func in form._meta.autopopulate.iteritems():
         setattr(new_obj, field, func(form.request))
     return save_instance(form,
                          new_obj,
                          exclude=[self._pk_field.name],
                          commit=commit)
コード例 #19
0
ファイル: forms.py プロジェクト: katemy/django-ledger
 def save_existing(self, form, instance, commit=True):
     # ignore amount and quantity from POSTed transaction if reconciled
     exclude = [self._pk_field.name]
     if instance.id and instance.reconciled():
         exclude.extend((
             'amount',
             'quantity',
             'debit_reconciled',
             'credit_reconciled',
         ))
     return save_instance(form, instance, exclude=exclude, commit=commit)
コード例 #20
0
    def test_articleadminbase_save_related(self):
        form = self.article_admin.get_form(self.request, obj=self.article)({
            'date':
            self.date,
            'news_feed':
            self.feed.pk,
            'slug':
            'bar',
            'title':
            'Bar'
        })
        self.assertTrue(form.is_valid())

        save_instance(form, self.article, commit=False)
        formsets = self.article_admin.get_formsets_with_inlines(self.request)
        self.article_admin.save_related(self.request, form, formsets, True)

        form.save()
        self.request.user = MockSuperUser().pk
        self.article_admin.save_related(self.request, form, formsets, False)
コード例 #21
0
ファイル: formsets.py プロジェクト: creativify/merengueproj
 def save_new(self, form, commit=True):
     fk_attname = self.fk.get_attname()
     kwargs = {fk_attname: self.instance.pk}
     new_obj = self.model(**kwargs)
     if fk_attname == self._pk_field.attname:
         exclude = [self._pk_field.name]
     else:
         exclude = []
     if 'baselink_ptr' in form.cleaned_data and not form.cleaned_data['baselink_ptr']:
         del(form.cleaned_data['baselink_ptr'])
     return save_instance(form, new_obj, exclude=exclude, commit=commit)
コード例 #22
0
ファイル: formsets.py プロジェクト: teury/merengueproj
 def save_new(self, form, commit=True):
     fk_attname = self.fk.get_attname()
     kwargs = {fk_attname: self.instance.pk}
     new_obj = self.model(**kwargs)
     if fk_attname == self._pk_field.attname:
         exclude = [self._pk_field.name]
     else:
         exclude = []
     if 'baselink_ptr' in form.cleaned_data and not form.cleaned_data[
             'baselink_ptr']:
         del (form.cleaned_data['baselink_ptr'])
     return save_instance(form, new_obj, exclude=exclude, commit=commit)
コード例 #23
0
ファイル: shed.py プロジェクト: zchi88/toolshare
 def save(self, owner, address, commit=True):
     shed = Shed.objects.create(owner=owner,
                                address=address,
                                **self.cleaned_data)
     self.instance = shed
     fail_message = 'created'
     return save_instance(self,
                          self.instance,
                          self._meta.fields,
                          fail_message,
                          commit,
                          self._meta.exclude,
                          construct=False)
コード例 #24
0
ファイル: generic.py プロジェクト: MechanisM/django-easymode
 def save_new(self, form, commit=True):
     # Avoid a circular import.
     kwargs = {
         self.ct_field.get_attname(): ContentType.objects.get_for_model(self.instance).pk,
         self.ct_fk_field.get_attname(): self.instance.pk,
     }
     
     # try to add all data that can be used to initialize the model.
     cleaned_data = form.cleaned_data
     initial_data = dict([(key, cleaned_data[key]) for key  in cleaned_data.keys() if key in dir(self.model)])
     initial_data.update(kwargs)
     new_obj = self.model(**initial_data)
     return save_instance(form, new_obj, commit=commit)    
コード例 #25
0
ファイル: forms.py プロジェクト: mnts26/ManPower
    def save(self, commit=True):
        """
        Saves this ``form``'s cleaned_data into model instance
        ``self.instance``.

        If commit=True, then the changes to ``instance`` will be saved to the
        database. Returns ``instance``.
        """
        if self.instance.pk is None:
            fail_message = 'created'
        else:
            fail_message = 'changed'
        return save_instance(self, self.instance, self._meta.fields, fail_message, commit)
コード例 #26
0
ファイル: add.py プロジェクト: airstrike/athena
    def form_valid(self, form):
        logging.info("Upload form is valid: %s" % form)
        self.upload = Upload()
        self.upload.created_by = self.request.user
        self.upload.last_edited_by = self.request.user
        self.status = 1
        self.upload.timestamp = datetime.datetime.now()
        self.cache_key = None

        if 'X-Progress-ID' in self.request.GET:
            self.progress_id = self.request.GET['X-Progress-ID']
            self.cache_key = "%s_%s" % (self.request.META['REMOTE_ADDR'], self.progress_id)
            self.upload.cache_key = self.cache_key

        save_instance(form, self.upload, commit=False)

        self.upload.save()
        self.uploaded = self.upload.file
        upload_task = tasks.Convert
        task_opts = {'user_pk': self.request.user.pk,
                     'upload_pk': self.upload.pk,
                     'cache': self.cache_key,
                     'converter': form.cleaned_data.get('converter', None)}

        logging.debug(task_opts)
        result = upload_task.delay(task_opts, callback=subtask(tasks.delete_upload))

        self.upload.celery_task_id = result.task_id
        self.upload.result = result.status
        self.upload.update_progress()
        self.upload.save()

        logging.info("Saved upload: %s" % self.upload)

        error(self.request, u'%s' % _('File %s is being processed.') % self.uploaded)

        return super(UploadAdd, self).form_valid(form)
コード例 #27
0
ファイル: generic.py プロジェクト: alexsilva/Report
    def save_new(self, form, commit=True):
        # Avoid a circular import.
        kwargs = {
            self.ct_field.get_attname():
            ContentType.objects.get_for_model(self.instance).pk,
            self.ct_fk_field.get_attname():
            self.instance.pk,
        }

        # try to add all data that can be used to initialize the model.
        cleaned_data = form.cleaned_data
        initial_data = dict([(key, cleaned_data[key])
                             for key in cleaned_data.keys()
                             if key in dir(self.model)])
        initial_data.update(kwargs)
        new_obj = self.model(**initial_data)
        return save_instance(form, new_obj, commit=commit)
コード例 #28
0
ファイル: forms.py プロジェクト: jamilatta/scielo-manager
 def save(self, commit=True):
     instance = self.instance or models.Issue()
     if self.is_valid():
         return save_instance(self, instance, commit=commit)
     else:
         return None
コード例 #29
0
ファイル: newman_admin.py プロジェクト: rpgplanet/ella
    def save(self, commit=True):
        cleaned_list_cats = self.cleaned_data.pop("listings")
        list_cats = []
        # Order of items should be preserved (in cleaned_data is order not preserved)
        for pk in self.data.getlist(self.get_part_id("")):
            list_cats.append(Category.objects.get(pk=int(pk)))
        publish_from_fields = self.data.getlist(self.get_part_id("publish_from"))
        instance = self.instance

        def save_them():
            if not list_cats:
                return
            listings = dict([(l.category, l) for l in Listing.objects.filter(placement=instance.pk)])
            forloop_counter = 0  # used for counting delete checkboxes
            for c, pub in zip(list_cats, publish_from_fields):
                forloop_counter += 1
                delete_listing = self.data.get(self.get_part_id("%d-DELETE" % forloop_counter), "off")
                if delete_listing == "on":
                    # skip following for-cycle body, so the listing will be deleted
                    continue
                publish_from = self.get_publish_date(pub)
                if not c in listings:
                    # create listing
                    l = Listing(placement=instance, category=c, publish_from=publish_from)
                    l.save()
                else:
                    del listings[c]
                    lst = Listing.objects.filter(placement=instance, category=c)
                    if not lst:
                        continue
                    l = lst[0]
                    # if publish_from differs, modify Listing object
                    if l.publish_from != publish_from:
                        l.publish_from = publish_from
                        l.save()
            for l in listings.values():
                l.delete()

        if commit:
            save_them()
        else:
            save_m2m = getattr(self, "save_m2m", None)

            def save_all():
                if save_m2m:
                    save_m2m()
                save_them()

            self.save_m2m = save_all
        instance.category = self.cleaned_data["category"]
        instance.publish_from = self.cleaned_data["publish_from"]
        instance.publish_to = self.cleaned_data["publish_to"]
        instance.slug = self.cleaned_data["slug"]
        instance.static = self.cleaned_data["static"]
        if not commit:
            return instance
        if self.instance.pk is None:
            fail_message = "created"
        else:
            fail_message = "changed"
        return save_instance(self, instance, self._meta.fields, fail_message, commit, exclude=self._meta.exclude)
コード例 #30
0
ファイル: products.py プロジェクト: techpub/whats-fresh-api
def product(request, id=None):
    """
    */entry/products/<id>*, */entry/products/new*

    The entry interface's edit/add/delete product view. This view creates the
    edit page for a given product, or the "new product" page if it is not
    passed an ID. It also accepts POST requests to create or edit products, and
    DELETE requests to delete them.

    If called with DELETE, it will return a 200 upon success or a 404 upon
    failure. This is to be used as part of an AJAX call, or some other API
    call.
    """
    if request.method == 'DELETE':
        product = get_object_or_404(Product, pk=id)
        product.delete()
        return HttpResponse()

    if request.method == 'POST':
        message = ''
        post_data = request.POST.copy()
        errors = []

        try:
            if len(post_data['preparation_ids']) == 0:
                errors.append("You must choose at least one preparation.")
                preparations = []
            else:
                preparations = [int(p) for p in set(
                    post_data['preparation_ids'].split(','))]
        except MultiValueDictKeyError:
            errors.append("You must choose at least one preparation.")
            preparations = []

        if id:
            product = Product.objects.get(id=id)
        else:
            product = None

        product_form = ProductForm(post_data, product)
        if product_form.is_valid() and not errors:
            if id:
                for preparation in product.preparations.all():
                    # Delete any that aren't in the returned list
                    if preparation.id not in preparations:
                        product_preparation = ProductPreparation.objects.get(
                            product=product, preparation=preparation)
                        product_preparation.delete()
                    # And ignore any that are in both the existing and the
                    # returned list
                    elif preparation.id in preparations:
                        preparations.remove(preparation.id)
                # Then, create all of the new ones
                for preparation in preparations:
                    preparation = ProductPreparation.objects.create(
                        product=product,
                        preparation=Preparation.objects.get(
                            id=preparation))
                save_instance(product_form, product)
            else:
                product = Product.objects.create(**product_form.cleaned_data)
                for preparation in preparations:
                    product_preparation = ProductPreparation.objects.create(
                        product=product,
                        preparation=Preparation.objects.get(
                            id=preparation))
                product.save()
            return HttpResponseRedirect(
                "%s?saved=true" % reverse('entry-list-products'))
    else:
        errors = []
        message = ''

    if id:
        product = Product.objects.get(id=id)
        title = "Edit {0}".format(product.name)
        post_url = reverse('edit-product', kwargs={'id': id})
        product_form = ProductForm(instance=product)

        existing_preparations = product.preparations.all()

        if request.GET.get('success') == 'true':
            message = "Product saved successfully!"

    elif request.method != 'POST':
        product_form = ProductForm()
        post_url = reverse('new-product')
        title = "New Product"
        existing_preparations = []

    else:
        post_url = reverse('new-product')
        title = "New Product"
        existing_preparations = []

    data = {'preparations': []}

    for preparation in Preparation.objects.all():
        data['preparations'].append({
            'id': preparation.id,
            'name': preparation.name
        })

    json_preparations = json.dumps(data)

    return render(request, 'product.html', {
        'parent_url': [
            {'url': reverse('home'), 'name': 'Home'},
            {'url': reverse('entry-list-products'), 'name': 'Products'}],
        'json_preparations': json_preparations,
        'preparation_dict': data,
        'existing_preparations': existing_preparations,
        'parent_text': 'Product List',
        'message': message,
        'title': title,
        'post_url': post_url,
        'errors': errors,
        'product_form': product_form,
    })
コード例 #31
0
ファイル: newman_admin.py プロジェクト: joskid/ella
    def save(self, commit=True):
        cleaned_list_cats = self.cleaned_data.pop('listings')
        list_cats = []
        # Order of items should be preserved (in cleaned_data is order not preserved)
        for pk in self.data.getlist( self.get_part_id('') ):
            list_cats.append(Category.objects.get(pk=int(pk)))
        publish_from_fields = self.data.getlist(self.get_part_id('publish_from'))
        commercial_fields = self.data.getlist(self.get_part_id('commercial'))
        # commercial_fields are optionul thus
        if len(commercial_fields) != len(list_cats):
            commercial_fields = [ None for c in list_cats ]
        else:
            commercial_fields = [ int(f) for f in commercial_fields ]

        instance = self.instance

        def save_them():
            if not list_cats:
                return
            listings = dict([ (l.category, l) for l in Listing.objects.filter(placement=instance.pk) ])
            forloop_counter = 0 # used for counting delete checkboxes
            for c, pub, commercial in zip(list_cats, publish_from_fields, commercial_fields):
                forloop_counter += 1
                delete_listing = self.data.get(self.get_part_id('%d-DELETE' % forloop_counter), 'off')
                if delete_listing == 'on':
                    # skip following for-cycle body, so the listing will be deleted
                    continue
                publish_from = self.get_publish_date(pub)
                if not c in listings:
                    # create listing
                    l = Listing(
                        placement=instance,
                        category=c,
                        publish_from=publish_from
                    )
                    if commercial is not None:
                        l.commercial = commercial
                    l.save()
                else:
                    del listings[c]
                    lst = Listing.objects.filter(placement=instance, category=c)
                    if not lst:
                        continue
                    l = lst[0]
                    # if publish_from differs, modify Listing object
                    if l.publish_from != publish_from or (commercial is not None and l.commercial != commercial):
                        l.publish_from = publish_from
                        if commercial is not None:
                            l.commercial = commercial
                        l.save()
            for l in listings.values():
                l.delete()

        if commit:
            save_them()
        else:
            save_m2m = getattr(self, 'save_m2m', None)
            def save_all():
                if save_m2m:
                    save_m2m()
                save_them()
            self.save_m2m = save_all
        instance.category = self.cleaned_data['category']
        instance.publish_from = self.cleaned_data['publish_from']
        instance.publish_to = self.cleaned_data['publish_to']
        instance.slug = self.cleaned_data['slug']
        instance.static = self.cleaned_data['static']
        if not commit:
            return instance
        if self.instance.pk is None:
            fail_message = 'created'
        else:
            fail_message = 'changed'
        return save_instance(self, instance, self._meta.fields,
                             fail_message, commit, exclude=self._meta.exclude)
コード例 #32
0
ファイル: main.py プロジェクト: CARocha/albastryde
 def save_existing(self, form, instance, commit=True):
     """Saves and returns an existing model instance for the given form."""
     for field, func in form._meta.autopopulate.iteritems():
         setattr(instance, field, func(form.request))
     return save_instance(form, instance, exclude=[self._pk_field.name], commit=commit)
コード例 #33
0
def product(request, id=None):
    """
    */entry/products/<id>*, */entry/products/new*

    The entry interface's edit/add/delete product view. This view creates the
    edit page for a given product, or the "new product" page if it is not
    passed an ID. It also accepts POST requests to create or edit products, and
    DELETE requests to delete them.

    If called with DELETE, it will return a 200 upon success or a 404 upon
    failure. This is to be used as part of an AJAX call, or some other API
    call.
    """
    if request.method == 'DELETE':
        product = get_object_or_404(Product, pk=id)
        product.delete()
        return HttpResponse()

    if request.method == 'POST':
        message = ''
        post_data = request.POST.copy()
        errors = []

        try:
            if len(post_data['preparation_ids']) == 0:
                errors.append("You must choose at least one preparation.")
                preparations = []
            else:
                preparations = [
                    int(p)
                    for p in set(post_data['preparation_ids'].split(','))
                ]
        except MultiValueDictKeyError:
            errors.append("You must choose at least one preparation.")
            preparations = []

        if id:
            product = Product.objects.get(id=id)
        else:
            product = None

        product_form = ProductForm(post_data, product)
        if product_form.is_valid() and not errors:
            if id:
                for preparation in product.preparations.all():
                    # Delete any that aren't in the returned list
                    if preparation.id not in preparations:
                        product_preparation = ProductPreparation.objects.get(
                            product=product, preparation=preparation)
                        product_preparation.delete()
                    # And ignore any that are in both the existing and the
                    # returned list
                    elif preparation.id in preparations:
                        preparations.remove(preparation.id)
                # Then, create all of the new ones
                for preparation in preparations:
                    preparation = ProductPreparation.objects.create(
                        product=product,
                        preparation=Preparation.objects.get(id=preparation))
                save_instance(product_form, product)
            else:
                product = Product.objects.create(**product_form.cleaned_data)
                for preparation in preparations:
                    product_preparation = ProductPreparation.objects.create(
                        product=product,
                        preparation=Preparation.objects.get(id=preparation))
                product.save()
            return HttpResponseRedirect("%s?saved=true" %
                                        reverse('entry-list-products'))
    else:
        errors = []
        message = ''

    if id:
        product = Product.objects.get(id=id)
        title = "Edit {0}".format(product.name)
        post_url = reverse('edit-product', kwargs={'id': id})
        product_form = ProductForm(instance=product)

        existing_preparations = product.preparations.all()

        if request.GET.get('success') == 'true':
            message = "Product saved successfully!"

    elif request.method != 'POST':
        product_form = ProductForm()
        post_url = reverse('new-product')
        title = "New Product"
        existing_preparations = []

    else:
        post_url = reverse('new-product')
        title = "New Product"
        existing_preparations = []

    data = {'preparations': []}

    for preparation in Preparation.objects.all():
        data['preparations'].append({
            'id': preparation.id,
            'name': preparation.name
        })

    json_preparations = json.dumps(data)

    return render(
        request, 'product.html', {
            'parent_url': [{
                'url': reverse('home'),
                'name': 'Home'
            }, {
                'url': reverse('entry-list-products'),
                'name': 'Products'
            }],
            'json_preparations':
            json_preparations,
            'preparation_dict':
            data,
            'existing_preparations':
            existing_preparations,
            'parent_text':
            'Product List',
            'message':
            message,
            'title':
            title,
            'post_url':
            post_url,
            'errors':
            errors,
            'product_form':
            product_form,
        })
コード例 #34
0
    def save(self, commit=True):
        cleaned_list_cats = self.cleaned_data.pop('listings')
        list_cats = []
        # Order of items should be preserved (in cleaned_data is order not preserved)
        for pk in self.data.getlist(self.get_part_id('')):
            list_cats.append(Category.objects.get(pk=int(pk)))
        publish_from_fields = self.data.getlist(
            self.get_part_id('publish_from'))
        instance = self.instance

        def save_them():
            if not list_cats:
                return
            listings = dict([
                (l.category, l)
                for l in Listing.objects.filter(placement=instance.pk)
            ])
            forloop_counter = 0  # used for counting delete checkboxes
            for c, pub in zip(list_cats, publish_from_fields):
                forloop_counter += 1
                delete_listing = self.data.get(
                    self.get_part_id('%d-DELETE' % forloop_counter), 'off')
                if delete_listing == 'on':
                    # skip following for-cycle body, so the listing will be deleted
                    continue
                publish_from = self.get_publish_date(pub)
                if not c in listings:
                    # create listing
                    l = Listing(placement=instance,
                                category=c,
                                publish_from=publish_from)
                    l.save()
                else:
                    del listings[c]
                    lst = Listing.objects.filter(placement=instance,
                                                 category=c)
                    if not lst:
                        continue
                    l = lst[0]
                    # if publish_from differs, modify Listing object
                    if l.publish_from != publish_from:
                        l.publish_from = publish_from
                        l.save()
            for l in listings.values():
                l.delete()

        if commit:
            save_them()
        else:
            save_m2m = getattr(self, 'save_m2m', None)

            def save_all():
                if save_m2m:
                    save_m2m()
                save_them()

            self.save_m2m = save_all
        instance.category = self.cleaned_data['category']
        instance.publish_from = self.cleaned_data['publish_from']
        instance.publish_to = self.cleaned_data['publish_to']
        instance.slug = self.cleaned_data['slug']
        instance.static = self.cleaned_data['static']
        if not commit:
            return instance
        if self.instance.pk is None:
            fail_message = 'created'
        else:
            fail_message = 'changed'
        return save_instance(self,
                             instance,
                             self._meta.fields,
                             fail_message,
                             commit,
                             exclude=self._meta.exclude)
コード例 #35
0
ファイル: forms.py プロジェクト: jamilatta/scielo-manager
 def save(self, commit=True):
     instance = self.instance or models.Issue()
     if self.is_valid():
         return save_instance(self, instance, commit=commit)
     else:
         return None
コード例 #36
0
ファイル: wizard.py プロジェクト: vivek2010/django_bolts
 def save(self,instance=None,commit=False):
     instance = instance or self.instance or (self.model() if self.model else None)
     if not instance: return None
     if self.model and not isinstance(instance,self.model): return None
     save_instance(self,instance,commit=commit)
     return instance