1

我已经创建了 api 端点,用于使用 DRF 和序列化器在 django 中锁定和解锁用户。

我想在我的 django 模板中调用这个休息服务来锁定用户和解锁用户。

这是模板中的代码

<a href="{% url 'rest-auth/rest_lock/' %}?username={{user.username}}" class="table-btn"><span class="glyphicon glyphicon-lock" /></a> {% else %} <a href="{% url 'rest-auth/rest_unlock/' %}?username={{user.username}}" class="table-btn"><span class="glyphicon glyphicon-briefcase" /></a>

问题是我正在调用上述 Web 服务,但我无法使用该 Web 服务锁定用户。

这是休息服务的代码。

在串行器中:

class LockUserSerializer(serializers.ModelSerializer):
"""
User model w/o password
"""
class Meta:
   model = UserModel
   #fields=('username')
   exclude = ('password','email','last_login','is_superuser','is_active','first_name','last_name','is_staff','date_joined','groups','user_permissions')

class UnlockUserSerializer(serializers.ModelSerializer):
"""
User model w/o password
"""
class Meta:
   model = UserModel
   #fields=('username')
   exclude = ('password','email','last_login','is_superuser','is_active','first_name','last_name','is_staff','date_joined','groups','user_permissions')

在views.py中:

class LockUserView(GenericAPIView):
serializer_class=LockUserSerializer
permission_classes = (AllowAny,)

def post(self, request):
    user = User.objects.get(username=request.POST.get('username'))
    print user
    user.is_active=False;
    user.save()
    return Response({"success": "User has been locked."})

class UnlockUserView(GenericAPIView):
serializer_class=UnlockUserSerializer
permission_classes = (AllowAny,)

def post(self, request):
    user = User.objects.get(username=request.POST.get('username'))
    print user
    user.is_active=True;
    user.save()
    return Response({"success": "User has been unlocked."})

在 urls.py

from rest_auth.views import (
LoginView, LogoutView, UserDetailsView, PasswordChangeView,
PasswordResetView, PasswordResetConfirmView,LockUserView,UnlockUserView

)

urlpatterns = [
    **url(r'^rest_lock/$', LockUserView.as_view(), name='rest_lock'),
    url(r'^rest_unlock/$', UnlockUserView.as_view(), name='rest_unlock'),**
]

当我从 REST 客户端(如 RESTEASY、POSTMAN)发布用户名数据时,我编写的其余服务运行良好,但是当从用户名模板发送值时,我能够调用该服务并实现它。任何人都可以说如何做这个工作???

4

1 回答 1

1

您没有发送 HTTP POST。为此,您需要创建一个<form>. 所以,你应该有这样的东西:

<form action="{% url 'rest-auth/rest_lock/' %}?username={{user.username}}" method="POST"
    <input type="submit" value="Submit">
</form>

您还需要将您的样式应用到“提交”按钮。

您可以在此处了解有关 HTML 表单的更多信息。

于 2016-01-14T12:59:30.677 回答