在django模板中显示json数据

时间:2014-09-18 08:49:58

标签: ajax json django forms model

我正在尝试使用ajax保存表单值。我已经这样做了,现在表单数据被保存到db中。我现在想要的是只在没有刷新它的情况下在该django模板中显示保存的数据。但是在表单提交时,正在显示json数据字符串(仅显示结果)

models.py

from django.db import models

class TestModel(models.Model):
    title = models.TextField(max_length=255)

views.py

import json
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson
from vijayapp.forms import *
from django.http import *
from vijayapp.models import *
def main(request):
   return render_to_response('index.html',
        {'form':TestForm()}, RequestContext(request))

def index(request):
    if request.method == "POST":
            form = TestForm(request.POST)
            #message = 'something wrong'
            if form.is_valid():
                message=request.POST['title'] #model field name
                form.save()
                dict = {}
                dict['value']=message
                #return HttpResponse(json.dumps({'message': message}))
                return HttpResponse(json.dumps(dict), content_type="application/json") 

    else:

        form = TestForm()


    return render_to_response('index.html',
        {'form':TestForm()}, RequestContext(request))

的index.html

    <body>
    <h1>Leave a Suggestion Here</h1>
        <div class="message"></div>
        <div class="hello">
            <form action="/forms/" method="POST" id="MY_FORM">{% csrf_token %}
                {{ form.as_p }} 
                <input type="submit" value="Submit Feedback" id="button"/>
            </form>
            <p></p><p></p>
            <div id="result">
            </div>
        </div>

</body>

    <script type="text/javascript">
$(document).ready(function() {
$("#button").click(function() {
e.preventDefault();
var input_string1 = $(".textclass").val();
alert(input_string1);
$.ajax({
url :"forms",
type : "POST",
dataType: "json",
data: $(this).serialize(),
success : function(json) {
$('#result').html(json.value);
alert(json['value']);
},
error : function(xhr,errmsg,err) {
alert("wrong entry");
}
});
return false;
});
});
</script>


forms.py
from django.forms import ModelForm
from vijayapp.models import TestModel
from django import forms 

class TestForm(ModelForm):
    class Meta:
        model = TestModel
        widgets={
                      "title":forms.TextInput(attrs={'placeholder':'Name','name':'Name','id':'common_id_for_imputfields','class':'textclass'}),


                  }  

1 个答案:

答案 0 :(得分:0)

是的,您将json数据作为字符串获取,因此您可以使用$ .parseJson在jquery代码中解析json。现在您将获得数据的数据结构(字典,元组,列表)。现在您可以显示数据结构中的每个数据(dict,tuple,list)。