使用Django / DRF-React-Redux项目。所以我想返回用于用户登录验证的特定消息。如果凭据不匹配,则会收到一个错误字符串,如果用户处于非活动状态,则会收到另一个错误字符串。
我想要做的是其中一条消息我需要两个换行符,另一条我要渲染HTML,因为它应该包含一个电子邮件地址。我在SO上读到的任何内容都无效。例如,关于HTML:
Put HTML into ValidationError in Django
以下是方法:
def validate(self, data):
username = data['username']
password = data['password']
user_qs = User.objects.filter(username__iexact=username)
# user_b = User.objects.filter(email__iexact=username)
# user_qs = (user_a | user_b).distinct()
if user_qs.exists() and user_qs.count() == 1:
user_obj = user_qs.first()
password_passes = user_obj.check_password(password)
if not user_obj.is_active:
raise ValidationError((mark_safe('This user is inactive. Please contact The Company at <a href="mailto:accounts@example.com?subject=Inactive Account">accounts@example.com</a>.')))
if password_passes:
data['username'] = user_obj.username
payload = jwt_payload_handler(user_obj)
token = jwt_encode_handler(payload)
data['token'] = token
return data
raise ValidationError('The credentials provided are invalid.\nPlease verify the username and password are correct.')
毋庸置疑,它并未在前端呈现预期效果。不会破坏行并且不会呈现HTML,只需将其显示为键入。
我想如果所有其他方法都失败了,我可以将服务器响应简化为&#34;无效&#34;或&#34;无效&#34;并且只是在客户端呈现完整的消息。
答案 0 :(得分:0)
好吧,我最后遇到了:dangerouslySetInnerHTML
来处理这个问题。
https://facebook.github.io/react/docs/dom-elements.html#dangerouslysetinnerhtml
我为DRF序列化程序更改了以下内容。
def validate(self, data):
username = data['username']
password = data['password']
user_qs = User.objects.filter(username__iexact=username)
# user_b = User.objects.filter(email__iexact=username)
# user_qs = (user_a | user_b).distinct()
if user_qs.exists() and user_qs.count() == 1:
user_obj = user_qs.first()
password_passes = user_obj.check_password(password)
if not user_obj.is_active:
raise ValidationError(mark_safe('This user is inactive.<br><br>Please contact The Company at <a href="mailto:accounts@example.com?subject=Inactive Account">accounts@example.com</a>.'))
if password_passes:
data['username'] = user_obj.username
payload = jwt_payload_handler(user_obj)
token = jwt_encode_handler(payload)
data['token'] = token
return data
raise ValidationError(mark_safe('The credentials provided are invalid.<br><br>Please verify the username and password are correct.'))
然后在React FE上我必须更改signin.js
容器:
renderAlert() {
if (this.props.errorMessage) {
return (
<div className="alert alert-danger">
{this.props.errorMessage}
</div>
);
}
}
要:
renderAlert() {
if (this.props.errorMessage) {
return (
<div className="alert alert-danger"
dangerouslySetInnerHTML={{__html: this.props.errorMessage}}>
</div>
);
}
}