Skip to main content

Django application that allows creation, preview and usage of custom multivariant restrictions applied on the forms.

Project description

Demo application

  1. You can check it online http://offermaker.kjw.pt

  2. Or checkout and install locally:

    git clone git@bitbucket.org:kkujawinski/offer-maker-demo-site.git

Quick start

  1. Install django-offermaker

    pip install django-offermaker
  2. Site configuration in settings.py

    INSTALLED_APPS = (
        ...
        'offermaker',
    )
  3. Create Django form:

    from django import forms
    
    class MyForm(forms.Form):
        product = forms.ChoiceField(
            label=u'Product',
            choices=(
                ('', '---'), ('PROD1', 'Product X'), ('PROD2', 'Product Y'), ('PROD3', 'Product Z'),
            ),
            required=False)
        crediting_period = forms.ChoiceField(
            label=u'Crediting period',
            choices=(('', '---'), ('12', '12'), ('24', '24'), ('36', '36'), ('48', '48')))
        interest_rate = forms.FloatField(label=u'Interest rate', min_value=1, max_value=5)
        contribution = forms.FloatField(label=u'Contribution', min_value=0)
  4. Define your offer (in case you do not store it in database):

    offer = {
        'variants': [
            [{
                'params': {'product': 'PROD1', 'crediting_period': ['24']},
            }, {
                'params': {'product': 'PROD2'},
                'variants': [
                    {'params': {'crediting_period': ['12']}},
                    {'params': {'crediting_period': ['36']}},
                    {'params': {'crediting_period': ['48']}}]
            }, {
                'params': {'product': 'PROD3'},
            }],
            [{
                'params': {'product': 'PROD1'},
                'variants': [
                    {'params': {'contribution': (10, 20), 'interest_rate': (2, 2)}},
                    {'params': {'contribution': (30, 40), 'interest_rate': (4, 4)}}]
            }, {
                'params': {'product': ['PROD2', 'PROD3']},
                'variants': [{
                    'params': {'contribution': (30, 70), 'interest_rate': (5, 5)}
                }]
            }]
        ]
    }
  5. Offer form:

  1. Use dispatcher code in Django view

    import offermaker
    
    def my_form_view(request):
        core_object = offermaker.OfferMakerCore(DemoOfferMakerForm, offer)
    
        def handler_get(form):
            return render(request, 'my_form.html', ({'form': form})
    
        def handler_post(form):
            if form.is_valid():
                return HttpResponseRedirect('success')
            return handler_get(form)
    
        dispatcher = offermaker.OfferMakerDispatcher.from_core_object(handler_get, handler_post, core_object=core_object)
        return dispatcher.handle_request(request)
  2. Initialize offerform in template

    <head>
    {% load offermaker %}
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    {% offermaker_javascript %}
    </head>
    
    <body>
    
    <form action="?" method="post" id="offer_form">
        <div class="alert-placeholder" style="height: 30px;"></div>
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>
    
    
    <script type="text/javascript">
        (function() {
            $('#offer_form').offer_form();
        })();
    </script>
  1. Offer preview:

  1. Pass offerform object from view to template:

    def my_form_view(request):
        core_object = offermaker.OfferMakerCore(DemoOfferMakerForm, offer)
  2. Use proper template tag in template to print table:

    {% load offermaker %}
    
    {% offermaker_preview offer %}
  1. Offer editor:

  1. Use OfferJSONField field in your model. Remember to pass your django form created in 3.:

    import offermaker
    
    class MyOffer(models.Model):
        id = models.AutoField(primary_key=True)
        name = models.CharField(max_length=30)
        offer = offermaker.OfferJSONField(form_object=MyForm())
  2. Create your own Admin Site for model:

    import models
    
    class OfferAdmin(admin.ModelAdmin):
        list_display = ('name',)
        search_fields = ('name', 'user')
        fields = ('name', 'offer')
    
    admin.site.register(models.Offer, OfferAdmin)

Basic customization

  1. Using offers stored in database:

  1. you need to pass proper offer object to Offermaker in form/preview view:

    offer = MyOffer.objects.filter(id=request.GET['id']).first()
    core_object = offermaker.OfferMakerCore(DemoOfferMakerForm, offer.offer)
  2. and configure proper params to be used ajax requests:

    $('#offer_form').offer_form({
        ajax_extra_params: function(params) {
            return { id: {{ request.GET.id }} };
        },
    });
  1. Substituting builtin formatters for infotip and error alerts:

    $('#offer_form').offer_form({
        error_alert_factory: function (msg) {
            var $error = $('<p class="error"><span>' + msg + '</span></p>');
            $('.alert-placeholder', $form).append($error);
            return $error;
        },
        tooltip_factory: function ($field, msg) {
            var $tooltip = $('<p class="infotip">' + msg + '</p>');
            $field.parent().append($tooltip);
            return $tooltip;
        }
    });
  2. Use builtin formatters for Twitter Bootstap3:

    (function() {
        $('#offer_form').offer_form({
            bootstrap3: true,
        });
    })();
  3. Customizing messages:

    (function() {
        $('#offer_form').offer_form({
            msgs: {
                'NO_VARIANTS': 'No matching variants',
                'INFO_ITEMS': 'Available values are: %s.',
                'INFO_FIXED': 'Only available value is %s.',
                'RANGE_left': 'to %2$s',
                'RANGE_right': 'from %1$s',
                'RANGE_both': 'from %1$s to %2$s',
                'AND': ' and '
            },
            iteration_str: function (items) {
                return items.slice(0, -2).concat(items.slice(-2).join(msgs.AND)).join(', ');
            }
        });
    })();
  4. Creating preview table for certain fields:

    {% offermaker_preview offer fields='product, crediting_period' %}
  5. Add html attributes to generated preview table:

    {% offermaker_preview offer class='table table-bordered' %}

Troubleshooting

  1. I run Django 1.5 and I have jQuery older than 1.9.

You need to add new jQuery library dependency in you django admin site:

class OfferAdmin(admin.ModelAdmin):
    ...
    class Media:
        js = ('//code.jquery.com/jquery-1.11.0.min.js',)
  1. I run Django 1.5 and django-offermaker doesn’t recognize field types properly.

Django 1.5 admin site is not using HTML5 input types (ex. number), you can give hint to django-offermaker about field type with following code:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['interest_rate'].widget.attrs['data-om-type'] = 'number'
    self.fields['interest_rate'].widget.attrs['data-om-min'] = 1
    self.fields['interest_rate'].widget.attrs['data-om-max'] = 5
    self.fields['contribution'].widget.attrs['data-om-type'] = 'number'
    self.fields['contribution'].widget.attrs['data-om-min'] = 0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-offermaker-0.9.3.tar.gz (108.3 kB view details)

Uploaded Source

File details

Details for the file django-offermaker-0.9.3.tar.gz.

File metadata

File hashes

Hashes for django-offermaker-0.9.3.tar.gz
Algorithm Hash digest
SHA256 f8306851305b24541486cc754da8d4d5dc23d7eb8ef74c5f7d4698b2918e45e6
MD5 bda9d3eb6fa247edf8469be29d662a3c
BLAKE2b-256 8084b0fa355ce632ee89aabcb44f22f10c0c0ed00c47fb99c6faeeecbbbf8843

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page