Esempio n. 1
0
def view(request, id):
    '''
    Show the nutrition plan with the given ID
    '''
    template_data = {}

    plan = get_object_or_404(NutritionPlan, pk=id)
    user = plan.user
    is_owner = request.user == user

    if not is_owner and not user.userprofile.ro_access:
        return HttpResponseForbidden()

    uid, token = make_token(user)

    # Load the language and pass it to the template
    language = load_language()
    template_data['language'] = language
    template_data['MEALITEM_WEIGHT_GRAM'] = MEALITEM_WEIGHT_GRAM
    template_data['MEALITEM_WEIGHT_UNIT'] = MEALITEM_WEIGHT_UNIT

    # Get the nutritional info
    template_data['plan'] = plan
    template_data['nutritional_data'] = plan.get_nutritional_values()

    # Tokens for the links
    template_data['uid'] = uid
    template_data['token'] = token
    template_data['owner_user'] = user
    template_data['is_owner'] = is_owner
    template_data['show_shariff'] = is_owner

    return render(request, 'plan/view.html', template_data)
Esempio n. 2
0
def view(request, id):
    """
    Show the nutrition plan with the given ID
    """
    template_data = {}

    plan = get_object_or_404(NutritionPlan, pk=id)
    user = plan.user
    is_owner = request.user == user

    if not is_owner and not user.userprofile.ro_access:
        return HttpResponseForbidden()

    uid, token = make_token(user)

    # Load the language and pass it to the template
    language = load_language()
    template_data["language"] = language
    template_data["MEALITEM_WEIGHT_GRAM"] = MEALITEM_WEIGHT_GRAM
    template_data["MEALITEM_WEIGHT_UNIT"] = MEALITEM_WEIGHT_UNIT

    # Get the nutritional info
    template_data["plan"] = plan
    template_data["nutritional_data"] = plan.get_nutritional_values()

    # Tokens for the links
    template_data["uid"] = uid
    template_data["token"] = token
    template_data["owner_user"] = user
    template_data["is_owner"] = is_owner
    template_data["show_shariff"] = is_owner

    return render(request, "plan/view.html", template_data)
Esempio n. 3
0
def processor(request):

    language = load_language()
    full_path = request.get_full_path()
    i18n_path = {}
    for lang in settings.LANGUAGES:
        i18n_path[lang[0]] = '/{0}{1}'.format(lang[0], full_path[3:])

    context = {
        # Application version
        'version': get_version(),

        # User language
        'language': language,

        # Available application languages
        'languages': settings.LANGUAGES,

        # The current path
        'request_full_path': full_path,

        # Translation links
        'i18n_path': i18n_path,

        # Translation links
        'datepicker_i18n_path': 'js/bootstrap-datepicker/locales/bootstrap-datepicker.{0}.js'.
        format(language.short_name),

        # Flag for guest users
        'has_demo_data': request.session.get('has_demo_data', False),

        # Don't show messages on AJAX requests (they are deleted if shown)
        'no_messages': request.META.get('HTTP_X_WGER_NO_MESSAGES', False),

        # Default cache time for template fragment caching
        'cache_timeout': settings.CACHES['default']['TIMEOUT']
    }

    # Pseudo-intelligent navigation here
    if '/software/' in request.get_full_path() \
       or '/contact' in request.get_full_path() \
       or '/api/v2' in request.get_full_path():
            context['active_tab'] = constants.SOFTWARE_TAB

    elif '/exercise/' in request.get_full_path():
        context['active_tab'] = constants.EXERCISE_TAB

    elif '/nutrition/' in request.get_full_path():
        context['active_tab'] = constants.NUTRITION_TAB

    elif '/weight/' in request.get_full_path():
        context['active_tab'] = constants.WEIGHT_TAB

    elif '/workout/' in request.get_full_path():
        context['active_tab'] = constants.WORKOUT_TAB

    else:
        context['active_tab'] = constants.USER_TAB

    return context
Esempio n. 4
0
    def form_valid(self, form):
        """
        Set language, author and status
        """
        form.instance.language = load_language()
        form.instance.set_author(self.request)
        existing = ExerciseBase.objects.filter(
            category=ExerciseCategory.objects.get(name=form.cleaned_data['category']))
        for elem in form.cleaned_data['equipment'].all():
            existing = existing.filter(equipment=elem)
        for elem in form.cleaned_data['muscles'].all():
            existing = existing.filter(muscles=elem)
        for elem in form.cleaned_data['muscles_secondary'].all():
            existing = existing.filter(equipment=elem)
        if not existing:
            print(form.cleaned_data)
            print('-------------------------')
            exercise_base = ExerciseBase.objects.create(
                category=ExerciseCategory.objects.get(name=form.cleaned_data['category']),
                license=License.objects.get(id=form.cleaned_data['license']),
                license_author=License.objects.get(id=form.cleaned_data['license_author']),
            )
            exercise_base.equipment.set(form.cleaned_data['equipment'].all())
            exercise_base.muscles.set(form.cleaned_data['muscles'].all())
            exercise_base.muscles_secondary.set(form.cleaned_data['muscles_secondary'].all())
            exercise_base.save()
        else:
            exercise_base = existing.first()

        form.instance.exercise_base = exercise_base
        form.instance.save()

        return super(ExerciseAddView, self).form_valid(form)
Esempio n. 5
0
    def clean_name_original(self):
        """
        Throws a validation error if the newly submitted name is too similar to
        an existing exercise's name
        """
        name_original = self.cleaned_data['name_original']

        if not self.instance.id:
            language = load_language()
            exercises = Exercise.objects.accepted() \
                .filter(language=language)
            for exercise in exercises:
                exercise_name = str(exercise)
                min_edit_dist = levenshtein(exercise_name.casefold(),
                                            name_original.casefold())
                if min_edit_dist < MIN_EDIT_DISTANCE_THRESHOLD:
                    raise ValidationError(
                        _('%(name_original)s is too similar to existing exercise '
                          '"%(exercise_name)s"'),
                        params={
                            'name_original': name_original,
                            'exercise_name': exercise_name
                        },
                    )
        return name_original
Esempio n. 6
0
def search(request):
    """
    Searches for ingredients.

    This format is currently used by the ingredient search autocompleter
    """
    term = request.GET.get('term', None)
    requested_language = request.GET.get('language', None)
    results = []
    json_response = {}
    if term:
        if requested_language:
            languages = [load_language(requested_language)]
        else:
            languages = load_ingredient_languages(request)
        ingredients = Ingredient.objects.filter(
            name__icontains=term,
            language__in=languages,
            status=Ingredient.STATUS_ACCEPTED,
        )

        for ingredient in ingredients:
            ingredient_json = {
                'value': ingredient.name,
                'data': {
                    'id': ingredient.id,
                    'name': ingredient.name,
                }
            }
            results.append(ingredient_json)
        json_response['suggestions'] = results

    return Response(json_response)
Esempio n. 7
0
File: plan.py Progetto: helenst/wger
def view(request, id):
    '''
    Show the nutrition plan with the given ID
    '''
    template_data = {}
    user = request.user
    uid, token = make_token(user)

    plan = get_object_or_404(NutritionPlan, pk=id, user=user)
    template_data['plan'] = plan

    # Load the language and pass it to the template
    language = load_language()
    template_data['language'] = language
    template_data['MEALITEM_WEIGHT_GRAM'] = MEALITEM_WEIGHT_GRAM
    template_data['MEALITEM_WEIGHT_UNIT'] = MEALITEM_WEIGHT_UNIT

    # Get the nutritional info
    template_data['nutritional_data'] = plan.get_nutritional_values()

    # Tokens for the links
    template_data['uid'] = uid
    template_data['token'] = token

    return render(request, 'plan/view.html', template_data)
Esempio n. 8
0
File: plan.py Progetto: romansp/wger
def view(request, id):
    '''
    Show the nutrition plan with the given ID
    '''
    template_data = {}

    plan = get_object_or_404(NutritionPlan, pk=id)
    user = plan.user
    is_owner = request.user == user

    if not is_owner and not user.userprofile.ro_access:
        return HttpResponseForbidden()

    uid, token = make_token(user)

    # Load the language and pass it to the template
    language = load_language()
    template_data['language'] = language
    template_data['MEALITEM_WEIGHT_GRAM'] = MEALITEM_WEIGHT_GRAM
    template_data['MEALITEM_WEIGHT_UNIT'] = MEALITEM_WEIGHT_UNIT

    # Get the nutritional info
    template_data['plan'] = plan
    template_data['nutritional_data'] = plan.get_nutritional_values()

    # Tokens for the links
    template_data['uid'] = uid
    template_data['token'] = token
    template_data['owner_user'] = user
    template_data['is_owner'] = is_owner
    template_data['show_shariff'] = is_owner

    return render(request, 'plan/view.html', template_data)
Esempio n. 9
0
def view(request, id):
    '''
    Show the nutrition plan with the given ID
    '''
    template_data = {}
    user = request.user
    uid, token = make_token(user)

    plan = get_object_or_404(NutritionPlan, pk=id, user=user)
    template_data['plan'] = plan

    # Load the language and pass it to the template
    language = load_language()
    template_data['language'] = language
    template_data['MEALITEM_WEIGHT_GRAM'] = MEALITEM_WEIGHT_GRAM
    template_data['MEALITEM_WEIGHT_UNIT'] = MEALITEM_WEIGHT_UNIT

    # Get the nutritional info
    template_data['nutritional_data'] = plan.get_nutritional_values()

    # Tokens for the links
    template_data['uid'] = uid
    template_data['token'] = token

    return render(request, 'plan/view.html', template_data)
Esempio n. 10
0
        class IngredientWeightUnitForm(ModelForm):
            unit = ModelChoiceField(queryset=WeightUnit.objects.filter(
                language=load_language()))

            class Meta:
                model = IngredientWeightUnit
                fields = ['unit', 'gram', 'amount']
Esempio n. 11
0
 def form_valid(self, form):
     '''
     Set language, author and status
     '''
     form.instance.language = load_language()
     form.instance.set_author(self.request)
     return super(ExerciseAddView, self).form_valid(form)
Esempio n. 12
0
    def form_valid(self, form):
        '''
        Set the user that submitted the exercise

        If admin, set appropriate status
        '''
        form.instance.language = load_language()

        if self.request.user.has_perm('exercises.add_exercise'):
            form.instance.status = Exercise.EXERCISE_STATUS_ADMIN
            if not form.instance.license_author:
                form.instance.license_author = 'wger.de'

        else:
            if not form.instance.license_author:
                form.instance.license_author = self.request.user.username

            subject = _('New user submitted exercise')
            message = _(u'''The user {0} submitted a new exercise "{1}".'''.format(
                        self.request.user.username, form.instance.name))
            mail.mail_admins(subject,
                             message,
                             fail_silently=True)

        return super(ExerciseAddView, self).form_valid(form)
Esempio n. 13
0
 def form_valid(self, form):
     '''
     Set language, author and status
     '''
     form.instance.language = load_language()
     form.instance.set_author(self.request)
     return super(ExerciseAddView, self).form_valid(form)
Esempio n. 14
0
    def form_valid(self, form):

        # set the submitter, if admin, set approrpiate status
        form.instance.user = self.request.user
        if self.request.user.has_perm('nutrition.add_ingredient'):
            form.instance.status = Ingredient.INGREDIENT_STATUS_ADMIN
        else:
            subject = _('New user submitted ingredient')
            message = _(
                u'''The user {0} submitted a new ingredient "{1}".'''.format(
                    self.request.user.username, form.instance.name))
            mail.mail_admins(subject, message, fail_silently=True)

        form.instance.language = load_language()
        author_name = self.request.POST.get('license_author')
        if author_name:
            if author_name.strip() != '':
                author, created = LicenseAuthor.objects.get_or_create(
                    author_name=author_name)
                author_obj = LicenseAuthor.objects.get(id=author.id)
                self.license_author_id = author.id
                form.instance.license_author = author_obj

        # print(self.license_author_id)
        return super(IngredientCreateView, self).form_valid(form)
Esempio n. 15
0
def view(request, id, slug=None):
    """
    Detail view for an exercise
    """

    template_data = {}
    template_data['comment_edit'] = False
    template_data['show_shariff'] = True

    exercise = get_object_or_404(Exercise, pk=id)

    template_data['exercise'] = exercise

    template_data["muscles_main_front"] = exercise.muscles.filter(is_front=True)
    template_data["muscles_main_back"] = exercise.muscles.filter(is_front=False)
    template_data["muscles_sec_front"] = exercise.muscles_secondary.filter(is_front=True)
    template_data["muscles_sec_back"] = exercise.muscles_secondary.filter(is_front=False)

    # If the user is logged in, load the log and prepare the entries for
    # rendering in the D3 chart
    entry_log = []
    chart_data = []
    if request.user.is_authenticated:
        logs = WorkoutLog.objects.filter(user=request.user, exercise=exercise)
        entry_log, chart_data = process_log_entries(logs)

    template_data['logs'] = entry_log
    template_data['json'] = chart_data
    template_data['svg_uuid'] = str(uuid.uuid4())
    template_data['cache_vary_on'] = "{}-{}".format(exercise.id, load_language().id)

    return render(request, 'exercise/view.html', template_data)
Esempio n. 16
0
 def perform_create(self, serializer):
     '''
     Set author and status
     '''
     language = load_language()
     obj = serializer.save(language=language)
     # Todo is it right to call set author after save?
     obj.set_author(self.request)
     obj.save()
Esempio n. 17
0
 def perform_create(self, serializer):
     '''
     Set author and status
     '''
     language = load_language()
     obj = serializer.save(language=language)
     # Todo is it right to call set author after save?
     obj.set_author(self.request)
     obj.save()
Esempio n. 18
0
        class ExerciseForm(ModelForm):
            language = load_language()
            category = ModelChoiceField(
                queryset=ExerciseCategory.objects.filter(language=language.id))

            class Meta:
                model = Exercise

            class Media:
                js = ('js/tinymce/tiny_mce.js', )
Esempio n. 19
0
def add(request):
    '''
    Add a new nutrition plan and redirect to its page
    '''

    plan = NutritionPlan()
    plan.user = request.user
    plan.language = load_language()
    plan.save()

    return HttpResponseRedirect(reverse('nutrition:plan:view', kwargs={'id': plan.id}))
Esempio n. 20
0
File: plan.py Progetto: romansp/wger
def add(request):
    '''
    Add a new nutrition plan and redirect to its page
    '''

    plan = NutritionPlan()
    plan.user = request.user
    plan.language = load_language()
    plan.save()

    return HttpResponseRedirect(reverse('nutrition:plan:view', kwargs={'id': plan.id}))
Esempio n. 21
0
def add(request):
    """
    Add a new nutrition plan and redirect to its page
    """

    plan = NutritionPlan()
    plan.user = request.user
    plan.language = load_language()
    plan.save()

    return HttpResponseRedirect(reverse("nutrition:plan:view", kwargs={"id": plan.id}))
Esempio n. 22
0
def processor(request):

    full_path = request.get_full_path()

    context = {
        # Application version
        'version': get_version(),

        # User language
        'language': load_language(),

        # The current path
        'request_full_path': full_path,

        # Translation links
        'i18n_path': {
            'de': '/de' + full_path[3:],
            'en': '/en' + full_path[3:]
        },

        # Contact email
        'contact_email': 'roland @ geider.net',

        # Flag for guest users
        'has_demo_data': request.session.get('has_demo_data', False),

        # Don't show messages on AJAX requests (they are deleted if shown)
        'no_messages': request.META.get('HTTP_X_WGER_NO_MESSAGES', False),
    }

    # Pseudo-intelligent navigation here
    if '/software/' in request.get_full_path() \
       or '/contact' in request.get_full_path():
        context['active_tab'] = constants.SOFTWARE_TAB

    elif '/exercise/' in request.get_full_path():
        context['active_tab'] = constants.EXERCISE_TAB

    elif '/nutrition/' in request.get_full_path():
        context['active_tab'] = constants.NUTRITION_TAB

    elif '/weight/' in request.get_full_path():
        context['active_tab'] = constants.WEIGHT_TAB

    elif '/workout/' in request.get_full_path():
        context['active_tab'] = constants.WORKOUT_TAB

    else:
        context['active_tab'] = constants.USER_TAB

    return context
Esempio n. 23
0
def view(request, id):
    """
    Show the nutrition plan with the given ID
    """
    template_data = {}

    plan = get_object_or_404(NutritionPlan, pk=id)
    user = plan.user
    is_owner = request.user == user

    if not is_owner and not user.userprofile.ro_access:
        return HttpResponseForbidden()

    uid, token = make_token(user)

    # Process and show the last 5 diary entries
    log_data = []
    planned_calories = plan.get_nutritional_values()['total']['energy']
    for item in plan.get_log_overview()[:5]:
        log_data.append({
            'date': item['date'],
            'planned_calories': planned_calories,
            'logged_calories': item['energy'],
            'difference': item['energy'] - planned_calories
        })

    # Load the language and pass it to the template
    language = load_language()
    template_data['language'] = language
    template_data['MEALITEM_WEIGHT_GRAM'] = MEALITEM_WEIGHT_GRAM
    template_data['MEALITEM_WEIGHT_UNIT'] = MEALITEM_WEIGHT_UNIT

    # Get the nutritional info
    template_data['plan'] = plan
    template_data['nutritional_data'] = \
        plan.get_nutritional_values()

    # Get the weight entry used
    template_data['weight_entry'] = plan.get_closest_weight_entry()

    # Tokens for the links
    template_data['uid'] = uid
    template_data['log_data'] = log_data
    template_data['token'] = token
    template_data['owner_user'] = user
    template_data['is_owner'] = is_owner
    template_data['show_shariff'] = is_owner

    return render(request, 'plan/view.html', template_data)
Esempio n. 24
0
def processor(request):

    full_path = request.get_full_path()

    context = {
        # Application version
        'version': get_version(),

        # User language
        'language': load_language(),

        # The current path
        'request_full_path': full_path,

        # Translation links
        'i18n_path': {'de': '/de' + full_path[3:],
                      'en': '/en' + full_path[3:]},

        # Contact email
        'contact_email': 'roland @ geider.net',

        # Flag for guest users
        'has_demo_data': request.session.get('has_demo_data', False),

        # Don't show messages on AJAX requests (they are deleted if shown)
        'no_messages': request.META.get('HTTP_X_WGER_NO_MESSAGES', False),
    }

    # Pseudo-intelligent navigation here
    if '/software/' in request.get_full_path() \
       or '/contact' in request.get_full_path():
            context['active_tab'] = constants.SOFTWARE_TAB

    elif '/exercise/' in request.get_full_path():
        context['active_tab'] = constants.EXERCISE_TAB

    elif '/nutrition/' in request.get_full_path():
        context['active_tab'] = constants.NUTRITION_TAB

    elif '/weight/' in request.get_full_path():
        context['active_tab'] = constants.WEIGHT_TAB

    elif '/workout/' in request.get_full_path():
        context['active_tab'] = constants.WORKOUT_TAB

    else:
        context['active_tab'] = constants.USER_TAB

    return context
Esempio n. 25
0
    def form_valid(self, form):

        # set the submitter, if admin, set approrpiate status
        form.instance.user = self.request.user
        if self.request.user.has_perm('nutrition.add_ingredient'):
            form.instance.status = Ingredient.INGREDIENT_STATUS_ADMIN
        else:
            subject = _('New user submitted ingredient')
            message = _(
                u"""The user {0} submitted a new ingredient "{1}".""".format(
                    self.request.user.username, form.instance.name))
            mail.mail_admins(subject, message, fail_silently=True)

        form.instance.language = load_language()
        return super(IngredientCreateView, self).form_valid(form)
Esempio n. 26
0
def overview(request):
    '''
    Overview with all exercises
    '''
    language = load_language()

    template_data = {}
    template_data.update(csrf(request))

    categories = (ExerciseCategory.objects.filter(language=language.id).filter(
        exercise__status__in=Exercise.EXERCISE_STATUS_OK).distinct())

    template_data['categories'] = categories
    return render_to_response('overview.html',
                              template_data,
                              context_instance=RequestContext(request))
Esempio n. 27
0
    def form_valid(self, form):

        # set the submitter, if admin, set approrpiate status
        form.instance.user = self.request.user
        if self.request.user.has_perm('nutrition.add_ingredient'):
            form.instance.status = Ingredient.INGREDIENT_STATUS_ADMIN
        else:
            subject = _('New user submitted ingredient')
            message = _(u'''The user {0} submitted a new ingredient "{1}".'''.format(
                        self.request.user.username, form.instance.name))
            mail.mail_admins(subject,
                             message,
                             fail_silently=True)

        form.instance.language = load_language()
        return super(IngredientCreateView, self).form_valid(form)
Esempio n. 28
0
def overview(request):
    '''
    Overview with all exercises
    '''
    language = load_language()

    template_data = {}
    template_data.update(csrf(request))

    categories = (ExerciseCategory.objects.filter(language=language.id)
                                          .filter(exercise__status__in=Exercise.EXERCISE_STATUS_OK)
                                          .distinct())

    template_data['categories'] = categories
    return render_to_response('overview.html',
                              template_data,
                              context_instance=RequestContext(request))
Esempio n. 29
0
def search(request):
    '''
    Search an exercise, return the result as a JSON list
    '''

    # Perform the search
    q = request.GET.get('term', '')
    user_language = load_language()
    exercises = (Exercise.objects.filter(name__icontains=q)
                                 .filter(category__language_id=user_language)
                                 .filter(status__in=Exercise.EXERCISE_STATUS_OK)
                                 .order_by('category__name', 'name')
                                 .distinct())

    # AJAX-request, this comes from the autocompleter. Create a list and send
    # it back as JSON
    if request.is_ajax():

        results = []
        for exercise in exercises:
            exercise_json = {}
            exercise_json['id'] = exercise.id
            exercise_json['name'] = exercise.name
            exercise_json['value'] = exercise.name
            exercise_json['category'] = exercise.category.name

            results.append(exercise_json)
        data = json.dumps(results)

        # Return the results to the server
        mimetype = 'application/json'
        return HttpResponse(data, mimetype)

    # Usual search (perhaps JS disabled), present the results as normal HTML page
    else:
        template_data = {}
        template_data.update(csrf(request))
        template_data['exercises'] = exercises
        template_data['search_term'] = q
        return render_to_response('exercise_search.html',
                                  template_data,
                                  context_instance=RequestContext(request))
Esempio n. 30
0
def search(request):
    '''
    Search an exercise, return the result as a JSON list
    '''

    # Perform the search
    q = request.GET.get('term', '')
    user_language = load_language()
    exercises = (Exercise.objects.filter(name__icontains=q).filter(
        category__language_id=user_language).filter(
            status__in=Exercise.EXERCISE_STATUS_OK).order_by(
                'category__name', 'name').distinct())

    # AJAX-request, this comes from the autocompleter. Create a list and send
    # it back as JSON
    if request.is_ajax():

        results = []
        for exercise in exercises:
            exercise_json = {}
            exercise_json['id'] = exercise.id
            exercise_json['name'] = exercise.name
            exercise_json['value'] = exercise.name
            exercise_json['category'] = exercise.category.name

            results.append(exercise_json)
        data = json.dumps(results)

        # Return the results to the server
        mimetype = 'application/json'
        return HttpResponse(data, mimetype)

    # Usual search (perhaps JS disabled), present the results as normal HTML page
    else:
        template_data = {}
        template_data.update(csrf(request))
        template_data['exercises'] = exercises
        template_data['search_term'] = q
        return render_to_response('exercise_search.html',
                                  template_data,
                                  context_instance=RequestContext(request))
Esempio n. 31
0
File: plan.py Progetto: httpdss/wger
def view(request, id):
    '''
    Show the nutrition plan with the given ID
    '''
    template_data = {}

    plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)
    template_data['plan'] = plan

    # Load the language and pass it to the template
    language = load_language()
    template_data['language'] = language
    template_data['MEALITEM_WEIGHT_GRAM'] = MEALITEM_WEIGHT_GRAM
    template_data['MEALITEM_WEIGHT_UNIT'] = MEALITEM_WEIGHT_UNIT

    # Get the nutritional info
    template_data['nutritional_data'] = plan.get_nutritional_values()

    return render_to_response('plan/view.html',
                              template_data,
                              context_instance=RequestContext(request))
Esempio n. 32
0
def view(request, id):
    '''
    Show the nutrition plan with the given ID
    '''
    template_data = {}

    plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)
    template_data['plan'] = plan

    # Load the language and pass it to the template
    language = load_language()
    template_data['language'] = language
    template_data['MEALITEM_WEIGHT_GRAM'] = MEALITEM_WEIGHT_GRAM
    template_data['MEALITEM_WEIGHT_UNIT'] = MEALITEM_WEIGHT_UNIT

    # Get the nutrional info

    template_data['nutritional_data'] = plan.get_nutritional_values()

    return render_to_response('plan/view.html',
                              template_data,
                              context_instance=RequestContext(request))
Esempio n. 33
0
    def form_valid(self, form):
        '''
        Set the user that submitted the exercise

        If admin, set appropriate status
        '''
        form.instance.language = load_language()

        if self.request.user.has_perm('exercises.add_exercise'):
            form.instance.status = Exercise.EXERCISE_STATUS_ADMIN
            if not form.instance.license_author:
                form.instance.license_author = 'wger.de'

        else:
            if not form.instance.license_author:
                form.instance.license_author = self.request.user.username

            subject = _('New user submitted exercise')
            message = _(
                u'''The user {0} submitted a new exercise "{1}".'''.format(
                    self.request.user.username, form.instance.name))
            mail.mail_admins(subject, message, fail_silently=True)

        return super(ExerciseAddView, self).form_valid(form)
Esempio n. 34
0
def create_demo_entries(user):
    '''
    Creates some demo data for temporary users
    '''

    # (this is a bit ugly and long...)
    language = load_language()

    #
    # Workout and exercises
    #
    setting_list = []
    weight_log = []
    workout = Workout(user=user, comment=_('Sample workout'))
    workout.save()
    monday = DaysOfWeek.objects.get(pk=1)
    wednesday = DaysOfWeek.objects.get(pk=3)
    day = Day(training=workout, description=_('Sample day'))
    day.save()
    day.day.add(monday)

    day2 = Day(training=workout, description=_('Another sample day'))
    day2.save()
    day2.day.add(wednesday)

    # Biceps curls with dumbbell
    if language.short_name == 'de':
        exercise = Exercise.objects.get(pk=26)
    else:
        exercise = Exercise.objects.get(pk=81)
    day_set = Set(exerciseday=day, sets=4, order=2)
    day_set.save()
    day_set.exercises.add(exercise)

    setting = Setting(set=day_set, exercise=exercise, reps=8, order=1)
    setting.save()

    # Weight log entries
    for reps in (8, 10, 12):
        for i in range(1, 8):
            log = WorkoutLog(user=user,
                             exercise=exercise,
                             workout=workout,
                             reps=reps,
                             weight=18 - reps + random.randint(1, 4),
                             date=datetime.date.today() - datetime.timedelta(weeks=i))
            weight_log.append(log)

    # French press
    if language.short_name == 'de':
        exercise = Exercise.objects.get(pk=25)
    else:
        exercise = Exercise.objects.get(pk=84)
    day_set = Set(exerciseday=day, sets=4, order=2)
    day_set.save()
    day_set.exercises.add(exercise)

    setting_list.append(Setting(set=day_set, exercise=exercise, reps=8, order=1))

    # Weight log entries
    for reps in (7, 10):
        for i in range(1, 8):
            log = WorkoutLog(user=user,
                             exercise=exercise,
                             workout=workout,
                             reps=reps,
                             weight=30 - reps + random.randint(1, 4),
                             date=datetime.date.today() - datetime.timedelta(weeks=i))
            weight_log.append(log)

    # Squats
    if language.short_name == 'de':
        exercise = Exercise.objects.get(pk=6)
    else:
        exercise = Exercise.objects.get(pk=111)
    day_set = Set(exerciseday=day, sets=4, order=3)
    day_set.save()
    day_set.exercises.add(exercise)

    setting_list.append(Setting(set=day_set, exercise=exercise, reps=10, order=1))

    # Weight log entries
    for reps in (5, 10, 12):
        for i in range(1, 8):
            log = WorkoutLog(user=user,
                             exercise=exercise,
                             workout=workout,
                             reps=reps,
                             weight=110 - reps + random.randint(1, 10),
                             date=datetime.date.today() - datetime.timedelta(weeks=i))
            weight_log.append(log)

    # Crunches
    if language.short_name == 'de':
        exercise = Exercise.objects.get(pk=4)
    else:
        exercise = Exercise.objects.get(pk=91)
    day_set = Set(exerciseday=day, sets=4, order=4)
    day_set.save()
    day_set.exercises.add(exercise)

    setting_list.append(Setting(set=day_set, exercise=exercise, reps=30, order=1))
    setting_list.append(Setting(set=day_set, exercise=exercise, reps=99, order=2))
    setting_list.append(Setting(set=day_set, exercise=exercise, reps=35, order=3))

    # Leg raises, supersets with crunches
    if language.short_name == 'de':
        exercise = Exercise.objects.get(pk=35)
    else:
        exercise = Exercise.objects.get(pk=126)
    day_set.exercises.add(exercise)

    setting_list.append(Setting(set=day_set, exercise=exercise, reps=30, order=1))
    setting_list.append(Setting(set=day_set, exercise=exercise, reps=40, order=2))
    setting_list.append(Setting(set=day_set, exercise=exercise, reps=99, order=3))

    Setting.objects.bulk_create(setting_list)

    # Save all the log entries
    WorkoutLog.objects.bulk_create(weight_log)

    #
    # (Body) weight entries
    #
    temp = []
    existing_entries = [i.date for i in WeightEntry.objects.filter(user=user)]
    for i in range(1, 20):
        creation_date = datetime.date.today() - datetime.timedelta(days=i)
        if creation_date not in existing_entries:
            entry = WeightEntry(user=user,
                                weight=80 + 0.5 * i + random.randint(1, 3),
                                date=creation_date)
            temp.append(entry)
    WeightEntry.objects.bulk_create(temp)

    #
    # Nutritional plan
    #
    plan = NutritionPlan()
    plan.user = user
    plan.language = language
    plan.description = _('Sample nutrional plan')
    plan.save()

    # Breakfast
    meal = Meal()
    meal.plan = plan
    meal.order = 1
    meal.time = datetime.time(7, 30)
    meal.save()

    # Oatmeal
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8197)
    else:
        ingredient = Ingredient.objects.get(pk=2126)

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.ingredient = ingredient
    mealitem.order = 1
    mealitem.amount = 100
    mealitem.save()

    # Milk
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8198)
    else:
        ingredient = Ingredient.objects.get(pk=154)

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.ingredient = ingredient
    mealitem.order = 2
    mealitem.amount = 100
    mealitem.save()

    # Protein powder
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8244)
    else:
        ingredient = Ingredient.objects.get(pk=196)

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.ingredient = ingredient
    mealitem.order = 3
    mealitem.amount = 30
    mealitem.save()

    #
    # 11 o'clock meal
    meal = Meal()
    meal.plan = plan
    meal.order = 2
    meal.time = datetime.time(11, 0)
    meal.save()

    # Bread, in slices
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8225)
        unit = None
        amount = 80
    else:
        ingredient = Ingredient.objects.get(pk=5370)
        unit = IngredientWeightUnit.objects.get(pk=9874)
        amount = 2

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.ingredient = ingredient
    mealitem.weight_unit = unit
    mealitem.order = 1
    mealitem.amount = amount
    mealitem.save()

    # Turkey
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8201)
    else:
        ingredient = Ingredient.objects.get(pk=1643)

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.order = 2
    mealitem.ingredient = ingredient
    mealitem.amount = 100
    mealitem.save()

    # Cottage cheese
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8222)  # TODO: check this!
    else:
        ingredient = Ingredient.objects.get(pk=17)

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.ingredient = ingredient
    mealitem.order = 3
    mealitem.amount = 50
    mealitem.save()

    # Tomato, one
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8217)
        unit = None
        amount = 120
    else:
        ingredient = Ingredient.objects.get(pk=3208)
        unit = IngredientWeightUnit.objects.get(pk=5950)
        amount = 1

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.weight_unit = unit
    mealitem.ingredient = ingredient
    mealitem.order = 4
    mealitem.amount = amount
    mealitem.save()

    #
    # Lunch (leave empty so users can add their own ingredients)
    meal = Meal()
    meal.plan = plan
    meal.order = 3
    meal.time = datetime.time(13, 0)
    meal.save()

    #
    # Workout schedules
    #

    # create some empty workouts to fill the list
    workout2 = Workout(user=user, comment=_('Placeholder workout nr {0} for schedule').format(1))
    workout2.save()
    workout3 = Workout(user=user, comment=_('Placeholder workout nr {0} for schedule').format(2))
    workout3.save()
    workout4 = Workout(user=user, comment=_('Placeholder workout nr {0} for schedule').format(3))
    workout4.save()

    schedule = Schedule()
    schedule.user = user
    schedule.name = _('My cool workout schedule')
    schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=4)
    schedule.is_active = True
    schedule.is_loop = True
    schedule.save()

    # Add the workouts
    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout2
    step.duration = 2
    step.order = 1
    step.save()

    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout
    step.duration = 4
    step.order = 2
    step.save()

    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout3
    step.duration = 1
    step.order = 3
    step.save()

    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout4
    step.duration = 6
    step.order = 4
    step.save()

    #
    # Add two more schedules, to make the overview more interesting
    schedule = Schedule()
    schedule.user = user
    schedule.name = _('Empty placeholder schedule')
    schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=15)
    schedule.is_active = False
    schedule.is_loop = False
    schedule.save()

    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout2
    step.duration = 2
    step.order = 1
    step.save()

    schedule = Schedule()
    schedule.user = user
    schedule.name = _('Empty placeholder schedule')
    schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=30)
    schedule.is_active = False
    schedule.is_loop = False
    schedule.save()

    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout4
    step.duration = 2
    step.order = 1
    step.save()
Esempio n. 35
0
 def items(self):
     return (Ingredient.objects.filter(language=load_language()).filter(
         status=Ingredient.STATUS_ACCEPTED))
Esempio n. 36
0
File: unit.py Progetto: teadur/wger
 def form_valid(self, form):
     form.instance.language = load_language()
     return super(WeightUnitCreateView, self).form_valid(form)
Esempio n. 37
0
 def perform_create(self, serializer):
     """
     Set the owner
     """
     serializer.save(user=self.request.user, language=load_language())
Esempio n. 38
0
def processor(request):

    language = load_language()
    full_path = request.get_full_path()
    i18n_path = {}
    static_path = static('images/logos/logo-marketplace-256.png')

    for lang in settings.LANGUAGES:
        i18n_path[lang[0]] = u'/{0}{1}'.format(lang[0], full_path[3:])

    context = {
        # Application version
        'version': get_version(),

        # User language
        'language': language,

        # Available application languages
        'languages': settings.LANGUAGES,

        # The current path
        'request_full_path': full_path,

        # The current full path with host
        'request_absolute_path': request.build_absolute_uri(),
        'image_absolute_path': request.build_absolute_uri(static_path),


        # Translation links
        'i18n_path': i18n_path,

        # Flag for guest users
        'has_demo_data': request.session.get('has_demo_data', False),

        # Don't show messages on AJAX requests (they are deleted if shown)
        'no_messages': request.META.get('HTTP_X_WGER_NO_MESSAGES', False),

        # Default cache time for template fragment caching
        'cache_timeout': settings.CACHES['default']['TIMEOUT'],

        # Used for logged in trainers
        'trainer_identity': request.session.get('trainer.identity'),
    }

    # Pseudo-intelligent navigation here
    if '/software/' in request.get_full_path() \
       or '/contact' in request.get_full_path() \
       or '/api/v2' in request.get_full_path():
            context['active_tab'] = constants.SOFTWARE_TAB
            context['show_shariff'] = True

    elif '/exercise/' in request.get_full_path():
        context['active_tab'] = constants.EXERCISE_TAB

    elif '/nutrition/' in request.get_full_path():
        context['active_tab'] = constants.NUTRITION_TAB

    elif '/weight/' in request.get_full_path():
        context['active_tab'] = constants.WEIGHT_TAB

    elif '/workout/' in request.get_full_path():
        context['active_tab'] = constants.WORKOUT_TAB

    else:
        context['active_tab'] = constants.USER_TAB

    return context
Esempio n. 39
0
File: unit.py Progetto: teadur/wger
 def get_queryset(self):
     '''
     Only show ingredient units in the current user's language
     '''
     return WeightUnit.objects.filter(language=load_language())
Esempio n. 40
0
 def items(self):
     return (Ingredient.objects.filter(language=load_language())
                               .filter(status=Ingredient.STATUS_ACCEPTED))
Esempio n. 41
0
    def form_valid(self, form):
        form.instance.language = load_language()

        return super(ExerciseCategoryUpdateView, self).form_valid(form)
Esempio n. 42
0
File: unit.py Progetto: drkarl/wger
 def get_queryset(self):
     """
     Only show ingredient units in the current user's language
     """
     return WeightUnit.objects.filter(language=load_language())
Esempio n. 43
0
File: views.py Progetto: voszp/wger
 def pre_save(self, obj):
     '''
     Set language, author and status
     '''
     obj.language = load_language()
     obj.set_author(self.request)
Esempio n. 44
0
    def form_valid(self, form):

        form.instance.language = load_language()
        form.instance.set_author(self.request)
        return super(IngredientCreateView, self).form_valid(form)
Esempio n. 45
0
def create_demo_entries(user):
    """
    Creates some demo data for temporary users
    """

    # (this is a bit ugly and long...)
    language = load_language()

    #
    # Workout and exercises
    #
    setting_list = []
    weight_log = []
    workout = Workout(user=user, name=_('Sample workout'))
    workout.save()
    monday = DaysOfWeek.objects.get(pk=1)
    wednesday = DaysOfWeek.objects.get(pk=3)
    day = Day(training=workout, description=_('Sample day'))
    day.save()
    day.day.add(monday)

    day2 = Day(training=workout, description=_('Another sample day'))
    day2.save()
    day2.day.add(wednesday)

    # Biceps curls with dumbbell
    if language.short_name == 'de':
        exercise = Exercise.objects.get(pk=26)
    else:
        exercise = Exercise.objects.get(pk=81)
    day_set = Set(exerciseday=day, sets=4, order=2)
    day_set.save()

    setting = Setting(set=day_set, exercise=exercise, reps=8, order=1)
    setting.save()

    # Weight log entries
    for reps in (8, 10, 12):
        for i in range(1, 8):
            log = WorkoutLog(user=user,
                             exercise=exercise,
                             workout=workout,
                             reps=reps,
                             weight=18 - reps + random.randint(1, 4),
                             date=datetime.date.today() -
                             datetime.timedelta(weeks=i))
            weight_log.append(log)

    # French press
    if language.short_name == 'de':
        exercise = Exercise.objects.get(pk=25)
    else:
        exercise = Exercise.objects.get(pk=84)
    day_set = Set(exerciseday=day, sets=4, order=2)
    day_set.save()

    setting_list.append(
        Setting(set=day_set, exercise=exercise, reps=8, order=1))

    # Weight log entries
    for reps in (7, 10):
        for i in range(1, 8):
            log = WorkoutLog(user=user,
                             exercise=exercise,
                             workout=workout,
                             reps=reps,
                             weight=30 - reps + random.randint(1, 4),
                             date=datetime.date.today() -
                             datetime.timedelta(weeks=i))
            weight_log.append(log)

    # Squats
    if language.short_name == 'de':
        exercise = Exercise.objects.get(pk=6)
    else:
        exercise = Exercise.objects.get(pk=111)
    day_set = Set(exerciseday=day, sets=4, order=3)
    day_set.save()

    setting_list.append(
        Setting(set=day_set, exercise=exercise, reps=10, order=1))

    # Weight log entries
    for reps in (5, 10, 12):
        for i in range(1, 8):
            log = WorkoutLog(user=user,
                             exercise=exercise,
                             workout=workout,
                             reps=reps,
                             weight=110 - reps + random.randint(1, 10),
                             date=datetime.date.today() -
                             datetime.timedelta(weeks=i))
            weight_log.append(log)

    # Crunches
    if language.short_name == 'de':
        exercise = Exercise.objects.get(pk=4)
    else:
        exercise = Exercise.objects.get(pk=91)
    day_set = Set(exerciseday=day, sets=4, order=4)
    day_set.save()

    setting_list.append(
        Setting(set=day_set, exercise=exercise, reps=30, order=1))
    setting_list.append(
        Setting(set=day_set, exercise=exercise, reps=99, order=2))
    setting_list.append(
        Setting(set=day_set, exercise=exercise, reps=35, order=3))

    # Leg raises, supersets with crunches
    if language.short_name == 'de':
        exercise = Exercise.objects.get(pk=35)
    else:
        exercise = Exercise.objects.get(pk=126)

    setting_list.append(
        Setting(set=day_set, exercise=exercise, reps=30, order=1))
    setting_list.append(
        Setting(set=day_set, exercise=exercise, reps=40, order=2))
    setting_list.append(
        Setting(set=day_set, exercise=exercise, reps=99, order=3))

    Setting.objects.bulk_create(setting_list)

    # Save all the log entries
    WorkoutLog.objects.bulk_create(weight_log)

    #
    # (Body) weight entries
    #
    temp = []
    existing_entries = [i.date for i in WeightEntry.objects.filter(user=user)]
    for i in range(1, 20):
        creation_date = datetime.date.today() - datetime.timedelta(days=i)
        if creation_date not in existing_entries:
            entry = WeightEntry(user=user,
                                weight=80 + 0.5 * i + random.randint(1, 3),
                                date=creation_date)
            temp.append(entry)
    WeightEntry.objects.bulk_create(temp)

    #
    # Nutritional plan
    #
    plan = NutritionPlan()
    plan.user = user
    plan.language = language
    plan.description = _('Sample nutrional plan')
    plan.save()

    # Breakfast
    meal = Meal()
    meal.plan = plan
    meal.order = 1
    meal.time = datetime.time(7, 30)
    meal.save()

    # Oatmeal
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8197)
    else:
        ingredient = Ingredient.objects.get(pk=2126)

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.ingredient = ingredient
    mealitem.order = 1
    mealitem.amount = 100
    mealitem.save()

    # Milk
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8198)
    else:
        ingredient = Ingredient.objects.get(pk=154)

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.ingredient = ingredient
    mealitem.order = 2
    mealitem.amount = 100
    mealitem.save()

    # Protein powder
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8244)
    else:
        ingredient = Ingredient.objects.get(pk=196)

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.ingredient = ingredient
    mealitem.order = 3
    mealitem.amount = 30
    mealitem.save()

    #
    # 11 o'clock meal
    meal = Meal()
    meal.plan = plan
    meal.order = 2
    meal.time = datetime.time(11, 0)
    meal.save()

    # Bread, in slices
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8225)
        unit = None
        amount = 80
    else:
        ingredient = Ingredient.objects.get(pk=5370)
        unit = IngredientWeightUnit.objects.get(pk=9874)
        amount = 2

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.ingredient = ingredient
    mealitem.weight_unit = unit
    mealitem.order = 1
    mealitem.amount = amount
    mealitem.save()

    # Turkey
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8201)
    else:
        ingredient = Ingredient.objects.get(pk=1643)

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.order = 2
    mealitem.ingredient = ingredient
    mealitem.amount = 100
    mealitem.save()

    # Cottage cheese
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8222)  # TODO: check this!
    else:
        ingredient = Ingredient.objects.get(pk=17)

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.ingredient = ingredient
    mealitem.order = 3
    mealitem.amount = 50
    mealitem.save()

    # Tomato, one
    if language.short_name == 'de':
        ingredient = Ingredient.objects.get(pk=8217)
        unit = None
        amount = 120
    else:
        ingredient = Ingredient.objects.get(pk=3208)
        unit = IngredientWeightUnit.objects.get(pk=5950)
        amount = 1

    mealitem = MealItem()
    mealitem.meal = meal
    mealitem.weight_unit = unit
    mealitem.ingredient = ingredient
    mealitem.order = 4
    mealitem.amount = amount
    mealitem.save()

    #
    # Lunch (leave empty so users can add their own ingredients)
    meal = Meal()
    meal.plan = plan
    meal.order = 3
    meal.time = datetime.time(13, 0)
    meal.save()

    #
    # Workout schedules
    #

    # create some empty workouts to fill the list
    workout2 = Workout(
        user=user, name=_('Placeholder workout nr {0} for schedule').format(1))
    workout2.save()
    workout3 = Workout(
        user=user, name=_('Placeholder workout nr {0} for schedule').format(2))
    workout3.save()
    workout4 = Workout(
        user=user, name=_('Placeholder workout nr {0} for schedule').format(3))
    workout4.save()

    schedule = Schedule()
    schedule.user = user
    schedule.name = _('My cool workout schedule')
    schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=4)
    schedule.is_active = True
    schedule.is_loop = True
    schedule.save()

    # Add the workouts
    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout2
    step.duration = 2
    step.order = 1
    step.save()

    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout
    step.duration = 4
    step.order = 2
    step.save()

    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout3
    step.duration = 1
    step.order = 3
    step.save()

    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout4
    step.duration = 6
    step.order = 4
    step.save()

    #
    # Add two more schedules, to make the overview more interesting
    schedule = Schedule()
    schedule.user = user
    schedule.name = _('Empty placeholder schedule')
    schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=15)
    schedule.is_active = False
    schedule.is_loop = False
    schedule.save()

    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout2
    step.duration = 2
    step.order = 1
    step.save()

    schedule = Schedule()
    schedule.user = user
    schedule.name = _('Empty placeholder schedule')
    schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=30)
    schedule.is_active = False
    schedule.is_loop = False
    schedule.save()

    step = ScheduleStep()
    step.schedule = schedule
    step.workout = workout4
    step.duration = 2
    step.order = 1
    step.save()
Esempio n. 46
0
File: unit.py Progetto: drkarl/wger
 def form_valid(self, form):
     form.instance.language = load_language()
     return super(WeightUnitCreateView, self).form_valid(form)
Esempio n. 47
0
 def perform_create(self, serializer):
     '''
     Set the owner
     '''
     serializer.save(user=self.request.user, language=load_language())
Esempio n. 48
0
 def items(self):
     return (Ingredient.objects.filter(language=load_language())
                               .filter(status__in=Ingredient.INGREDIENT_STATUS_OK))
Esempio n. 49
0
def processor(request):

    language = load_language()
    full_path = request.get_full_path()
    i18n_path = {}
    static_path = static('images/logos/logo-social.png')

    for lang in settings.LANGUAGES:
        i18n_path[lang[0]] = '/{0}{1}'.format(lang[0], full_path[3:])

    context = {
        # Application version
        'version': get_version(),

        # Twitter handle for this instance
        'twitter': settings.WGER_SETTINGS['TWITTER'],

        # User language
        'language': language,

        # Available application languages
        'languages': settings.LANGUAGES,

        # The current path
        'request_full_path': full_path,

        # The current full path with host
        'request_absolute_path': request.build_absolute_uri(),
        'image_absolute_path': request.build_absolute_uri(static_path),

        # Translation links
        'i18n_path': i18n_path,

        # Flag for guest users
        'has_demo_data': request.session.get('has_demo_data', False),

        # Don't show messages on AJAX requests (they are deleted if shown)
        'no_messages': request.META.get('HTTP_X_WGER_NO_MESSAGES', False),

        # Default cache time for template fragment caching
        'cache_timeout': settings.CACHES['default']['TIMEOUT'],

        # Used for logged in trainers
        'trainer_identity': request.session.get('trainer.identity'),

        # current gym, if available
        'custom_header': get_custom_header(request),
    }

    # Pseudo-intelligent navigation here
    if '/software/' in request.get_full_path() \
       or '/contact' in request.get_full_path() \
       or '/api/v2' in request.get_full_path():
        context['active_tab'] = constants.SOFTWARE_TAB
        context['show_shariff'] = True

    elif '/exercise/' in request.get_full_path():
        context['active_tab'] = constants.WORKOUT_TAB

    elif '/nutrition/' in request.get_full_path():
        context['active_tab'] = constants.NUTRITION_TAB

    elif '/weight/' in request.get_full_path():
        context['active_tab'] = constants.WEIGHT_TAB

    elif '/workout/' in request.get_full_path():
        context['active_tab'] = constants.WORKOUT_TAB

    return context
Esempio n. 50
0
    def form_valid(self, form):
        form.instance.language = load_language()

        return super(ExerciseCategoryUpdateView, self).form_valid(form)
Esempio n. 51
0
def processor(request):

    language = load_language()
    full_path = request.get_full_path()
    i18n_path = {}
    for lang in settings.LANGUAGES:
        i18n_path[lang[0]] = u'/{0}{1}'.format(lang[0], full_path[3:])

    context = {
        # Application version
        'version':
        get_version(),

        # User language
        'language':
        language,

        # Available application languages
        'languages':
        settings.LANGUAGES,

        # The current path
        'request_full_path':
        full_path,

        # Translation links
        'i18n_path':
        i18n_path,

        # Translation links
        'datepicker_i18n_path':
        'js/bootstrap-datepicker/locales/bootstrap-datepicker.{0}.js'.format(
            language.short_name),

        # Flag for guest users
        'has_demo_data':
        request.session.get('has_demo_data', False),

        # Don't show messages on AJAX requests (they are deleted if shown)
        'no_messages':
        request.META.get('HTTP_X_WGER_NO_MESSAGES', False),

        # Default cache time for template fragment caching
        'cache_timeout':
        settings.CACHES['default']['TIMEOUT'],

        # Used for logged in trainers
        'trainer_identity':
        request.session.get('trainer.identity'),
    }

    # Pseudo-intelligent navigation here
    if '/software/' in request.get_full_path() \
       or '/contact' in request.get_full_path() \
       or '/api/v2' in request.get_full_path():
        context['active_tab'] = constants.SOFTWARE_TAB
        context['show_shariff'] = True

    elif '/exercise/' in request.get_full_path():
        context['active_tab'] = constants.EXERCISE_TAB

    elif '/nutrition/' in request.get_full_path():
        context['active_tab'] = constants.NUTRITION_TAB

    elif '/weight/' in request.get_full_path():
        context['active_tab'] = constants.WEIGHT_TAB

    elif '/workout/' in request.get_full_path():
        context['active_tab'] = constants.WORKOUT_TAB

    else:
        context['active_tab'] = constants.USER_TAB

    return context
Esempio n. 52
0
    def form_valid(self, form):

        form.instance.language = load_language()
        form.instance.set_author(self.request)
        return super(IngredientCreateView, self).form_valid(form)
Esempio n. 53
0
File: views.py Progetto: voszp/wger
 def pre_save(self, obj):
     '''
     Set the owner
     '''
     obj.user = self.request.user
     obj.language = load_language()
Esempio n. 54
0
 def items(self):
     return (Exercise.objects.filter(category__language=load_language())
                             .filter(status__in=Exercise.EXERCISE_STATUS_OK))