我试图通过在类的扩展中使用ModelSerializer的create方法来保存一些工作,然后在扩展中添加我需要的额外字段.当我这样做时,我从DRF收到一个错误,指出不支持嵌套序列化程序中的可写字段.有没有办法实现这一点,以便我不必显式定义create方法中的每个字段,而是将该工作推送到超级构造函数?包括我的代码:
class CreateUserSerializer(ModelSerializer):
school = SchoolSerializer(required=False)
class Meta:
model = User
fields = ('id', 'username', 'password', 'first_name', 'last_name',
'user_type', 'school', 'email')
extra_kwargs = {
'password': {'write_only': True},
'user_type': {'read_only': True}
}
def create(self, validated_data):
original_validated_data = validated_data.copy()
if 'password' in validated_data:
password = validated_data.pop('password')
user = super(CreateUserSerializer, self).create(validated_data)
if 'password' in original_validated_data:
user.set_password(original_validated_data['password'])
if 'school' in original_validated_data:
user.user_type = User.TYPE_ADVISOR
return user
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
File "/serializers/user.py", line 41, in create
user = super(CreateUserSerializer, self).create(validated_data)
File "/lib/python2.7/site-packages/rest_framework/serializers.py", line 832, in create
raise_errors_on_nested_writes('create', …Run Code Online (Sandbox Code Playgroud) 我们正在使用带有 DRF(Django Rest Framework)的 Django OAuth 工具包。现在,我们要提供手机号码登录。为了进行身份验证,我们将使用 OTP(一次性密码)。如何做到这一点?
我创建了一个端点localhost:8000/getauthtoken来生成身份验证令牌.
我用来获取身份验证令牌的curl命令是:
curl --request POST --url localhost:8000/getauthtoken --header 'content-type: application/json' --data '{"username":"admin", "password":"admin123"}'
Run Code Online (Sandbox Code Playgroud)
但我得到了
{"password":["This field is required."],"username":["This field is required."]}
Run Code Online (Sandbox Code Playgroud)
但在命令中我传递了用户名和密码
根据DRF文档http://www.django-rest-framework.org/api-guide/authentication/, 这是正确的方法.
我想要一个简单的api身份验证路由django-rest-framework和'django-rest-auth`.注册部分工作正常,由默认的django管理控制台确认,我也可以看到用户.不幸的是,api身份验证继续让我错误
{
"non_field_errors": [
"Unable to log in with provided credentials."
]
}
Run Code Online (Sandbox Code Playgroud)
目前我对我的配置allauth如下
# all-auth configuration
ACCOUNT_EMAIL_REQUIRED=True
ACCOUNT_AUTHENTICATION_METHOD="email"
ACCOUNT_USERNAME_REQUIRED=False
ACCOUNT_EMAIL_VERIFICATION="none"
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE=False
# CORS Configuration
CORS_ORIGIN_ALLOW_ALL=True
Run Code Online (Sandbox Code Playgroud)
我不确定我错过了哪一部分.请指导我正确的方向.没有错误,响应代码为400.凭证从django管理面板验证正确.提前致谢
问题在于电子邮件.我对配置进行了评论,并尝试使用用户名和密码生成令牌.这没有任何错误.
django django-rest-framework django-allauth django-rest-auth
我正在 Django REST Framework 上完成这个系列,还剩下一些视频:https : //www.youtube.com/playlist?list=PLEsfXFp6DpzTOcOVdZF-th7BS_GYGguAS
除非我以某种方式错过了它,否则我没有看到任何关于如何要求登录才能查看 API 的信息。我在谷歌上搜索了诸如“Django REST 需要登录”之类的东西,但除了使用 Django REST API 创建授权之外,没有看到任何其他内容。我想有一种方法可以做到并希望实现它,因为拥有一个广泛开放的 API 对我的项目不起作用。
有人可以为我指出正确的方向来设置 API 所需的登录吗?
我正在使用所有身份验证(所有身份验证休息)进行基本授权/身份验证。默认情况下,当用户注册时,Django all-auth尝试发送验证电子邮件。
如何禁用它以防止其发送验证电子邮件?
我已经按照安装教程设置了django-rest-auth,但是我无法使用登录API端点。当我发送带有正确信息的POST请求时,响应“不允许使用方法“ GET””,我收到405状态错误。
但是,当我导航到实际URL并从在线表单发布它时,它可以正常工作并返回令牌。
救命?!
邮递员示例:
https://i.imgur.com/574rERm.png
Axios示例:
axios.post('http://----.com/api/accounts/login/', data: {'username': ---, 'password': ---})
.then(function (response) {console.log(response);})
.catch(function (response) {console.log(response);})
Run Code Online (Sandbox Code Playgroud)
更新:
这似乎是Heroku或Gunicorn的问题?该网站使用Gunicorn部署在Heroku上,但是所有POST请求都作为GET请求接收。
我对可用的django中间件感到完全困惑:
我只是想让密码重置(以及以后的密码更改)功能运行,在后端使用djangowith rest_auth并在前端使用Vue。
到目前为止,我已经做了CustomPasswordResetView:
# project/accounts/views.py
from rest_auth.views import PasswordResetView
class CustomPasswordResetView(PasswordResetView):
pass
Run Code Online (Sandbox Code Playgroud)
和一个CustomPasswordResetSerializer:
# project/accounts/serializers.py
from rest_auth.serializers import PasswordResetSerializer
class CustomPasswordResetSerializer(PasswordResetSerializer):
email = serializers.EmailField()
password_reset_form_class = ResetPasswordForm
def validate_email(self, value):
# Create PasswordResetForm with the serializer
self.reset_form = self.password_reset_form_class(data=self.initial_data)
if not self.reset_form.is_valid():
raise serializers.ValidationError(self.reset_form.errors)
###### FILTER YOUR USER MODEL ######
if not get_user_model().objects.filter(email=value).exists():
raise serializers.ValidationError(_('Invalid e-mail address'))
return value
def save(self):
request = self.context.get('request')
# Set some values to …Run Code Online (Sandbox Code Playgroud) python django django-rest-framework django-allauth django-rest-auth
我正在使用 django-rest-auth 并且我试图通过覆盖表单的方法之一来修复密码重置视图中的错误。尽管我已经使用不同的 django-rest-auth 表单成功地完成了类似的操作,但我无法让它在这个表单上工作。无论我做什么,都使用旧形式。
api/urls.py
from django.urls import include, path
from django.contrib.auth import views
from django.conf.urls import include, url
from django.views.generic.base import RedirectView
from .forms import SetPasswordFormCustom
from .forms import PasswordResetFormCustom
urlpatterns = [
path('password/reset/',
views.PasswordResetView.as_view(form_class=PasswordResetFormCustom),
name='rest_password_reset'),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
path('users/', include('users.urls')),
path('reset/<uidb64>/<token>/',
views.PasswordResetConfirmView.as_view(template_name='account/password_reset_confirm.html', form_class=SetPasswordFormCustom),
name='password_reset_confirm'),
path('reset/done/', views.PasswordResetCompleteView.as_view(template_name='account/password_reset_complete.html'),
name='password_reset_complete'),
path('content/', include('lists.endpoints')),
# content is a path for lists, items etc found in the lists app
]
Run Code Online (Sandbox Code Playgroud)
表格.py
from django import forms
from django.contrib.auth.forms import SetPasswordForm
from django.contrib.auth import …Run Code Online (Sandbox Code Playgroud) 现在我使用 rest_auth 重置密码,无论发送的电子邮件和 URL 像这样打开,但我在其上添加值:这是我单击电子邮件中发送的 URL 时的页面:

在填写字段并提出发布请求后,我得到了这个:这是我得到的错误:

这是我的网址:
urlpatterns = [
path('', include('rest_auth.urls')),
path('login/', LoginView.as_view(), name='account_login'),
path('registration/', include('rest_auth.registration.urls')),
path('registration/', RegisterView.as_view(), name='account_signup'),
re_path(r'^account-confirm-email/', VerifyEmailView.as_view(),
name='account_email_verification_sent'),
re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(),
name='account_confirm_email'),
re_path(r'^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(),
name='password_reset_confirm')
]
Run Code Online (Sandbox Code Playgroud)
视图是但它内置于 rest_auth 中:
class PasswordResetConfirmView(GenericAPIView):
"""
Password reset e-mail link is confirmed, therefore
this resets the user's password.
Accepts the following POST parameters: token, uid,
new_password1, new_password2
Returns the success/fail message.
"""
serializer_class = PasswordResetConfirmSerializer
permission_classes = (AllowAny,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super(PasswordResetConfirmView, self).dispatch(*args, **kwargs)
def …Run Code Online (Sandbox Code Playgroud) django django-rest-framework django-allauth django-rest-auth
我正在使用Django,Django REST框架,Django-rest-auth和Django-allauth编写服务器应用程序。我有一种用于在用户之间传递消息的方法,只有在接收者登录后才应该发生这种情况。
但是,is_authenticated()即使用户已注销(似乎叫rest-auth/logout/,该对象又应调用Django的注销),该用户对象的方法似乎仍返回True 。是什么原因造成的?我在这里想念什么吗?
这是我的代码:
class SendMessage(generics.CreateAPIView):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = MessageSerializer
def perform_create(self, serializer):
m = self.request.data['msg']
targetUser = User.objects.get(pk = self.request.data['user'])
if targetUser.is_authenticated():
# Send message
else:
# Don't send message
Run Code Online (Sandbox Code Playgroud) authentication django django-rest-framework django-allauth django-rest-auth
我使用标准表格作为确认电子邮件:从allauth.account.views导入Confirm_email作为allauthemailconfirmation
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^accounts/', include('allauth.urls')),
url(r'^rest-auth/registration/account-confirm-email/(?P<key>\w+)/$', allauthemailconfirmation, name="account_confirm_email"),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
]
Run Code Online (Sandbox Code Playgroud)
设定:
LOGIN_REDIRECT_URL='/'
ACCOUNT_EMAIL_VERIFICATION='mandatory'
ACCOUNT_CONFIRM_EMAIL_ON_GET=False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False
Run Code Online (Sandbox Code Playgroud)
我正确地收到了一封电子邮件,但是当您尝试链接时:
ImproperlyConfigured at /rest-auth/registration/account-confirm-email/MTU:1bn1OD:dQ_mCYi6Zpr8h2aKS9J9BvNdDjA/
TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
Run Code Online (Sandbox Code Playgroud) python django django-rest-framework django-allauth django-rest-auth