Форум сайта python.su
Мне была поставлена задача в создании простого форума на Django.
Так, как я только начал изучать Питон, то самостоятельно написать с нуля было сложно.
Нашел готовый пример: http://www.lightbird.net/dbe/forum1.html
но с подключением тоже оказалось кучу проблем.
В результате долгих мучений практически все заработало (регистрация, активация) вот только проблема с авторизацией.
Я выкладываю содержимое важных файлов, а остальное можно посмотреть по вышеуказанной ссылке.
settings.py
# Django settings for dbe project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Name', 'mysite@yandex.ru'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'postgres', # Or path to database file if using sqlite3.
'USER': 'postgres', # Not used with sqlite3.
'PASSWORD': 'password', # Not used with sqlite3.
'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '5432', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'zc%wenyj-bdpambck8bl26r#0f@1re--j2qqjm*u0kj15gkph4'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'dbe.urls'
TEMPLATE_DIRS = ( 'C:/goo/dbe/templates/forum',
'C:/goo/dbe/templates/registration'
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
ACCOUNT_ACTIVATION_DAYS = 2
AUTH_USER_EMAIL_UNIQUE = True
EMAIL_HOST = 'smtp.mail.ru'
EMAIL_PORT = 2525
EMAIL_HOST_USER = 'myaccount@mail.ru'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_USE_TLS = False
DEFAULT_FROM_EMAIL = 'myaccount@mail.ru'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.messages',
'django.contrib.staticfiles',
'dbe.forum',
'registration'
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
from django.conf.urls.defaults import patterns, include, url
from forum.views import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'dbe.views.home', name='home'),
url(r'^list/', main),
#url(r'^forum/(?P<pk>\d+)', forum),
url(r'^forum/', forum),
url(r'^thread/', thread),
url(r'^profile/', profile),
url(r'^post/', post),
#url(r'^register/$', 'registration.views.register', {'form': RegistrationFormUniqueEmail}, name='registration_register'),
# url('', include('registration.urls')),
url(r'^accounts/', include('registration.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
Отредактировано (Апрель 13, 2011 00:10:25)
Офлайн
1. Чему вы удивляетесь? Существует /profile/ (не забывайте кстати завершающие слэши), а вы после регистрации посылаете на /accounts/profile/. Если не хотите изменять стандартные настойки, то измените:
url(r'^profile/', profile),
url(r'^/accounts/profile/', profile),
url(r'^forum/(?P<pk>\d+)/', forum),
def forum(request, pk):
....
url(r'^forum/', forum),
def forum(request):
....
Офлайн
LoggosЕсли для регистрации используется стандартный модуль django.contrib.auth (похоже, так оно и есть), то редирект на /accounts/profile/ – это поведение по умолчанию. Адрес можно переопределить, задав значение settings.LOGIN_REDIRECT_URL
Сейчас 2 проблемы:
1.После того, как пытаюсь авторизоваться переадресация идет на http://127.0.0.1:8000/accounts/profile где выдает ошибку Page not found (404), хотя страница 127.0.0.1/profile существует….я не до конца наверное еще разобрался.
Офлайн
fthСделал, что Вы посоветовали…но ничего. все та же ошибка 404.
1. Чему вы удивляетесь? Существует /profile/ (не забывайте кстати завершающие слэши), а вы после регистрации посылаете на /accounts/profile/. Если не хотите изменять стандартные настойки, то измените:наurl(r'^profile/', profile),url(r'^/accounts/profile/', profile),
fthДумаю, что нужно использовать первый вариант.
2. Что такое pk? Номер треда? Как вы его собираетесь передавать? Через url или через GET-запрос? (На будущее, лучше использовать более “говорящие” названия)
В первом случае, в urls.py надо:Т.е. вы передаёте номер в самой ссылке.url(r'^forum/(?P<pk>\d+)/', forum),
И уже во вьюхе:def forum(request, pk):
....
class ProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ["posts", "user"]
def mk_paginator(request, items, num_items):
"""Create and return a paginator."""
paginator = Paginator(items, num_items)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
items = paginator.page(page)
except (InvalidPage, EmptyPage):
items = paginator.page(paginator.num_pages)
return items
def main(request):
"""Main listing."""
forums = Forum.objects.all()
return render_to_response("list.html", dict(forums=forums, user=request.user))
def forum(request, pk):
"""Listing of threads in a forum."""
threads = Thread.objects.filter(forum=pk).order_by("-created")
threads = mk_paginator(request, threads, 20)
return render_to_response("forum.html", add_csrf(request, threads=threads, pk=pk))
def thread(request, pk):
"""Listing of posts in a thread."""
posts = Post.objects.filter(thread=pk).order_by("created")
posts = mk_paginator(request, posts, 15)
t = Thread.objects.get(pk=pk)
return render_to_response("thread.html", add_csrf(request, posts=posts, pk=pk, title=t.title,
forum_pk=t.forum.pk, media_url=MEDIA_URL))
@login_required
def profile(request, pk):
"""Edit user profile."""
profile = UserProfile.objects.get(user=pk)
img = None
if request.method == "POST":
pf = ProfileForm(request.POST, request.FILES, instance=profile)
if pf.is_valid():
pf.save()
# resize and save image under same filename
imfn = pjoin(MEDIA_ROOT, profile.avatar.name)
im = PImage.open(imfn)
im.thumbnail((160,160), PImage.ANTIALIAS)
im.save(imfn, "JPEG")
else:
pf = ProfileForm(instance=profile)
if profile.avatar:
img = "/media/" + profile.avatar.name
return render_to_response("profile.html", add_csrf(request, pf=pf, img=img))
@login_required
def post(request, ptype, pk):
"""Display a post form."""
action = reverse("dbe.forum.views.%s" % ptype, args=[pk])
if ptype == "new_thread":
title = "Start New Topic"
subject = ''
elif ptype == "reply":
title = "Reply"
subject = "Re: " + Thread.objects.get(pk=pk).title
return render_to_response("post.html", add_csrf(request, subject=subject, action=action,
title=title))
def increment_post_counter(request):
profile = request.user.userprofile_set.all()[0]
profile.posts += 1
profile.save()
@login_required
def new_thread(request, pk):
"""Start a new thread."""
p = request.POST
if p["subject"] and p["body"]:
forum = Forum.objects.get(pk=pk)
thread = Thread.objects.create(forum=forum, title=p["subject"], creator=request.user)
Post.objects.create(thread=thread, title=p["subject"], body=p["body"], creator=request.user)
increment_post_counter(request)
return HttpResponseRedirect(reverse("dbe.forum.views.forum", args=[pk]))
@login_required
def reply(request, pk):
"""Reply to a thread."""
p = request.POST
if p["body"]:
thread = Thread.objects.get(pk=pk)
post = Post.objects.create(thread=thread, title=p["subject"], body=p["body"], creator=request.user)
increment_post_counter(request)
return HttpResponseRedirect(reverse("dbe.forum.views.thread", args=[pk]) + "?page=last")
def add_csrf(request, **kwargs):
"""Add CSRF to dictionary."""
d = dict(user=request.user, **kwargs)
d.update(csrf(request))
return d
from django.conf.urls.defaults import patterns, include, url
from forum.views import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'dbe.views.home', name='home'),
url(r'^/list/', main),
url(r'^forum/(?P<pk>\d+)/', forum),
url(r'^thread/', thread),
url(r'^/accounts/profile/', profile),
url(r'^post/', post),
#url(r'^register/$', 'registration.views.register', {'form': RegistrationFormUniqueEmail}, name='registration_register'),
# url('', include('registration.urls')),
url(r'^accounts/', include('registration.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
#url(r'^admin/', include(admin.site.urls)),
)
<body>
<div id="sidebar"> {% block sidebar %} {% endblock %} </div>
<div id="container">
<div id="menu">
{% block nav-global %}
<!-- MENU -->
<h3><a href="{% url forum.views.main %}">ForumApp</a></h3>
{% if user.is_staff %} <a href="{% url admin:index %}">Admin</a> {% endif %}
{% if user.is_authenticated %}
<a href="{% url forum.views.profile user.pk %}">Edit profile</a> {% endif %} // строка с указанной ошибкой
{% if not user.is_authenticated %}<a href="/accounts/login/?next=/forum/">login</a> | <a
href="/accounts/register/">register</a>{% endif %}
{% if user.is_authenticated %}<a href="/accounts/logout/?next=/forum/">logout</a>
{% endif %}
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</div>
Отредактировано (Апрель 13, 2011 16:14:06)
Офлайн
LoggosНужно в ваш settings.py добавить выше указанную переменную
Я использую стандартную django-registration, полагаю изменять стандартные настройки нужно именно в самом модуле registration?
Офлайн
ChernА можно немного конкретнее о переменной. что именно?LoggosНужно в ваш settings.py добавить выше указанную переменную
Я использую стандартную django-registration, полагаю изменять стандартные настройки нужно именно в самом модуле registration?
Офлайн
Loggosв settings.py необходимо добавить строчку: LOGIN_REDIRECT_URL = ‘адрес куда должны попадать пользователи после аутентификации’
А можно немного конкретнее о переменной. что именно?
Офлайн
fthПервую проблему было решено - необходимо было убрать просто лишний слеш.
1. Чему вы удивляетесь? Существует /profile/ (не забывайте кстати завершающие слэши), а вы после регистрации посылаете на /accounts/profile/. Если не хотите изменять стандартные настойки, то измените:наurl(r'^profile/', profile),url(r'^/accounts/profile/', profile),
rl(r'^accounts/profile/', profile)
from django.conf.urls.defaults import patterns, include, url
from forum.views import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'dbe.views.home', name='home'),
url(r'^list/', main),
url(r'^forum/(?P<pk>\d+)/', forum),
url(r'^thread/', thread),
url(r'^accounts/profile/', profile),
url(r'^post/', post),
#url(r'^register/$', 'registration.views.register', {'form': RegistrationFormUniqueEmail}, name='registration_register'),
# url('', include('registration.urls')),
url(r'^accounts/', include('registration.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
#url(r'^admin/', include(admin.site.urls)),
)
Офлайн
Loggos
Выделите наконец вечер и ознакомьтесь, хотя бы вот с этим http://djbook.ru/ch03.html
Отвечать на каждую ошибку возникающую из-за незнания основ является не особенно продуктивным занятием…
P.S.: На будущее в привязке url лучше указывайте имя представления напрямую, т.е. например url(r'^forum/(?P<pk>\d+)/', forum, name='forum') и уже в шаблоне пишите {% url forum pk %}
P.P.S.: Для аккаунтов укажите pk по аналогии с форумом.
Отредактировано (Апрель 13, 2011 21:47:12)
Офлайн