修复评论若干bug及界面显示错误

sh_branch
车亮亮 9 years ago
parent af16e083c9
commit a99446fcac

@ -51,9 +51,9 @@ MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.gzip.GZipMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
# 'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
# 'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
@ -144,6 +144,8 @@ HAYSTACK_CONNECTIONS = {
}
# 自动更新搜索索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
#允许使用用户名或密码登录
AUTHENTICATION_BACKENDS = ['accounts.user_login_backend.EmailOrUsernameModelBackend']
STATIC_ROOT = os.path.join(SITE_ROOT, 'collectedstatic')
@ -157,7 +159,7 @@ TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DATE_TIME_FORMAT = '%Y-%m-%d'
SITE_NAME = '且听风吟'
SITE_URL = 'http://blog.lylinux.org'
SITE_URL = 'http://www.lylinux.net'
SITE_DESCRIPTION = '大巧无工,重剑无锋.'
SITE_SEO_DESCRIPTION = '小站主要用来分享和记录学习经验,教程,记录个人生活的点滴以及一些随笔.欢迎大家访问小站'
SITE_SEO_KEYWORDS = 'linux,apache,mysql,服务器,ubuntu,shell,web,csharp,.net,asp,mac,swift'
@ -196,7 +198,7 @@ OAHUTH = {
'sina': {
'appkey': '3161614143',
'appsecret': 'ee17c099317f872eeddb25204ea46721',
'callbackurl': 'http://blog.lylinux.org/oauth/weibo'
'callbackurl': 'http://www.lylinux.net/oauth/weibo'
},
'google': {
'appkey': os.environ.get('GOOGLE_APP_KEY'),

@ -23,12 +23,14 @@ import logging
logger = logging.getLogger('djangoblog')
def cache_decorator(expiration=3 * 60):
def cache_decorator(expiration=3 * 60, cache_key=None):
def wrapper(func):
def news(*args, **kwargs):
unique_str = repr((func, args, kwargs))
m = md5(unique_str.encode('utf-8'))
key = m.hexdigest()
key = cache_key
if not key:
unique_str = repr((func, args, kwargs))
m = md5(unique_str.encode('utf-8'))
key = m.hexdigest()
value = cache.get(key)
if value:
logger.info('cache_decorator get cache %s' % func.__name__)

@ -21,18 +21,18 @@ from django.contrib.auth import get_user_model
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.fields['username'].widget = widgets.TextInput(attrs={'placeholder': "用户名", "class": "form-control"})
self.fields['password'].widget = widgets.PasswordInput(attrs={'placeholder': "密码", "class": "form-control"})
self.fields['username'].widget = widgets.TextInput(attrs={'placeholder': "username", "class": "form-control"})
self.fields['password'].widget = widgets.PasswordInput(attrs={'placeholder': "password", "class": "form-control"})
class RegisterForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget = widgets.TextInput(attrs={'placeholder': "用户名", "class": "form-control"})
self.fields['email'].widget = widgets.EmailInput(attrs={'placeholder': "邮箱", "class": "form-control"})
self.fields['password1'].widget = widgets.PasswordInput(attrs={'placeholder': "密码", "class": "form-control"})
self.fields['password2'].widget = widgets.PasswordInput(attrs={'placeholder': "确认密码", "class": "form-control"})
self.fields['username'].widget = widgets.TextInput(attrs={'placeholder': "username", "class": "form-control"})
self.fields['email'].widget = widgets.EmailInput(attrs={'placeholder': "email", "class": "form-control"})
self.fields['password1'].widget = widgets.PasswordInput(attrs={'placeholder': "password", "class": "form-control"})
self.fields['password2'].widget = widgets.PasswordInput(attrs={'placeholder': "repeat password", "class": "form-control"})
class Meta:
model = get_user_model()

@ -0,0 +1,39 @@
#!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: liangliangyy
@license: MIT Licence
@contact: liangliangyy@gmail.com
@site: https://www.lylinux.org/
@software: PyCharm
@file: user_login_backend.py
@time: 2017/2/17 下午8:45
"""
from django.conf import settings
from django.contrib.auth import get_user_model
class EmailOrUsernameModelBackend(object):
"""
允许使用用户名或邮箱登录
"""
def authenticate(self, username=None, password=None):
if '@' in username:
kwargs = {'email': username}
else:
kwargs = {'username': username}
try:
user = get_user_model().objects.get(**kwargs)
if user.check_password(password):
return user
except get_user_model().DoesNotExist:
return None
def get_user(self, username):
try:
return get_user_model().objects.get(pk=username)
except get_user_model().DoesNotExist:
return None

@ -12,6 +12,7 @@ from django.contrib import auth
from django.views.decorators.cache import never_cache
from django.shortcuts import redirect
# Create your views here.
class RegisterView(FormView):
@ -20,9 +21,10 @@ class RegisterView(FormView):
def form_valid(self, form):
user = form.save(False)
user.save(True)
return HttpResponseRedirect('/')
url = reverse('accounts:login')
return HttpResponseRedirect(url)
@never_cache
def LogOut(requests):

@ -0,0 +1,24 @@
#!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: liangliangyy
@license: MIT Licence
@contact: liangliangyy@gmail.com
@site: https://www.lylinux.org/
@software: PyCharm
@file: clear_cache.py
@time: 2017/2/17 下午10:30
"""
from DjangoBlog.utils import cache
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'clear the whole cache'
def handle(self, *args, **options):
cache.clear()
self.stdout.write(self.style.SUCCESS('Cleared cache\n'))

@ -24,7 +24,7 @@ urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^page/(?P<page>\d+)$', views.IndexView.as_view(), name='index_page'),
url(r'^article/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/(?P<article_id>\d+)-(?P<slug>\S+).html$',
views.ArticleDetailView.as_view(),
cache_page(60 * 60 * 10)(views.ArticleDetailView.as_view()),
name='detail'),
url(r'^blogpage/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/(?P<page_id>\d+)-(?P<slug>\S+).html$',
views.ArticleDetailView.as_view(),

@ -21,6 +21,7 @@ import datetime
from django.views.decorators.csrf import csrf_exempt
import os
from django.contrib.auth.decorators import login_required
from DjangoBlog.utils import cache, cache_decorator
"""
class SeoProcessor():
@ -79,7 +80,7 @@ class ArticleDetailView(DetailView):
def get_context_data(self, **kwargs):
articleid = int(self.kwargs[self.pk_url_kwarg])
print(str(articleid) + "get_context_data")
comment_form = CommentForm()
u = self.request.user
@ -91,6 +92,7 @@ class ArticleDetailView(DetailView):
user = self.request.user
comment_form.fields["email"].initial = user.email
comment_form.fields["name"].initial = user.username
key = "article_comment_{}".format(articleid)
article_comments = self.object.comment_set.all()
@ -222,9 +224,11 @@ def fileupload(request):
@login_required
def refresh_memcache(request):
try:
if request.user.is_superuser:
result = os.popen(' service memcached restart ').readline()
return HttpResponse(result)
from DjangoBlog.utils import cache
cache.clear()
return HttpResponse("ok")
else:
from django.http import HttpResponseForbidden
return HttpResponseForbidden()

@ -5,6 +5,7 @@ from blog.models import Article
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.models import Site
import _thread
from DjangoBlog.utils import cache
# Create your models here.
@ -26,7 +27,10 @@ class Comment(models.Model):
verbose_name_plural = verbose_name
def send_comment_email(self, msg):
msg.send()
try:
msg.send()
except:
pass
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
@ -47,6 +51,7 @@ class Comment(models.Model):
msg = EmailMultiAlternatives(subject, html_content, from_email='no-reply@lylinux.net', to=[tomail])
msg.content_subtype = "html"
_thread.start_new_thread(self.send_comment_email, (msg,))
if self.parent_comment:
@ -59,7 +64,8 @@ class Comment(models.Model):
tomail = self.parent_comment.author.email
msg = EmailMultiAlternatives(subject, html_content, from_email='no-reply@lylinux.net', to=[tomail])
msg.content_subtype = "html"
_thread.start_new_thread(self.send_comment_email, (msg,))
def __str__(self):
return self.body
def __str__(self):
return self.body

@ -9,6 +9,7 @@ from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django import forms
from django.contrib import auth
class CommentPostView(FormView):
@ -17,7 +18,9 @@ class CommentPostView(FormView):
def get(self, request, *args, **kwargs):
article_id = self.kwargs['article_id']
url = reverse('blog:detail', kwargs={'article_id': article_id})
article = Article.objects.get(pk=article_id)
url = article.get_absolute_url()
return HttpResponseRedirect(url + "#comments")
def form_invalid(self, form):
@ -49,20 +52,17 @@ class CommentPostView(FormView):
email = form.cleaned_data['email']
username = form.cleaned_data['name']
user = get_user_model().objects.create_user(username=username, email=email, password=None,
nikename=username)
author_id = user.pk
user = get_user_model().objects.get_or_create(username=username, email=email)[0]
# auth.login(self.request, user)
comment = form.save(False)
comment.article = article
comment.author = get_user_model().objects.get(pk=author_id)
comment.author = user
if form.cleaned_data['parent_comment_id']:
parent_comment = Comment.objects.get(pk=form.cleaned_data['parent_comment_id'])
comment.parent_comment = parent_comment
comment.save(True)
# return HttpResponseRedirect(article.get_absolute_url() + "#div-comment-" + comment.pk)
return HttpResponseRedirect("%s#div-comment-%d" % (article.get_absolute_url(), comment.pk))

@ -23,7 +23,7 @@
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<div class="checkbox">
<a class="pull-right">Need help?</a>
{% comment %}<a class="pull-right">Need help?</a>{% endcomment %}
<label>
<input type="checkbox" value="remember-me"> Stay signed in
</label>
@ -33,7 +33,8 @@
</div>
<p class="text-center">
<a href="{% url "account:register" %}">Create an account</a>
<a href="{% url "account:register" %}">Create Account</a>
|
<a href="/">Home Page</a>
</p>

@ -3,7 +3,7 @@
{% block content %}
<div class="container">
<h2 class="form-signin-heading text-center">Sign in with your Account</h2>
<h2 class="form-signin-heading text-center">Create Your Account</h2>
<div class="card card-signin">
<img class="img-circle profile-img" src="{% static 'blog/img/avatar.png' %}" alt="">
@ -20,7 +20,7 @@
{% endfor %}
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<button class="btn btn-lg btn-primary btn-block" type="submit">Create Your Account</button>
{% comment %}
<div class="checkbox">
@ -34,7 +34,7 @@
</div>
<p class="text-center">
<a href="{% url "account:login" %}">LogIn</a>
<a href="{% url "account:login" %}">Sign In</a>
</p>
</div> <!-- /container -->

@ -85,7 +85,7 @@
</li>
{% else %}
<li><a href="{% url "account:login" %}"></a>
<li><a href="{% url "account:login" %}"></a>
{% endif %}
</ul>

@ -65,9 +65,8 @@
{% block content %}
{% endblock %}
{% cache 36000 sidebar %}
{% cache 36000 sidebar request.user.username %}
{% block sidebar %}
{% endblock %}
{% endcache %}
</div><!-- #main .wrapper -->

Loading…
Cancel
Save