2017-03-18 94 views
0

我希望有人能夠提供幫助,因爲我曾多次嘗試過這種方式,但獲得的成功很少。我試圖用django書來使用探戈來適應這種情況,並在網上做了許多其他的例子,但沒有運氣。無論如何...Django - 使用jQuery/AJAX訪問數據庫

我目前正在設計一個帶有Django的小型'假新聞'網站,它有一個向用戶顯示新聞文章(標題,描述,圖片)的迷你遊戲,他們必須投票是否它是'事實'或'小說',他們會被告知他們是否正確,以及有多少人已經爲此答案投票過。

我有它的工作完全沒問題,如果我有存儲在JavaScript變量像這樣的所有數據:

var questions = [ 
    ["Pope Francis Shocks World, Endorses Donald Trump for President, Releases Statement", 
    "News outlets around the world are reporting on the news that Pope Francis has made the unprecedented decision to endorse a US presidential candidate. His statement in support of Donald Trump was released from the Vatican this evening: 'I have been hesitant to offer any kind of support for either candidate in the US presidential election but I now feel that to not voice my concern would be a dereliction of my duty as the Holy See...", 
    "fake", 7, 15, '../../static/images/popetrump.jpg'], 
    ["Trump Offering Free One-Way Tickets to Africa & Mexico for Those Who Wanna Leave America", 
    "President elect Donald Trump has sensationally offered free one-way tickets to Mexico or Africa for anyone who wants to leave America in the aftermath of his election victory. The extraordinary, and highly controversial, offer was revealed by an aid at a press conference in New York this morning...", 
    "fake", 13, 17, '../../static/images/TrumpTickets.jpg'], 
    ["Feral pig drinks 18 cans of beer, fights cow and then passes out drunk under tree", 
    "The swine drank 18 beers on its bender in Port Hedland, Western Australia, according to ABC News. The alcohol also made the pig hungry and was seen looking through rubbish bags for something to eat...", 
    "true", 8, 19, '../../static/images/pig.jpg'], 
    ["Cinnamon Roll Can Explodes Inside Man's Butt During Shoplifting Incident", 
    "Las Vegas – Martin Klein, 41 of Las Vegas, was arrested after a shopping lifting incident turned horribly wrong. According to reports, Mr. Klein and his partner, Jerry Weis, had stolen several grocery items from the Las Vegas Walmart...", 
    "fake", 19, 7, '../../static/images/CinnamonRollMan.jpg'], 
    ["Poll: 38% of Florida voters believe Ted Cruz could be the Zodiac Killer", 
    "While a 62 percent majority of voters answered 'No' when asked if they believed Cruz was responsible for the string of murders in the early 70s, 10 percent answered 'Yes' and an additional 28 percent said they were unsure...", 
    "true", 11, 6, '../../static/images/FloridaPoll.jpg'], 
    ["Hamster resurrection: Pet rises from the grave at Easter after being buried in garden", 
    "Tink the hamster was found ‘cold and lifeless’ in the bottom of her cage and laid to rest by a couple who were looking after her for a friend. But the next day the rodent – who was not dead but hibernating – reappeared as perplexed Les Kilbourne-Smith crushed a pile of old boxes for recycling...", 
    "true", 15, 9, '../../static/images/hamster.jpg'], 
] 

我已經能夠所有的文章添加到數據庫中,但是我不能確定如何提取從我需要的數據庫中獲取數據,並隨着更多人玩遊戲而更新事實和虛構投票的數量。從網上閱讀我相信我需要使用AJAX來做到這一點,但我誠實地不知道從哪裏開始,以便每次按下下一個按鈕時顯示新文章,更新票數等。

希望有人可以至少指出我正確的方向,我會發布我到目前爲止所有的代碼,並認爲可能在下面相關。

game.js:

var questions = [ 
    ["Pope Francis Shocks World, Endorses Donald Trump for President, Releases Statement", 
    "News outlets around the world are reporting on the news that Pope Francis has made the unprecedented decision to endorse a US presidential candidate. His statement in support of Donald Trump was released from the Vatican this evening: 'I have been hesitant to offer any kind of support for either candidate in the US presidential election but I now feel that to not voice my concern would be a dereliction of my duty as the Holy See...", 
    "fake", 7, 15, '../../static/images/popetrump.jpg'], 
    ["Trump Offering Free One-Way Tickets to Africa & Mexico for Those Who Wanna Leave America", 
    "President elect Donald Trump has sensationally offered free one-way tickets to Mexico or Africa for anyone who wants to leave America in the aftermath of his election victory. The extraordinary, and highly controversial, offer was revealed by an aid at a press conference in New York this morning...", 
    "fake", 13, 17, '../../static/images/TrumpTickets.jpg'], 
    ["Feral pig drinks 18 cans of beer, fights cow and then passes out drunk under tree", 
    "The swine drank 18 beers on its bender in Port Hedland, Western Australia, according to ABC News. The alcohol also made the pig hungry and was seen looking through rubbish bags for something to eat...", 
    "true", 8, 19, '../../static/images/pig.jpg'], 
    ["Cinnamon Roll Can Explodes Inside Man's Butt During Shoplifting Incident", 
    "Las Vegas – Martin Klein, 41 of Las Vegas, was arrested after a shopping lifting incident turned horribly wrong. According to reports, Mr. Klein and his partner, Jerry Weis, had stolen several grocery items from the Las Vegas Walmart...", 
    "fake", 19, 7, '../../static/images/CinnamonRollMan.jpg'], 
    ["Poll: 38% of Florida voters believe Ted Cruz could be the Zodiac Killer", 
    "While a 62 percent majority of voters answered 'No' when asked if they believed Cruz was responsible for the string of murders in the early 70s, 10 percent answered 'Yes' and an additional 28 percent said they were unsure...", 
    "true", 11, 6, '../../static/images/FloridaPoll.jpg'], 
    ["Hamster resurrection: Pet rises from the grave at Easter after being buried in garden", 
    "Tink the hamster was found ‘cold and lifeless’ in the bottom of her cage and laid to rest by a couple who were looking after her for a friend. But the next day the rodent – who was not dead but hibernating – reappeared as perplexed Les Kilbourne-Smith crushed a pile of old boxes for recycling...", 
    "true", 15, 9, '../../static/images/hamster.jpg'], 
] 

var questionCount = 0; 
var correctAnswer = 0; 


$(document).ready(function() { 
     $("#answer").hide(); 
     $("#game_home").hide(); 
     $("#game_title").html(questions[questionCount][0]); 
     $("#game_description").html(questions[questionCount][1]); 
     $("#game_picture").attr('src', questions[questionCount][5]); 
     $("#game_fact").click(function() { 

      $("#game_picture").hide(); 
      $("#game_fact").prop('disabled', true); 
      $("#game_fiction").prop('disabled', true); 
      if(questions[questionCount][2] == "true"){ 
       $("#your_answer").html("Correct! This story is a Fact!"); 
       $("#current_answer_fact").html("Fact: " + (((questions[questionCount][3])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%"); 
       $("#current_answer_fiction").html("Fiction: " + (((questions[questionCount][4])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%"); 
       questions[questionCount][3] = questions[questionCount][3]+1; 
       correctAnswer += 1; 
      } 
      else{ 
       $("#your_answer").html("Incorrect! This story is actually Fiction!"); 
       $("#current_answer_fact").html("Fact: " + (((questions[questionCount][3])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%"); 
       $("#current_answer_fiction").html("Fiction: " + (((questions[questionCount][4])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%"); 
       questions[questionCount][3] = questions[questionCount][3]+1 
      } 
      $("#answer").show(); 
     }); 
     $("#game_fiction").click(function() { 
      $("#game_picture").hide(); 
      $("#game_fact").prop('disabled', true); 
      $("#game_fiction").prop('disabled', true); 
      if(questions[questionCount][2] == "fake"){ 
       $("#your_answer").html("Correct! This story is Fiction!"); 
       $("#current_answer_fact").html("Fact: " + (((questions[questionCount][3])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%"); 
       $("#current_answer_fiction").html("Fiction: " + (((questions[questionCount][4])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%"); 
       questions[questionCount][3] = questions[questionCount][4]+1 
       correctAnswer += 1; 
      } 
      else{ 
       $("#your_answer").html("Incorrect! This story is actually a Fact!"); 
       $("#current_answer_fact").html("Fact: " + (((questions[questionCount][3])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%"); 
       $("#current_answer_fiction").html("Fiction: " + (((questions[questionCount][4])/(questions[questionCount][3]+questions[questionCount][4]))*100).toFixed(2) + "%"); 
       questions[questionCount][3] = questions[questionCount][4]+1 
      } 
      $("#answer").show(); 
     }); 
     $("#game_next").click(function() { 
      questionCount += 1; 
      if(questionCount == questions.length){ 
       $("#your_answer").html("Thanks for playing!"); 
       $("#current_answer").html("You scored " + correctAnswer + " out of " + questions.length); 
       $("#game_home").show(); 
       $("#game_fact").hide(); 
       $("#game_fiction").hide(); 
       $("#game_title").hide(); 
       $("#game_description").hide(); 
       $("#game_next").hide(); 
       $("#current_answer_fact").hide(); 
       $("#current_answer_fiction").hide(); 
       $("#game_or").hide(); 
      } 
      else{ 
      $("#game_picture").attr('src', questions[questionCount][5]); 
      $("#answer").hide(); 
      $("#game_picture").show(); 
      $("#game_title").html(questions[questionCount][0]); 
      $("#game_description").html(questions[questionCount][1]); 
      $("#game_fact").prop('disabled', false); 
      $("#game_fiction").prop('disabled', false); 
      } 
     }); 
     }); 

人口腳本:

import os 
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fact_or_fiction.settings') 

import django 
django.setup() 
from factorfiction.models import Page, GameArticle 

def populate(): 

    game_articles = [ 
     {"title":"Pope Francis Shocks World, Endorses Donald Trump for President, Releases Statement", 
     "description":"News outlets around the world are reporting on the news that Pope Francis has made the unprecedented decision to endorse a US presidential candidate. His statement in support of Donald Trump was released from the Vatican this evening: 'I have been hesitant to offer any kind of support for either candidate in the US presidential election but I now feel that to not voice my concern would be a dereliction of my duty as the Holy See...", 
     "answer":"fake", 
     "fact": 7, 
     "fiction": 15, 
     "picture": "../../static/images/popetrump.jpg"}, 
     {"title":"Trump Offering Free One-Way Tickets to Africa & Mexico for Those Who Wanna Leave America", 
     "description":"President elect Donald Trump has sensationally offered free one-way tickets to Mexico or Africa for anyone who wants to leave America in the aftermath of his election victory. The extraordinary, and highly controversial, offer was revealed by an aid at a press conference in New York this morning...", 
     "answer":"fake", 
     "fact": 13, 
     "fiction": 17, 
     "picture": "../../static/images/TrumpTickets.jpg"}, 
     {"title":"Feral pig drinks 18 cans of beer, fights cow and then passes out drunk under tree", 
     "description":"The swine drank 18 beers on its bender in Port Hedland, Western Australia, according to ABC News. The alcohol also made the pig hungry and was seen looking through rubbish bags for something to eat...", 
     "answer":"true", 
     "fact": 8, 
     "fiction": 19, 
     "picture": "../../static/images/pig.jpg"}, 
     {"title":"Cinnamon Roll Can Explodes Inside Man's Butt During Shoplifting Incident", 
     "description":"Las Vegas – Martin Klein, 41 of Las Vegas, was arrested after a shopping lifting incident turned horribly wrong. According to reports, Mr. Klein and his partner, Jerry Weis, had stolen several grocery items from the Las Vegas Walmart...", 
     "answer":"fake", 
     "fact": 19, 
     "fiction": 7, 
     "picture": "../../static/images/CinnamonRollMan.jpg"}, 
     {"title":"Poll: 38% of Florida voters believe Ted Cruz could be the Zodiac Killer", 
     "description":"While a 62 percent majority of voters answered 'No' when asked if they believed Cruz was responsible for the string of murders in the early 70s, 10 percent answered 'Yes' and an additional 28 percent said they were unsure...", 
     "answer":"true", 
     "fact": 11, 
     "fiction": 6, 
     "picture": "../../static/images/FloridaPoll.jpg"}, 
     {"title":"Hamster resurrection: Pet rises from the grave at Easter after being buried in garden", 
     "description":"Tink the hamster was found ‘cold and lifeless’ in the bottom of her cage and laid to rest by a couple who were looking after her for a friend. But the next day the rodent – who was not dead but hibernating – reappeared as perplexed Les Kilbourne-Smith crushed a pile of old boxes for recycling...", 
     "answer":"true", 
     "fact": 15, 
     "fiction": 9, 
     "picture": "../../static/images/hamster.jpg"}] 

    for eachArticle in game_articles: 
     add_game_article(eachArticle["title"], eachArticle["description"], eachArticle["picture"], eachArticle["answer"], eachArticle["fact"], eachArticle["fiction"]) 



def add_game_article(title,description,picture, answer, fact=0, fiction=0): 
    games = GameArticle.objects.get_or_create(title=title)[0] 
    games.description=description 
    games.answer=answer 
    games.fact=fact 
    games.fiction=fiction 
    games.picture=picture 
    games.save() 
    return games 


if __name__ == '__main__': 
    print("Starting FactOrFiction population script...") 
    populate() 

fofgame.html:

{% extends 'factorfiction/base.html' %} 
    {% load staticfiles %} 

    {% block title_block %} 
    FoF Game 
    {% endblock %} 


    {% block main_body_block %} 
    <div class="current_article"> 
    <div class="row"> 
     <h1 id="game_title"></h1> 
    </div> 
    <div class="row"> 
     <p id="game_description">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean 
     commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus 
     et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, 
     ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p> 
    </div> 
     <button id="game_fact" type="button">Fact</button> 
     <p id="game_or">OR</p> 
     <button id="game_fiction" type="button">Fiction</button> 
     <img id="game_picture" src='{% static "images/fakenews.jpg" %}' alt="Article Picture" /> 
     <div id="answer"> 
      <h1 id="your_answer"></h1> 
      <p id="current_answer">Currently, other users have said:</p> 
      <p id="current_answer_fact"></p> 
      <p id="current_answer_fiction"></p> 
      <button id="game_next" type="button">Next</button> 
      <a href="{% url 'index' %}"><button id="game_home" type="button">Homepage</button></a> 
     </div> 
    </div> 
    {% endblock %} 

回答

0

這裏是Ajax的請求的一個例子。點擊按鈕時觸發,並向{%url「ajax_requests」%}發出POST請求。它成功地將一些數據加載到一個div中... console.log()僅用於檢查返回的數據。

<script> 
    $("#button1").click(function() { 
    var itemid=1; 

     $.ajaxSetup({ 
      data: {csrfmiddlewaretoken: '{{ csrf_token }}' }, 
     }); 

     $.ajax({ 
     url: '{% url "ajax_requests" %}', 
     type: 'POST', 
     data: { 
      'item_id': itemid, 
     }, 
     dataType: 'json', 
     success: function (data) { 
      if (data) { 
      console.log(data); 

      html = '<img src="/user_images/' + data[6].fields.requesting_user[2] + ' "class="img-responsive" alt="Kuva">'; 
      $("#test").append(html); 
      } 
     } 
     }); 

    }); 

    </script> 

因此,要做到這一點,您需要在your_app/urls.py中添加一個視圖並指向它。就像這樣:

url(r'^ajax_requests/', ajaxrequests_view, name='ajax_requests'), 

和您查詢的數據views.py,然後序列化到JSON和返回:

def ajaxrequests_view(request): 
    item_id = request.POST.get('item_id', None) 
    get_data = MyModel.objects.select_related('item_owner').filter(item_id=item_id) 
    ser_data = serializers.serialize("json", get_data) 

    return HttpResponse(ser_data, content_type="application/json")