我正在尝试在django rest框架中创建一个Signup逻辑。我想使用HTML表单注册用户,这意味着当用户点击'signup'url时,应该生成一个类似django的html表单,用户可以填写所有凭据然后按一下注册按钮进行注册。但是我很困惑。如果我错了,请建议我,如果有人可以编写自己的代码,那么对我来说会更有利。谢谢。这是我的'serializers.py'代码:
在此处输入代码。
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User(username=validated_data['username'], email=validated_data['email'])
user.set_password(validated_data['password'])
user.save()
return user
现在这是'views.py'代码:
class CreateUserView(generics.ListCreateAPIView):
queryset = User.objects.all()
renderer_classes = [TemplateHTMLRenderer]
template_name = 'accounts/signup.html'
serializer_class = CreateUserSerializer
这是'urls.py':
urlpatterns = [
path('signup/', CreateUserView.as_view(template_name="accounts/signup.html"), name="signup"),
]
模板代码'signup.html'
{% load rest_framework %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<form action="{% url 'signup' %}" method="POST">
{% csrf_token %}
{% render_form serializer %}
<input type="submit" value="signup">
</form>
</body>
</html>