Reputation: 18271
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?
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!
Upvotes: 0
Views: 898
Reputation: 74705
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());" ../>
Upvotes: 1