制作一个"like wise"按钮的过程可以分为以下几个步骤:
django-admin startproject myproject
python manage.py startapp myapp
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
likes = models.IntegerField(default=0)
python manage.py makemigrations
python manage.py migrate
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .models import Post
def like_wise(request, post_id):
post = get_object_or_404(Post, pk=post_id)
post.likes += 1
post.save()
return JsonResponse({'likes': post.likes})
from django.urls import path
from . import views
urlpatterns = [
path('like_wise/<int:post_id>/', views.like_wise, name='like_wise'),
]
<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
<p>Likes: <span id="likes">{{ post.likes }}</span></p>
<button id="likeButton">Like wise</button>
<script>
document.getElementById('likeButton').addEventListener('click', function() {
var post_id = {{ post.id }};
var xhr = new XMLHttpRequest();
xhr.open('POST', '/like_wise/' + post_id + '/');
xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}');
xhr.onload = function() {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
document.getElementById('likes').textContent = response.likes;
}
};
xhr.send();
});
</script>
以上是一个简单的示例,展示了如何制作一个"like wise"按钮的Django应用。你可以根据自己的需求进行修改和扩展。在实际开发中,你可能还需要添加用户认证、前端样式等功能。关于Django的更多信息和详细文档,请参考腾讯云的Django产品介绍。
领取专属 10元无门槛券
手把手带您无忧上云