Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Edit and delete plans and meals with generic views

Roland Geider2e06797210c0
diff --git a/manager/views.py b/manager/views.py
index 74b49070a..84082d9b4 100644
--- a/manager/views.py
+++ b/manager/views.py
@@ -429,7 +429,7 @@ class WorkoutEditView(YamlFormMixin, UpdateView):
# Check that only the owner can access this
def get_object(self, queryset = None):
- return get_object_or_404(TrainingSchedule,
+ return get_object_or_404(self.model,
pk = self.kwargs['pk'],
user = self.request.user)
diff --git a/nutrition/templates/edit_meal.html b/nutrition/templates/edit_meal.html
deleted file mode 100644
index ebc604321..000000000
--- a/nutrition/templates/edit_meal.html
+++ /dev/null
@@ -1,28 +0,0 @@
-{% extends "base.html" %}
-{% load i18n %}
-{% load staticfiles %}
-
-{% block title %}{% trans "Edit meal" %}{% endblock %}
-
-
-{% block content %}
-
-<h2>{% trans "Edit meal" %}</h2>
-
-<form action="{% url nutrition.views.edit_meal plan.id meal.id %}"
- method="post"
- class="ym-form">
-{% csrf_token %}
-{{ form.non_field_errors }}
-<table>
- {% include "form_snippet.html" with field=form.time %}
- <tr>
- <td><input type="submit" value="{% trans "Save" %}" /></td>
- <td></td>
- </tr>
-</table>
-</form>
-
-
-
-{% endblock %}
diff --git a/nutrition/templates/edit_plan.html b/nutrition/templates/edit_plan.html
deleted file mode 100644
index 02cd76709..000000000
--- a/nutrition/templates/edit_plan.html
+++ /dev/null
@@ -1,28 +0,0 @@
-{% extends "base.html" %}
-{% load i18n %}
-{% load staticfiles %}
-
-{% block title %}{% trans "Edit nutritional plan" %}{% endblock %}
-
-
-{% block content %}
-
-<h2>{% trans "Edit nutritional plan" %}</h2>
-
-<form action="{% url nutrition.views.edit_plan plan.id %}"
- method="post"
- class="ym-form">
-{% csrf_token %}
-{{ form.non_field_errors }}
-<table>
- {% include "form_snippet.html" with field=form.description %}
- <tr>
- <td><input type="submit" value="{% trans "Save" %}" /></td>
- <td></td>
- </tr>
-</table>
-</form>
-
-
-
-{% endblock %}
diff --git a/nutrition/templates/view_nutrition_plan.html b/nutrition/templates/view_nutrition_plan.html
index c422d7659..dce44e18c 100644
--- a/nutrition/templates/view_nutrition_plan.html
+++ b/nutrition/templates/view_nutrition_plan.html
@@ -70,7 +70,7 @@ $(document).ready(function() {
alt="{% trans 'Delete meal' %}"
title="{% trans 'Delete meal' %}">
</a>
- <a href="{% url nutrition.views.edit_meal plan.id meal.id %}"
+ <a href="{% url meal-edit meal.id %}"
title="{% trans 'Edit' %}"
class="modal-dialog">
<img src="{% static 'images/icons/edit.svg' %}"
@@ -137,7 +137,8 @@ $(document).ready(function() {
{% empty %}
<div class="box warning">
{% trans "No meals for this plan." %}
- <a href="{% url nutrition.views.add_meal plan.id %}">
+ <a href="{% url meal-add plan.id %}"
+ class="modal-dialog">
{% trans "Add one now." %}
</a>
</div>
@@ -145,7 +146,8 @@ $(document).ready(function() {
{% endfor %}
<tr>
<td colspan="2">
- <a href="{% url nutrition.views.add_meal plan.id %}">
+ <a href="{% url meal-add plan.id %}"
+ class="modal-dialog">
<img src="{% static 'images/icons/edit.svg' %}"
width="16"
height="16"
@@ -249,7 +251,7 @@ $(document).ready(function() {
</p>
<p>
-<a href="{% url nutrition.views.edit_plan plan.id %}"
+<a href="{% url nutrition-edit plan.id %}"
class="modal-dialog">
<img src="{% static 'images/icons/edit.svg' %}"
width="32"
@@ -260,7 +262,8 @@ $(document).ready(function() {
</p>
<p>
-<a href="{% url nutrition.views.delete_plan plan.id %}">
+<a href="{% url nutrition-delete plan.id %}"
+ class="modal-dialog">
<img src="{% static 'images/icons/trash.svg' %}"
width="32"
height="32"
diff --git a/nutrition/urls.py b/nutrition/urls.py
index b7912c4a1..54d19ec4f 100644
--- a/nutrition/urls.py
+++ b/nutrition/urls.py
@@ -1,21 +1,36 @@
from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import permission_required
+from django.contrib.auth.decorators import login_required
from nutrition.views import IngredientDeleteView
+from nutrition.views import PlanDeleteView
+from nutrition.views import PlanEditView
+from nutrition.views import MealCreateView
+from nutrition.views import MealEditView
+
urlpatterns = patterns('nutrition.views',
url(r'^nutrition/overview/$', 'overview'),
# Plans
url(r'^nutrition/add/$', 'add'),
- url(r'^nutrition/(?P<id>\d+)/view/$', 'view'),
- url(r'^nutrition/(?P<id>\d+)/delete/$', 'delete_plan'),
- url(r'^nutrition/(?P<id>\d+)/edit/$', 'edit_plan'),
+ url(r'^nutrition/(?P<id>\d+)/view/$', 'view'),
+ url(r'^nutrition/(?P<pk>\d+)/delete/$',
+ login_required(PlanDeleteView.as_view()),
+ name='nutrition-delete'),
+ url(r'^nutrition/(?P<pk>\d+)/edit/$',
+ login_required(PlanEditView.as_view()),
+ name='nutrition-edit'),
url(r'^nutrition/(?P<id>\d+)/pdf/$', 'export_pdf'),
# Meals
- url(r'^nutrition/(?P<id>\d+)/edit/meal/(?P<meal_id>\w*)$', 'edit_meal'),
- url(r'^nutrition/(?P<id>\d+)/add/meal/$', 'add_meal'),
+ url(r'^nutrition/(?P<plan_pk>\d+)/meal/add/$',
+ login_required(MealCreateView.as_view()),
+ name='meal-add'),
+ url(r'^nutrition/meal/(?P<pk>\d+)/edit/$',
+ login_required(MealEditView.as_view()),
+ name='meal-edit'),
+
url(r'^nutrition/(?P<id>\d+)/delete/meal/$', 'delete_meal'),
# Meal items
@@ -30,5 +45,5 @@ urlpatterns = patterns('nutrition.views',
url(r'^nutrition/ingredient/overview/$', 'ingredient_overview'),
url(r'^nutrition/ingredient/(?P<id>\d+)/view/$', 'ingredient_view'),
url(r'^nutrition/ingredient/(?P<id>\w*)/edit/$', 'ingredient_edit'),
- url(r'^nutrition/ingredient/search/$', 'ingredient_search'),
+ url(r'^nutrition/ingredient/search/$', 'ingredient_search'),
)
diff --git a/nutrition/views.py b/nutrition/views.py
index 7ab6b13c1..6eff6c5f9 100644
--- a/nutrition/views.py
+++ b/nutrition/views.py
@@ -29,15 +29,12 @@ from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.forms import ModelForm
from django.utils.translation import ugettext as _
+from django.utils.translation import ugettext_lazy
from django.views.generic import DeleteView
from django.views.generic import CreateView
from django.views.generic import UpdateView
-from workout_manager import get_version
-from workout_manager.generic_views import YamlFormMixin
-from workout_manager.generic_views import YamlDeleteMixin
-
from nutrition.models import NutritionPlan
from nutrition.models import Meal
from nutrition.models import MealItem
@@ -51,7 +48,11 @@ from reportlab.lib import colors
from manager.utils import load_language
from manager.utils import load_ingredient_languages
+from workout_manager import get_version
from workout_manager.constants import NUTRITION_TAB
+from workout_manager.generic_views import YamlFormMixin
+from workout_manager.generic_views import YamlDeleteMixin
+
logger = logging.getLogger('workout_manager.custom')
@@ -90,16 +91,54 @@ def add(request):
return HttpResponseRedirect(reverse('nutrition.views.view', kwargs= {'id': plan.id}))
-@login_required
-def delete_plan(request, id):
- """Deletes the nutritional plan with the given ID
+class PlanDeleteView(YamlDeleteMixin, DeleteView):
+ """
+ Generic view to delete a nutritional plan
"""
- # Load the plan
- plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)
- plan.delete()
+ active_tab = NUTRITION_TAB
+ model = NutritionPlan
+ success_url = reverse_lazy('nutrition.views.overview')
+ title = ugettext_lazy('Delete nutritional plan?')
+
+ # Send some additional data to the template
+ def get_context_data(self, **kwargs):
+ context = super(PlanDeleteView, self).get_context_data(**kwargs)
+ context['form_action'] = reverse('nutrition-delete',
+ kwargs={'pk': self.object.id})
+
+ return context
+
+ # Check that only the owner can access this
+ def get_object(self, queryset = None):
+ return get_object_or_404(self.model,
+ pk = self.kwargs['pk'],
+ user = self.request.user)
+
+class PlanEditView(YamlFormMixin, UpdateView):
+ """
+ Generic view to update an existing nutritional plan
+ """
- return HttpResponseRedirect(reverse('manager.views.index'))
+ active_tab = NUTRITION_TAB
+ model = NutritionPlan
+ form_class = PlanForm
+ title = ugettext_lazy('Add a new nutritional plan')
+
+ # Send some additional data to the template
+ def get_context_data(self, **kwargs):
+ context = super(PlanEditView, self).get_context_data(**kwargs)
+ context['form_action'] = reverse('nutrition-edit',
+ kwargs={'pk': self.object.id})
+
+ return context
+
+ # Check that only the owner can access this
+ def get_object(self, queryset = None):
+ return get_object_or_404(self.model,
+ pk = self.kwargs['pk'],
+ user = self.request.user)
+
@login_required
def view(request, id):
@@ -123,37 +162,6 @@ def view(request, id):
template_data,
context_instance=RequestContext(request))
-@login_required
-def edit_plan(request, id):
- """Edits a nutrition plan
- """
- template_data = {}
- template_data['active_tab'] = NUTRITION_TAB
-
- # Load the plan
- plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)
- template_data['plan'] = plan
-
- # Process request
- if request.method == 'POST':
- form = PlanForm(request.POST, instance=plan)
-
- # If the data is valid, save and redirect
- if form.is_valid():
- plan = form.save(commit=False)
- #plan.language = load_language()
- plan.save()
-
- return HttpResponseRedirect(reverse('nutrition.views.view', kwargs= {'id': id}))
- else:
- form = PlanForm(instance=plan)
- template_data['form'] = form
-
-
- return render_to_response('edit_plan.html',
- template_data,
- context_instance=RequestContext(request))
-
def export_pdf(request, id):
"""Generates a PDF with the contents of a nutrition plan
@@ -287,71 +295,73 @@ def export_pdf(request, id):
class MealForm(ModelForm):
class Meta:
model = Meal
- exclude=('plan',)
+ exclude=('plan', 'order')
class MealItemForm(ModelForm):
class Meta:
model = MealItem
exclude=('meal', 'order')
-@login_required
-def edit_meal(request, id, meal_id):
- """Form to add a meal to a plan
+
+class MealCreateView(YamlFormMixin, CreateView):
+ """
+ Generic view to add a new meal to a nutrition plan
"""
- template_data = {}
- template_data['active_tab'] = NUTRITION_TAB
-
- # Load the plan
- plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)
- template_data['plan'] = plan
-
- # Load the meal
- meal = get_object_or_404(Meal, pk=meal_id)
- template_data['meal'] = meal
-
- if meal.plan != plan:
- return HttpResponseForbidden()
-
-
- # Process request
- if request.method == 'POST':
- meal_form = MealForm(request.POST, instance=meal)
-
- # If the data is valid, save and redirect
- if meal_form.is_valid():
- meal_item = meal_form.save(commit=False)
- meal_item.order = 1
- meal_item.save()
-
- return HttpResponseRedirect(reverse('nutrition.views.view', kwargs= {'id': id}))
- else:
- meal_form = MealForm(instance=meal)
- template_data['form'] = meal_form
+ active_tab = NUTRITION_TAB
+ model = Meal
+ form_class = MealForm
+ title = ugettext_lazy('Add new meal')
- return render_to_response('edit_meal.html',
- template_data,
- context_instance=RequestContext(request))
+ def form_valid(self, form):
+ plan = get_object_or_404(NutritionPlan, pk = self.kwargs['plan_pk'], user=self.request.user)
+ form.instance.plan = plan
+ form.instance.order = 1
+ return super(MealCreateView, self).form_valid(form)
+ def get_success_url(self):
+ return reverse('nutrition.views.view', kwargs ={'id': self.object.plan.id})
+ # Send some additional data to the template
+ def get_context_data(self, **kwargs):
+ context = super(MealCreateView, self).get_context_data(**kwargs)
+ context['form_action'] = reverse('meal-add',
+ kwargs={'plan_pk': self.kwargs['plan_pk']})
+
+ return context
-@login_required
-def add_meal(request, id, meal_id=None):
- """Form to add a meal to a plan
+
+class MealEditView(YamlFormMixin, UpdateView):
+ """
+ Generic view to update an existing meal
"""
- template_data = {}
- template_data['active_tab'] = NUTRITION_TAB
-
- # Load the plan
- plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)
- template_data['plan'] = plan
- meal = Meal()
- meal.plan = plan
- meal.order = 1
- meal.save()
+ active_tab = NUTRITION_TAB
+ model = Meal
+ form_class = MealForm
+ title = ugettext_lazy('Edit meal')
- return HttpResponseRedirect(reverse('nutrition.views.view', kwargs= {'id': plan.id}))
+ def get_success_url(self):
+ return reverse('nutrition.views.view', kwargs ={'id': self.object.plan.id})
+
+ # Send some additional data to the template
+ def get_context_data(self, **kwargs):
+ context = super(MealEditView, self).get_context_data(**kwargs)
+ context['form_action'] = reverse('meal-edit',
+ kwargs={'pk': self.object.id})
+
+ return context
+
+ # Check that only the owner can access this
+ def get_object(self, queryset = None):
+ meal = get_object_or_404(self.model,
+ pk = self.kwargs['pk'])
+
+ # TODO: check this
+ if meal.plan.user != self.request.user:
+ return HttpResponseForbidden()
+ else:
+ return meal
@login_required
def delete_meal(request, id):