I have a view function that allows a user to Add / Edit / Delete an object. How does the following function look, and in what ways could I improve it? I was thinking about separating aspects of the function into different parts, but since no ‘component’ is more than four-five lines of code, I thought that would be a bit overkill.
@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})
And in my template, if this help to clarify anything:
{% 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 %}
Thank you.
You get
educationfrom DB every time, but if you delete or add object, it isn’t used. Extra request to DB with no use.Same for form, you don’t need it if you delete object. And you redefine it for edit and save_changes.
add_schoollogic is form-specific, no need to place it in view.You often use something like
Education.objects.get(id=request.POST['education_id']). There is no validation or exception handling, which is bad.You use
forcycle over the list andreturninside a cycle to process only the first item. This is very strange approach, if you need the first item just uselst[0]. Or if you need to process all the itemsreturnshould be placed outside a cycle.