Django новичок на работе, и я мог бы использовать некоторые указатели. Я использую django-профиль и работаю на моей странице профиля, которая обрабатывается view.profile_detail. Проблема, с которой я столкнулась, заключается в том, что я не могу добавить другую переменную в свой шаблон, используя этот вид. Вот мой взгляд функция:django-profile, передающий переменные в шаблон
def profile_detail(request, username, public_profile_field=None,
template_name='profiles/profile_detail.html',
extra_context=None):
"""
Detail view of a user's profile.
If no profile model has been specified in the
``AUTH_PROFILE_MODULE`` setting,
``django.contrib.auth.models.SiteProfileNotAvailable`` will be
raised.
If the user has not yet created a profile, ``Http404`` will be
raised.
**Required arguments:**
``username``
The username of the user whose profile is being displayed.
**Optional arguments:**
``extra_context``
A dictionary of variables to add to the template context. Any
callable object in this dictionary will be called to produce
the end result which appears in the context.
``public_profile_field``
The name of a ``BooleanField`` on the profile model; if the
value of that field on the user's profile is ``False``, the
``profile`` variable in the template will be ``None``. Use
this feature to allow users to mark their profiles as not
being publicly viewable.
If this argument is not specified, it will be assumed that all
users' profiles are publicly viewable.
``template_name``
The name of the template to use for displaying the profile. If
not specified, this will default to
:template:`profiles/profile_detail.html`.
**Context:**
``profile``
The user's profile, or ``None`` if the user's profile is not
publicly viewable (see the description of
``public_profile_field`` above).
**Template:**
``template_name`` keyword argument or
:template:`profiles/profile_detail.html`.
"""
user = get_object_or_404(User, username=username)
# accuracy = ''
try:
profile_obj = user.get_profile()
accuracy = str(profile_obj.number_of_answers/profile_obj.number_of_answers) + '%'
except ObjectDoesNotExist:
raise Http404
if public_profile_field is not None and \
not getattr(profile_obj, public_profile_field):
profile_obj = None
if extra_context is None:
# extra_context = {'accuracy': potato}
extra_context = {}
context = RequestContext(request)
# context['accuracy'] = 'potato'
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{'profile': profile_obj},
# { 'profile': profile_obj, 'accuracy': accuracy},
# locals(),
context_instance=context)
и вот мой шаблон:
{% extends "base.html" %}
{% load i18n %}
{% block content %}
<p><strong>Level:</strong><br>{{ profile.level }}</p>
<p><strong>Bounty Points:</strong><br>{{ profile.total_bounty_points }}</p>
<p><strong>Number of questions:</strong><br>{{ profile.number_of_questions_asked }}</p>
<p><strong>Number of replies:</strong><br>{{ profile.number_of_replies }}</p>
<p><strong>Number of answers:</strong><br>{{ profile.number_of_answers }}</p>
<p><strong>Accuracy:</strong><br>{{ accuracy }}</p>
<p><strong>Number of times reported:</strong><br>{{ profile.reported_by_others }}</p>
{% endblock %}
Могу ли я узнать, где профиль значение передается от? Это из словаря {'profile': profile_obj} или это из контекста? Я пробовал комментировать оба, но шаблон все равно отлично.
Я также попытался создать новую переменную, называемую точностью в моем шаблоне, но я не могу ее отобразить, и шаблон просто терпит неудачу. Затем я добавил TEMPLATE_STRING_IF_INVALID = '% s' в файл настроек, который позволил мне увидеть, что переменная точности не найдена. Могу я узнать, что я сделал неправильно?
Любой совет будет рад! Спасибо :)
Я не уверен, что вы просите. Если это представление из стороннего приложения, вы не должны его модифицировать самостоятельно - вся аргумента 'extra_context' заключается в том, что вы можете передать дополнительные значения из urlconf, то есть как вы передадите любые' Точность' должна быть. –
@ DanielRoseman Спасибо за комментарий, и я полностью понимаю, что вы имеете в виду :) Я пробовал этот url (r '^ (? P \ w +)/$', views.profile_detail, extra_context = {'precision': 'potato' }, name = 'profiles_profile_detail'), означает ли это, что я должен иметь возможность использовать переменную {{precision}} напрямую, потому что она, похоже, не работает. Еще раз спасибо! –
nightscent