Skip to content

Commit

Permalink
django 4.0支持
Browse files Browse the repository at this point in the history
  • Loading branch information
liangliangyy committed Mar 23, 2022
2 parents 534c42f + f4d7f9e commit 2700581
Show file tree
Hide file tree
Showing 15 changed files with 46 additions and 118 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/django.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions accounts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)))
Expand Down
2 changes: 1 addition & 1 deletion blog/templatetags/blog_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 1 addition & 9 deletions blog/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
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.
Expand Down Expand Up @@ -98,12 +98,7 @@ def test_validate_article(self):
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)
Expand Down Expand Up @@ -140,9 +135,6 @@ def test_validate_article(self):
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)

Expand Down
5 changes: 1 addition & 4 deletions blog/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,4 @@
r'upload',
views.fileupload,
name='upload'),
path(
r'refresh',
views.refresh_memcache,
name='refresh')]
]
28 changes: 0 additions & 28 deletions blog/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
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
Expand Down Expand Up @@ -118,17 +116,7 @@ def get_object(self, queryset=None):
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()

Expand Down Expand Up @@ -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,
Expand Down
10 changes: 0 additions & 10 deletions comments/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,6 @@


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)

Expand Down
20 changes: 8 additions & 12 deletions comments/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,34 +41,32 @@ def test_validate_comment(self):
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
Expand All @@ -83,15 +81,13 @@ def test_validate_comment(self):
''',
'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)
Expand Down
1 change: 0 additions & 1 deletion comments/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

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(),
Expand Down
27 changes: 9 additions & 18 deletions comments/views.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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']

Expand All @@ -23,16 +28,6 @@ def get(self, request, *args, **kwargs):
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,
Expand All @@ -45,13 +40,9 @@ def form_valid(self, form):

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

Expand Down
18 changes: 9 additions & 9 deletions djangoblog/whoosh_cn_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
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
Expand Down Expand Up @@ -376,7 +376,7 @@ def search(
'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.
Expand Down Expand Up @@ -467,7 +467,7 @@ def search(

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 {
Expand Down Expand Up @@ -614,7 +614,7 @@ def more_like_this(

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 {
Expand Down Expand Up @@ -771,7 +771,7 @@ def create_spelling_suggestion(self, query_string):
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
Expand Down Expand Up @@ -811,12 +811,12 @@ def _from_python(self, value):
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):
Expand Down Expand Up @@ -873,9 +873,9 @@ def _to_python(self, value):
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):
"""
Expand Down
9 changes: 5 additions & 4 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,19 @@ 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
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
Loading

0 comments on commit 2700581

Please sign in to comment.