我是Django的新手,正在尝试创建一个最喜欢的应用程序。
我想有喜欢的按钮变化的基础上,用户是否已经偏爱医生。
我将内科医生和喜欢的列表传递给我的模板,但不确定接下来要做什么才能从数组中提取喜欢的内容,也不确定这是否是最优雅的方法。
任何帮助都将不胜感激!
模型。py公司
class Physician(models.Model):
speciality = models.CharField(null=False, blank=False, max_length=30)
first_name = models.CharField(null=False, blank=False, max_length=50)
last_name = models.CharField(null=False, blank=False, max_length=50)
title = models.CharField(null=False, blank=False, max_length=2)
address1 = models.CharField(null=False, blank=True, max_length=50)
address2 = models.CharField(null=True, blank=True, max_length=20)
city = models.CharField(null=False, blank=False, max_length=50)
state = models.CharField(null=False, blank=False, max_length=2)
zip = models.CharField(null=False, blank=False, max_length=12)
likes = models.IntegerField(default=1)
def __str__(self):
template = '{0.last_name} {0.first_name} {0.speciality}'
return template.format(self)
class Voter(models.Model):
user = models.ForeignKey(User)
physician = models.ForeignKey(Physician)
我的模板是
{% if physicians %}
{% for physician in physicians %}
<tr>
<td>
<a href="/getmd/{{physician.id}}/">
{{ physician.last_name }}, {{ physician.first_name }} </a>
</td>
<td>{{ physician.state }}</td>
<td>{{ physician.speciality }}</td>
<td>{{ physician.id}}</td>
<td><strong id="like_count{{physician.id}}">{{ physician.likes }}</strong> </td>
<td>
{% if user.is_authenticated %}
{% if likedalready.physician].liked %}
<button id="alreadyvoted" data-catid="{{physician.id}}" class="likes btn btn-secondary" type="button" title="Already faved">
<span class="glyphicon glyphicon-check"></span>
Faved
</button>
{%else%}
<button id="{{physician.id}}like" data-catid="{{physician.id}}" class="likes btn btn-primary" type="button" title="Fave Me">
<span class="glyphicon glyphicon-thumbs-up"></span>
Fav
</button>
{% endif %}
{% endif %}
</td>
</tr>
{% endfor %}
{% else %}
<p>Sign in to fave</p>
{% endif %}
</tbody>
我的观点。py公司
def医生(请求):
user = User;
liked = False;
args = {}
args.update(csrf(request))
physicians = Physician.objects.all().order_by('last_name')
page = request.GET.get('page', 1)
paginator = Paginator(physicians, 10)
try:
physicians = paginator.page(page)
except PageNotAnInteger:
physicians = paginator.page(1)
except EmptyPage:
physicians = paginator.page(paginator.num_pages)
#Create list of already liked physicians
return_list = []
for physician in physicians:
liked = Voter.objects.filter(physician_id=physician.id, user_id=request.user.id).exists()
return_list.append((physician, {'liked': liked}))
args['physicians'] = physicians
return render(request, 'physicians.html', args, {'liked': return_list})