改善Python / Django视图代码


问题内容

我对Python /
Django和一般编程非常陌生。使用我的编程工具包中的有限工具,我为用户注册后编写了三种视图功能:允许用户在激活帐户之前添加信息并上传缩略图。

我已经发布了到目前为止已经编写的代码,以便比我有更多经验的人可以向我展示如何改进代码。毫无疑问,这是带有新手所有标记的原始代码,但是我从编写代码中学到了最好的知识-
看到改进代码的方式并学习新工具-并重写它。

我知道该问题的答案将花费大量时间。因此, 我将奖励这个问题200点奖励。
因此,仅允许我在问题发布两天后添加赏金,因此我将在周二对此问题添加赏金(尽快添加)。请注意,由于我要等到发布赏金后才选择答案,所以在添加赏金之前提供的答案仍然是“好像”存在该问题的赏金

以下是我的自我注释代码。特别是,对于每个函数的前10-14行,我有很多样板代码,可根据用户是否登录,是否已经填写此信息,是否具有会话信息等来重定向用户。

# in model.py
choices = ([(x,str(x)) for x in range(1970,2015)])
choices.reverse()

class UserProfile(models.Model):
    """
    Fields are user, network, location, graduation, headline, and position.
    user is a ForeignKey, unique = True (OneToOne). network is a ForeignKey.
    loation, graduation, headline, and position are optional.
    """
    user = models.ForeignKey(User, unique=True)
    network = models.ForeignKey(Network)
    location = models.CharField(max_length=100, blank=True)
    graduation = models.CharField(max_length=100, blank=True, choices=choices)
    headline = models.CharField(max_length=100, blank=True)
    positions = models.ManyToManyField(Position, blank=True)
    avatar = models.ImageField(upload_to='images/%Y/%m/%d', blank=True, default='default_profile_picture.jpg')
    # if the user has already filled out the 'getting started info', set boolean=True
    getting_started_boolean = models.BooleanField(default=False)

一般情况:用户注册后,我给他们两个会话变量:

    request.session['location'] = get_location_function(request)
    request.session['username'] = new_user   # this is an email address

用户注册后,他们将被重定向到Getting_started页面。

第一页:

# in views.py

def getting_started_info(request, positions=[]):
    """
    This is the first of two pages for the user to
    add additional info after they have registrered.
    There is no auto log-in after the user registers,
    so the individiaul is an 'inactive user' until he
    clicks the activation link in his email.
    """
    location = request.session.get('location')
    if request.user.is_authenticated():
        username = request.user.username        # first see if the user is logged in
        user = User.objects.get(email=username) # if so, get the user object
        if user.get_profile().getting_started_boolean: 
             return redirect('/home/')                       # redirect to User home if user has already filled out  page
        else:
            pass
    else:                                                   
        username = request.session.get('username', False)    # if not logged in, see if session info exists from registration
        if not username:
            return redirect('/account/login')                # if no session info, redirect to login page
        else:
            user = User.objects.get(email=username)
    if request.method == 'POST':
          if 'Next Step' in request.POST.values():      # do custom processing on this form
              profile = UserProfile.objects.get(user=user)
              profile.location = request.POST.get('location')
              populate_positions = []
              for position in positions:
                  populate_positions.append(Position.objects.get(label=position))
              profile.positions = request.POST.get('position')
              profile.headline = request.POST.get('headline') 
              profile.graduation = request.POST.get('graduation') 
              profile.save()
              return redirect('/account/gettingstarted/add_pic/')         
    else:
        form = GettingStartedForm(initial={'location': location})
    return render_to_response('registration/getting_started_info1.html', {'form':form, 'positions': positions,}, context_instance=RequestContext(request))

第二页:

def getting_started_pic(request):
    """
    Second page of user entering info before first login.
    This is where a user uploads a photo.
    After this page has been finished, set getting_started_boolean = True,
    so user will be redirected if hits this page again.
    """
    if request.user.is_authenticated():
        username = request.user.username                      
        user = User.objects.get(email=username)            
        if user.get_profile().getting_started_boolean: 
             return redirect('/home/')                      
        else:
            pass
    else:                                                   
        username = request.session.get('username', False)    
        if not username:
            return redirect('/account/login')                
        else:
            user = User.objects.get(email=username)
    try:
        profile = UserProfile.objects.get(user=User.objects.get(email=username)) # get the profile to display the user's picture
    except UserProfile.DoesNotExist:        # if no profile exists, redirect to login 
        return redirect('/account/login')   # this is a repetition of "return redirect('/account/login/')" above
    if request.method == 'POST':
        if 'upload' in request.POST.keys():
            form = ProfilePictureForm(request.POST, request.FILES, instance = profile)
            if form.is_valid():
                if UserProfile.objects.get(user=user).avatar != 'default_profile_picture.jpg': # if the user has an old avatar image
                    UserProfile.objects.get(user=user).avatar.delete()   # delete the image file unless it is the default image
                object = form.save(commit=False)
                try:
                    t = handle_uploaded_image(request.FILES['avatar']) # do processing on the image to make a thumbnail
                    object.avatar.save(t[0],t[1])
                except KeyError:
                    object.save()
                return render_to_response('registration/getting_started_pic.html', {'form': form, 'profile': profile,}, context_instance=RequestContext(request))
        if 'finish' in request.POST.keys():
            UserProfile.objects.filter(user=user).update(getting_started_boolean='True') # now add boolean = True so the user won't hit this page again
            return redirect('/account/gettingstarted/check_email/')       
    else:
        form = ProfilePictureForm()
    return render_to_response('registration/getting_started_pic.html', {'form': form, 'profile': profile,}, context_instance=RequestContext(request))

第三页:

def check_email(request):
    """
    End of getting started. Will redirect to user home
    if activation link has been clicked. Otherwise, will
    allow user to have activation link re-sent.
    """
    if request.user.is_authenticated():    # if the user has already clicked his activation link, redirect to User home
        return redirect('/home/')
    else:                                  # if the user is not logged in, load this page
        resend_msg=''
        user = email = request.session.get('username')
        if not email:
            return redirect('/account/login/')
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        if request.method == 'POST':
            RegistrationProfile.objects.resend_activation(email, site)
            resend_msg = 'An activation email has been resent to %s' %(email)
            return render_to_response('registration/getting_started_check_email.html', {'email':email, 'resend_msg':resend_msg}, context_instance=RequestContext(request))
        return render_to_response('registration/getting_started_check_email.html', {'email':email, 'resend_msg':resend_msg}, context_instance=RequestContext(request))

问题答案:

我最初尝试使用django.contrib.formtools.wizard复制注册过程的行为,但是考虑到您的过程只有两个步骤,它变得太复杂了,其中之一只是选择一个图像。如果您打算保留多步骤注册过程,我强烈建议您考虑使用表单向导解决方案。这将意味着基础架构负责在请求之间传递状态,而您所需要做的就是定义一系列表格。

无论如何,我选择将您的整个过程简化为一个步骤。使用基本的模型形式,我们可以用很少的代码简单地捕获一页上需要的所有UserProfile信息。

我还介绍了Django
1.3中引入的基于类的视图。它使样板代码(例如,您在每个功能的顶部检查要完成的过程)更易于管理,但代价是前期的复杂性更高。但是,一旦您了解了它们,它们对于许多用例来说都是很棒的。好吧
在代码上。

# in models.py

graduation_choices = ([(x,str(x)) for x in range(1970,2015)])
graduation_choices.reverse()

class UserProfile(models.Model):
    # usually you want null=True if blank=True. blank allows empty forms in admin, but will 
    # get a database error when trying to save the instance, because null is not allowed
    user = models.OneToOneField(User)       # OneToOneField is more explicit
    network = models.ForeignKey(Network)
    location = models.CharField(max_length=100, blank=True, null=True)
    graduation = models.CharField(max_length=100, blank=True, null=True, choices=graduation_choices)
    headline = models.CharField(max_length=100, blank=True, null=True)
    positions = models.ManyToManyField(Position, blank=True)
    avatar = models.ImageField(upload_to='images/%Y/%m/%d', blank=True, null=True)

    def get_avatar_path(self):
        if self.avatar is None:
            return 'images/default_profile_picture.jpg'
        return self.avatar.name

    def is_complete(self):
        """ Determine if getting started is complete without requiring a field. Change this method appropriately """
        if self.location is None and self.graduation is None and self.headline is None:
            return False
        return True

我偷了这个答案来处理默认图像位置,因为这是非常好的建议。将“要渲染的图片”留给模板和模型。另外,在模型上定义一个可以回答“完成?”的方法。问题,而不是尽可能定义另一个字段。使过程更容易。

# forms.py

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        widgets = {
            'user': forms.HiddenInput() # initial data MUST be used to assign this
        }

一个基于UserProfile对象的简单ModelForm。这将确保模型的所有字段都暴露于表单,并且所有内容都可以原子保存。这就是我主要偏离您的方法的方式。而不是使用多种形式,只有一种可以。我认为这也是一种更好的用户体验,尤其是因为根本没有太多的领域。您还可以在用户想要修改其信息时重复使用此确切的表格。

# in views.py - using class based views available from django 1.3 onward

class SignupMixin(View):
    """ If included within another view, will validate the user has completed 
    the getting started page, and redirects to the profile page if incomplete
    """
    def dispatch(self, request, *args, **kwargs):
        user = request.user
        if user.is_authenticated() and not user.get_profile().is_complete()
            return HttpResponseRedirect('/profile/')
        return super(SignupMixin, self).dispatch(request, *args, **kwargs)

class CheckEmailMixin(View):
    """ If included within another view, will validate the user is active,
    and will redirect to the re-send confirmation email URL if not.

    """
    def dispatch(self, request, *args, **kwargs):
        user = request.user
        if user.is_authenticated() and not user.is_active
            return HttpResponseRedirect('/confirm/')
        return super(CheckEmailMixin, self).dispatch(request, *args, **kwargs)

class UserProfileFormView(FormView, ModelFormMixin):
    """ Responsible for displaying and validating that the form was 
    saved successfully. Notice that it sets the User automatically within the form """

    form_class = UserProfileForm
    template_name = 'registration/profile.html' # whatever your template is...
    success_url = '/home/'

    def get_initial(self):
        return { 'user': self.request.user }

class HomeView(TemplateView, SignupMixin, CheckEmailMixin):
    """ Simply displays a template, but will redirect to /profile/ or /confirm/
    if the user hasn't completed their profile or confirmed their address """
    template_name = 'home/index.html'

这些视图可能是最复杂的部分,但是我觉得比意大利面条视图功能代码更容易理解。我已经简短地内联记录了这些函数,因此应该使它更易于理解。剩下的唯一事情就是将您的URL连接到这些视图类。

# urls.py

urlpatterns = patterns('',

    url(r'^home/$', HomeView.as_view(), name='home'),
    url(r'^profile/$', UserProfileFormView.as_view(), name='profile'),
    url(r'^confirm/$', HomeView.as_view(template_name='checkemail.html'), name='checkemail'),
)

现在,这些都是未经测试的代码,因此可能需要进行一些调整才能开始工作,并将其集成到您的特定站点中。而且,它完全偏离您的多步骤过程。在很多领域的情况下,多步过程会很好。.但是对我来说,单独做化身的页面似乎有点极端。希望无论走哪条路都可以。

有关基于类的视图的一些链接:

API参考
主题简介

我还想提到一些关于您的代码的一般信息。例如,您有:

populate_positions = []
for position in positions:
    populate_positions.append(Position.objects.get(label=position))

可以替换为:

populate_positions = Position.objects.filter(label__in=positions)

前者将打击每个位置的DB。评估时,后者将执行单个查询。

也;

if request.user.is_authenticated():
    username = request.user.username                      
    user = User.objects.get(email=username)

以上是多余的。您已经可以访问用户对象,然后尝试再次获取它。

user = request.user

做完了

顺便说一句,如果您想使用电子邮件地址作为用户名,则会遇到问题。该数据库最多只能接受30个字符(这是在contrib.auth中写入用户模型的方式)。在此线程上阅读其中的一些评论,其中讨论了一些陷阱。