我正在使用自定义后端(子类 django-registration 的 SimpleBackend)。我重写了该register()
方法,因为我需要在注册过程中做一些处理(例如,与外部服务通信)。
如果注册失败,我可以告诉注册表错误吗?
这是否需要在表单验证级别实现?
作为另一个示例,在创建用户时可能会发生数据库错误。注册如何优雅地失败?
编辑:这是我的 SimpleBackend 子类:
class MySimpleBackend(SimpleBackend):
def register(self, request, **kwargs):
username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
#
# Make a call to some external API, for example
retval = api_call_to_somewhere()
if retval is False:
# Request failed: display some error message on registration form
return something
# OR
raise some_other
# Rest of code is the same as django-registration
User.objects.create_user(username, email, password)
# authenticate() always has to be called before login(), and
# will return the user we just created.
new_user = authenticate(username=username, password=password)
login(request, new_user)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user