我的注册页面使用以下视图.我很想知道如何改进这种视图代码改进或流程改进(或其他任何东西,真的).
def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valID(): message = None form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username,password=password) first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = user.email # If valID new user account if (user is not None) and (user.is_active): login(request,user) message = "<strong>Congratulations!</strong> You have been registered." # Send emails try: # admin email pk = None try: pk = User.objects.filter(username=username)[0].pk except: pass admin_email_template = loader.get_template('accounts/email_notify_admin_of_registration.txt') admin_email_context = Context({ 'first_name': first_name,'last_name': last_name,'username': username,'email': email,'pk': pk,}) admin_email_body = admin_email_template.render(admin_email_context) mail_admins("New User Registration",admin_email_body) # User email user_email_template = loader.get_template('accounts/email_registration_success.txt') user_email_context = Context({ 'first_name': form.cleaned_data['first_name'],'password': password,}) user_email_body = user_email_template.render(user_email_context) user.email_user("Successfully Registered at example.com",user_email_body) except: message = "There was an error sending you the confirmation email. You should still be able to login normally." else: message = "There was an error automatically logging you in. Try <a href=\"/login/\">logging in</a> manually." # display success page return render_to_response('accounts/register_success.HTML',{ 'username': username,'message': message,},context_instance=RequestContext(request) ) else: # If not POST form = UserCreationForm() return render_to_response('accounts/register.HTML',{ 'form': form,context_instance=RequestContext(request) )解决方法 你甚至不需要这个代码,但我认为风格:
pk = Nonetry: pk = User.objects.filter(username=username)[0].pkexcept: pass
更自然地写得像:
try: user = User.objects.get(username=username)except User.DoesNotExist: user = None
然后在管理员通知模板中使用{{user.ID}}而不是{{pk}}.
但是,就像我说的那样,你根本不需要那些代码,因为你已经有了一个用户对象来验证authenticate().
通常在Python中,将try / except块中的异常处理程序设置为空是不好的做法.换句话说,在这种情况下,始终捕获特定的异常,例如User.DoesNotExist.
在try / except块的try部分中包含许多行也是不好的做法.以这种方式编码是更好的形式:
try: ... a line of code that can generate exceptions to be handled ...except SomeException: ... handle this particular exception ...else: ... the rest of the code to execute if there were no exceptions ...
最终的次要建议是不要直接在您的视图中发送电子邮件,因为如果您的网站开始看到繁重的注册请求,这将无法扩展.最好在django-mailer应用程序中添加将工作卸载到由另一个进程处理的队列中.
总结以上是内存溢出为你收集整理的python – 如何在Django中改进这个“注册”视图?全部内容,希望文章能够帮你解决python – 如何在Django中改进这个“注册”视图?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)