master
barney 2 years ago
parent 2256642abe
commit aba3d37c1c
  1. 16
      blog/admin.py
  2. 25
      blog/migrations/0002_blog_createtime_blog_modifytime.py
  3. 23
      blog/migrations/0003_alter_blog_createtime_alter_blog_modifytime.py
  4. 23
      blog/migrations/0004_alter_blog_createtime_alter_blog_modifytime.py
  5. 24
      blog/migrations/0005_alter_blog_createtime_alter_blog_modifytime.py
  6. 24
      blog/migrations/0006_alter_blog_createtime_alter_blog_modifytime.py
  7. 24
      blog/migrations/0007_alter_blog_createtime_alter_blog_modifytime.py
  8. 32
      blog/migrations/0008_remove_blog_createtime_remove_blog_modifytime_and_more.py
  9. 32
      blog/migrations/0009_remove_blog_add_date_remove_blog_mod_date_and_more.py
  10. 5
      blog/models.py
  11. 5
      blog/urls.py
  12. 6
      blog/view.py
  13. 4
      blog/views/blogListView.py
  14. BIN
      db.sqlite3
  15. 37
      demo/settings.py
  16. 4
      demo/urls.py
  17. 0
      myapi/__init__.py
  18. 3
      myapi/admin.py
  19. 6
      myapi/apps.py
  20. 0
      myapi/migrations/__init__.py
  21. 3
      myapi/models.py
  22. 16
      myapi/serializers.py
  23. 3
      myapi/tests.py
  24. 13
      myapi/urls.py
  25. 16
      myapi/views.py
  26. 0
      snippets/__init__.py
  27. 5
      snippets/admin.py
  28. 6
      snippets/apps.py
  29. 29
      snippets/migrations/0001_initial.py
  30. 0
      snippets/migrations/__init__.py
  31. 23
      snippets/models.py
  32. 29
      snippets/serializers.py
  33. 3
      snippets/tests.py
  34. 12
      snippets/urls.py
  35. 134
      snippets/views.py
  36. BIN
      static/images/apple.png
  37. 40
      templates/blog/index.html

@ -4,18 +4,18 @@ from .models import Blog
# Register your models here.
class BlogAdmin(admin.ModelAdmin):
list_display = ['title','author','content','author_name']
list_display = ['title','author','content','create_time']
# author字段是关系表,必须用两条下划线指定对应属性
search_fields = ['title','content','author__username']
# readonly_fields = ['author']
readonly_fields = ['author','create_time']
# # 保存模型时执行的操作
# def save_model(self, request, obj, form, change):
# if not change:
# # 只有创建时指定作者
# obj.author = request.user
# super(BlogAdmin, self).save_model(request,obj,form,change)
# 保存模型时执行的操作
def save_model(self, request, obj, form, change):
if not change:
# 只有创建时指定作者
obj.author = request.user
super(BlogAdmin, self).save_model(request,obj,form,change)
admin.site.register(Blog,BlogAdmin)

@ -0,0 +1,25 @@
# Generated by Django 4.1.1 on 2022-09-17 17:30
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='blog',
name='createTime',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now, verbose_name='创建时间'),
preserve_default=False,
),
migrations.AddField(
model_name='blog',
name='modifyTime',
field=models.DateField(auto_now=True, verbose_name='修改时间'),
),
]

@ -0,0 +1,23 @@
# Generated by Django 4.1.1 on 2022-09-17 17:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_blog_createtime_blog_modifytime'),
]
operations = [
migrations.AlterField(
model_name='blog',
name='createTime',
field=models.DateTimeField(auto_now_add=True, verbose_name='创建时间'),
),
migrations.AlterField(
model_name='blog',
name='modifyTime',
field=models.DateTimeField(auto_now=True, verbose_name='修改时间'),
),
]

@ -0,0 +1,23 @@
# Generated by Django 4.1.1 on 2022-09-17 17:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_alter_blog_createtime_alter_blog_modifytime'),
]
operations = [
migrations.AlterField(
model_name='blog',
name='createTime',
field=models.DateField(auto_now_add=True, verbose_name='创建时间'),
),
migrations.AlterField(
model_name='blog',
name='modifyTime',
field=models.DateField(auto_now=True, verbose_name='修改时间'),
),
]

@ -0,0 +1,24 @@
# Generated by Django 4.1.1 on 2022-09-17 17:40
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0004_alter_blog_createtime_alter_blog_modifytime'),
]
operations = [
migrations.AlterField(
model_name='blog',
name='createTime',
field=models.DateField(auto_now_add=True, verbose_name=django.utils.timezone.now),
),
migrations.AlterField(
model_name='blog',
name='modifyTime',
field=models.DateField(auto_now=True, verbose_name=django.utils.timezone.now),
),
]

@ -0,0 +1,24 @@
# Generated by Django 4.1.1 on 2022-09-17 17:43
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0005_alter_blog_createtime_alter_blog_modifytime'),
]
operations = [
migrations.AlterField(
model_name='blog',
name='createTime',
field=models.DateField(default=django.utils.timezone.now, verbose_name='创建时间'),
),
migrations.AlterField(
model_name='blog',
name='modifyTime',
field=models.DateField(auto_now=True, verbose_name='修改时间'),
),
]

@ -0,0 +1,24 @@
# Generated by Django 4.1.1 on 2022-09-17 17:44
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_alter_blog_createtime_alter_blog_modifytime'),
]
operations = [
migrations.AlterField(
model_name='blog',
name='createTime',
field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='创建时间'),
),
migrations.AlterField(
model_name='blog',
name='modifyTime',
field=models.DateTimeField(auto_now=True, verbose_name='修改时间'),
),
]

@ -0,0 +1,32 @@
# Generated by Django 4.1.1 on 2022-09-17 18:00
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0007_alter_blog_createtime_alter_blog_modifytime'),
]
operations = [
migrations.RemoveField(
model_name='blog',
name='createTime',
),
migrations.RemoveField(
model_name='blog',
name='modifyTime',
),
migrations.AddField(
model_name='blog',
name='add_date',
field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='保存日期'),
),
migrations.AddField(
model_name='blog',
name='mod_date',
field=models.DateTimeField(auto_now=True, verbose_name='最后修改日期'),
),
]

@ -0,0 +1,32 @@
# Generated by Django 4.1.1 on 2022-09-17 18:04
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0008_remove_blog_createtime_remove_blog_modifytime_and_more'),
]
operations = [
migrations.RemoveField(
model_name='blog',
name='add_date',
),
migrations.RemoveField(
model_name='blog',
name='mod_date',
),
migrations.AddField(
model_name='blog',
name='create_time',
field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='创建时间'),
),
migrations.AddField(
model_name='blog',
name='modify_time',
field=models.DateTimeField(auto_now=True, verbose_name='修改时间'),
),
]

@ -1,5 +1,5 @@
from django.db import models
from django.utils import timezone
# Create your models here.
@ -9,6 +9,9 @@ class Blog(models.Model):
verbose_name='作者')
content = models.TextField('内容')
create_time = models.DateTimeField('创建时间', default=timezone.now)
modify_time = models.DateTimeField('修改时间', auto_now=True)
def __str__(self):
return self.title

@ -1,12 +1,13 @@
from django.urls import path
import blog.views as blog_views
from blog.views.blogListView import BlogListView
from blog.views.blogDetailView import BlogDetailView
import blog.view as blog_views
urlpatterns = [
# path('list/', blog_views.blog_list, name='list'),
# path('detail/<int:blog_id>/', blog_views.blog_detail, name='detail')
path('list/', BlogListView.as_view(), ),
path('detail/<int:pk>/', BlogDetailView.as_view())
path('detail/<int:pk>/', BlogDetailView.as_view()),
path('index/',blog_views.index)
]

@ -1,4 +1,6 @@
from django.http import JsonResponse,HttpResponse
from django.shortcuts import render
from blog.models import Blog
from django.core.paginator import Paginator # 引入分页功能
@ -47,3 +49,7 @@ def blog_detail(request,blog_id):
]
}
return HttpResponse(resp.values())
def index(request):
return render(request, 'blog/index.html')

@ -12,8 +12,8 @@ class BlogListView(BaseListView):
return self.request.GET.get('page_size') or self.paginate_by
def render_to_response(self, context):
paginator = context['paginator']
current_page = context['page_obj']
paginator = context['paginator'] # 分页
current_page = context['page_obj'] # 页号
blogs = current_page.object_list
data = {

Binary file not shown.

@ -1,16 +1,5 @@
"""
Django settings for demo project.
Generated by 'django-admin startproject' using Django 4.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
@ -31,13 +20,16 @@ ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog'
'blog',
'myapi',
'snippets'
]
MIDDLEWARE = [
@ -107,19 +99,34 @@ AUTH_PASSWORD_VALIDATORS = [
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'static'),
)
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
],
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}

@ -18,5 +18,7 @@ from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls'))
path('blog/', include('blog.urls')),
path('myapi/',include('myapi.urls')),
path('',include('snippets.urls')),
]

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

@ -0,0 +1,6 @@
from django.apps import AppConfig
class MyapiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'myapi'

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

@ -0,0 +1,16 @@
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -0,0 +1,13 @@
from django.urls import path, include
from rest_framework import routers
from myapi import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

@ -0,0 +1,16 @@
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from myapi.serializers import UserSerializer,GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().order_by('date_joined')
serializer_class = UserSerializer
permissions_classes = [permissions.IsAuthenticated]
class GroupViewSet(viewsets.ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
permissions_classes = [permissions.IsAuthenticated]

@ -0,0 +1,5 @@
from django.contrib import admin
from snippets.models import Snippet
# Register your models here.
admin.site.register(Snippet)

@ -0,0 +1,6 @@
from django.apps import AppConfig
class SnippetsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'snippets'

File diff suppressed because one or more lines are too long

@ -0,0 +1,23 @@
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0],item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item,item) for item in get_all_styles()])
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100,blank=True,default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES,default='python',max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly',max_length=100)
def __str__(self):
return str(self.id) + ' ' + self.title + ' ' + self.code
class Meta:
ordering = ['created']

@ -0,0 +1,29 @@
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
# class SnippetSerializer(serializers.Serializer):
# id = serializers.IntegerField(read_only=True)
# title = serializers.CharField(required=False, allow_blank=True, max_length=100)
# code = serializers.CharField(style={'base_template': 'textarea.html'})
# linenos = serializers.BooleanField(required=False)
# language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,default='python')
# style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
#
# def create(self, validated_data):
# return Snippet.objects.create(**validated_data)
#
# def update(self, instance, validated_data):
# instance.title = validated_data.get('title', instance.title)
# instance.code = validated_data.get('code', instance.code)
# instance.linenos = validated_data.get('linenos', instance.linenos)
# instance.language = validated_data.get('language', instance.language)
# instance.style = validated_data.get('style', instance.style)
# instance.save()
# return instance
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ['id','created','title','code','linenos','language','style']

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -0,0 +1,12 @@
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets.views import SnippetView,SnippetDetailView
urlpatterns = [
path('snippets/',SnippetView.as_view()),
path('snippet/<int:pk>/',SnippetDetailView.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)

@ -0,0 +1,134 @@
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_204_NO_CONTENT, HTTP_201_CREATED
from django.http import Http404
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.views import APIView
# @csrf_exempt
# def snippet_list(request):
# if request.method == 'GET':
# snippets = Snippet.objects.all()
# serializer = SnippetSerializer(snippets,many=True)
# return JsonResponse(serializer.data,safe=False)
#
# elif request.method == 'POST':
# data = JSONParser().parse(request)
# serializer = SnippetSerializer(data=data) # 序列化成JSON格式
# if serializer.is_valid():
# serializer.save()
# return JsonResponse(serializer.data,status=HTTP_201_CREATED)
# return JsonResponse(serializer.errors, status=HTTP_400_BAD_REQUEST)
#
# @csrf_exempt
# def snippet_detail(request,pk):
# try:
# snippet = Snippet.objects.get(pk=pk)
# except Snippet.DoesNotExist:
# return HttpResponse(status=HTTP_400_BAD_REQUEST)
#
# if request.method == 'GET':
# serializer = SnippetSerializer(snippet)
# return JsonResponse(serializer.data)
#
# elif request.method == 'PUT':
# data = JSONParser().parse(request)
# serializer = SnippetSerializer(data=data)
# if serializer.is_valid():
# serializer.save()
# return JsonResponse(serializer.data)
# return JsonResponse(serializer.errors,status=HTTP_400_BAD_REQUEST)
#
# elif request.method == 'DELETE':
# snippet.delete()
# return HttpResponse(status=HTTP_204_NO_CONTENT)
# @api_view(['GET', 'POST'])
# def snippet_list(request, format=None):
# if request.method == 'GET':
# snippets = Snippet.objects.all()
# serializer = SnippetSerializer(snippets,many=True)
# return Response(serializer.data)
#
# elif request.method == 'POST':
# # 序列化成JSON格式
# serializer = SnippetSerializer(data=request.data)
# if serializer.is_valid():
# serializer.save()
# return Response(serializer.data, status=HTTP_201_CREATED)
# return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
#
# @api_view(['GET', 'PUT', 'DELETE'])
# def snippet_detail(request, pk, format=None):
# try:
# snippet = Snippet.objects.get(pk=pk)
# except Snippet.DoesNotExist:
# return Response(status=HTTP_400_BAD_REQUEST)
#
# if request.method == 'GET':
# serializer = SnippetSerializer(snippet)
# return Response(serializer.data)
#
# elif request.method == 'PUT':
# serializer = SnippetSerializer(snippet,data=request.data)
# if serializer.is_valid():
# serializer.save()
# return Response(serializer.data)
# return Response(serializer.errors,status=HTTP_400_BAD_REQUEST)
#
# elif request.method == 'DELETE':
# snippet.delete()
# return Response(status=HTTP_204_NO_CONTENT)
class SnippetView(APIView):
# 获取所有的snippet
def get(self, request, format=None):
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
# 创建一个新的snippet
def post(self, request, format=None):
serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=HTTP_201_CREATED)
return Response(status=HTTP_400_BAD_REQUEST)
class SnippetDetailView(APIView):
def get_object(self, pk):
try:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return Http404
# 查询某个snippet的数据
def get(self,request,pk,format=None):
snippet = self.get_object(pk)
serializer = SnippetSerializer(snippet)
return Response(serializer.data)
# 更新某个snippet的数据
def put(self,request,pk,format=None):
snippet = self.get_object(pk)
serializer = SnippetSerializer(snippet,data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(status=HTTP_400_BAD_REQUEST)
# 删除某一个snippet
def delete(self,request,pk,format=None):
snippet = self.get_object(pk)
snippet.delete()
return Response(status=HTTP_204_NO_CONTENT)

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

@ -0,0 +1,40 @@
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
h2 {
text-align: center;
}
.center {
display: flex;
align-items: center;
justify-content: center;
}
.info {
font-size: 20px;
font-weight: bold;
color: red;
}
</style>
</head>
<body>
<h2>blog欢迎界面</h2>
<div class="center">
<img src={% static 'images/apple.png' %}>
<ul>
{% for blog in blog_ %}
</ul>
</div>
</body>
</html>
Loading…
Cancel
Save