以下按钮在网站上不起作用

时间:2017-05-06 19:36:32

标签: python html django

嘿伙计我正在为我的网站编写以下系统,当我进入管理页面并强制用户关注它工作正常但我的后续按钮不起作用,它只是刷新网站,只是想知道是否有人可以帮助我请它。提前谢谢。

EDITED

这是我的HTML

`<button type="button" class="btn btn-primary btn-lg" href="{% url "accounts:follow" username=object.username%}">
{% if following %}Unfollow{% else %}Follow{% endif %}
</button>`

urls.py

urlpatterns = [
    url(r'^profile/(?P<username>[\w.@+-]+)', views.UserDetailView.as_view(), name="viewprofile"),
    url(r'^profile/(?P<username>[\w.@+-]+)/follow', views.UserFollowView.as_view(), name="follow"),]

views.py

class UserFollowView(View):
    def get(self, request, username, *args, **kwargs):
        toggle_user = get_object_or_404(User, username__iexact=username)
        if request.user.is_authenticated():
            is_following = UserProfile.objects.toggle_follow(request.user, toggle_user)

        return redirect("accounts:viewprofile")

models.py

class UserProfileManager(models.Manager):
    use_for_related_fields = True

    def all(self):
        qs = self.get_queryset().all()
        try:
            if self.instance:
                qs = qs.exclude(user=self.instance)
        except:
            pass
        return qs

    def toggle_follow(self, user, to_toggle_user):
        user_profile, created = UserProfile.objects.get_or_create(user=user)
        if to_toggle_user in user_profile.following.all():
            user_profile.following.remove(to_toggle_user)
            added = False
        else:
            user_profile.following.add(to_toggle_user)
            added = True
        return added

    def is_following(self, user, followed_by_user):
        user_profile, created = UserProfile.objects.get_or_create(user=user)
        if  created:
            return False
        if followed_by_user in user_profile.following.all():
            return True
        return False


class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile')
    following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,related_name='followed_by')

    objects = UserProfileManager()

    def __str__(self):
        return str(self.following.all().count())

    def get_following(self):
        users = self.following.all()
        return users.exclude(username=self.user.username)

2 个答案:

答案 0 :(得分:1)

尝试在网址末尾添加“$”。 Django尝试从头到尾匹配网址,并且由于您的第一个正则表达式与您尝试访问的网址匹配,因此它不会进一步查看并转到它。 '$'将结束正则表达式。

urls.py

urlpatterns = [
    url(r'^profile/(?P<username>[\w.@+-]+)$', views.UserDetailView.as_view(), name="viewprofile"),
    url(r'^profile/(?P<username>[\w.@+-]+)/follow$', views.UserFollowView.as_view(), name="follow"),]

答案 1 :(得分:0)

如果页面“只是刷新”,听起来像按钮HTML本身是不正确的。我昨天遇到了这个问题,经过一个小时的挖掘我的JS和Python,我意识到一个按钮会自动在页面上提交一个表单,除非它是用类型“按钮”声明的,如下所示:

<button type="button" ....>