评估添加/编辑视图功能

时间:2011-07-19 02:17:16

标签: django

我有一个允许用户添加/编辑/删除对象的视图功能。以下功能如何显示,以及以何种方式改进它?我正在考虑将功能的各个方面分成不同的部分,但由于没有“组件”。超过四行代码,我认为这有点矫枉过正。

@login_required
def edit_education(request, edit=0):
    profile = request.user.get_profile()
    education = profile.education_set.order_by('-class_year')
    form = EducationForm(data=request.POST or None, request=request)

    if request.method == 'POST':

        ##### to add a new school entry ######
        if 'add_school' in request.POST:
            if form.is_valid():
                new_education = form.save(commit=False)
                new_education.user = profile
                new_education.save()
                return redirect('edit_education')

        ##### to delete a school entry #####
        for education_id in [key[7:] for key, value in request.POST.iteritems() if key.startswith('delete')]:
            Education.objects.get(id=education_id).delete()
            return redirect('edit_education')

        ###### to edit a school entry -- essentially, re-renders the page passing an "edit" variable #####
        for education_id in [key[5:] for key, value in request.POST.iteritems() if key.startswith('edit')]:
            edit = 1
            school_object = Education.objects.get(id = education_id)
            form = EducationForm(instance = school_object, request=request)
            return render(request, 'userprofile/edit_education.html', 
                        {'form': form, 
                         'education':education, 
                         'edit': 1, 
                         'education_id': education_id}
                    )
        ##### to save changes after you edit a previously-added school entry ######
        if 'save_changes' in request.POST:
            instance = Education.objects.get(id=request.POST['education_id']) 
            form = EducationForm(data = request.POST, instance=instance, request=request, edit=1)
            if form.is_valid():
                form.save()
                return redirect('edit_education')

return render(request, 'userprofile/edit_education.html', {'form': form, 'education': education})

在我的模板中,如果这有助于澄清任何内容:

{% for education in education %}
    <p><b>{{ education.school }}</b> {% if education.class_year %}{{ education.class_year|shorten_year}}, {% endif %} {{ education.degree}}
        <input type="submit" name="edit_{{education.id}}" value='Edit' />
        <input type="submit" name="delete_{{education.id}}" value="Delete" />
    </p>
{% endfor %}

谢谢。

1 个答案:

答案 0 :(得分:1)

  1. 每次都会从DB获得education,但如果删除或添加对象,则不会使用它。对DB的额外请求没有用处。

  2. 对于表单,如果删除对象,则不需要它。然后重新定义它以进行编辑和save_changes。

  3. add_school逻辑是特定于表单的,无需将其置于视图中。

  4. 您经常使用Education.objects.get(id=request.POST['education_id'])之类的内容。没有验证或异常处理,这很糟糕。

  5. 您在列表中使用for个循环,在循环内使用return来仅处理第一个项目。这是一种非常奇怪的方法,如果您需要第一项只使用lst[0]。或者,如果您需要处理所有项目return应放置在一个周期之外。