[Answer]-Web text input save into database without form- Django Javascript

1👍

Your mistake in view function add:

created_date = models.DateTimeField('date published', default=datetime.now)

It must be value assign:

created_date = datetime.now()

Not field definition.

In advance you could specify auto_now_add=True in your model: https://docs.djangoproject.com/en/dev/ref/models/fields/#datefield

In that case field will be filled automatically.

Additional:

It is error in urls.py

You should do some fixes:

urls.py:

url(r'^add/$', 'entries.views.add'),

post.js

$("#input").bind("keypress", function(e) {

    //enter key pressed
    if (e.keyCode == 13) {

        var text = $("#input").val();

        var args = {'text': text};

        $.get("/add/", args).done(function(data) {
            console.log("message: " + data);
        });
    }

});

views.py

def add(request):
    created_date = default=datetime.now()
    created_score = '0'
    created_text = request.GET.get('text')   
    e = Entry(text=created_text, score=created_score,pub_date=created_date)
    e.save()

    return HttpResponse('done')

Update – Solution

The solution in addition to the changes below was to add ‘from datetime import datetime’ in views….

Leave a comment