Compare commits

..

61 Commits
main ... master

Author SHA1 Message Date
starrysky yuanye ef9c8d5a7b 作业
3 months ago
zhangyu 60c7d20074 正式版
3 months ago
zhangyu a2784f1681 第七周
4 months ago
starrysky yuanye 4965a60cf7 第七周
4 months ago
zhangyu 8f2d67f278 修改
4 months ago
prcsjxomk 35bdacbe9a Merge pull request '第六周' (#13) from develop into master
4 months ago
prcsjxomk 6bc8c95ca7 Merge pull request 'wmw' (#12) from wmw_branch into develop
4 months ago
starrysky yuanye f01bf37760 feat: 第六周作业
4 months ago
starrysky yuanye a5e87f5478 feat: 第六周作业
4 months ago
prcsjxomk bb48692d4b Merge pull request 'chy' (#11) from chy_branch into develop
4 months ago
prcsjxomk 1b67c1cd4a Merge pull request 'xjh' (#10) from xjh_branch into develop
4 months ago
prcsjxomk 57ad107a50 Merge pull request 'zyg' (#9) from zyg_branch into develop
4 months ago
zyg123 e01da7978b 第六周
4 months ago
xjh123 9203ae6e45 第六周
4 months ago
chy 16280453dd 第六周
4 months ago
prcsjxomk 30910f745a Merge pull request 'zy' (#8) from zy_branch into develop
4 months ago
zhangyu 029004f302 第六周作业
4 months ago
zhangyu d999a80bc7 第六周作业
4 months ago
prcsjxomk f8710a5838 Merge pull request 'zy' (#7) from zy_branch into develop
4 months ago
prcsjxomk e784c68373 Merge pull request '第五周' (#6) from develop into master
4 months ago
zhangyu 0d1dd8452c 第五周
4 months ago
prcsjxomk 92f26e9b63 Merge pull request 'chy' (#5) from chy_branch into develop
4 months ago
prcsjxomk 69b8a2c3fb Merge pull request 'zyg' (#4) from zyg_branch into develop
4 months ago
prcsjxomk 0c6c5deaf0 Merge pull request 'xjh' (#3) from xjh_branch into develop
4 months ago
prcsjxomk b588237954 Merge pull request 'wmw' (#2) from wmw_branch into develop
4 months ago
zhangyu e4305eec3a 合并 zy_branch 到 develop,解决 modify/delete 冲突
4 months ago
xjh123 79f17f6da6 第五周
4 months ago
starrysky yuanye fc4bcdfae2 feat: 第五周作业
4 months ago
chy ac6a4d8921 第五周
4 months ago
zhangyu e399e59d54 第五周
4 months ago
zyg123 81228bb3c9 第五周
4 months ago
starrysky yuanye 11b2ae07ff 同步
5 months ago
xjh123 2a5aae7897 同步
5 months ago
chy 3585d385ed 同步
5 months ago
zhangyu 5919d3fd02 云端数据库版本更新
5 months ago
zyg123 d68dbfc91b 同步
5 months ago
zhangyu 9cf68e5de0 1
5 months ago
zhangyu 011832b7ab v1.0
5 months ago
zhangyu e8541ab1a1 v1.0
5 months ago
zhangyu dff4740297 v1.0
5 months ago
zhangyu 1bd5a88c89 v1.0
5 months ago
zhangyu f0ce734a15 basis
5 months ago
zhangyu 3c7dc23036 update
5 months ago
zhangyu 256f3daf4e update
5 months ago
zhangyu 162f462dc2 update
5 months ago
zhangyu 37c4b4c00e update
5 months ago
zhangyu 0c1c18915c update
5 months ago
zhangyu 136d521b86 update
5 months ago
zhangyu de84c29b11 update
5 months ago
zhangyu ff108496b4 update
5 months ago
zhangyu 93969f99ee update
5 months ago
starrysky yuanye 734ef1bddc Merge branch 'wmw_branch' of https://bdgit.educoder.net/prcsjxomk/DjangoBlog into wmw_branch
5 months ago
starrysky yuanye 03816a988f feat: 添加 wmw .txt 到 doc 文件夹
5 months ago
prcsjxomk 9f94fd97b9 ADD file via upload
5 months ago
prcsjxomk 0cedadfb4f ADD file via upload
5 months ago
prcsjxomk 8cb3ebf6e6 ADD file via upload
5 months ago
prcsjxomk 60c30e136c ADD file via upload
5 months ago
prcsjxomk 4b790d2546 Add zyg_branch
5 months ago
prcsjxomk 56ebf77b80 ADD file via upload
5 months ago
prcsjxomk 78672a2e66 ADD file via upload
5 months ago
prcsjxomk 4b73716286 ADD file via upload
5 months ago

@ -1,2 +0,0 @@
# DjangoBlog

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -0,0 +1,73 @@
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, get_object_or_404
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Article, Category, Tag, ArticleImage
from .forms import ArticleForm
class ArticleCreateView(LoginRequiredMixin, CreateView):
"""创建文章视图"""
model = Article
form_class = ArticleForm
template_name = 'blog/article_create.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['all_categories'] = Category.objects.all()
context['all_tags'] = Tag.objects.all()
return context
def form_valid(self, form):
# 先不保存表单,先处理分类
form.instance.author = self.request.user
# 处理分类
category_name = form.cleaned_data['category']
category, created = Category.objects.get_or_create(
name=category_name,
defaults={'parent_category': None}
)
# 直接设置分类对象,而不是名称
form.instance.category = category
# 先保存文章实例,以便可以添加多对多关系
# 但在保存前先从表单中移除category字段避免表单尝试保存它
category_temp = form.cleaned_data.pop('category')
tags_temp = form.cleaned_data.pop('tags')
response = super().form_valid(form)
# 处理标签
if tags_temp:
tag_names = [tag.strip() for tag in tags_temp.split(',') if tag.strip()]
for tag_name in tag_names:
tag, created = Tag.objects.get_or_create(name=tag_name)
form.instance.tags.add(tag)
# 关联临时图片到新创建的文章
# 获取会话中的临时图片ID列表
temp_image_ids = self.request.session.get('temp_image_ids', [])
# 查找这些临时图片
temp_images = ArticleImage.objects.filter(id__in=temp_image_ids)
# 将这些图片关联到新创建的文章
for image in temp_images:
image.article = form.instance
image.save()
# 清除会话中的临时图片ID列表
self.request.session['temp_image_ids'] = []
self.request.session.modified = True
return response
def get_success_url(self):
return reverse_lazy('blog:detailbyid', kwargs={
'article_id': self.object.id,
'year': self.object.creation_time.year,
'month': self.object.creation_time.month,
'day': self.object.creation_time.day
})

@ -0,0 +1,46 @@
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, get_object_or_404
from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy
from .models import Article, Category, Tag, ArticleImage
class ArticleDeleteView(LoginRequiredMixin, DeleteView):
"""删除文章视图"""
model = Article
template_name = 'blog/article_delete_confirm.html'
pk_url_kwarg = 'article_id'
def dispatch(self, request, *args, **kwargs):
obj = self.get_object()
# 只有文章作者或管理员可以删除
if obj.author != request.user and not request.user.is_superuser:
return redirect('blog:detailbyid',
article_id=obj.id,
year=obj.creation_time.year,
month=obj.creation_time.month,
day=obj.creation_time.day)
return super().dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['all_categories'] = Category.objects.all()
context['all_tags'] = Tag.objects.all()
return context
def delete(self, request, *args, **kwargs):
# 删除文章前先删除所有相关图片
self.object = self.get_object()
images = ArticleImage.objects.filter(article=self.object)
for image in images:
# 删除图片文件
image.image.delete()
# 删除图片记录
image.delete()
# 调用父类的delete方法删除文章
return super().delete(request, *args, *kwargs)
def get_success_url(self):
return reverse_lazy('blog:index')

@ -0,0 +1,101 @@
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, get_object_or_404
from django.views.generic.edit import UpdateView
from django.urls import reverse_lazy
from .models import Article, Category, Tag, ArticleImage
from .forms import ArticleForm
class ArticleUpdateView(LoginRequiredMixin, UpdateView):
"""更新文章视图"""
model = Article
form_class = ArticleForm
template_name = 'blog/article_edit.html'
pk_url_kwarg = 'article_id'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['all_categories'] = Category.objects.all()
context['all_tags'] = Tag.objects.all()
return context
def get_initial(self):
initial = super().get_initial()
# 设置分类初始值
if self.object.category:
initial['category'] = self.object.category.name
# 设置标签初始值
if self.object.tags.exists():
tag_names = [tag.name for tag in self.object.tags.all()]
initial['tags'] = ', '.join(tag_names)
return initial
def dispatch(self, request, *args, **kwargs):
obj = self.get_object()
# 只有文章作者或管理员可以编辑
if obj.author != request.user and not request.user.is_superuser:
return redirect('blog:detailbyid',
article_id=obj.id,
year=obj.creation_time.year,
month=obj.creation_time.month,
day=obj.creation_time.day)
return super().dispatch(request, *args, **kwargs)
def form_valid(self, form):
# 先不保存表单,先处理分类
form.instance.author = self.request.user
# 处理分类
category_name = form.cleaned_data['category']
category, created = Category.objects.get_or_create(
name=category_name,
defaults={'parent_category': None}
)
# 直接设置分类对象,而不是名称
form.instance.category = category
# 先保存文章实例,以便可以添加多对多关系
# 但在保存前先从表单中移除category字段避免表单尝试保存它
category_temp = form.cleaned_data.pop('category')
tags_temp = form.cleaned_data.pop('tags')
response = super().form_valid(form)
# 处理标签
if tags_temp:
tag_names = [tag.strip() for tag in tags_temp.split(',') if tag.strip()]
form.instance.tags.clear() # 清除现有标签
for tag_name in tag_names:
tag, created = Tag.objects.get_or_create(name=tag_name)
form.instance.tags.add(tag)
else:
form.instance.tags.clear() # 如果没有标签,清除所有标签
# 关联临时图片到文章
# 获取会话中的临时图片ID列表
temp_image_ids = self.request.session.get('temp_image_ids', [])
# 查找这些临时图片
temp_images = ArticleImage.objects.filter(id__in=temp_image_ids)
# 将这些图片关联到文章
for image in temp_images:
image.article = form.instance
image.save()
# 清除会话中的临时图片ID列表
self.request.session['temp_image_ids'] = []
self.request.session.modified = True
return response
def get_success_url(self):
return reverse_lazy('blog:detailbyid', kwargs={
'article_id': self.object.id,
'year': self.object.creation_time.year,
'month': self.object.creation_time.month,
'day': self.object.creation_time.day
})

@ -0,0 +1,135 @@
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, get_object_or_404
from django.views.generic.edit import CreateView, UpdateView
from django.urls import reverse_lazy
from .models import Article, Category, Tag, ArticleImage
from .forms import ArticleForm
class ArticleCreateView(LoginRequiredMixin, CreateView):
"""创建文章视图"""
model = Article
form_class = ArticleForm
template_name = 'blog/article_create.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['all_categories'] = Category.objects.all()
context['all_tags'] = Tag.objects.all()
return context
def form_valid(self, form):
# 先不保存表单,先处理分类
form.instance.author = self.request.user
# 处理分类
category_name = form.cleaned_data['category']
category, created = Category.objects.get_or_create(
name=category_name,
defaults={'parent_category': None}
)
# 直接设置分类对象,而不是名称
form.instance.category = category
# 先保存文章实例,以便可以添加多对多关系
# 但在保存前先从表单中移除category字段避免表单尝试保存它
category_temp = form.cleaned_data.pop('category')
tags_temp = form.cleaned_data.pop('tags')
response = super().form_valid(form)
# 处理标签
if tags_temp:
tag_names = [tag.strip() for tag in tags_temp.split(',') if tag.strip()]
for tag_name in tag_names:
tag, created = Tag.objects.get_or_create(name=tag_name)
form.instance.tags.add(tag)
return response
def get_success_url(self):
return reverse_lazy('blog:detailbyid', kwargs={
'article_id': self.object.id,
'year': self.object.creation_time.year,
'month': self.object.creation_time.month,
'day': self.object.creation_time.day
})
class ArticleUpdateView(LoginRequiredMixin, UpdateView):
"""更新文章视图"""
model = Article
form_class = ArticleForm
template_name = 'blog/article_edit.html'
pk_url_kwarg = 'article_id'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['all_categories'] = Category.objects.all()
context['all_tags'] = Tag.objects.all()
return context
def get_initial(self):
initial = super().get_initial()
# 设置分类初始值
if self.object.category:
initial['category'] = self.object.category.name
# 设置标签初始值
if self.object.tags.exists():
tag_names = [tag.name for tag in self.object.tags.all()]
initial['tags'] = ', '.join(tag_names)
return initial
def dispatch(self, request, *args, **kwargs):
obj = self.get_object()
# 只有文章作者或管理员可以编辑
if obj.author != request.user and not request.user.is_superuser:
return redirect('blog:detailbyid',
article_id=obj.id,
year=obj.creation_time.year,
month=obj.creation_time.month,
day=obj.creation_time.day)
return super().dispatch(request, *args, **kwargs)
def form_valid(self, form):
# 先不保存表单,先处理分类
form.instance.author = self.request.user
# 处理分类
category_name = form.cleaned_data['category']
category, created = Category.objects.get_or_create(
name=category_name,
defaults={'parent_category': None}
)
# 直接设置分类对象,而不是名称
form.instance.category = category
# 先保存文章实例,以便可以添加多对多关系
# 但在保存前先从表单中移除category字段避免表单尝试保存它
category_temp = form.cleaned_data.pop('category')
tags_temp = form.cleaned_data.pop('tags')
response = super().form_valid(form)
# 处理标签
if tags_temp:
tag_names = [tag.strip() for tag in tags_temp.split(',') if tag.strip()]
form.instance.tags.clear() # 清除现有标签
for tag_name in tag_names:
tag, created = Tag.objects.get_or_create(name=tag_name)
form.instance.tags.add(tag)
else:
form.instance.tags.clear() # 如果没有标签,清除所有标签
return response
def get_success_url(self):
return reverse_lazy('blog:detailbyid', kwargs={
'article_id': self.object.id,
'year': self.object.creation_time.year,
'month': self.object.creation_time.month,
'day': self.object.creation_time.day
})

@ -0,0 +1,153 @@
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, get_object_or_404
from django.views.generic.edit import CreateView, UpdateView
from django.urls import reverse_lazy
from .models import Article, Category, Tag, ArticleImage
from .forms import ArticleForm
class ArticleCreateView(LoginRequiredMixin, CreateView):
"""创建文章视图"""
model = Article
form_class = ArticleForm
template_name = 'blog/article_create.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['all_categories'] = Category.objects.all()
context['all_tags'] = Tag.objects.all()
return context
def form_valid(self, form):
# 先不保存表单,先处理分类
form.instance.author = self.request.user
# 处理分类
category_name = form.cleaned_data['category']
category, created = Category.objects.get_or_create(
name=category_name,
defaults={'parent_category': None}
)
# 直接设置分类对象,而不是名称
form.instance.category = category
# 先保存文章实例,以便可以添加多对多关系
# 但在保存前先从表单中移除category字段避免表单尝试保存它
category_temp = form.cleaned_data.pop('category')
tags_temp = form.cleaned_data.pop('tags')
response = super().form_valid(form)
# 处理标签
if tags_temp:
tag_names = [tag.strip() for tag in tags_temp.split(',') if tag.strip()]
for tag_name in tag_names:
tag, created = Tag.objects.get_or_create(name=tag_name)
form.instance.tags.add(tag)
# 处理临时上传的图片
temp_image_ids = self.request.session.get('temp_image_ids', [])
if temp_image_ids:
# 关联这些图片到当前文章
ArticleImage.objects.filter(id__in=temp_image_ids).update(article=self.object)
# 清除会话中的临时图片ID列表
self.request.session['temp_image_ids'] = []
self.request.session.modified = True
return response
def get_success_url(self):
return reverse_lazy('blog:detailbyid', kwargs={
'article_id': self.object.id,
'year': self.object.creation_time.year,
'month': self.object.creation_time.month,
'day': self.object.creation_time.day
})
class ArticleUpdateView(LoginRequiredMixin, UpdateView):
"""更新文章视图"""
model = Article
form_class = ArticleForm
template_name = 'blog/article_edit.html'
pk_url_kwarg = 'article_id'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['all_categories'] = Category.objects.all()
context['all_tags'] = Tag.objects.all()
return context
def get_initial(self):
initial = super().get_initial()
# 设置分类初始值
if self.object.category:
initial['category'] = self.object.category.name
# 设置标签初始值
if self.object.tags.exists():
tag_names = [tag.name for tag in self.object.tags.all()]
initial['tags'] = ', '.join(tag_names)
return initial
def dispatch(self, request, *args, **kwargs):
obj = self.get_object()
# 只有文章作者或管理员可以编辑
if obj.author != request.user and not request.user.is_superuser:
return redirect('blog:detailbyid',
article_id=obj.id,
year=obj.creation_time.year,
month=obj.creation_time.month,
day=obj.creation_time.day)
return super().dispatch(request, *args, **kwargs)
def form_valid(self, form):
# 先不保存表单,先处理分类
form.instance.author = self.request.user
# 处理分类
category_name = form.cleaned_data['category']
category, created = Category.objects.get_or_create(
name=category_name,
defaults={'parent_category': None}
)
# 直接设置分类对象,而不是名称
form.instance.category = category
# 先保存文章实例,以便可以添加多对多关系
# 但在保存前先从表单中移除category字段避免表单尝试保存它
category_temp = form.cleaned_data.pop('category')
tags_temp = form.cleaned_data.pop('tags')
response = super().form_valid(form)
# 处理标签
if tags_temp:
tag_names = [tag.strip() for tag in tags_temp.split(',') if tag.strip()]
form.instance.tags.clear() # 清除现有标签
for tag_name in tag_names:
tag, created = Tag.objects.get_or_create(name=tag_name)
form.instance.tags.add(tag)
else:
form.instance.tags.clear() # 如果没有标签,清除所有标签
# 处理临时上传的图片
temp_image_ids = self.request.session.get('temp_image_ids', [])
if temp_image_ids:
# 关联这些图片到当前文章
ArticleImage.objects.filter(id__in=temp_image_ids).update(article=self.object)
# 清除会话中的临时图片ID列表
self.request.session['temp_image_ids'] = []
self.request.session.modified = True
return response
def get_success_url(self):
return reverse_lazy('blog:detailbyid', kwargs={
'article_id': self.object.id,
'year': self.object.creation_time.year,
'month': self.object.creation_time.month,
'day': self.object.creation_time.day
})

@ -1,7 +1,9 @@
import logging
from django import forms
from django.utils.translation import gettext_lazy as _
from haystack.forms import SearchForm
from .models import Article, Category, Tag
logger = logging.getLogger(__name__)
@ -17,3 +19,62 @@ class BlogSearchForm(SearchForm):
if self.cleaned_data['querydata']:
logger.info(self.cleaned_data['querydata'])
return datas
class ArticleForm(forms.ModelForm):
"""文章表单"""
title = forms.CharField(label='标题', max_length=200, required=True)
body = forms.CharField(label='内容', widget=forms.Textarea(attrs={'id': 'id_body_md'}), required=True)
status = forms.ChoiceField(
label='状态',
choices=[('p', '发布'), ('d', '草稿')],
initial='p',
widget=forms.Select,
required=True
)
comment_status = forms.ChoiceField(
label='评论状态',
choices=[('o', '开启'), ('c', '关闭')],
initial='o',
widget=forms.Select,
required=True
)
type = forms.ChoiceField(
label='类型',
choices=[('a', '文章'), ('p', '页面')],
initial='a',
widget=forms.Select,
required=True
)
show_toc = forms.BooleanField(label='显示目录', required=False)
category = forms.CharField(
label='分类',
required=True,
widget=forms.TextInput(attrs={
'class': 'form-control',
'list': 'category-list',
'placeholder': '选择或输入分类名称'
})
)
tags = forms.CharField(
label='标签',
required=False,
widget=forms.TextInput(attrs={
'class': 'form-control',
'list': 'tag-list',
'placeholder': '选择或输入标签,多个标签用逗号分隔'
})
)
class Meta:
model = Article
fields = ['title', 'body', 'status', 'comment_status', 'type', 'show_toc']
def __init__(self, *args, **kwargs):
super(ArticleForm, self).__init__(*args, **kwargs)
self.fields['title'].widget.attrs.update({'class': 'form-control'})
self.fields['body'].widget.attrs.update({'class': 'form-control mdeditor', 'rows': 20})
self.fields['status'].widget.attrs.update({'class': 'form-control'})
self.fields['comment_status'].widget.attrs.update({'class': 'form-control'})
self.fields['type'].widget.attrs.update({'class': 'form-control'})
self.fields['show_toc'].widget.attrs.update({'class': 'form-check-input'})

@ -0,0 +1,15 @@
from django import forms
from django.utils.translation import gettext_lazy as _
from .models import ArticleImage
class ImageUploadForm(forms.ModelForm):
"""图片上传表单"""
class Meta:
model = ArticleImage
fields = ['image', 'description']
widgets = {
'image': forms.FileInput(attrs={'class': 'form-control', 'accept': 'image/*'}),
'description': forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('可选,添加图片描述')})
}

@ -0,0 +1,127 @@
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.generic.edit import CreateView, DeleteView
from django.urls import reverse_lazy
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
import json
from .models import Article, ArticleImage
from .forms_image import ImageUploadForm
class ImageUploadView(LoginRequiredMixin, CreateView):
"""上传图片视图"""
model = ArticleImage
form_class = ImageUploadForm
template_name = 'blog/image_upload.html'
def form_valid(self, form):
article_id = self.kwargs.get('article_id')
article = get_object_or_404(Article, id=article_id)
# 检查用户是否有权限上传图片
if article.author != self.request.user and not self.request.user.is_superuser:
return JsonResponse({'status': 'error', 'message': '没有权限上传图片'}, status=403)
form.instance.article = article
self.object = form.save()
# 返回JSON响应包含图片URL和ID
return JsonResponse({
'status': 'success',
'image_id': self.object.id,
'image_url': self.object.image.url,
'description': self.object.description
})
def form_invalid(self, form):
return JsonResponse({'status': 'error', 'errors': form.errors}, status=400)
@login_required
@require_POST
@csrf_exempt
def markdown_image_upload(request):
"""为Markdown编辑器提供的图片上传接口"""
if request.method == 'POST' and request.FILES.get('image'):
image_file = request.FILES['image']
description = request.POST.get('description', '')
article_id = request.POST.get('article_id')
try:
# 获取会话中的临时图片ID列表
temp_image_ids = request.session.get('temp_image_ids', [])
# 创建图片对象,但不立即关联到文章
temp_image = ArticleImage(
image=image_file,
description=description or "Markdown编辑器上传"
)
# 如果有文章ID尝试关联到文章
if article_id:
try:
from blog.models import Article
article = Article.objects.get(id=article_id, author=request.user)
temp_image.article = article
except Article.DoesNotExist:
# 文章不存在,不关联
temp_image.article_id = None
else:
# 没有文章ID保存为临时图片
temp_image.article_id = None
# 保存图片
temp_image.save()
# 如果是临时图片将图片ID添加到会话中的临时图片列表
if not temp_image.article:
temp_image_ids.append(temp_image.id)
request.session['temp_image_ids'] = temp_image_ids
request.session.modified = True
# 返回Markdown编辑器需要的格式
return JsonResponse({
'success': 1,
'message': '上传成功',
'url': temp_image.image.url,
'image_id': temp_image.id # 添加图片ID以便后续可以删除
})
except Exception as e:
# 记录错误并返回失败信息
import logging
logger = logging.getLogger(__name__)
logger.error(f"图片上传失败: {str(e)}")
return JsonResponse({
'success': 0,
'message': f'上传失败: {str(e)}'
})
return JsonResponse({
'success': 0,
'message': '上传失败:未提供图片文件'
})
class ImageDeleteView(LoginRequiredMixin, DeleteView):
"""删除图片视图"""
model = ArticleImage
pk_url_kwarg = 'image_id'
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
# 检查用户是否有权限删除图片
if self.object.article.author != request.user and not request.user.is_superuser:
return JsonResponse({'status': 'error', 'message': '没有权限删除图片'}, status=403)
# 删除图片文件
self.object.image.delete()
self.object.delete()
return JsonResponse({'status': 'success', 'message': '图片已删除'})

@ -0,0 +1,41 @@
from django.core.management.base import BaseCommand
from blog.models import Category
class Command(BaseCommand):
help = '创建文章分类'
def handle(self, *args, **options):
categories = [
'技术',
'生活',
'旅行',
'美食',
'摄影',
'读书',
'电影',
'音乐',
'编程',
'设计',
'健康',
'教育',
'职场',
'财经',
'历史',
'文化',
'体育',
'游戏',
'科技'
]
for name in categories:
category, created = Category.objects.get_or_create(
name=name,
defaults={'parent_category': None}
)
if created:
self.stdout.write(self.style.SUCCESS(f'创建分类: {name}'))
else:
self.stdout.write(self.style.WARNING(f'分类已存在: {name}'))
self.stdout.write(self.style.SUCCESS('分类创建完成'))

@ -0,0 +1,13 @@
from django.core.management.base import BaseCommand
from blog.models import Category
class Command(BaseCommand):
help = '列出所有文章分类'
def handle(self, *args, **options):
categories = Category.objects.all()
self.stdout.write('当前数据库中的分类:')
for category in categories:
self.stdout.write(f'- {category.name} (ID: {category.id})')
self.stdout.write(f'总计: {categories.count()} 个分类')

@ -0,0 +1,24 @@
# Generated by Django
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='articleimage',
name='article',
field=models.ForeignKey(
blank=True,
null=True,
on_delete=models.deletion.CASCADE,
related_name='images',
to='blog.article'
),
),
]

@ -0,0 +1,29 @@
# Generated by Django 4.2.14 on 2025-11-20 20:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_alter_blogsettings_options'),
]
operations = [
migrations.CreateModel(
name='ArticleImage',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(upload_to='article_images/%Y/%m/%d/', verbose_name='图片')),
('description', models.CharField(blank=True, max_length=255, verbose_name='图片描述')),
('created_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
('article', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='blog.article')),
],
options={
'verbose_name': '文章图片',
'verbose_name_plural': '文章图片',
'ordering': ['-created_time'],
},
),
]

@ -0,0 +1,14 @@
# Generated by Django 4.2.14 on 2025-11-20 22:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_auto_20231201_1200'),
('blog', '0007_articleimage'),
]
operations = [
]

@ -304,6 +304,22 @@ class SideBar(models.Model):
return self.name
class ArticleImage(models.Model):
"""文章图片模型"""
article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='images', null=True, blank=True)
image = models.ImageField(_('图片'), upload_to='images/')
description = models.CharField(_('图片描述'), max_length=255, blank=True)
created_time = models.DateTimeField(_('创建时间'), auto_now_add=True)
class Meta:
verbose_name = _('文章图片')
verbose_name_plural = verbose_name
ordering = ['-created_time']
def __str__(self):
return f"{self.article.title} - {self.image.name}"
class BlogSettings(models.Model):
"""blog的配置"""
site_name = models.CharField(

@ -1,162 +0,0 @@
/* 文章归档页面样式 */
/* 归档标题样式 */
.archive-header {
margin-bottom: 2rem;
padding: 1.5rem;
background: linear-gradient(135deg, var(--primary-color), #2980b9);
border-radius: 8px;
box-shadow: var(--box-shadow);
position: relative;
overflow: hidden;
}
.archive-header::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="none"/><path d="M0 0L50 50M50 0L100 50M0 50L50 100M50 50L100 100" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></svg>');
background-size: 100px 100px;
opacity: 0.5;
}
.archive-title {
font-size: 1.8rem;
font-weight: 600;
color: #fff;
margin: 0;
position: relative;
z-index: 1;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
/* 归档内容样式 */
.entry-content {
background-color: #fff;
border-radius: 8px;
box-shadow: var(--box-shadow);
padding: 2rem;
}
/* 年份样式 */
.archive-year {
margin-bottom: 1.5rem;
list-style-type: none;
position: relative;
padding-left: 2.5rem;
}
.archive-year::before {
content: '📅';
position: absolute;
left: 0;
top: 0.5rem;
width: 1.5rem;
height: 1.5rem;
background-color: var(--primary-color);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-weight: bold;
font-size: 0.8rem;
}
.year-label {
font-size: 1.3rem;
font-weight: 600;
color: var(--dark-color);
margin-bottom: 0.5rem;
display: block;
}
/* 月份样式 */
.archive-month {
margin-bottom: 1rem;
list-style-type: none;
position: relative;
padding-left: 2rem;
}
.archive-month::before {
content: '';
position: absolute;
left: 0;
top: 0.5rem;
width: 0.8rem;
height: 0.8rem;
background-color: var(--secondary-color);
border-radius: 50%;
}
.month-label {
font-size: 1.1rem;
font-weight: 500;
color: var(--dark-color);
margin-bottom: 0.5rem;
display: block;
}
/* 文章列表样式 */
.article-list {
margin-top: 0.5rem;
padding-left: 1rem;
}
.article-list > li {
margin-bottom: 0.5rem;
list-style-type: none;
position: relative;
padding-left: 1.5rem;
}
.article-list > li::before {
content: '📄';
position: absolute;
left: 0;
top: 0.2rem;
font-size: 0.9rem;
}
.article-list > li a {
color: var(--text-color);
text-decoration: none;
transition: var(--transition);
display: inline-block;
padding: 0.3rem 0.5rem;
border-radius: 4px;
}
.article-list > li a:hover {
color: var(--primary-color);
background-color: rgba(52, 152, 219, 0.1);
transform: translateX(5px);
}
/* 响应式设计 */
@media screen and (max-width: 768px) {
.archive-header {
padding: 1rem;
}
.archive-title {
font-size: 1.5rem;
}
.entry-content {
padding: 1rem;
}
.entry-content > ul > li {
padding-left: 2rem;
}
.entry-content > ul > li > ul > li {
padding-left: 1.5rem;
}
}

@ -1,22 +0,0 @@
/* 网页背景选项 - 默认背景和自定义图片背景 */
/* 自定义图片背景 - 请将图片放在 /blog/static/blog/images/ 目录下 */
.bg-custom-image {
background-image: url('{% static "blog/images/background.jpg" %}');
background-attachment: fixed;
background-size: cover;
background-position: center;
}
/* 半透明遮罩层,用于自定义图片背景上 */
.bg-overlay::before {
content: '';
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.7);
z-index: -1;
}

@ -0,0 +1,91 @@
/* 自定义样式 - 修改导航栏背景色和按钮样式 */
/* 导航栏背景色改为天蓝色 */
.main-navigation {
background: linear-gradient(to right, #2e9ac5, #66b8db) !important;
}
/* 文章标题链接样式 - 去掉蓝色按钮效果 */
.entry-title a {
color: #2c3e50 !important;
text-decoration: none !important;
background: none !important;
padding: 0 !important;
border-radius: 0 !important;
box-shadow: none !important;
}
.entry-title a:hover {
color: #3498db !important;
text-decoration: underline !important;
background: none !important;
}
/* 侧边栏链接样式 - 去掉蓝色按钮效果 */
.widget a {
color: #34495e !important;
text-decoration: none !important;
background: none !important;
padding: 0 !important;
border-radius: 0 !important;
box-shadow: none !important;
}
.widget a:hover {
color: #3498db !important;
text-decoration: underline !important;
background: none !important;
}
/* 文章阅读更多链接 - 去掉蓝色按钮效果 */
.read-more {
background: none !important;
color: #3498db !important;
padding: 0 !important;
border-radius: 0 !important;
box-shadow: none !important;
text-decoration: underline !important;
}
.read-more:hover {
background: none !important;
color: #2980b9 !important;
transform: none !important;
box-shadow: none !important;
}
/* 文章链接 - 去掉蓝色按钮效果 */
a[href*="/p/"],
a[href*="/article/"] {
background: none !important;
color: #3498db !important;
padding: 0 !important;
border-radius: 0 !important;
box-shadow: none !important;
text-decoration: underline !important;
margin: 0 !important;
}
a[href*="/p/"]:hover,
a[href*="/article/"]:hover {
background: none !important;
color: #2980b9 !important;
transform: none !important;
box-shadow: none !important;
}
/* 背景图片样式 */
body {
background-color: #f8f9fa;
background-image: url('/static/blog/img/default_bg.jpg');
background-size: cover;
background-position: center;
background-attachment: fixed;
background-repeat: no-repeat;
}
/* 网站容器样式,确保背景图片可见 */
.site {
background-color: rgba(255, 255, 255, 0.9);
}

@ -0,0 +1,90 @@
/* 简单的图标样式 */
/* 图标基础样式 */
[class^="icon-"], [class*=" icon-"] {
display: inline-block;
width: 1em;
height: 1em;
margin-right: 0.2em;
line-height: 1;
font-style: normal;
font-weight: normal;
text-align: center;
text-decoration: inherit;
text-transform: none;
speak: none;
}
/* 文件夹图标 */
.icon-folder:before {
content: "📁";
}
/* 标签图标 */
.icon-tag:before {
content: "🏷️";
}
/* 评论图标 */
.icon-comment:before {
content: "💬";
}
/* 搜索图标 */
#searchform input[type="submit"]:before {
content: "🔍";
margin-right: 0.25em;
}
/* 首页图标 */
#menu-item-3498 a:before {
content: "🏠";
margin-right: 0.25em;
}
/* 归档图标 */
.menu-item a[href*="archives"]:before {
content: "📚";
margin-right: 0.25em;
}
/* 管理站点图标 */
.menu-item a[href*="admin"]:before {
content: "⚙️";
margin-right: 0.25em;
}
/* 登录/登出图标 */
.menu-item a[href*="login"]:before {
content: "🔑";
margin-right: 0.25em;
}
.menu-item a[href*="logout"]:before {
content: "🚪";
margin-right: 0.25em;
}
/* 发布文章图标 */
.menu-item a[href*="create"]:before {
content: "✍️";
margin-right: 0.25em;
}
/* 我的文章图标 */
.menu-item a[href*="my_articles"]:before {
content: "📝";
margin-right: 0.25em;
}
/* 返回顶部按钮 */
#rocket:before {
content: "⬆️";
font-size: 1.5rem;
}
/* 背景切换按钮 */
.bg-toggle-btn i {
font-size: 1.5rem;
}

File diff suppressed because it is too large Load Diff

@ -1,16 +0,0 @@
# 博客背景图片
将您想用作背景的图片放在此目录下然后在background-options.css中更新路径。
支持的图片格式:
- JPG
- PNG
- GIF
- WebP
建议的图片尺寸:
- 宽度1920px或更大
- 高度1080px或更大
- 分辨率72dpi或更高
推荐使用有轻微纹理或图案的图片,避免过于复杂的图像,以免影响内容可读性。

Binary file not shown.

Before

Width:  |  Height:  |  Size: 440 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 330 KiB

@ -1,185 +0,0 @@
// 背景切换工具
document.addEventListener('DOMContentLoaded', function() {
// 创建背景切换器
function createBackgroundSwitcher() {
// 创建背景切换器容器
const switcher = document.createElement('div');
switcher.className = 'bg-switcher';
switcher.innerHTML = `
<button class="bg-switcher-toggle" title="切换背景">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 16C14.2091 16 16 14.2091 16 12C16 9.79086 14.2091 8 12 8C9.79086 8 8 9.79086 8 12C8 14.2091 9.79086 16 12 16Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 2V4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 20V22" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4.93 4.93L6.34 6.34" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M17.66 17.66L19.07 19.07" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M2 12H4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M20 12H22" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6.34 17.66L4.93 19.07" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M19.07 4.93L17.66 6.34" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
<div class="bg-switcher-panel">
<h4>选择背景</h4>
<div class="bg-options">
<button class="bg-option active" data-bg="default">默认</button>
<button class="bg-option" data-bg="custom-image">自定义背景</button>
</div>
</div>
`;
// 添加样式
const style = document.createElement('style');
style.textContent = `
.bg-switcher {
position: fixed;
bottom: 20px;
left: 20px;
z-index: 1000;
}
.bg-switcher-toggle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: var(--primary-color);
color: white;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
box-shadow: var(--box-shadow);
transition: var(--transition);
}
.bg-switcher-toggle:hover {
background-color: #2980b9;
transform: scale(1.1);
}
.bg-switcher-panel {
position: absolute;
bottom: 60px;
left: 0;
background-color: white;
border-radius: 8px;
box-shadow: var(--box-shadow);
padding: 15px;
width: 200px;
opacity: 0;
visibility: hidden;
transform: translateY(10px);
transition: var(--transition);
}
.bg-switcher.active .bg-switcher-panel {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.bg-switcher-panel h4 {
margin: 0 0 10px;
font-size: 16px;
color: var(--dark-color);
}
.bg-options {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.bg-option {
padding: 8px;
border: 1px solid var(--border-color);
border-radius: 4px;
background-color: #f9f9f9;
cursor: pointer;
transition: var(--transition);
font-size: 14px;
}
.bg-option:hover {
background-color: #f0f0f0;
border-color: var(--primary-color);
}
.bg-option.active {
background-color: var(--primary-color);
color: white;
border-color: var(--primary-color);
}
`;
document.head.appendChild(style);
// 添加到页面
document.body.appendChild(switcher);
// 切换面板显示/隐藏
const toggle = switcher.querySelector('.bg-switcher-toggle');
toggle.addEventListener('click', function() {
switcher.classList.toggle('active');
});
// 点击其他地方关闭面板
document.addEventListener('click', function(e) {
if (!switcher.contains(e.target)) {
switcher.classList.remove('active');
}
});
// 背景切换功能
const options = switcher.querySelectorAll('.bg-option');
options.forEach(option => {
option.addEventListener('click', function() {
// 移除所有active类
options.forEach(opt => opt.classList.remove('active'));
// 添加active类到当前选项
this.classList.add('active');
// 切换背景
const bgType = this.getAttribute('data-bg');
switchBackground(bgType);
// 保存用户选择
localStorage.setItem('preferredBackground', bgType);
});
});
// 检查用户之前的选择
const savedBg = localStorage.getItem('preferredBackground');
if (savedBg) {
// 设置对应的选项为active
options.forEach(opt => {
if (opt.getAttribute('data-bg') === savedBg) {
opt.classList.add('active');
} else {
opt.classList.remove('active');
}
});
// 应用保存的背景
switchBackground(savedBg);
}
}
// 切换背景函数
function switchBackground(bgType) {
const body = document.body;
// 移除所有背景类
body.classList.remove('bg-custom-image', 'bg-overlay');
// 根据类型添加对应的背景类
if (bgType === 'custom-image') {
body.classList.add('bg-custom-image', 'bg-overlay');
}
}
// 初始化背景切换器
createBackgroundSwitcher();
});

@ -1,134 +0,0 @@
// 现代化UI交互效果
document.addEventListener('DOMContentLoaded', function() {
// 返回顶部按钮功能
const backToTopButton = document.getElementById('back-to-top');
if (backToTopButton) {
// 监听滚动事件
window.addEventListener('scroll', function() {
// 当页面滚动超过300px时显示返回顶部按钮
if (window.pageYOffset > 300) {
backToTopButton.classList.add('visible');
} else {
backToTopButton.classList.remove('visible');
}
});
// 点击返回顶部
backToTopButton.addEventListener('click', function(e) {
e.preventDefault();
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
}
// 为所有外部链接添加target="_blank"属性
const links = document.querySelectorAll('a[href^="http"]:not([href*="' + window.location.hostname + '"])');
links.forEach(function(link) {
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
});
// 文章内容图片添加懒加载效果
const articleImages = document.querySelectorAll('.entry-content img');
if ('IntersectionObserver' in window) {
const imageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
const img = entry.target;
img.classList.add('fade-in');
imageObserver.unobserve(img);
}
});
});
articleImages.forEach(function(img) {
imageObserver.observe(img);
});
}
// 搜索框交互效果
const searchForms = document.querySelectorAll('.search-form');
searchForms.forEach(function(form) {
const input = form.querySelector('input[type="search"]');
const button = form.querySelector('button');
if (input && button) {
input.addEventListener('focus', function() {
form.classList.add('active');
});
input.addEventListener('blur', function() {
if (!input.value) {
form.classList.remove('active');
}
});
}
});
// 为代码块添加复制按钮
const codeBlocks = document.querySelectorAll('pre code');
codeBlocks.forEach(function(block) {
const button = document.createElement('button');
button.className = 'copy-button';
button.textContent = '复制';
button.setAttribute('title', '复制代码');
const pre = block.parentElement;
pre.style.position = 'relative';
pre.appendChild(button);
button.addEventListener('click', function() {
navigator.clipboard.writeText(block.textContent).then(function() {
button.textContent = '已复制!';
setTimeout(function() {
button.textContent = '复制';
}, 2000);
}).catch(function(err) {
console.error('复制失败:', err);
});
});
});
});
// 添加代码块复制按钮的CSS
const style = document.createElement('style');
style.textContent = `
.copy-button {
position: absolute;
top: 8px;
right: 8px;
background-color: rgba(0, 0, 0, 0.7);
color: white;
border: none;
border-radius: 4px;
padding: 4px 8px;
font-size: 12px;
cursor: pointer;
opacity: 0;
transition: opacity 0.2s;
}
pre:hover .copy-button {
opacity: 1;
}
.fade-in {
animation: fadeIn 0.6s ease-out;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
.search-form.active input[type="search"] {
border-color: var(--primary-color);
box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}
`;
document.head.appendChild(style);

@ -2,6 +2,10 @@ from django.urls import path
from django.views.decorators.cache import cache_page
from . import views
from . import article_views
from .article_views_new import ArticleCreateView, ArticleUpdateView
from .article_delete_view import ArticleDeleteView
from . import image_views
app_name = "blog"
urlpatterns = [
@ -17,6 +21,22 @@ urlpatterns = [
r'article/<int:year>/<int:month>/<int:day>/<int:article_id>.html',
views.ArticleDetailView.as_view(),
name='detailbyid'),
path(
r'article/create/',
ArticleCreateView.as_view(),
name='article_create'),
path(
r'article/edit/<int:article_id>/',
ArticleUpdateView.as_view(),
name='article_edit'),
path(
r'article/delete/<int:article_id>/',
ArticleDeleteView.as_view(),
name='article_delete'),
path(
r'my-articles/',
views.my_articles,
name='my_articles'),
path(
r'category/<slug:category_name>.html',
views.CategoryDetailView.as_view(),
@ -59,4 +79,17 @@ urlpatterns = [
r'clean',
views.clean_cache_view,
name='clean'),
# 图片相关路由
path(
'article/<int:article_id>/upload-image/',
image_views.ImageUploadView.as_view(),
name='upload_image'),
path(
'markdown-image-upload/',
image_views.markdown_image_upload,
name='markdown_image_upload'),
path(
'image/<int:image_id>/delete/',
image_views.ImageDeleteView.as_view(),
name='delete_image'),
]

@ -150,6 +150,11 @@ class ArticleDetailView(DetailView):
kwargs['next_article'] = self.object.next_article
kwargs['prev_article'] = self.object.prev_article
# 获取文章关联的图片
from .models import ArticleImage
article_images = ArticleImage.objects.filter(article=self.object)
kwargs['article_images'] = article_images
context = super(ArticleDetailView, self).get_context_data(**kwargs)
article = self.object
@ -378,3 +383,102 @@ def permission_denied_view(
def clean_cache_view(request):
cache.clear()
return HttpResponse('ok')
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.views.generic.edit import CreateView, UpdateView
from django.urls import reverse_lazy
from .forms import ArticleForm
class ArticleCreateView(LoginRequiredMixin, CreateView):
"""创建文章视图"""
model = Article
form_class = ArticleForm
template_name = 'blog/article_create.html'
def form_valid(self, form):
form.instance.author = self.request.user
# 处理分类
category_name = form.cleaned_data['category']
category, created = Category.objects.get_or_create(
name=category_name,
defaults={'parent_category': None}
)
form.instance.category = category
# 处理标签
tags_str = form.cleaned_data['tags']
if tags_str:
tag_names = [tag.strip() for tag in tags_str.split(',') if tag.strip()]
form.instance.save() # 保存文章实例,以便可以添加多对多关系
for tag_name in tag_names:
tag, created = Tag.objects.get_or_create(name=tag_name)
form.instance.tags.add(tag)
# 先保存文章,以便可以关联图片
response = super().form_valid(form)
# 将临时图片关联到新创建的文章
from .models import ArticleImage
# 获取会话中的临时图片ID列表
temp_image_ids = self.request.session.get('temp_image_ids', [])
# 查找这些临时图片
temp_images = ArticleImage.objects.filter(id__in=temp_image_ids)
# 将这些图片关联到新创建的文章
for image in temp_images:
image.article = form.instance
image.save()
# 清除会话中的临时图片ID列表
self.request.session['temp_image_ids'] = []
self.request.session.modified = True
return response
def get_success_url(self):
return reverse_lazy('blog:detailbyid', kwargs={
'article_id': self.object.id,
'year': self.object.creation_time.year,
'month': self.object.creation_time.month,
'day': self.object.creation_time.day
})
class ArticleUpdateView(LoginRequiredMixin, UpdateView):
"""更新文章视图"""
model = Article
form_class = ArticleForm
template_name = 'blog/article_edit.html'
pk_url_kwarg = 'article_id'
def dispatch(self, request, *args, **kwargs):
obj = self.get_object()
# 只有文章作者或管理员可以编辑
if obj.author != request.user and not request.user.is_superuser:
return redirect('blog:detailbyid',
article_id=obj.id,
year=obj.creation_time.year,
month=obj.creation_time.month,
day=obj.creation_time.day)
return super().dispatch(request, *args, **kwargs)
def get_success_url(self):
return reverse_lazy('blog:detailbyid', kwargs={
'article_id': self.object.id,
'year': self.object.creation_time.year,
'month': self.object.creation_time.month,
'day': self.object.creation_time.day
})
@login_required
def my_articles(request):
"""显示当前用户的文章列表"""
articles = Article.objects.filter(author=request.user)
return render(request, 'blog/my_articles.html', {'articles': articles})

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save