tags:

views:

30

answers:

1

I would like to create a button that records date and time in the browser, when the user clicks it and then send that information to a django db.

1.db part: Would the db field I save it to best be a DateTimeField() or a CharField()? I want the exact date and time of that button clicked?

  1. jQuery part: I heard (here) that jQuery can accomplish to record the exact time when the button was clicked. I am not familiar with jQuery and have the basics in javascript. But what I would like to know is why/how jquery and/or javascript is able to record when the user clicks, while in django that would be when the server gets the info.

I would like to be able to record all sorts of click behavior in browser and therefor my question.

Also if somebody could give me an example roundtrip on this. That would be the max.

Thanks!

+1  A: 

DateTimeField would be a (far) better choice than CharField. You can define a model similar to this:

class ButtonClick(models.Model):
    clicked_on = models.DateTimeField()

You can define a view that creates an instance of this model and saves it when called. this uses a ModelForm.

class ButtonClickForm(forms.ModelForm):
    class Meta:
        model = ButtonClick

def record_button_click(request, *args, **kwargs):
    if request.is_ajax() and request.method == 'POST':
        form = ButtonClickForm(request.POST.copy())
        if form.is_valid():
            instance = form.save()
            return render_to_response(... XML snippet indicating success ...)

    else:
        # Return invalid request? This depends on your scenario.

Now comes the interesting part - calling this view from your browser. The following snippet is an example of how to go about this. Warning: My knowledge of jQuery is very limited. The snippet may contain mistakes and/or there may be better ways to do this.

function on_button_click(date) {
    $.ajax({
      url: 'app/record_button_click/',
      data: "date=" + date.toString(), // Use appropriate formatting option.
      success: function(data) {
        alert('Button click recorded.');
      }
    });
}

<button onClick="return on_button_click(new Date());" ../>
Manoj Govindan
Cool! Thanks a lot. The ModelForm is where exactly? In the views.py or models.py? Is jquery ajax? Or is it the same? Sorry for my ignornace and thanks again. You helped me out a lot. Fantastic.
MacPython
@MacPython: (1) I generally define forms inside `app/forms.py`. That said forms can live inside `models.py` or `views.py` as well. (2) jQuery is not "AJAX"; it is a fantastic Javascript library that simplifies the process of making "AJAX" calls See: http://en.wikipedia.org/wiki/Ajax_\(programming\)
Manoj Govindan