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
Show 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.db
import
models
from
django.contrib.auth
import
get_user_model
from
django.contrib.auth
import
get_user_model
class
UserManager
(
models
.
Manager
):
class
CustomUserManager
(
User
Manager
):
def
all
(
self
):
def
all
(
self
):
return
super
()
.
all
()
.
filter
(
is_active
=
True
)
return
super
()
.
all
()
.
filter
(
is_active
=
True
)
...
@@ -16,7 +16,7 @@ class UserManager(models.Manager):
...
@@ -16,7 +16,7 @@ class UserManager(models.Manager):
class
User
(
AbstractUser
):
class
User
(
AbstractUser
):
objects
=
UserManager
()
objects
=
Custom
UserManager
()
class
Profile
(
models
.
Model
):
class
Profile
(
models
.
Model
):
...
...
api/serializers.py
View file @
89cd7948
from
rest_framework
import
serializers
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
):
class
ArticleSerializer
(
serializers
.
ModelSerializer
):
...
@@ -19,21 +20,43 @@ class ArticlePartialUpdateSerializer(serializers.ModelSerializer):
...
@@ -19,21 +20,43 @@ class ArticlePartialUpdateSerializer(serializers.ModelSerializer):
fields
=
[
'id'
,
'title'
,
'text'
,
'author'
,
'status'
,
'created_at'
,
'updated_at'
]
fields
=
[
'id'
,
'title'
,
'text'
,
'author'
,
'status'
,
'created_at'
,
'updated_at'
]
class
ArticleSerializerOld
(
serializers
.
Serializer
):
class
AuthorGetSerializer
(
serializers
.
ModelSerializer
):
id
=
serializers
.
IntegerField
(
read_only
=
True
)
class
Meta
:
title
=
serializers
.
CharField
(
max_length
=
200
,
required
=
True
)
model
=
User
text
=
serializers
.
CharField
(
max_length
=
3000
,
required
=
True
)
fields
=
[
'username'
,
'email'
]
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
)
def
create
(
self
,
validated_data
):
class
CommentGetSerializer
(
serializers
.
ModelSerializer
):
return
Article
.
objects
.
create
(
**
validated_data
)
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
()
class
ArticleGetSerializer
(
serializers
.
ModelSerializer
):
return
instance
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
from
api
import
views
router
=
routers
.
DefaultRouter
()
router
.
register
(
'article'
,
views
.
ArticleViewSet
)
urlpatterns
=
[
urlpatterns
=
[
path
(
'echo'
,
views
.
echo_view
),
path
(
''
,
include
(
router
.
urls
)),
path
(
'articles'
,
views
.
ArticlesView
.
as_view
()),
path
(
'login'
,
obtain_auth_token
),
path
(
'articles/<int:id_>'
,
views
.
ArticleUpdateView
.
as_view
())
]
]
api/views.py
View file @
89cd7948
import
json
from
rest_framework.viewsets
import
ModelViewSet
from
rest_framework
import
permissions
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
api
import
serializers
from
api
import
serializers
from
web.models
import
Article
from
web.models
import
Article
@
ensure_csrf_cookie
class
ArticleViewSet
(
ModelViewSet
):
def
echo_view
(
request
,
*
args
,
**
kwargs
):
queryset
=
Article
.
objects
.
all
()
answer
=
{
serializer_class
=
serializers
.
ArticleSerializer
'time'
:
datetime
.
now
()
.
strftime
(
'
%
Y-
%
m-
%
d
%
H:
%
M:
%
S'
),
lookup_url_kwarg
=
'id'
'method'
:
request
.
method
,
method_serializers
=
{
'get'
:
serializers
.
ArticleGetSerializer
,
'patch'
:
serializers
.
ArticlePartialUpdateSerializer
,
}
}
permission_classes
=
(
print
(
request
.
body
)
permissions
.
AllowAny
,
permissions
.
IsAdminUser
,
if
request
.
method
==
'POST'
:
permissions
.
IsAuthenticatedOrReadOnly
,
if
request
.
body
:
permissions
.
DjangoModelPermissions
,
answer
[
'content'
]
=
json
.
loads
(
request
.
body
)
permissions
.
DjangoModelPermissionsOrAnonReadOnly
,
)
return
JsonResponse
(
answer
)
def
get_permissions
(
self
):
if
self
.
request
.
method
in
permissions
.
SAFE_METHODS
:
class
ArticlesView
(
APIView
):
return
[]
def
get
(
self
,
request
,
*
args
,
**
kwargs
):
return
super
()
.
get_permissions
()
qs
=
Article
.
objects
.
all
()
serializer
=
serializers
.
ArticleSerializer
(
qs
,
many
=
True
)
def
get_serializer_class
(
self
):
return
JsonResponse
(
serializer
.
data
,
safe
=
False
)
method
=
self
.
request
.
method
.
lower
()
if
method
in
self
.
method_serializers
:
def
post
(
self
,
request
,
*
args
,
**
kwargs
):
return
self
.
method_serializers
.
get
(
method
)
data
=
json
.
loads
(
request
.
body
)
serializer
=
serializers
.
ArticleSerializer
(
data
=
data
)
return
self
.
serializer_class
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_
)
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 = [
...
@@ -42,6 +42,7 @@ INSTALLED_APPS = [
'django_extensions'
,
'django_extensions'
,
'rest_framework'
,
'rest_framework'
,
'rest_framework.authtoken'
,
'web'
,
'web'
,
'accounts'
,
'accounts'
,
'api'
,
'api'
,
...
@@ -151,3 +152,15 @@ LOGIN_URL = 'login'
...
@@ -151,3 +152,15 @@ LOGIN_URL = 'login'
# LOGOUT_REDIRECT_URL = 'main_page'
# LOGOUT_REDIRECT_URL = 'main_page'
faker
=
Faker
()
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 @@
...
@@ -10,12 +10,14 @@
integrity=
"sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
integrity=
"sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
crossorigin=
"anonymous"
referrerpolicy=
"no-referrer"
/>
crossorigin=
"anonymous"
referrerpolicy=
"no-referrer"
/>
<link
rel=
"stylesheet"
href=
"{% static 'css/styles.css' %}"
>
<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>
<title>
Title
</title>
</head>
</head>
<body>
<body>
<nav
class=
"navbar navbar-expand-lg navbar-light bg-light"
>
<nav
class=
"navbar navbar-expand-lg navbar-light bg-light"
>
<div
class=
"container"
>
<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"
<button
class=
"navbar-toggler"
type=
"button"
data-bs-toggle=
"collapse"
data-bs-target=
"#navbarNav"
aria-controls=
"navbarNav"
aria-expanded=
"false"
aria-label=
"Toggle navigation"
>
aria-controls=
"navbarNav"
aria-expanded=
"false"
aria-label=
"Toggle navigation"
>
<span
class=
"navbar-toggler-icon"
></span>
<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