add: profile avatar
This commit is contained in:
parent
910644a804
commit
9b6c5547f0
@ -13,7 +13,7 @@ class EditView(APIView):
|
|||||||
authentication_classes = (SessionAuthentication,)
|
authentication_classes = (SessionAuthentication,)
|
||||||
|
|
||||||
def get(self, request: HttpRequest):
|
def get(self, request: HttpRequest):
|
||||||
return Response({"username": request.user.username})
|
return Response({"username": request.user.username, "id": request.user.pk})
|
||||||
|
|
||||||
def patch(self, request: HttpRequest):
|
def patch(self, request: HttpRequest):
|
||||||
data: dict = request.data
|
data: dict = request.data
|
||||||
|
@ -13,4 +13,6 @@ class LoggedView(APIView):
|
|||||||
authentication_classes = (SessionAuthentication,)
|
authentication_classes = (SessionAuthentication,)
|
||||||
|
|
||||||
def get(self, request: HttpRequest):
|
def get(self, request: HttpRequest):
|
||||||
return Response(str(request.user.is_authenticated), status=status.HTTP_200_OK)
|
if (request.user.is_authenticated):
|
||||||
|
return Response({'id': request.user.pk}, status=status.HTTP_200_OK)
|
||||||
|
return Response('false', status=status.HTTP_200_OK)
|
@ -20,4 +20,4 @@ class LoginView(APIView):
|
|||||||
if user is None:
|
if user is None:
|
||||||
return Response({'user': ['Username or password wrong.']}, status.HTTP_200_OK)
|
return Response({'user': ['Username or password wrong.']}, status.HTTP_200_OK)
|
||||||
login(request, user)
|
login(request, user)
|
||||||
return Response('user connected', status=status.HTTP_200_OK)
|
return Response({'id': user.pk}, status=status.HTTP_200_OK)
|
@ -1,4 +1,5 @@
|
|||||||
import { Account } from "./account.js";
|
import { Account } from "./account.js";
|
||||||
|
import { Profile } from "./profile.js";
|
||||||
|
|
||||||
function getCookie(name)
|
function getCookie(name)
|
||||||
{
|
{
|
||||||
@ -73,12 +74,26 @@ class Client
|
|||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async _patch_file(uri, file)
|
||||||
|
{
|
||||||
|
let response = await fetch(this._url + uri, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
"X-CSRFToken": getCookie("csrftoken"),
|
||||||
|
},
|
||||||
|
body: file,
|
||||||
|
});
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
async login(username, password)
|
async login(username, password)
|
||||||
{
|
{
|
||||||
let response = await this._post("/api/accounts/login", {username: username, password: password})
|
let response = await this._post("/api/accounts/login", {username: username, password: password})
|
||||||
let data = await response.json();
|
let data = await response.json();
|
||||||
if (data == "user connected")
|
if (data.id != undefined)
|
||||||
{
|
{
|
||||||
|
this.me = new Profile(this)
|
||||||
|
await this.me.init(data.id)
|
||||||
this.logged = true;
|
this.logged = true;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -95,7 +110,13 @@ class Client
|
|||||||
{
|
{
|
||||||
let response = await this._get("/api/accounts/logged");
|
let response = await this._get("/api/accounts/logged");
|
||||||
let data = await response.json();
|
let data = await response.json();
|
||||||
return data === "True";
|
|
||||||
|
if (data.id !== undefined)
|
||||||
|
{
|
||||||
|
this.me = new Profile(this)
|
||||||
|
await this.me.init(data.id)
|
||||||
|
}
|
||||||
|
return data.id !== undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
34
frontend/static/js/api/profile.js
Normal file
34
frontend/static/js/api/profile.js
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
class Profile
|
||||||
|
{
|
||||||
|
constructor (client)
|
||||||
|
{
|
||||||
|
this.client = client;
|
||||||
|
this.username = undefined;
|
||||||
|
this.avatar_url = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
async init(id)
|
||||||
|
{
|
||||||
|
let response = await this.client._get(`/api/profiles/${id}`);
|
||||||
|
let response_data = await response.json();
|
||||||
|
|
||||||
|
this.id = id;
|
||||||
|
this.username = response_data.username;
|
||||||
|
this.avatar_url = response_data.avatar_url;
|
||||||
|
}
|
||||||
|
|
||||||
|
async change_avatar(form_data)
|
||||||
|
{
|
||||||
|
let response = await this.client._patch_file(`/api/profiles/${this.id}`, form_data);
|
||||||
|
let response_data = await response.json()
|
||||||
|
|
||||||
|
return response_data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async setData (data)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export {Profile}
|
@ -91,18 +91,31 @@ export default class extends AbstractAuthentificateView
|
|||||||
if (error_display != null)
|
if (error_display != null)
|
||||||
error_display.innerHTML = response_data[error_field];
|
error_display.innerHTML = response_data[error_field];
|
||||||
});
|
});
|
||||||
|
let avatar = document.getElementById("avatar");
|
||||||
|
|
||||||
|
if (avatar.files[0] !== undefined)
|
||||||
|
{
|
||||||
|
let form_data = new FormData();
|
||||||
|
form_data.append("file", avatar.files[0]);
|
||||||
|
await client.me.change_avatar(form_data)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getHtml()
|
async getHtml()
|
||||||
{
|
{
|
||||||
return `
|
return `
|
||||||
<h1>ME</h1>
|
<h1>ME</h1>
|
||||||
<input type=text placeholder="username" id="username">
|
<div class="accounts">
|
||||||
|
<input type="text" placeholder="username" id="username">
|
||||||
<span id="error_username"></span>
|
<span id="error_username"></span>
|
||||||
<input type=password placeholder="new password" id="new_password">
|
<input type=password placeholder="new password" id="new_password">
|
||||||
<span id="error_new_password"></span>
|
<span id="error_new_password"></span>
|
||||||
<input type=password placeholder="current password" id="current_password">
|
<input type=password placeholder="current password" id="current_password">
|
||||||
<span id="error_current_password"></span>
|
<span id="error_current_password"></span>
|
||||||
|
</div>
|
||||||
|
<div class="profile">
|
||||||
|
<input type="file" placeholder="username" id="avatar" accept="image/png, image/jpeg">
|
||||||
|
</div>
|
||||||
<input type="button" value="Save" id="save-button">
|
<input type="button" value="Save" id="save-button">
|
||||||
<span id="error_save"></span>
|
<span id="error_save"></span>
|
||||||
<input type="button" value="Delete" id="delete-button">
|
<input type="button" value="Delete" id="delete-button">
|
||||||
|
@ -3,11 +3,15 @@ from django.db import models
|
|||||||
from django.contrib.auth.models import User
|
from django.contrib.auth.models import User
|
||||||
from django.db.models.signals import post_save
|
from django.db.models.signals import post_save
|
||||||
from django.dispatch import receiver
|
from django.dispatch import receiver
|
||||||
|
from django.conf import settings
|
||||||
|
|
||||||
|
def upload_to(instance, filename: str):
|
||||||
|
return f"./profiles/static/avatars/{instance.pk}.{filename.split('.')[1]}"
|
||||||
|
|
||||||
# Create your models here.
|
# Create your models here.
|
||||||
class ProfileModel(models.Model):
|
class ProfileModel(models.Model):
|
||||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
||||||
title = models.CharField(max_length=40)
|
avatar_url = models.ImageField(upload_to=upload_to, default="../static/avatars/default.avif") #blank=True, null=True)
|
||||||
|
|
||||||
@receiver(post_save, sender=User)
|
@receiver(post_save, sender=User)
|
||||||
def on_user_created(sender, instance, created, **kwargs):
|
def on_user_created(sender, instance, created, **kwargs):
|
||||||
|
12
profiles/serializers.py
Normal file
12
profiles/serializers.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
from rest_framework import serializers
|
||||||
|
from .models import ProfileModel
|
||||||
|
|
||||||
|
class ProfileSerializer(serializers.ModelSerializer):
|
||||||
|
|
||||||
|
username = serializers.ReadOnlyField(source='user.username')
|
||||||
|
#creator_id = serializers.ReadOnlyField(source='user.pk')
|
||||||
|
avatar_url = serializers.ImageField(required=False)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = ProfileModel
|
||||||
|
fields = ["username", "avatar_url"]
|
BIN
profiles/static/avatars/1.JPG
Normal file
BIN
profiles/static/avatars/1.JPG
Normal file
Binary file not shown.
After Width: | Height: | Size: 823 KiB |
BIN
profiles/static/avatars/default.avif
Normal file
BIN
profiles/static/avatars/default.avif
Normal file
Binary file not shown.
@ -1 +0,0 @@
|
|||||||
PROFILE_NOT_FOUND = "Profile Not Found"
|
|
@ -1,7 +1,10 @@
|
|||||||
from django.urls import path
|
from django.urls import path
|
||||||
|
from django.conf import settings
|
||||||
|
from django.conf.urls.static import static
|
||||||
|
|
||||||
from . import views
|
from . import viewsets
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path("<int:pk>", views.ProfileView.as_view(), name="profile_page"),
|
path("<int:pk>", viewsets.ProfileViewSet.as_view({'get': 'retrieve', 'patch': 'partial_update'}), name="profile_page"),
|
||||||
]
|
#path("me", viewsets.ProfileViewSet.as_view(), name="my_profile_page"),
|
||||||
|
] + static("/static/avatars/", document_root="./avatars")
|
@ -1,19 +0,0 @@
|
|||||||
from django.http import HttpRequest
|
|
||||||
from rest_framework.views import APIView
|
|
||||||
from rest_framework.response import Response
|
|
||||||
from rest_framework import permissions, status
|
|
||||||
|
|
||||||
from .models import ProfileModel
|
|
||||||
|
|
||||||
# Create your views here.
|
|
||||||
class ProfileView(APIView):
|
|
||||||
permission_classes = (permissions.AllowAny,)
|
|
||||||
|
|
||||||
def get(self, request: HttpRequest, pk: int):
|
|
||||||
|
|
||||||
profile: ProfileModel = ProfileModel.objects.get(pk=pk)
|
|
||||||
if (profile is None):
|
|
||||||
return Response(status=status.HTTP_404_NOT_FOUND)
|
|
||||||
|
|
||||||
return Response(status=status.HTTP_200_OK, data={'name': profile.user.username,
|
|
||||||
'title': profile.title})
|
|
33
profiles/viewsets.py
Normal file
33
profiles/viewsets.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
from rest_framework import permissions
|
||||||
|
from rest_framework.parsers import MultiPartParser, FormParser
|
||||||
|
from rest_framework import permissions, status
|
||||||
|
from rest_framework import viewsets
|
||||||
|
from rest_framework.response import Response
|
||||||
|
|
||||||
|
|
||||||
|
from django.db.models import QuerySet
|
||||||
|
|
||||||
|
from .serializers import ProfileSerializer
|
||||||
|
from .models import ProfileModel
|
||||||
|
|
||||||
|
class ProfileViewSet(viewsets.ModelViewSet):
|
||||||
|
queryset = ProfileModel.objects.order_by('-pk')
|
||||||
|
serializer_class = ProfileSerializer
|
||||||
|
parser_classes = (MultiPartParser, FormParser)
|
||||||
|
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
|
||||||
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
serializer.save(user=self.request.user)
|
||||||
|
|
||||||
|
def perform_update(self, serializer):
|
||||||
|
query: QuerySet = ProfileModel.objects.filter(pk=self.request.user.pk)
|
||||||
|
if (not query.exists()):
|
||||||
|
return Response("profile not found", status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
profile: ProfileModel = ProfileModel.objects.get(pk=self.request.user.pk)
|
||||||
|
avatar = self.request.data.get("file", None)
|
||||||
|
if (avatar is not None):
|
||||||
|
print(profile.avatar_url.name)
|
||||||
|
if (profile.avatar_url.name != "default.avif"):
|
||||||
|
profile.avatar_url.storage.delete(profile.avatar_url.name)
|
||||||
|
profile.avatar_url = avatar
|
||||||
|
profile.save()
|
@ -10,6 +10,8 @@ For the full list of settings and their values, see
|
|||||||
https://docs.djangoproject.com/en/4.2/ref/settings/
|
https://docs.djangoproject.com/en/4.2/ref/settings/
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||||
|
Loading…
Reference in New Issue
Block a user