Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Contribute to GitLab
Sign in
Toggle navigation
A
ap-11_django
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
1
Issues
1
List
Board
Labels
Milestones
Merge Requests
1
Merge Requests
1
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Давид Ли
ap-11_django
Commits
89cd7948
Commit
89cd7948
authored
Sep 23, 2023
by
Давид Ли
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
lesson 70
parent
7ef9d749
Hide whitespace changes
Inline
Side-by-side
Showing
7 changed files
with
117 additions
and
88 deletions
+117
-88
models.py
accounts/models.py
+3
-3
serializers.py
api/serializers.py
+39
-16
urls.py
api/urls.py
+9
-4
views.py
api/views.py
+28
-64
main.js
banana/js/main.js
+22
-0
settings.py
core/settings.py
+13
-0
base.html
web/templates/base.html
+3
-1
No files found.
accounts/models.py
View file @
89cd7948
from
django.contrib.auth.models
import
AbstractUser
from
django.contrib.auth.models
import
AbstractUser
,
UserManager
from
django.db
import
models
from
django.contrib.auth
import
get_user_model
class
UserManager
(
models
.
Manager
):
class
CustomUserManager
(
User
Manager
):
def
all
(
self
):
return
super
()
.
all
()
.
filter
(
is_active
=
True
)
...
...
@@ -16,7 +16,7 @@ class UserManager(models.Manager):
class
User
(
AbstractUser
):
objects
=
UserManager
()
objects
=
Custom
UserManager
()
class
Profile
(
models
.
Model
):
...
...
api/serializers.py
View file @
89cd7948
from
rest_framework
import
serializers
from
web.models
import
StatusChoices
,
Article
from
accounts.models
import
User
from
web.models
import
StatusChoices
,
Article
,
Comment
class
ArticleSerializer
(
serializers
.
ModelSerializer
):
...
...
@@ -19,21 +20,43 @@ class ArticlePartialUpdateSerializer(serializers.ModelSerializer):
fields
=
[
'id'
,
'title'
,
'text'
,
'author'
,
'status'
,
'created_at'
,
'updated_at'
]
class
ArticleSerializerOld
(
serializers
.
Serializer
):
id
=
serializers
.
IntegerField
(
read_only
=
True
)
title
=
serializers
.
CharField
(
max_length
=
200
,
required
=
True
)
text
=
serializers
.
CharField
(
max_length
=
3000
,
required
=
True
)
author
=
serializers
.
PrimaryKeyRelatedField
(
read_only
=
True
)
status
=
serializers
.
ChoiceField
(
choices
=
StatusChoices
.
choices
,
required
=
False
)
created_at
=
serializers
.
DateTimeField
(
read_only
=
True
)
updated_at
=
serializers
.
DateTimeField
(
read_only
=
True
)
class
AuthorGetSerializer
(
serializers
.
ModelSerializer
):
class
Meta
:
model
=
User
fields
=
[
'username'
,
'email'
]
def
create
(
self
,
validated_data
):
return
Article
.
objects
.
create
(
**
validated_data
)
class
CommentGetSerializer
(
serializers
.
ModelSerializer
):
author
=
AuthorGetSerializer
()
class
Meta
:
model
=
Comment
fields
=
[
'text'
,
'author'
,
'created_at'
,
'updated_at'
]
def
update
(
self
,
instance
,
validated_data
):
for
k
,
v
in
validated_data
.
items
():
setattr
(
instance
,
k
,
v
)
instance
.
save
()
return
instance
class
ArticleGetSerializer
(
serializers
.
ModelSerializer
):
author
=
AuthorGetSerializer
()
comments
=
CommentGetSerializer
(
many
=
True
)
class
Meta
:
model
=
Article
fields
=
[
'id'
,
'title'
,
'text'
,
'author'
,
'status'
,
'comments'
,
'created_at'
,
'updated_at'
,
]
#
# class CommentsCreateSerializer(serializers.ModelSerializer):
# class Meta:
# model = Comment
# fields = ['text', 'author']
# class ArticleCreateSerializer(serializers.ModelSerializer):
# comments = CommentsCreateSerializer(many=True)
#
# class Meta:
# model = Article
# fields = ['title', 'text', 'author', 'status', 'comments']
api/urls.py
View file @
89cd7948
from
django.urls
import
path
from
django.urls
import
path
,
include
from
rest_framework
import
routers
from
rest_framework.authtoken.views
import
obtain_auth_token
from
api
import
views
router
=
routers
.
DefaultRouter
()
router
.
register
(
'article'
,
views
.
ArticleViewSet
)
urlpatterns
=
[
path
(
'echo'
,
views
.
echo_view
),
path
(
'articles'
,
views
.
ArticlesView
.
as_view
()),
path
(
'articles/<int:id_>'
,
views
.
ArticleUpdateView
.
as_view
())
path
(
''
,
include
(
router
.
urls
)),
path
(
'login'
,
obtain_auth_token
),
]
api/views.py
View file @
89cd7948
import
json
from
django.http
import
JsonResponse
from
rest_framework.views
import
APIView
from
datetime
import
datetime
from
django.views.decorators.csrf
import
ensure_csrf_cookie
from
rest_framework.viewsets
import
ModelViewSet
from
rest_framework
import
permissions
from
api
import
serializers
from
web.models
import
Article
@
ensure_csrf_cookie
def
echo_view
(
request
,
*
args
,
**
kwargs
):
answer
=
{
'time'
:
datetime
.
now
()
.
strftime
(
'
%
Y-
%
m-
%
d
%
H:
%
M:
%
S'
),
'method'
:
request
.
method
,
class
ArticleViewSet
(
ModelViewSet
):
queryset
=
Article
.
objects
.
all
()
serializer_class
=
serializers
.
ArticleSerializer
lookup_url_kwarg
=
'id'
method_serializers
=
{
'get'
:
serializers
.
ArticleGetSerializer
,
'patch'
:
serializers
.
ArticlePartialUpdateSerializer
,
}
print
(
request
.
body
)
if
request
.
method
==
'POST'
:
if
request
.
body
:
answer
[
'content'
]
=
json
.
loads
(
request
.
body
)
return
JsonResponse
(
answer
)
class
ArticlesView
(
APIView
):
def
get
(
self
,
request
,
*
args
,
**
kwargs
):
qs
=
Article
.
objects
.
all
()
serializer
=
serializers
.
ArticleSerializer
(
qs
,
many
=
True
)
return
JsonResponse
(
serializer
.
data
,
safe
=
False
)
def
post
(
self
,
request
,
*
args
,
**
kwargs
):
data
=
json
.
loads
(
request
.
body
)
serializer
=
serializers
.
ArticleSerializer
(
data
=
data
)
if
serializer
.
is_valid
():
serializer
.
save
()
return
JsonResponse
(
serializer
.
data
,
safe
=
False
)
else
:
return
JsonResponse
(
status
=
400
,
data
=
{
'errors'
:
serializer
.
error_messages
})
class
ArticleUpdateView
(
APIView
):
def
update
(
self
,
request
,
id_
,
partial
:
bool
=
True
):
serializer
=
serializers
.
ArticleSerializer
if
partial
:
serializer
=
serializers
.
ArticlePartialUpdateSerializer
instance
=
Article
.
objects
.
get
(
id
=
id_
)
data
=
json
.
loads
(
request
.
body
)
serializer
=
serializer
(
data
=
data
,
instance
=
instance
)
if
serializer
.
is_valid
():
serializer
.
save
()
return
JsonResponse
(
serializer
.
data
,
safe
=
True
)
else
:
return
JsonResponse
(
status
=
400
,
data
=
{
'errors'
:
serializer
.
error_messages
})
def
put
(
self
,
request
,
id_
:
int
,
*
args
,
**
kwargs
):
return
self
.
update
(
request
,
id_
,
partial
=
False
)
def
patch
(
self
,
request
,
id_
,
*
args
,
**
kwargs
):
return
self
.
update
(
request
,
id_
)
permission_classes
=
(
permissions
.
AllowAny
,
permissions
.
IsAdminUser
,
permissions
.
IsAuthenticatedOrReadOnly
,
permissions
.
DjangoModelPermissions
,
permissions
.
DjangoModelPermissionsOrAnonReadOnly
,
)
def
get_permissions
(
self
):
if
self
.
request
.
method
in
permissions
.
SAFE_METHODS
:
return
[]
return
super
()
.
get_permissions
()
def
get_serializer_class
(
self
):
method
=
self
.
request
.
method
.
lower
()
if
method
in
self
.
method_serializers
:
return
self
.
method_serializers
.
get
(
method
)
return
self
.
serializer_class
banana/js/main.js
0 → 100644
View file @
89cd7948
$
(
'#articlesMain'
).
on
(
'click'
,
async
function
(
event
)
{
event
.
preventDefault
()
let
token
await
$
.
ajax
({
url
:
'/api/login'
,
method
:
'post'
,
data
:
JSON
.
stringify
({
username
:
'admin'
,
password
:
'root'
}),
contentType
:
'application/json'
})
.
then
(
function
(
resp
)
{
token
=
resp
.
token
})
await
$
.
ajax
({
url
:
'/api/article'
,
method
:
'get'
,
headers
:
{
Authorization
:
'Token '
+
token
}
}).
then
(
resp
=>
console
.
log
(
resp
))
})
core/settings.py
View file @
89cd7948
...
...
@@ -42,6 +42,7 @@ INSTALLED_APPS = [
'django_extensions'
,
'rest_framework'
,
'rest_framework.authtoken'
,
'web'
,
'accounts'
,
'api'
,
...
...
@@ -151,3 +152,15 @@ LOGIN_URL = 'login'
# LOGOUT_REDIRECT_URL = 'main_page'
faker
=
Faker
()
# REST FRAMEWORK
REST_FRAMEWORK
=
{
'DEFAULT_AUTHENTICATION_CLASSES'
:
(
'rest_framework.authentication.TokenAuthentication'
,
),
'DEFAULT_PERMISSION_CLASSES'
:
(
'rest_framework.permissions.IsAuthenticated'
,
)
}
web/templates/base.html
View file @
89cd7948
...
...
@@ -10,12 +10,14 @@
integrity=
"sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
crossorigin=
"anonymous"
referrerpolicy=
"no-referrer"
/>
<link
rel=
"stylesheet"
href=
"{% static 'css/styles.css' %}"
>
<script
defer
src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"
integrity=
"sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
crossorigin=
"anonymous"
referrerpolicy=
"no-referrer"
></script>
<script
src=
"{% static 'js/main.js' %}"
defer
></script>
<title>
Title
</title>
</head>
<body>
<nav
class=
"navbar navbar-expand-lg navbar-light bg-light"
>
<div
class=
"container"
>
<a
class=
"navbar-brand"
href=
"{% url 'main_page' %}"
>
Articles
</a>
<a
class=
"navbar-brand"
href=
"{% url 'main_page' %}"
id=
"articlesMain"
>
Articles
</a>
<button
class=
"navbar-toggler"
type=
"button"
data-bs-toggle=
"collapse"
data-bs-target=
"#navbarNav"
aria-controls=
"navbarNav"
aria-expanded=
"false"
aria-label=
"Toggle navigation"
>
<span
class=
"navbar-toggler-icon"
></span>
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment