代码之家  ›  专栏  ›  技术社区  ›  nikm

根据usr django之前的“喜欢”状态更改按钮

  •  0
  • nikm  · 技术社区  · 7 年前

    我是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})
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Dalvtor    7 年前

    我会有一个不同的模型,比如:

    class Like(models.Model):
        user = models.ForeignKey(User)
        physician = models.ForeignKey(Physician)
    

    此表将在用户和医生之间建立关系。 您可以知道用户是否喜欢医生。

    Like.objects.filter(user=user, physician=physician).exists() 
    

    如果用户不喜欢医生等,则删除关系。

    要获得用户喜欢的医生的所有ID,您可以执行以下操作:

    physicians_liked = Like.objects.filter(user=user).values_list('physician', flat=True)
    

    然后在模板中进行检查:

    {% if physician.id in physicians_liked %}
        ...
    {% endif %}
    
        2
  •  0
  •   Saji Xavier    7 年前

    首先,改变你的模型设计,

    删除投票人模型,并在医生模型中添加多个字段。同时从医生模型中删除likes属性,

    class Physician(models.Model):
        ....
        #users liked the physcian
        likers = models.ManyToManyField(User, related_name='liked_physicians')
    

    意见。py公司

    context['physicians'] = Physician.objects.all().annotate(
        total_likes=Count('likers')
    )
    

    写一个模板标签来检查(计数/存在)loggedin用户是否喜欢医生

    @register.filter
    def is_liker(physician, user):
        return physician.likers.filter(id=user.id).exists()
    

    样板

    {% for physician in physicians  %}
    
        {% if physcian|is_liker:request.user == True %} 
          liked
        {% else %}
          <button>Like</button>
        {% endif %}  
    
    {% endfor %}
    
    推荐文章