我有一個視圖功能,允許用戶添加/編輯/刪除一個對象。以下功能如何顯示,以及我可以通過哪些方式改進它?我正在考慮將函數的各個方面分成不同的部分,但由於沒有「組件」的代碼超過四五行,我認爲這會有點矯枉過正。評估添加/編輯視圖功能
@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 %}
謝謝。
我會做這一切通過AJAX,利用活塞或Django的休息-framwork了很多變化,但你不需要重新加載頁面 – sacabuche