将序列化Django模型实例转换回Ajax中的对象

时间:2015-05-12 01:14:18

标签: javascript ajax django

我正在使用Ajax搜索模型实例,返回该实例,并将其作为变量传递给模板中的模板标记。在我看来,我在将对象发送到Ajax成功函数之前对其进行序列化。但是,一旦我回到Ajax函数中,我如何将其恢复为模型实例,以便在模板中使用它?

template.html

        <div class="row">
            <div class="col-md-10 col-md-offset-1" style="border: 2px solid #e4e4e4; border-radius: 8px">
                <p class="text-center" style="color: #27AE60; padding: 20px 20px 0px 20px"><b>Generate the citation for a desired dataset by typing its ID number in the box below:</b></p>
                <form role="form" method="get" action="{% url 'databank:get_citation' %}" id="citation-form" style="padding: 0px 20px 20px 20px">
                  <div class="input-group">
                    <span class="input-group-addon" id="doi-prefix">11.23/</span>
                    <input type="Search" placeholder="Data ID" class="form-control form-search2" id="data-id" name="q">
                    <div class="input-group-btn">
                      <button class="btn blue-search-button">
                         <span>Go</span>
                      </button>
                    </div>
                  </div>
                </form>
                <div class="row">
                    <div class="col-md-10 col-md-offset-1" id="results">{{ errors }}</div>
                    <div class="col-md-10 col-md-offset-1" id="generatedCitation">
                        <p style='font-size: 20px'class="citationResults">{% include 'databank/includes/citation.html' with dataset=citationdataset registration=citationregistration %}</p>
                    </div>
                </div>
            </div>
        </div>

main.js

$('#citation-form').on('submit', function(event){
    event.preventDefault();
    console.log("form submitted!")  // sanity check
    get_citation();
});

function get_citation(){
    console.log("create post is working!") // sanity check
    $.ajax({
        url : "get_citation/", // the endpoint
        type : "GET", // http method
        data : { data_id : $('#data-id').val() }, // data sent with the get request

        // handle a successful response
        success : function(json) {
            $('#data-id').val(''); // remove the value from the input
            console.log(json); // log the returned json to the console
            if(json.errors){
              $('.errors').html(json.errors);
            }
            else{
              $('.citationResults').html(json.citation.citationdataset);
              $('.citationResults').html(json.registration.citationregistration);
            }
            console.log("success"); // another sanity check
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

views.py

def get_citation(request):
    if request.method=='GET':
        dataset_id = request.GET.get('data_id')
        print "ID IS: ", dataset_id

        try:
            dataset = Dataset.objects.get(dataset_id=dataset_id)
            registration = Registration.objects.get(dataset=dataset)
            if dataset.status == 'public':
                print "PUBLIC: ", dataset, registration
                data_info = {}
                dataset = serializers.serialize('json', [ dataset, ])
                data_info['dataset'] = dataset
                registration = serializers.serialize('json', [ registration, ])
                data_info['registration'] =  registration
                return JsonResponse(data_info)

            else:
                return JsonResponse({"errors": "The dataset you requested has not yet been made public. Check back later."})

        except Dataset.DoesNotExist:
            return JsonResponse({"errors": "The dataset you requested could not be found. Make sure you are using the correct ID."})

新工作,追随守则@JulienGrégoire的建议 -

template.html:

    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <p><b>Citation Generator</b></p>
            <form role="form" method="get" action="{% url 'databank:get_citation' %}" id="citation-form">
              <div class="input-group">
                <span class="input-group-addon" id="doi-prefix">11.0/</span>
                <input type="Search" placeholder="Data ID" class="form-control form-search2" id="data-id" name="q">
                <div class="input-group-btn">
                  <button class="btn blue-search-button">
                     <span>Get Citation</span>
                  </button>
                </div>
              </div>
            </form>
            <div class="row">
                <div class="col-md-10 col-md-offset-1" id="generatedCitation">
                    <p style='font-size: 20px' class="citationResults"></p>
                </div>
            </div>
        </div>
    </div>

main.js:

$('#citation-form').on('submit', function(event){
    event.preventDefault();
    console.log("citation generator form submitted") 
    get_citation();
});

function get_citation(){
    console.log("citation generator is working!")
    $.ajax({
        url : "get_citation/", 
        type : "GET", 
        data : { data_id : $('#data-id').val() }, // data sent with the get request, the inputted data id

        // handle a successful response
        success : function(data) {
            $('#data-id').val(''); // remove the value from the input
            console.log(data); // log the returned json to the console
            $('.citationResults').html(data);
            console.log("success"); // another sanity check
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('.citationResults').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

views.py:

def get_citation(request):
    if request.method=='GET':
        dataset_id = request.GET.get('data_id')

        try:
            dataset = Dataset.objects.get(dataset_id=dataset_id)
            registration = Registration.objects.get(dataset=dataset)
            if dataset.status == 'public':
                context = {'registration': registration, 'dataset': dataset}
                html = render_to_string('databank/includes/citation.html', context)
                return HttpResponse(html)

            else:
                context = {'message': "The dataset you requested has not yet been made public. Check back later."}
                html = render_to_string('databank/includes/no_citation.html', context)
                return HttpResponse(html)

        except Dataset.DoesNotExist:
            context = {'message': "The dataset you requested could not be found. Make sure you are using a valid ID."}
            html = render_to_string('databank/includes/no_citation.html', context)
            return HttpResponse(html)

1 个答案:

答案 0 :(得分:0)

模板在服务器上呈现,所以我不知道如何在javascript(即客户端)中呈现它。

您可以做的是创建一个模板,该模板仅处理您要更新的部分,并从您的视图中发送渲染的html并重新注入。

所以在这里,你不会在你的视图中序列化,而是返回一个带有适当上下文和模板的渲染器,并使用你的jquery html函数来插入它和你的div,它应该可以工作。