django 4.0支持

develop
liangliangyy 4 years ago
commit 2700581078

@ -26,7 +26,7 @@ jobs:
strategy:
max-parallel: 4
matrix:
python-version: [ 3.7, 3.8, 3.9 ,3.10 ]
python-version: [ 3.8, 3.9 ]
steps:
- name: Start MySQL
@ -65,7 +65,7 @@ jobs:
strategy:
max-parallel: 4
matrix:
python-version: [ 3.7, 3.8, 3.9,3.10 ]
python-version: [ 3.8, 3.9 ]
steps:
- name: Start MySQL

@ -35,6 +35,10 @@ class RegisterView(FormView):
form_class = RegisterForm
template_name = 'account/registration_form.html'
@method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
return super(RegisterView, self).dispatch(*args, **kwargs)
def form_valid(self, form):
if form.is_valid():
user = form.save(False)
@ -149,8 +153,8 @@ def account_result(request):
if type and type in ['register', 'validation']:
if type == 'register':
content = '''
恭喜您注册成功一封验证邮件已经发送到您 {email} 的邮箱请验证您的邮箱后登录本站
'''.format(email=user.email)
恭喜您注册成功一封验证邮件已经发送到您的邮箱请验证您的邮箱后登录本站
'''
title = '注册成功'
else:
c_sign = get_sha256(get_sha256(settings.SECRET_KEY + str(user.id)))

@ -53,7 +53,7 @@ def custom_markdown(content):
def get_markdown_toc(content):
from djangoblog.utils import CommonMarkdown
body, toc = CommonMarkdown.get_markdown_with_toc(content)
return mark_safe(toc), mark_safe(body)
return mark_safe(toc)
@register.filter(is_safe=True)

@ -8,11 +8,11 @@ from django.test import Client, RequestFactory, TestCase
from django.urls import reverse
from django.utils import timezone
from djangoblog.utils import get_current_site, get_sha256
from accounts.models import BlogUser
from blog.forms import BlogSearchForm
from blog.models import Article, Category, Tag, SideBar, Links
from blog.templatetags.blog_tags import load_pagination_info, load_articletags
from djangoblog.utils import get_current_site, get_sha256
# Create your tests here.
@ -98,12 +98,7 @@ class ArticleTest(TestCase):
s = load_articletags(article)
self.assertIsNotNone(s)
rsp = self.client.get('/refresh')
self.assertEqual(rsp.status_code, 302)
self.client.login(username='liangliangyy', password='liangliangyy')
rsp = self.client.get('/refresh')
self.assertEqual(rsp.status_code, 200)
response = self.client.get(reverse('blog:archives'))
self.assertEqual(response.status_code, 200)
@ -140,9 +135,6 @@ class ArticleTest(TestCase):
response = self.client.get('/links.html')
self.assertEqual(response.status_code, 200)
rsp = self.client.get('/refresh')
self.assertEqual(rsp.status_code, 200)
response = self.client.get('/feed/')
self.assertEqual(response.status_code, 200)

@ -55,7 +55,4 @@ urlpatterns = [
r'upload',
views.fileupload,
name='upload'),
path(
r'refresh',
views.refresh_memcache,
name='refresh')]
]

@ -4,9 +4,7 @@ import logging
import os
import uuid
from django import forms
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.shortcuts import render
@ -118,17 +116,7 @@ class ArticleDetailView(DetailView):
return obj
def get_context_data(self, **kwargs):
articleid = int(self.kwargs[self.pk_url_kwarg])
comment_form = CommentForm()
user = self.request.user
# 如果用户已经登录,则隐藏邮件和用户名输入框
if user.is_authenticated and not user.is_anonymous and user.email and user.username:
comment_form.fields.update({
'email': forms.CharField(widget=forms.HiddenInput()),
'name': forms.CharField(widget=forms.HiddenInput()),
})
comment_form.fields["email"].initial = user.email
comment_form.fields["name"].initial = user.username
article_comments = self.object.comment_list()
@ -313,22 +301,6 @@ def fileupload(request):
return HttpResponse("only for post")
@login_required
def refresh_memcache(request):
try:
if request.user.is_superuser:
from djangoblog.utils import cache
if cache and cache is not None:
cache.clear()
return HttpResponse("ok")
else:
return HttpResponseForbidden()
except Exception as e:
logger.error(e)
return HttpResponse("error")
def page_not_found_view(
request,
exception,

@ -5,16 +5,6 @@ from .models import Comment
class CommentForm(ModelForm):
url = forms.URLField(label='网址', required=False)
email = forms.EmailField(label='电子邮箱', required=True)
name = forms.CharField(
label='姓名',
widget=forms.TextInput(
attrs={
'value': "",
'size': "30",
'maxlength': "245",
'aria-required': 'true'}))
parent_comment_id = forms.IntegerField(
widget=forms.HiddenInput, required=False)

@ -41,34 +41,32 @@ class CommentsTest(TestCase):
article.status = 'p'
article.save()
commenturl = reverse(
comment_url = reverse(
'comments:postcomment', kwargs={
'article_id': article.id})
response = self.client.post(commenturl,
response = self.client.post(comment_url,
{
'body': '123ffffffffff'
})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.status_code, 302)
article = Article.objects.get(pk=article.pk)
self.assertEqual(len(article.comment_list()), 0)
self.assertEqual(len(article.comment_list()), 1)
response = self.client.post(commenturl,
response = self.client.post(comment_url,
{
'body': '123ffffffffff',
'email': user.email,
'name': user.username
})
self.assertEqual(response.status_code, 302)
article = Article.objects.get(pk=article.pk)
self.assertEqual(len(article.comment_list()), 1)
self.assertEqual(len(article.comment_list()), 2)
parent_comment_id = article.comment_list()[0].id
response = self.client.post(commenturl,
response = self.client.post(comment_url,
{
'body': '''
# Title1
@ -83,15 +81,13 @@ class CommentsTest(TestCase):
''',
'email': user.email,
'name': user.username,
'parent_comment_id': parent_comment_id
})
self.assertEqual(response.status_code, 302)
article = Article.objects.get(pk=article.pk)
self.assertEqual(len(article.comment_list()), 2)
self.assertEqual(len(article.comment_list()), 3)
comment = Comment.objects.get(id=parent_comment_id)
tree = parse_commenttree(article.comment_list(), comment)
self.assertEqual(len(tree), 1)

@ -4,7 +4,6 @@ from . import views
app_name = "comments"
urlpatterns = [
# url(r'^po456stcomment/(?P<article_id>\d+)$', views.CommentPostView.as_view(), name='postcomment'),
path(
'article/<int:article_id>/postcomment',
views.CommentPostView.as_view(),

@ -1,7 +1,8 @@
# Create your views here.
from django import forms
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.views.generic.edit import FormView
from blog.models import Article
@ -13,6 +14,10 @@ class CommentPostView(FormView):
form_class = CommentForm
template_name = 'blog/article_detail.html'
@method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
return super(CommentPostView, self).dispatch(*args, **kwargs)
def get(self, request, *args, **kwargs):
article_id = self.kwargs['article_id']
@ -23,16 +28,6 @@ class CommentPostView(FormView):
def form_invalid(self, form):
article_id = self.kwargs['article_id']
article = Article.objects.get(pk=article_id)
u = self.request.user
if self.request.user.is_authenticated:
form.fields.update({
'email': forms.CharField(widget=forms.HiddenInput()),
'name': forms.CharField(widget=forms.HiddenInput()),
})
user = self.request.user
form.fields["email"].initial = user.email
form.fields["name"].initial = user.username
return self.render_to_response({
'form': form,
@ -45,13 +40,9 @@ class CommentPostView(FormView):
article_id = self.kwargs['article_id']
article = Article.objects.get(pk=article_id)
if not self.request.user.is_authenticated:
email = form.cleaned_data['email']
username = form.cleaned_data['name']
user = get_user_model().objects.get_or_create(
username=username, email=email)[0]
# auth.login(self.request, user)
if article.comment_status == 'c' or article.status == 'c':
raise ValidationError("该文章评论已关闭.")
comment = form.save(False)
comment.article = article

@ -13,7 +13,7 @@ import six
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.datetime_safe import datetime
from django.utils.encoding import force_text
from django.utils.encoding import force_str
from haystack.backends import BaseEngine, BaseSearchBackend, BaseSearchQuery, EmptyResults, log_query
from haystack.constants import DJANGO_CT, DJANGO_ID, ID
from haystack.exceptions import MissingDependency, SearchBackendError, SkipDocument
@ -376,7 +376,7 @@ class WhooshSearchBackend(BaseSearchBackend):
'hits': 0,
}
query_string = force_text(query_string)
query_string = force_str(query_string)
# A one-character query (non-wildcard) gets nabbed by a stopwords
# filter and should yield zero results.
@ -467,7 +467,7 @@ class WhooshSearchBackend(BaseSearchBackend):
for nq in narrow_queries:
recent_narrowed_results = narrow_searcher.search(
self.parser.parse(force_text(nq)), limit=None)
self.parser.parse(force_str(nq)), limit=None)
if len(recent_narrowed_results) <= 0:
return {
@ -614,7 +614,7 @@ class WhooshSearchBackend(BaseSearchBackend):
for nq in narrow_queries:
recent_narrowed_results = narrow_searcher.search(
self.parser.parse(force_text(nq)), limit=None)
self.parser.parse(force_str(nq)), limit=None)
if len(recent_narrowed_results) <= 0:
return {
@ -771,7 +771,7 @@ class WhooshSearchBackend(BaseSearchBackend):
spelling_suggestion = None
reader = self.index.reader()
corrector = reader.corrector(self.content_field_name)
cleaned_query = force_text(query_string)
cleaned_query = force_str(query_string)
if not query_string:
return spelling_suggestion
@ -811,12 +811,12 @@ class WhooshSearchBackend(BaseSearchBackend):
else:
value = 'false'
elif isinstance(value, (list, tuple)):
value = u','.join([force_text(v) for v in value])
value = u','.join([force_str(v) for v in value])
elif isinstance(value, (six.integer_types, float)):
# Leave it alone.
pass
else:
value = force_text(value)
value = force_str(value)
return value
def _to_python(self, value):
@ -873,9 +873,9 @@ class WhooshSearchBackend(BaseSearchBackend):
class WhooshSearchQuery(BaseSearchQuery):
def _convert_datetime(self, date):
if hasattr(date, 'hour'):
return force_text(date.strftime('%Y%m%d%H%M%S'))
return force_str(date.strftime('%Y%m%d%H%M%S'))
else:
return force_text(date.strftime('%Y%m%d000000'))
return force_str(date.strftime('%Y%m%d000000'))
def clean(self, query_fragment):
"""

@ -10,7 +10,7 @@ elasticsearch==7.16.1
elasticsearch-dsl==7.4.0
gevent==21.12.0
jieba==0.42.1
jsonpickle==2.0.0
jsonpickle==2.1.0
Markdown==3.3.6
mysqlclient==2.1.0
Pillow==9.0.1
@ -18,10 +18,11 @@ Pygments==2.11.2
python-logstash==0.4.6
python-memcached==1.59
python-slugify==6.1.1
pytz==2021.3
pytz==2022.1
raven==6.10.0
requests==2.26.0
urllib3==1.26.7
requests==2.27.1
urllib3==1.26.9
WeRoBot==1.13.1
Whoosh==2.7.4
user-agents==2.2.0
redis==4.1.4

@ -51,16 +51,16 @@
<p class='read-more'><a
href=' {{ article.get_absolute_url }}'>Read more</a></p>
{% else %}
{% get_markdown_toc article.body as markdown %}
{% if article.show_toc %}
{% if article.show_toc %}
{% get_markdown_toc article.body as toc %}
<b>目录:</b>
{{ markdown.0|safe }}
{{ toc|safe }}
<hr class="break_line"/>
{% endif %}
<div class="article">
{{ markdown.1|safe }}
{{ article.body|custom_markdown|escape }}
</div>
{% endif %}

@ -126,7 +126,6 @@
<li><a href="{% url "account:login" %}" rel="nofollow">登录</a></li>
{% endif %}
{% if user.is_superuser %}
<li><a href="{% url "blog:refresh" %}" target="_blank">刷新缓存</a></li>
<li><a href="{% url 'owntracks:show_dates' %}" target="_blank">运动轨迹记录</a></li>
{% endif %}
<li><a href="http://gitbook.lylinux.net" target="_blank" rel="nofollow">GitBook</a></li>

@ -13,19 +13,6 @@
{{ form.body }}
{{ form.body.errors }}
</p>
<p class="comment-form-author">
{% if not form.name.is_hidden %}
{{ form.name.label_tag }}
{% endif %}
{{ form.name }}
{{ form.name.errors }}
<p class="comment-form-email">
{% if not form.email.is_hidden %}
{{ form.email.label_tag }}
{% endif %}
{{ form.email }}
{{ form.email.errors }}
</p>
{{ form.parent_comment_id }}
<div class="form-submit">
<span class="comment-markdown"> 支持markdown</span>

Loading…
Cancel
Save