所以我有以下模型:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=254)
image_url = models.CharField(max_length=254)
title = models.CharField(max_length=254)
bio = models.CharField(max_length=20000)
vote = models.IntegerField(default=0)
def __str__(self):
return self.name
投票是我希望每次点击都加1的属性。
以下观点:
import json
from rest_framework.views import APIView
from rest_framework.response import Response
from urllib.request import urlopen
from .models import Person
from .serializers import PersonSerializer
from django.views.generic import ListView
class PersonApiView(APIView):
def get(self, request):
persons = Person.objects.all()
serializer = PersonSerializer(persons, many=True)
return Response(serializer.data)
class PersonView(ListView):
data = urlopen("<URL contatining JSON>").read()
json_persons = json.loads(data)
persons = Person.objects.all()
for person in json_persons:
if person['id'] not in [i.id for i in persons]:
Person.objects.create(id=person['id'],
name=person['name'],
image_url=person['image_url'],
title=person['title'],
bio=person['bio'])
model = Person
context_object_name = 'persons'
在视图中,我正在做两件事:
这就是我的html:
{% for person in persons %}
<div class="container">
<div ng-controller="mainController">
<div class="row">
<div class="col-xs-12 col-sm-5 col-md-4 col-lg-3">
<img ng-src="{{person.image_url}}"/>
</div>
<div class="col-xs-12 col-sm-7 col-md-8 col-lg-9">
<h2>{{ person.name }}</h2>
<h3>{{ person.title }}</h3>
<p>{{ person.bio }}</p>
<form method="POST">
<h4>Want to work with {{ person.name }}? <img src="{% static "svg/thumbs-up.svg" %}"><input type="submit" value="Yes!"></h4>
</form>
<h5><b>{{ person.vote }}</b> people have said Yes!</h5>
</div>
</div>
</div>
</div>
{% endfor %}
这是我显示所有信息的地方。
问题:
我要做的是能够点击<input>
标记,其值为“是!”,并将{{person.vote}}
增加一个。当然,我想将其保存在数据库中。
使用 ListView 时,如何实现此目的?或者我需要在views.py中创建另一个函数吗?
感谢您的时间。
答案 0 :(得分:1)
在您的情况下,您只需创建一个处理投票的功能视图并重定向回到列表视图即可完成此展会。
类似的东西:
def process_vote(request, person_id):
person = get_object_or_404(Person, id=person_id)
person.vote = F('vote') + 1 # Using an F expression to avoid race conditions
person.save()
return redirect('list_view') # Redirect to anywhere
然后在表单上,将表单的操作参数设置为该视图URL