我正在使用內置的Django用戶模型。這是我的serializers.py:如何使用AngularJS顯示Django表單錯誤?
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'password', 'email',)
這是我的看法:
class HomePageView(TemplateView):
template_name = "home.html"
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
return context
class user_list(APIView): #called when I go to the /CMS/users URL
"""
List all users, or create a new user.
"""
serializer_class = UserSerializer
def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
def post(self, request):
serializer = UserSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
,這是home.html的:
<html ng-app="notesApp">
<body ng-controller="MainCtrl as ctrl">
<form ng-submit="ctrl.add()" name="myForm">
<label>Username</label>
<input type="text" name="uname" ng-model="ctrl.user.username" required>
<label>Password</label>
<input type="password" name="pwd" ng-model="ctrl.user.password" required>
<label>Email</label>
<input type="email" name="mail" ng-model="ctrl.user.email" required>
<input type="submit" value="Submit" ng-disabled="myForm.$invalid">
</form>
</div>
,這是JS:
angular.module("notesApp", [])
.controller("MainCtrl", ["$http", function($http) {
var self = this;
self.users = {}
var fetchUsers = function() {
// the line below gets the list of all users
return $http.get("/CMS/users").then(function(response) {
self.users = response.data;
}, function(errResponse) {
console.error("Error while fetching users.");
});
};
fetchUsers();
self.add = function() {
$http.post("/CMS/users", self.user).then(fetchUsers);
console.log("User clicked submit with ", self.user);
};
}]);
我用表單併成功創建了一個用戶(我用了一個val ID用戶名,電子郵件和密碼)。我嘗試使用已存在的用戶名重新創建用戶。當我單擊窗體上的「提交」按鈕時,它會在日誌中返回400錯誤(如預測的那樣),因爲如果用戶名已存在,Django不允許創建新用戶。現在,django.admin.models.AbstractModel返回它說用戶名已經存在的錯誤:
class AbstractUser(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
Username, password and email are required. Other fields are optional.
"""
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, digits and '
'@/./+/-/_ only.'),
validators=[
validators.RegexValidator(r'^[\[email protected]+-]+$',
_('Enter a valid username. '
'This value may contain only letters, numbers '
'and @/./+/-/_ characters.'), 'invalid'),
],
error_messages={
'unique': _("A user with that username already exists."),
})
有沒有辦法對我來說,顯示「該用戶名的用戶已存在」與前面AngularJS -結束?
編輯: 我改變了self.add()函數來此:
self.add = function() {
$http.post("/CMS/users", self.user)
.error(function(data, status, headers, config) {
console.log(data);
})
.then(fetchUsers);
};
,然後當我嘗試使用已經存在一個用戶名來創建一個用戶,這會記錄:
Object {username: Array[1]}
username: Array[1]
0: "This field must be unique."
length: 1
__proto__: Array[0]
__proto__: Object
什麼我做了:self.add = function(){$ http.post(「/ CMS/users」,self.user).error(function(data,status,headers,config){console.log(data);} )。然後(fetchUsers);};現在,當我嘗試使用已經存在的用戶名創建一個用戶時,它會被記錄下來:Object {username:Array [1]} ...因此它返回錯誤信息。有沒有辦法讓我一般地訪問實際的錯誤信息?我的意思是,有時錯誤可能是:{username:Array [1]},有時可能是:{email:Array [1]}。有沒有辦法讓我訪問字符串列表中的所有實際錯誤信息? – user2719875
請更新您的問題與訊息 – sirrocco
我已更新我的問題(請參閱我的問題底部的'編輯'部分)。事實證明,而不是Django傳遞「具有該用戶名的用戶已經存在。「到前端,它通過」這個字段必須是唯一的。「我不知道Django在哪裏得到」這個字段必須是唯一的「字符串,但我希望有可能我可以改變它到「具有該用戶名的用戶已經存在。請嘗試一個不同的用戶名「或者其他的東西 – user2719875