Self hosted FLOSS fitness/workout, nutrition and weight tracker
Refactor the generic views
Roland Geiderd51fa1ccd808
diff --git a/exercises/templates/view.html b/exercises/templates/view.htmlindex b4ded1ff6..cd56d39ee 100644--- a/exercises/templates/view.html+++ b/exercises/templates/view.html@@ -63,8 +63,12 @@ $(document).ready(function() {<td class="align-right">{% if perms.exercises %}<div class="editoptions">- <a href="{% url exercises.views.exercisecomment_delete comment.id %}" title="{% trans 'Delete' %}">[x]</a>- <a href="{% url exercises.views.exercise_view exercise.id comment.id %}" title="{% trans 'Edit' %}">[e]</a>+ <a href="{% url exercises.views.exercisecomment_delete comment.id %}"+ title="{% trans 'Delete' %}"+ >[x]</a>+ <a href="{% url exercisecomment-edit comment.id %}"+ title="{% trans 'Edit' %}"+ class="modal-dialog">[e]</a></div>{% endif %}</td>@@ -74,24 +78,19 @@ $(document).ready(function() {<td>{% trans "No comments for this exercise" %}</td></tr>{% endfor %}+ </tbody>+</table>+++{% if perms.exercises %}-<tr>- <td>- <strong>{% trans "Add new comment" %}</strong>- <form action = "{% url exercises.views.exercise_view exercise.id %}"- method = "post"- id = "new_comment_form">- {% csrf_token %}- {{ comment_form.comment }}- <input type="submit" value="{% trans "Save" %}" />- </form>- </td>-</tr>+<p>+ <a href="{% url exercisecomment-add exercise.id %}"+ title="{% trans 'Add' %}"+ class="modal-dialog">{% trans "Add new comment" %}</a>+</p>{% endif %}-- </tbody>-</table>{% endblock %}diff --git a/exercises/tests/exercise.py b/exercises/tests/exercise.pyindex c7b571af5..ac6ff33fc 100644--- a/exercises/tests/exercise.py+++ b/exercises/tests/exercise.py@@ -137,7 +137,7 @@ class ExercisecommentsTestCase(WorkoutManagerTestCase):self.assertEqual(len(comments), 1)# Post a comment- response = self.client.post(reverse('exercises.views.exercise_view', kwargs={'id': 1}),+ response = self.client.post(reverse('exercisecomment-add', kwargs={'exercise_pk': 1}),{'comment': 'a new cool comment'})comments = exercise_1.exercisecomment_set.all()@@ -145,7 +145,7 @@ class ExercisecommentsTestCase(WorkoutManagerTestCase):self.assertEqual(len(comments), 2)# Post an empty comment and check it doesn't get added- response = self.client.post(reverse('exercises.views.exercise_view', kwargs={'id': 1}),+ response = self.client.post(reverse('exercisecomment-add', kwargs={'exercise_pk': 1}),{'comment': ''})comments = exercise_1.exercisecomment_set.all()diff --git a/exercises/urls.py b/exercises/urls.pyindex 0610a1ec1..b48c6581f 100644--- a/exercises/urls.py+++ b/exercises/urls.py@@ -1,30 +1,50 @@from django.conf.urls import patterns, include, url+from django.contrib.auth.decorators import permission_required+from exercises.views import ExerciseUpdateViewfrom exercises.views import ExerciseAddViewfrom exercises.views import ExerciseDeleteView+from exercises.views import ExerciseCategoryAddViewfrom exercises.views import ExerciseCategoryUpdateView+from exercises.views import ExerciseCommentAddView+from exercises.views import ExerciseCommentEditView+urlpatterns = patterns('exercises.views',url(r'^exercise/overview/$', 'exercise_overview'),url(r'^exercise/search/$', 'exercise_search'),url(r'^exercise/(?P<id>\d+)/view/$', 'exercise_view'),- url(r'^exercise/(?P<id>\d+)/view/edit/comment/(?P<comment_id>\d+)$', 'exercise_view'),- url(r'^exercise/(?P<pk>\d+)/edit/$', ExerciseUpdateView.as_view(), name='exercise-edit'),- url(r'^exercise/add/$', ExerciseAddView.as_view(), name='exercise-add'),- #url(r'^exercise/(?P<pk>\d+)/delete/$', ExerciseDeleteView.as_view(), name='exercise-delete'),- url(r'^exercise/(?P<id>\d*)/delete/$', 'exercise_delete', name='exercise-delete'),+ url(r'^exercise/add/$',+ permission_required('exercises.change_exercise')(ExerciseAddView.as_view()),+ name = 'exercise-add'),+ url(r'^exercise/(?P<pk>\d+)/edit/$',+ permission_required('exercises.change_exercise')(ExerciseUpdateView.as_view()),+ name = 'exercise-edit'),+ #url(r'^exercise/(?P<pk>\d+)/delete/$',+ # permission_required('exercises.change_exercise')(ExerciseDeleteView.as_view()),+ # name='exercise-delete'),+ url(r'^exercise/(?P<id>\d*)/delete/$', 'exercise_delete', name = 'exercise-delete'),# Comments+ url(r'^exercise/(?P<exercise_pk>\d+)/comment/add/$',+ permission_required('exercises.change_exercise')(ExerciseCommentAddView.as_view()),+ name = 'exercisecomment-add'),+ url(r'^exercise/comment/(?P<pk>\d+)/edit/$',+ permission_required('exercises.change_exercise')(ExerciseCommentEditView.as_view()),+ name = 'exercisecomment-edit'),url(r'^exercise/comment/(?P<id>\d+)/delete/$', 'exercisecomment_delete'),# Categories- url(r'^exercise/category/(?P<pk>\d+)/edit/$', ExerciseCategoryUpdateView.as_view(), name='exercisecategory-edit'),- url(r'^exercise/category/add/$', ExerciseCategoryAddView.as_view(), name='exercisecategory-add'),- #url(r'^exercise/category/(?P<id>\d*)/edit/$', 'exercise_category_edit'),+ url(r'^exercise/category/(?P<pk>\d+)/edit/$',+ permission_required('exercises.change_exercise')(ExerciseCategoryUpdateView.as_view()),+ name = 'exercisecategory-edit'),+ url(r'^exercise/category/add/$',+ permission_required('exercises.change_exercise')(ExerciseCategoryAddView.as_view()),+ name = 'exercisecategory-add'),url(r'^exercise/category/(?P<id>\d+)/delete/$', 'exercise_category_delete'),)diff --git a/exercises/views.py b/exercises/views.pyindex b8be6e74b..ddbc2f3b4 100644--- a/exercises/views.py+++ b/exercises/views.py@@ -37,7 +37,6 @@ from django.utils import translationfrom django.views.generic import DeleteViewfrom django.views.generic import CreateViewfrom django.views.generic import UpdateView-from django.views.generic.edit import ModelFormMixinfrom manager.utils import load_language@@ -46,6 +45,8 @@ from exercises.models import Exercisefrom exercises.models import ExerciseCommentfrom exercises.models import ExerciseCategory+from workout_manager.generic_views import YamlFormMixin+logger = logging.getLogger('workout_manager.custom')@@ -61,7 +62,6 @@ def exercisecomment_delete(request, id):return HttpResponseRedirect(reverse('exercises.views.exercise_view', kwargs= {'id': exercise_id}))-# ************************# Exercise functions@@ -107,10 +107,6 @@ def exercise_view(request, id, comment_id=None):template_data['exercise'] = exercisetemplate_data['active_tab'] = 'exercises'- #- # We can create and edit comments from this page, so look for Posts- template_data.update(csrf(request))-# Create the backgrounds that show what muscles the exercise works onbackgrounds_back = []backgrounds_front = []@@ -132,130 +128,20 @@ def exercise_view(request, id, comment_id=None):template_data['muscle_backgrounds_front'] = backgrounds_fronttemplate_data['muscle_backgrounds_back'] = backgrounds_back- # Only users with the appropriate permissions can work with comments- if request.user.has_perm('exercises.add_exercisecomment'):-- # Adding a new comment- if request.method == 'POST' and not comment_id:- comment_form = ExerciseCommentForm(request.POST)- comment_form.exercise = exercise-- # If the data is valid, save and redirect- if comment_form.is_valid():- new_comment = comment_form.save(commit=False)- new_comment.exercise = exercise- new_comment.save()- return HttpResponseRedirect(reverse('exercises.views.exercise_view', kwargs= {'id': id}))- else:- comment_form = ExerciseCommentForm()-- # Editing a comment- if comment_id:- exercise_comment = get_object_or_404(ExerciseComment, pk=comment_id)- template_data['comment_edit'] = exercise_comment-- comment_edit_form = ExerciseCommentForm(instance=exercise_comment)- template_data['comment_edit_form'] = comment_edit_form-- if request.method == 'POST':- comment_form = ExerciseCommentForm(request.POST, instance=exercise_comment)-- # If the data is valid, save and redirect- if comment_form.is_valid():- comment = comment_form.save(commit=False)- comment.save()- return HttpResponseRedirect(reverse('exercises.views.exercise_view', kwargs= {'id': id}))--- template_data['comment_form'] = comment_form+# Renderreturn render_to_response('view.html',template_data,context_instance=RequestContext(request))--class YamlFormMixin(ModelFormMixin):- template_name = 'form.html'-- active_tab = ''- form_fields = []- active_tab = ''- select_lists = []- static_files = []- custom_js = ''- form_action = ''- title = ''-- def get_context_data(self, **kwargs):- '''- Set necessary template data to correctly render the form- '''-- # Call the base implementation first to get a context- context = super(YamlFormMixin, self).get_context_data(**kwargs)-- # CSRF token- context.update(csrf(self.request))-- # Active tab, on top navigation- context['active_tab'] = self.active_tab-- # Custom order for form fields. The list comprehension is to avoid- # weird problems with django's template when accessing the fields with "form.fieldname"- if self.form_fields:- context['form_fields'] = [kwargs['form'][i] for i in self.form_fields]-- # Use the the order as defined in the model- else:- context['form_fields'] = kwargs['form']-- # Drop down lists get a special CSS class, there doesn't seem to be- # another way of detecting them- context['select_lists'] = self.select_lists-- # List of additional JS static files, will be passed to {% static %}- context['static_files'] = self.static_files-- # Custom JS code on form (autocompleter, editor, etc.)- context['custom_js'] = self.custom_js-- # When viewing the page on it's own, this is not necessary, but when- # opening it on a modal dialog, we need to make sure the POST request- # reaches the correct controller- context['form_action'] = self.form_action-- # Set the title- context['title'] = self.title-- return context--class ExercisesUpdateView(YamlFormMixin, UpdateView):- active_tab = 'exercises'-- @method_decorator(permission_required('exercises.change_exercise'))- def dispatch(self, *args, **kwargs):- return super(ExercisesUpdateView, self).dispatch(*args, **kwargs)--class ExercisesCreateView(YamlFormMixin, CreateView):- active_tab = 'exercises'-- @method_decorator(permission_required('exercises.change_exercise'))- def dispatch(self, *args, **kwargs):- return super(ExercisesCreateView, self).dispatch(*args, **kwargs)--class ExercisesDeleteView(YamlFormMixin, DeleteView):+class ExercisesEditAddView(YamlFormMixin):+ """+ Generic view to subclass from for exercise adding and editing, since they share all+ this settings+ """active_tab = 'exercises'- success_url = '/'- @method_decorator(permission_required('exercises.delete_exercise'))- def dispatch(self, *args, **kwargs):- return super(ExercisesDeleteView, self).dispatch(*args, **kwargs)-- def get_success_url(self):- return reverse('exercises.views.exercise_overview')--class ExerciseUpdateView(ExercisesUpdateView):model = Exerciseform_fields = ['name',@@ -281,6 +167,11 @@ class ExerciseUpdateView(ExercisesUpdateView):model = Exercisereturn ExerciseForm++class ExerciseUpdateView(ExercisesEditAddView, UpdateView):+ """+ Generic view to update an existing exercise+ """def get_context_data(self, **kwargs):context = super(ExerciseUpdateView, self).get_context_data(**kwargs)@@ -289,46 +180,27 @@ class ExerciseUpdateView(ExercisesUpdateView):return context--class ExerciseAddView(ExercisesCreateView):- model = Exercise-- form_fields = ['name',- 'category',- 'muscles',- 'description']+class ExerciseAddView(ExercisesEditAddView, CreateView):+ """+ Generic view to add a new exercise+ """- select_lists = ['category']- static_files = ['js/tinymce/tiny_mce.js',- 'js/workout-manager.js']-- custom_js = 'init_tinymce();'- title = ugettext_lazy('Add exercise')- form_action = reverse_lazy('exercise-add')-+ pass- def get_form_class(self):- '''- Define the form used for editing-- This is donw here because only at this point during the request have- we access to the currently used language. In other places Django defaults- to 'en-us'.- '''-- class ExerciseForm(ModelForm):- language = load_language()- category = ModelChoiceField(queryset=ExerciseCategory.objects.filter(language = language.id))- class Meta:- model = Exercise-- return ExerciseForm+class ExerciseDeleteView(YamlFormMixin, DeleteView):+ """+ Generic view to delete an existing exercise+ """-class ExerciseDeleteView(ExercisesDeleteView):model = Exercise-class ExerciseCategoryAddView(ExercisesCreateView):+class ExerciseCategoryAddView(YamlFormMixin, CreateView):+ """+ Generic view to add a new exercise category+ """++ active_tab = 'exercises'model = ExerciseCategoryform_class = ExerciseCategoryFormsuccess_url = reverse_lazy('exercises.views.exercise_overview')@@ -341,11 +213,17 @@ class ExerciseCategoryAddView(ExercisesCreateView):return super(ExerciseCategoryAddView, self).form_valid(form)-class ExerciseCategoryUpdateView(ExercisesUpdateView):+class ExerciseCategoryUpdateView(YamlFormMixin, UpdateView):+ """+ Generic view to update an existing exercise category+ """++ active_tab = 'exercises'model = ExerciseCategoryform_class = ExerciseCategoryFormsuccess_url = reverse_lazy('exercises.views.exercise_overview')+ # Send some additional data to the templatedef get_context_data(self, **kwargs):context = super(ExerciseCategoryUpdateView, self).get_context_data(**kwargs)context['form_action'] = reverse('exercisecategory-edit', kwargs={'pk': self.object.id})@@ -358,7 +236,37 @@ class ExerciseCategoryUpdateView(ExercisesUpdateView):return super(ExerciseCategoryUpdateView, self).form_valid(form)+class ExerciseCommentEditView(YamlFormMixin, UpdateView):+ """+ Generic view to update an existing exercise comment+ """++ active_tab = 'exercises'+ model = ExerciseComment+ form_class = ExerciseCommentForm+ def get_success_url(self):+ return reverse('exercises.views.exercise_view', kwargs ={'id': self.object.exercise.id})+++class ExerciseCommentAddView(YamlFormMixin, CreateView):+ """+ Generic view to add a new exercise comment+ """++ active_tab = 'exercises'+ model = ExerciseComment+ form_class = ExerciseCommentForm++ def form_valid(self, form):+ form.instance.exercise = Exercise.objects.get(pk = self.kwargs['exercise_pk'])++ return super(ExerciseCommentAddView, self).form_valid(form)++ def get_success_url(self):+ return reverse('exercises.views.exercise_view', kwargs ={'id': self.object.exercise.id})++@permission_required('exercises.delete_exercise')def exercise_delete(request, id):# Load the exercisediff --git a/workout_manager/generic_views.py b/workout_manager/generic_views.pynew file mode 100644index 000000000..c6487d9bc--- /dev/null+++ b/workout_manager/generic_views.py@@ -0,0 +1,73 @@+# -*- coding: utf-8 -*-++# This file is part of Workout Manager.+#+# Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++from django.core.context_processors import csrf+from django.views.generic.edit import ModelFormMixin++class YamlFormMixin(ModelFormMixin):+ template_name = 'form.html'++ active_tab = ''+ form_fields = []+ active_tab = ''+ select_lists = []+ static_files = []+ custom_js = ''+ form_action = ''+ title = ''++ def get_context_data(self, **kwargs):+ '''+ Set necessary template data to correctly render the form+ '''++ # Call the base implementation first to get a context+ context = super(YamlFormMixin, self).get_context_data(**kwargs)++ # CSRF token+ context.update(csrf(self.request))++ # Active tab, on top navigation+ context['active_tab'] = self.active_tab++ # Custom order for form fields. The list comprehension is to avoid+ # weird problems with django's template when accessing the fields with "form.fieldname"+ if self.form_fields:+ context['form_fields'] = [kwargs['form'][i] for i in self.form_fields]++ # Use the the order as defined in the model+ else:+ context['form_fields'] = kwargs['form']++ # Drop down lists get a special CSS class, there doesn't seem to be+ # another way of detecting them+ context['select_lists'] = self.select_lists++ # List of additional JS static files, will be passed to {% static %}+ context['static_files'] = self.static_files++ # Custom JS code on form (autocompleter, editor, etc.)+ context['custom_js'] = self.custom_js++ # When viewing the page on it's own, this is not necessary, but when+ # opening it on a modal dialog, we need to make sure the POST request+ # reaches the correct controller+ context['form_action'] = self.form_action++ # Set the title+ context['title'] = self.title++ return context