Django allauth url fetch from react 调用注册视图表单.如何将数据发送到 API 端点



我正在使用 React 作为独立的 SPA,连接到具有 allauth 的 Django 后端来管理身份验证。在本地浏览器上输入 URL(192.168.86.28:8000/accounts/signup/或 127.0.0.1:8000/accounts/signup/(,将我带到一个可以用我的自定义字段填充的表单。我可以输入信息,它在我的数据库中正确完成注册。 (见图1(。

然而,这个表单看起来很丑陋,所以我想使用 react 实现我自己的前端表单。包含数据的获取调用应该简单地将其发布到数据库,但对该 URL 的获取调用会显示表单!如何更改此设置,以便 URL 将数据发送到我的数据库?

我的网站/网址.py

from django.contrib import admin
from django.urls import path
from django.urls import include
from django.conf.urls import url
from allauth.account.views import confirm_email
from allauth.account.views import SignupView

urlpatterns = [
path('', include('pages.urls')),
path('admin/', admin.site.urls),
# path('accounts/signup/', SignupView.as_view(), name="account_signup"),
path('accounts/', include('allauth.urls')),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
]

我的网站/设置.py

# rest_framework authentications and permissions
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
'DEFAULT_AUTHENTICATION_CLASSS': [
'rest_framework.authentication.TokenAuthentication'
]
}
# cors
CORS_ORIGIN_WHITELIST = (
'http://localhost:3000',
'http://192.168.86.28:3000',
'http://192.168.86.33:3000',
)
CORS_ALLOW_CREDENTIALS = True
ALLOWED_HOSTS = [
'localhost', '127.0.0.1', '[::1]',
"192.168.86.33", "192.168.86.28",
]
# authentication
SITE_ID = 1
AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
]
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'users.serializers.CustomRegisterSerializer',
}
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = '/?verification=1'
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/?verification=1'
LOGIN_REDIRECT_URL = "http://192.168.86.28:3000/"
ACCOUNT_LOGOUT_REDIRECT_URL = "http://192.168.86.28:3000/"
ACCOUNT_FORMS = {
"signup": "users.forms.CustomSignupForm",
}
ACCOUNT_ADAPTER = "users.adapter.CustomAccountAdapter"

serializers.py

from rest_framework import serializers
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email
from rest_auth.registration.serializers import RegisterSerializer
# serializes the fields in /rest-auth/registration/ form

class CustomRegisterSerializer(RegisterSerializer):
first_name = serializers.CharField(max_length=25)
last_name = serializers.CharField(max_length=25)
is_teacher = serializers.BooleanField(required=False)
is_student = serializers.BooleanField(required=False)
is_admin = serializers.BooleanField(required=False)
is_parent = serializers.BooleanField(required=False)
is_visitor = serializers.BooleanField(required=False)
def get_cleaned_data(self):
data_dict = super().get_cleaned_data()
data_dict['first_name'] = self.validated_data.get('first_name', '')
data_dict['last_name'] = self.validated_data.get('last_name', '')
data_dict['is_teacher'] = self.validated_data.get('is_teacher', '')
data_dict['is_student'] = self.validated_data.get('is_student', '')
data_dict['is_admin'] = self.validated_data.get('is_admin', '')
data_dict['is_parent'] = self.validated_data.get('is_parent', '')
data_dict['is_visitor'] = self.validated_data.get('is_visitor', '')
return data_dict

forms.py

from allauth.account.forms import SignupForm
from django import forms
class CustomSignupForm(SignupForm):
# using forms.field to show widget
# I will have to remove this and pass the fields for JSON React API
first_name = forms.CharField(max_length=25, label='First Name')
last_name = forms.CharField(max_length=25, label='Last Name')
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
return user

adapters.py

from allauth.account.adapter import DefaultAccountAdapter

class CustomAccountAdapter(DefaultAccountAdapter):
def save_user(self, request, user, form, commit=False):
user = super().save_user(request, user, form, commit)
data = form.cleaned_data
user.first_name = data.get('first_name')
user.last_name = data.get('last_name')
user.is_teacher = data.get('is_teacher')
user.is_student = data.get('is_student')
user.is_admin = data.get('is_admin')
user.is_parent = data.get('is_parent')
user.is_visitor = data.get('is_visitor')
user.save()
return user

反应表单处理程序 (.js(

handleSubmit(event) {
event.preventDefault();
const csrftoken = Cookies.get("csrftoken");
const teacher_registration_url = url_prefix + "/accounts/signup/";
console.log(csrftoken);
try {
fetch(teacher_registration_url, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
"x-csrftoken": csrftoken,
},
body: JSON.stringify(this.state)
})
// .then(response => response.json())
// .then(response => {
// console.log(response);
// });
} catch(e) {
console.log(e);
}
}

我可以在此自定义表单中输入数据并成功注册用户。

如何从我的 React onSubmit 处理程序中做同样的事情?如您所见,它调用表单而不是将数据直接发送到数据库。

我在JS中更新了我的API调用,以调用rest-auth的API端点而不是all-auth的帐户注册表单,这解决了这个问题。把它留在这里,以防将来可以帮助其他人。

(不是获取"帐户/注册/",这会导致all-auth非常方便的注册表单,而是将获取更改为"rest-auth/registration"将信息直接发送到数据库。

最新更新