python – 如何在Django中改进这个“注册”视图?

我有一个基于Django的网站,允许用户注册(但需要管理员批准该帐户才能查看该网站的某些部分).我是基于
django.contrib.auth.我要求用户使用某个域名的电子邮件地址注册,因此我覆盖了UserCreationForm的save()和clean_email()方法.

我的注册页面使用以下视图.我很想知道如何改进这种视图代码改进或流程改进(或其他任何东西,真的).

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'],
                        'username': username,
                        '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 = None
try: pk = User.objects.filter(username=username)[0].pk
except: 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应用程序中添加将工作卸载到由另一个进程处理的队列中.

点赞