mercredi 6 mai 2015

adding dynamically a property to a class in HTML

I've got these css classes:

planning a span.icon {
    background-image:url(../img/icon1.png);
    background-position:left top;
    background-repeat:no-repeat;

.planning a:hover span.icon {
    background-position: left bottom;
}

In my template, I want to loop on an item (blurb) and dynamically update the value for the property background-image.

For now, I've tried to remove background-image from css class and added it in the template without success:

{% for blurb in page.homepage.blurbs.all %}
    <div class="span4">
    <a href={{ blurb.link }}>
    <span class="img_icon icon" style="background-image: {% static blurb.icon %}"></span>
       </a>
     </div>
{% endfor %}

It ends up that the background-image property isn't attributed to the class icon.

Any idea to do the trick?

Replace ArrayField for several fields from other models: ArrayField(ForeignKey) emulation in django-admin

I want to store model fields as array of foreign keys to other atomic-Models. It makes model more flexible: I can add/remove/inherit(if it's tree node) any of predefined properties without programming.

Let's start with atomic-Models. It contain some classified properties.

class Liquid(models.Model):
    volume = models.DecimalField(max_digits=12, decimal_places=6)

class Granular(models.Model):
    weight = models.DecimalField(max_digits=16, decimal_places=9)

class Serial(models.Model):
    lot_number = models.CharField(max_length=16)
    estimated_release_time = models.DateTimeField()
    deadline_time = models.DateTimeField())

I want to emulate the following code. It's not valid because:
1. I want to store foreign keys to several models (GenericForeignKey can help);
2. ArrayField doesn't support array of foreign keys yet;

class Entity(models.Model):
        arr = ArrayField(models.ForeignKey(DifferentAtomicModels))

Emulation is the following. Where even numbers is pk of django.contrib.contenttypes.models.ContentType, odd numbers is pk of atomic-Model (atomic-model obtained from the previous even number).

class Entity(models.Model):
    arr = ArrayField(models.IntegerField(), null=True, blank=True)

Well, in in django-admin changelist_view and changeform_view I want to replace arr field with the fields obtained from it.

What is the way to achieve this? Where it's better to intervene to django-admin behaviour (override formfield, make custom widget, smth. else...)?

P.S. What kind of emulation is better?

class Entity(models.Model):
    em01 = ArrayField(models.IntegerField())  # "ContentType_pk", "Model_pk", ...
    em02 = ArrayField(ArrayField(models.IntegerField(), size=2))  # "ContentType_pk", "Model_pk", ...
    em03 = ArrayField(ArrayField(models.CharField(), size=2))  # "Model_name", "Model_pk", ...
    em11 = HStoreField()  # {"ContentType_pk": "Model_pk"}
    em12 = HStoreField()  # {"Model_name": "Model_pk"}

How is this code supposed to be intended?

I'm learning django and python and I want to know how to indent this code properly. How should it be done?

{% block content %}
    <h2>Nyinkommet</h2>
    {% if request.GET.sorting == 'desc' %}
        <form method="get" action=".">
        <input type="hidden" name="sorting" value="asc">
        <input type="submit" value="Visa äldsta ärende först">
        </form>
    {% else %}
        <form method="get" action=".">
        <input type="hidden" name="sorting" value="desc">
        <input type="submit" value="Visa nyaste ärende först">
        </form>
{% endif %} 

How to get the custom payload from pyapns using phonegap push plugin?

we are using PYAPNS to send push notifications from an Django application to iOS devices running an phonegap application.

The server code looks like this:

def sendNotificationAPNS(title, message, targets, eventid):
    apns = APNs(use_sandbox=False, cert_file='/path/to/push_cert.pem', key_file='/path/to/push_cert.pem')

        # Send a notification
        for token_hex in targets:
            payload = Payload(alert=message, sound="default", badge=1, custom={'eventid':str(eventid)})
            apns.gateway_server.send_notification(token_hex, payload)
            print('Notification to APNS send!')

        return true

On the mobile application the code from Phonegap Push Plugin looks like this:

// handle APNS notifications for iOS
function onNotificationAPN(e) {
    if (e.alert) {
        console.log('APNS Notifiation recieved: ' +  e.alert);
        // showing an alert also requires the org.apache.cordova.dialogs plugin
        navigator.notification.alert(e.alert);
    }

    if (e.sound) {
        // playing a sound also requires the org.apache.cordova.media plugin
        var snd = new Media(e.sound);
        snd.play();
    }

    if (e.badge) {
        pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
    }
    //eventid
    if(e.eventid) {
        console.log('APNS eventid: ' + e.eventid);
    }

    //custom
    if(e.custom) {
        console.log('APNS eventid: ' + e.custom.eventid);
    }
}

The problem is: I don't get anything for e.custom or e.eventid?! What do I have to change to access the custom payload?

Thanks!

Show messages in Django

I am using Django's message framework.

When I have this view:

class ItemUpdateView(UpdateView):
    model = Item
    template_name = 'item_update_form.html'
    fields = ['name',]

    def dispatch(self, request, *args, **kwargs):
        messages.success(request, 'test')
        return super(ItemUpdateView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        messages.success(self.request, "test")
        return super(ItemUpdateView, self).form_valid(form)

it does show a message from the dispatch method but if I'm updating the object, the message from form_valid wont be shown.

What can cause the code not to show the message from form_valid?

Is the back end needed only to produce RESTful API?

I've just started learning Django and from the first tutorials i've followed or test i've done, it seemed to me (note: i'm a beginner at the whole web developing thing) that you can use it to do anything (back end as well as front end). Now thinking about the many frameworks and libraries for the front end I thought that I was missing something, so after a bit of research i came to the conclusion that the back end part is there only to provide a rest service to use with a front end framework. Do anyone for example uses the templates in Django, if so for what purposes? Am I missing something about front end - back end integration?

Thanks.

Create form from related models

I have 2 models, Message and Attachment. I want to use these in one form. The Attachment should have a reference to the message (a message can have more than 1 attachment).

Models:

class Message(models.Model): 
    createdby   = models.ForeignKey(User)
    subject     = models.CharField(max_length=200, null=True)
    body        = models.TextField(default=None,   blank=True)

class Attachment(models.Model):
    docfile     = models.FileField(upload_to='documents/%Y/%m/%d')
    message     = models.ForeignKey(Message,  null=True)

Forms

class MessageForm(forms.ModelForm):
    class Meta:
        model   = Message

AttachmentFormSet = inlineformset_factory(Message, Attachment, extra=1 )

Views

class MessageCreateView(CreateView):
     model       = Message
     fields      = ["subject", "body"]
     form_class  = MessageForm
     success_url = 'success/'

    def get(self, request, *args, **kwargs):
        """
        Handles GET requests and instantiates blank versions of the form
        and its inline formsets.
        """
        self.object = None
        form_class  = self.get_form_class()
        form        = self.get_form(form_class)
        attachment_form = AttachmentFormSet()

        return self.render_to_response(
            self.get_context_data(form  =form,
                                  attachment_form=attachment_form,
                                  ))

    def post(self, request, *args, **kwargs):
        """
        Handles POST requests, instantiating a form instance and its inline
        formsets with the passed POST variables and then checking them for
        validity.
        """
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        attachment_form = AttachmentFormSet(self.request.POST)
        if (form.is_valid() and attachment_form.is_valid()):
            return self.form_valid(form, attachment_form)
        else:
            return self.form_invalid(form, attachment_form)

    def form_valid(self, form, attachment_form):
        """
        Called if all forms are valid. Creates a Message instance along with
        associated Attachment then redirects to a success page.
        """
        self.object   = form.save()

        attachment_form.instance = self.object
        self.object   = attachment_form.save()
        return HttpResponseRedirect(self.get_success_url())

I tried many things, but for some reason the Attachment is never saved. There must be something missing in the form_valid() function, but I can't figure out what.

For completeness, here also the template:

<script type="text/javascript">
        $(function() {
            $(".inline.{{ attachment_form.prefix }}").formset({
                prefix: "{{ attachment_form.prefix }}"
            })
        });
</script>
<form class="" action="/bugtrack/project/{{ project_id }}/tickets/{{ ticket_id }}/replyform/" method="post" id="replyform">
        {% csrf_token %}
        {{ form |crispy }}        

        {{ attachment_form.management_form }}
        {% for formattach in attachment_form  %}
            {{ formattach.id }}
            <div class="inline {{ attachment_form.prefix }}">
                {{ formattach.docfile }}
            </div>
        {% endfor %}

       <button class="btn btn-info pull-right btn-sm" type="submit" name="submit" value="createReply">Submit</button>
</form>

What would be the correct way to save the Message and Attachment correctly using a formset?