Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

python - exceptions in django not showing

This is my first project in django framework, I am using visual studio code. I am trying to save data from user registration form to database. What I am trying to achieve is::

  1. how to check whether the form is validate or not in server side something like in asp.net Page.IsValid method.

  2. Now suppose my page is validate and then while trying to save my data, there occur some network error or via other reasons there is error. Then how can I show the complete error in my page.

Also what libraries I have to import for that?

My code::

user = User.objects.create_user(username = username, password = password)
         try:
            user.save()
            messages.success(request, 'successfully registered')
         except Error as e:
            raise ValidationError(e)         
            messages.error(request, e)

Here in my code, how can I show the complete error or exceptions occured during the user.save() method. Currently this code is not working. I did not know how to proceed further since this is my first project in django. Thank You!

question from:https://stackoverflow.com/questions/65644667/exceptions-in-django-not-showing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You reraise the erro before you add the message, so messages.error is "dead code". You thus should first add the message, and then raise the error, so:

try:
    user = User.objects.create_user(username = username, password = password)
    messages.success(request, 'successfully registered')
except Error as e:
    messages.error(request, str(e))
    raise ValidationError(e)

That being said, create_user will save the user, so that means that you need to wrap the .create_user call in a try-except statement. Furthermore it is not clear to me what you want to happen by raising a ValidationError. A view is not supposed to raise a ValidationError, in that case you normally rerender the page with a form that shows the errors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...