본문 바로가기

Python_WEB/Tweetme

[Django]Like Button Rendering

CodingEntrepreneurs Django 강의 정리

onclick>

개체를 클릭하면 이벤트 핸들러가 호출된다.

 

Bootstrap Button>

https://getbootstrap.com/docs/4.0/components/buttons/

 

Buttons

Use Bootstrap’s custom button styles for actions in forms, dialogs, and more with support for multiple sizes, states, and more.

getbootstrap.com

 

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>

<div class='mb-4 tweet' id='tweet-1'>
	<p>hello world</p>
    <div class='btn-group'>
    	<button class='btn btn-primary btn-sm'>20 Likes</button>
    </div>
</div>

</body>
</html>

 

home.html>

<!-- templates/pages/home.html -->

{% extends 'base.html' %}

{% block head_title %}
this is amazing!!!!
{% endblock head_title%}


{% block content %}
Welcome to Tweetme 2

<div id='tweets'>
    Loading...
</div>

<script>
    const tweetsElement = document.getElementById("tweets") // get an html element
    // tweetsElement.innerHTML = 'Loading...' // set new html in that element
    // var el1 = "<h1>Hi there 1</h1>"
    // var el2 = "<h1>Hi there 2</h1>"
    // var el3 = "<h1>Hi there 3</h1>"
    // tweetsElement.innerHTML = el1 + el2 + el3

    const xhr = new XMLHttpRequest()
    const method = 'GET' // "POST"
    const url = "/tweets"
    const responseType = "json"

    function handleDidLike(tweet_id, currentCount) {
        console.log(tweet_id, currentCount)
        return
    }

    function LikeBtn(tweet) {
        return "<button class='btn btn-primary btn-sm' onclick=handleDidLike(" +
            tweet.id + "," + tweet.likes + ")>" + tweet.likes + "Likes</button>"
    }

    function formatTweetElement(tweet) {
        var formattedTweet = "<div class='mb-4 tweet' id='tweet-" + tweet.id
            + "'><p>" + tweet.content +
            "</p><div class='btn-group'>" + LikeBtn(tweet) +
            "</div></div>"
        return formattedTweet
    }
    xhr.responseType = responseType
    xhr.open(method, url)
    xhr.onload = function () {
        const serverResponse = xhr.response
        const listedItems = serverResponse.response // array
        var finalTweetStr = ""
        var i;
        for (i = 0; i < listedItems.length; i++) {
            var tweetObj = listedItems[i]
            var currentItem = formatTweetElement(tweetObj)
            finalTweetStr += currentItem
        }
        tweetsElement.innerHTML = finalTweetStr
        // console.log(listedItems)
    }
    xhr.send()


</script>
{% endblock content %}

 

views.py>

# tweets/views.py

import random
from django.http import HttpResponse, Http404, JsonResponse
from django.shortcuts import render

from .models import Tweet

# Create your views here.
def home_view(request, *args, **kwargs):
    return render(request, "pages/home.html", context={}, status=200)


def tweet_list_view(request, *args, **kwargs):
    """
    REST API VIEW
    Consume by JavaScript or Swift or Java/ios/Andriod
    return json data
    """
    qs = Tweet.objects.all()
    tweets_list = [
        {"id": x.id, "content": x.content, "likes": random.randint(0, 1000)} for x in qs
    ]
    data = {"isUser": False, "response": tweets_list}
    return JsonResponse(data)


def tweet_detail_view(request, tweet_id, *args, **kwargs):
    """
    REST API VIEW
    Consume by JavaScript or Swift or Java/ios/Andriod
    return json data
    """
    data = {
        "id": tweet_id,
    }
    status = 200

    try:
        obj = Tweet.objects.get(id=tweet_id)
        data["content"] = obj.content
    except:
        data["message"] = "Not Found"
        status = 404

    return JsonResponse(
        data, status=status
    )  # json.dumps content_type='application/json'

 

결과물>

'Python_WEB > Tweetme' 카테고리의 다른 글

[Django]Tweet Create Form  (0) 2020.07.14
[Django]Rapid Implement of Bootstrap Theme  (0) 2020.07.14
[Django]Like Button Rendering  (0) 2020.07.08
[Django]Format Tweet Method  (0) 2020.07.08
[Django]Tweets to HTML via JavaScript  (0) 2020.07.08
[Django]Replace HTML Content with JavaScript  (0) 2020.07.08