add changing profile config

This commit is contained in:
Tan, Kian-ting 2022-11-17 01:51:26 +08:00
parent 57b1a870a8
commit 0216bf49cb
8 changed files with 91 additions and 4 deletions

4
.gitignore vendored
View file

@ -129,3 +129,7 @@ dmypy.json
.pyre/ .pyre/
tmp/restart.txt tmp/restart.txt
.htaccess .htaccess
# Django
migrations/
media/img/

View file

@ -2,6 +2,9 @@ from django.db import models
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import UserManager from django.contrib.auth.models import UserManager
from django.utils import timezone from django.utils import timezone
import hashlib
class User(AbstractUser): class User(AbstractUser):
"""customized user field.""" """customized user field."""
@ -13,6 +16,12 @@ class User(AbstractUser):
url = models.URLField(max_length=200) # max to 200 char url = models.URLField(max_length=200) # max to 200 char
def upload_path(instance, orig_filename):
avatar_filename = hashlib.sha256(orig_filename.encode('utf-8')).hexdigest()[:10]
return f"img/profile/user_{instance.id}/{avatar_filename}"
avatar = models.ImageField(upload_to=upload_path)
desc = models.TextField() # description desc = models.TextField() # description

View file

@ -133,4 +133,10 @@ LOGIN_REDIRECT_URL = '/home'
AUTH_USER_MODEL = 'khaikang.User' AUTH_USER_MODEL = 'khaikang.User'
# timezone # timezone
USE_TZ = True USE_TZ = True
# Media files
MEDIA_URL = '/media/'
# media_storing path
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

View file

@ -17,9 +17,12 @@ from django.contrib import admin
from django.urls import path from django.urls import path
from django.urls import include from django.urls import include
from . import views from . import views
from . import settings
from django.conf.urls.static import static
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('account/config', views.user_config),
path('account/', include('django.contrib.auth.urls')), path('account/', include('django.contrib.auth.urls')),
path('home/', views.home, name='home'), path('home/', views.home, name='home'),
path('signup/', views.signup), path('signup/', views.signup),
@ -29,3 +32,5 @@ urlpatterns = [
path('api/get_previous_posts', views.api_get_previous_posts), path('api/get_previous_posts', views.api_get_previous_posts),
] ]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

View file

@ -10,6 +10,10 @@ from datetime import datetime
from django.http import JsonResponse from django.http import JsonResponse
from django.core import serializers from django.core import serializers
from django.db.models import Q from django.db.models import Q
import string
import random
from django import forms
def api_get_previous_posts(request): def api_get_previous_posts(request):
if request.method == 'POST': if request.method == 'POST':
@ -77,6 +81,14 @@ def api_post(request):
return HttpResponse(200, str(post_text)) return HttpResponse(200, str(post_text))
def signup(request): def signup(request):
small_letters_a_to_z = string.ascii_letters
honeypot_name_length = random.choice(range(14,18))
honeypot_name = ("").join([random.choice(small_letters_a_to_z) for letter in range(honeypot_name_length)])
try:
request.session['hnyp_name'] = request.session['hnyp_name']
except KeyError:
request.session['hnyp_name'] = honeypot_name
class KhaikangUserCreationForm(UserCreationForm): class KhaikangUserCreationForm(UserCreationForm):
def save(self, commit=True): def save(self, commit=True):
@ -88,12 +100,18 @@ def signup(request):
class Meta(UserCreationForm.Meta): class Meta(UserCreationForm.Meta):
model = User model = User
fields = UserCreationForm.Meta.fields + ('email',)
fields = UserCreationForm.Meta.fields + ('email', )
form = KhaikangUserCreationForm() form = KhaikangUserCreationForm()
honeypot_name = request.session['hnyp_name']
if request.method == "POST": if request.method == "POST":
form = KhaikangUserCreationForm(request.POST) form = KhaikangUserCreationForm(request.POST)
if request.POST.get(honeypot_name) != "":
return HttpResponse(200, "")
if form.is_valid(): if form.is_valid():
form.fields['shown_name'] = form.fields['username'] form.fields['shown_name'] = form.fields['username']
print(form.fields['shown_name']) print(form.fields['shown_name'])
@ -106,6 +124,34 @@ def signup(request):
form = KhaikangUserCreationForm() form = KhaikangUserCreationForm()
template = loader.get_template('signup.html') template = loader.get_template('signup.html')
return HttpResponse(template.render({'form': form, 'honeypot_name': honeypot_name}, request))
def user_config(request):
class UserConfigForm(forms.ModelForm):
class Meta:
model = User
fields = ('shown_name', 'avatar', 'desc', 'email')
current_user = User.objects.get(id=request.user.id)
if request.method == "POST":
form = UserConfigForm(request.POST,request.FILES, instance=current_user)
if form.is_valid():
form.save()
else:
pass
form = UserConfigForm(initial={'shown_name': request.user.shown_name,
'desc' : request.user.desc,
'url' : request.user.url,
'email' : request.user.email})
template = loader.get_template('user_config.html')
return HttpResponse(template.render({'form': form}, request)) return HttpResponse(template.render({'form': form}, request))
def home(request): def home(request):

View file

@ -4,7 +4,7 @@
{% get_current_timezone as TIME_ZONE %} {% get_current_timezone as TIME_ZONE %}
{% block headbar %} {% block headbar %}
{{ request.user.shown_name }} (<a href="/user/{{ request.user.username}}">My timeline</a>) - <a href="/user/config">Configs</a> - <a href="/account/logout">Log out</a> {{ request.user.shown_name }} (<a href="/user/{{ request.user.username}}">My timeline</a>) - <a href="/account/config">Configs</a> - <a href="/account/logout">Log out</a>
{% endblock %} {% endblock %}
{% block content %} {% block content %}
@ -27,7 +27,7 @@
<option value="private">Private</option> <option value="private">Private</option>
</select> </select>
<button id="submit_post" type="button" class="btn">Post!</button> <button id="submit_post" type="button" class="btn">Post!</button>
</form> </form>
<div id="public_timeline"> <div id="public_timeline">

View file

@ -5,6 +5,13 @@
<form method="post"> <form method="post">
{% csrf_token %} {% csrf_token %}
{{ form.as_p }} {{ form.as_p }}
Leave it blank: <input id ="{{ honeypot_name }}" type="text" name="{{ honeypot_name }}"><br>
<button type="submit">Sign up</button> <button type="submit">Sign up</button>
</form> </form>
<script type="text/javascript">
$ = (x) => document.getElementById(x);
$("{{ honeypot_name }}").style.display = 'none';
</script>
{% endblock %} {% endblock %}

View file

@ -0,0 +1,10 @@
{% extends "base_generic.html" %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Refresh</button>
</form>
{% endblock %}