0

I have an sqlite3 database setup with django 1.6 where I want web users to be able to enter text and see it in 3 live tables (high, low and latest) all on the same page. The one page ideally should have text entry, voting, display of the three tables updated when new entries go in or are voted on, and a search if possible if all that gets sorted (personal project, not commercial). I am also on win7 64 if that matters...

Currently I have: a working database the three tables displaying in a web page without update and some web text input via js (and failing to save to the database in Django).

I shied away from forms at first, as they seem to want separate html pages for input. Asking an experienced django coder, he helped me out with some javascript for text entry on the page. He said I didn't need to do it via forms and POST, GET, as the text was just going in with the initial score of 0 and the current datetime.

My issue now is that I cannot get the entered text to save into the database without error.

Since I need to program this in 2-3 weeks and am new to django (and oblivious to javascript, though I've done some Processing with PHP), my questions are;

  • Am I missing something obvious with the text input save to database?

-and-

  • Is there a way to have all this using forms and GET, POST in one page so I can avoid a lot of javascript (unless it is truly easier)?

I am going to start to try to build this with Forms at the moment, but hope for a bit of guidance on best practice from wiser heads.

Here's the code so far:

urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^i/$', 'entries.views.index'),
    url(r'^add/(.*)$', 'entries.views.add'),
)

Models.py

from django.db import models
import datetime
from django.utils import timezone

class Entry(models.Model):
    text = models.CharField(max_length=15)
    score = models.IntegerField(default=0)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
        return self.text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

index.html

 <html>
 <head>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
 </head>
 <body>
 <ul>
 {% for entry in latest_entry_list %}
    <li><a href="/entries/{{ entry.id }}/">{{ entry.text }}&nbsp;&nbsp;&nbsp;&nbsp{{ entry.score }}</a></li>
 {% endfor %}
 </ul>
 <ul>
 {% for entry in high_entry_list %}
    <li><a href="/entries/{{ entry.id }}/">{{ entry.text }}&nbsp;&nbsp;&nbsp;&nbsp{{ entry.score }}</a></li>
 {% endfor %}
 </ul>
 <ul>
 {% for entry in low_entry_list %}
    <li><a href="/entries/{{ entry.id }}/">{{ entry.text }}&nbsp;&nbsp;&nbsp;&nbsp{{ entry.score }}</a></li>
 {% endfor %}
 </ul>
<style type="text/css" media="screen">
  div h2 span { color: #ff0000; }
  div span { color: #00ff00; }
  #box { width: 400px; height: 400px; }
  #h { color: #ff0000; }
</style>
<h3 id="h">title</h3>

<p>message: {{ text }}</p>  
<input type="text" name="word" value="" id="input"/>

<script type="text/javascript" src="{{STATIC_URL}}post.js"></script>
</body>

post.js

console.log("hi from js");

$(document).ready(function() {

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

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

        var args = {};

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

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

});

});

views.py

from django.shortcuts import render
from django.http import HttpResponse
from entries.models import Entry

from django.db import models
import datetime
from django.utils import timezone

def index(request):
    context = {
      'latest_entry_list': Entry.objects.order_by('-pub_date')[:10],
      'high_entry_list': Entry.objects.order_by('-score')[:10],
      'low_entry_list': Entry.objects.order_by('score')[:10],
    }
    return render(request, 'entries/index.html', context);

def add(request, thingtoadd):
    #created_date = models.DateTimeField('date published', default=datetime.now)
    #created_score = '0'
    #created_text = 'test'   
    #e = Entry(text=created_text, score=created_score,pub_date=created_date)
    #e.save()

    return HttpResponse('done')

I am unsure of defining the fields for populating the Entry....does the above look right?

I can uncomment the e=Entry(etc...) without error,

but when I uncomment the e.save(), the error is:

GET http://127.0.0.1:8000/add/a 500 (INTERNAL SERVER ERROR) jquery.min.js:4
send jquery.min.js:4
n.extend.ajax jquery.min.js:4
n.(anonymous function) jquery.min.js:4
(anonymous function) post.js:15
n.event.dispatch jquery.min.js:3
r.handle

I will be getting on with trying to do this in forms, but wonder if there is some good advice as to if that is possible - I would ideally like to avoid js extras as I am very unfamiliar with it and it would be another level of unknowns at this point. Any input greatly appreciated...

1 Answer 1

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....

Sign up to request clarification or add additional context in comments.

14 Comments

Thanks - I was using this advice though - david.feinzeig.com/blog/2011/12/06/… - and I still get the same error, so I doubt that is the cause of all this. I'll try the Auto add though now...
Still gives an error - seems to be some other problem.
Oh, sorry. It is an error in your urls.py file. Read this part of django docs: docs.djangoproject.com/en/1.2/topics/http/urls/…
And I think it bad style to pass text parameter through url. You should pass it through GET
CSRF token required if you sent POST, but you sent GET. So it is not reason of your problem. Try to call url directly from browser. And post full server response if problem still appear.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.