Now, redis is used in Django 🎉

master
Corentin LEMAIRE 8 months ago
parent ebf3ce2776
commit f639d779b4

@ -37,7 +37,7 @@ INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'redis',
'redis_app',
'debug_toolbar',
]
@ -106,6 +106,16 @@ AUTH_PASSWORD_VALIDATORS = [
},
]
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://0.0.0.0:6379/",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient"
},
}
}
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

@ -20,6 +20,6 @@ import debug_toolbar
urlpatterns = [
path('admin/', admin.site.urls),
path('redis/', include('redis.urls')),
path('redis/', include('redis_app.urls')),
path('__debug__/', include(debug_toolbar.urls))
]

@ -22,6 +22,12 @@ Now, you can install Django by doing `pipenv install django`.
This will create you a virtual environment and install Django into it.
### Django-Redis installation
Type `pip install redis` to install redis.
To run the redis server, type `docker run -d --name redis-stack -p 6379:6379 redis/redis-stack:latest`
## Configuration
In the repo folder, type `pipenv shell`. This will lead you to the venv of the project.

@ -1,9 +0,0 @@
<html>
<body>
{% if name %}
<h1>Welcome {{ name }}!</h1>
{% else %}
<h1>Welcome young padawan!</h1>
{% endif %}
</body>
</html>

@ -1,6 +0,0 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home')
]

@ -1,4 +0,0 @@
from django.shortcuts import render
def home(request):
return render(request, 'home.html', {'name': 'Plheyer'})

@ -0,0 +1,6 @@
from django.contrib import admin
from .models import Course, Person
admin.site.register(Course)
admin.site.register(Person)

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

@ -23,10 +23,19 @@ class Course(models.Model):
summary = models.CharField(max_length=1000)
level = models.CharField(choices=LEVELS_CHOICES, default=BEGINNER, max_length=12)
places = models.IntegerField(default=0)
teacher = models.ForeignKey('Person', on_delete=models.CASCADE, related_name='teacher', limit_choices_to={'role': 'Teacher'})
students = models.ManyToManyField('Person', blank=True, related_name='students', limit_choices_to={'role': 'Student'})
# Utils function
def __str__(self):
return self.title + " " + truncate_string(self.summary)
def getLevel(self):
if (self.level == "B"):
return "Beginner"
if (self.level == "I"):
return "Intermediate"
return "Advanced"
# Student or teacher, what differs? For teachers, courses will be the courses taught, and for students, the courses followed.
# However, this only deferrs into a 'role'. If it's a teacher, then the courses are taught, else they are followed.
@ -42,9 +51,18 @@ class Person(models.Model):
# Defining our attributes which equal the Course table's columns
name = models.CharField(max_length=200)
courses = models.ForeignKey(Course, on_delete=models.CASCADE)
role = models.CharField(choices=ROLE_CHOICES, default=STUDENT, max_length=7)
# Return the courses list for the Person
# If it's a teacher, returns all courses he teaches
# If it's a student, returns all courses he follows
@property
def courses(self):
if (self.role == "Student"):
return [course for course in Course.objects.all() if self in course.students.all()]
return Course.objects.filter(teacher=self)
# Utils function
def __str__(self):
return self.name + " is a " + self.role
return self.name + " is a " + self.role

@ -0,0 +1,12 @@
<html>
<body>
<h1>Courses for {{ person.name }}</h1>
{% if courses %}
{% for course in courses %}
<a href="{% url 'details' course.id %}">{{ course.title }}</a>
{% endfor %}
{% else %}
<p>No course yet</p>
{% endif %}
</body>
</html>

@ -0,0 +1,18 @@
<html>
<body>
{% if course %}
<h1>Welcome in the course {{ course.title }}!</h1>
<p>
{{ course.summary }}
</p>
<p>
This course is for {{ course.getLevel }} students
</p>
<p>
There's only {{ course.places }} places
</p>
{% else %}
<h1>No course found!</h1>
{% endif %}
</body>
</html>

@ -0,0 +1,13 @@
<html>
<body>
{% if person != '' %}
<h1>Welcome {{ person.name }}!</h1>
{% else %}
<h1>Welcome young padawan!</h1>
{% endif %}
<a href="{% url 'login_form' %}">Login</a>
<a href="{% url 'register_form' %}">Register</a>
<a href="{% url 'courses' %}">Courses</a>
<a href="{% url 'profile' %}">Profile</a>
</body>
</html>

@ -0,0 +1,20 @@
<html>
<body>
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<fieldset>
<legend><h1>Login</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<label for="name">Name</label><br>
<input name="name" id="name" value="{{ person.name }}"><br/>
<label for="role">Role</label><br>
<select name="role" id="role">
<option value="Student" {% if person.role == 'Student' %}selected{% endif %}>Student</option>
<option value="Teacher" {% if person.role == 'Teacher' %}selected{% endif %}>Teacher</option>
</select>
</fieldset>
<input type="submit" value="Login">
<a href="{% url 'register_form' %}">Register</a>
</form>
</body>
</html>

@ -0,0 +1,19 @@
<html>
<body>
<form action="{% url 'change_profile' %}" method="POST">
{% csrf_token %}
<fieldset>
<legend><h1>Profile</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<label for="name">Name</label><br>
<input name="name" id="name" value="{{ person.name }}"><br/>
<label for="role">Role</label><br>
<select name="role" id="role">
<option value="Student" {% if person.role == 'Student' %}selected{% endif %}>Student</option>
<option value="Teacher" {% if person.role == 'Teacher' %}selected{% endif %}>Teacher</option>
</select>
</fieldset>
<input type="submit" value="Update">
</form>
</body>
</html>

@ -0,0 +1,19 @@
<html>
<body>
<form action="{% url 'register' %}" method="POST">
{% csrf_token %}
<fieldset>
<legend><h1>Register</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<label for="name">Name</label><br>
<input name="name" id="name" value="{{ person.name }}"><br/>
<label for="role">Role</label><br>
<select name="role" id="role">
<option value="Student" {% if person.role == 'Student' %}selected{% endif %}>Student</option>
<option value="Teacher" {% if person.role == 'Teacher' %}selected{% endif %}>Teacher</option>
</select>
</fieldset>
<input type="submit" value="Register">
</form>
</body>
</html>

@ -0,0 +1,7 @@
<html>
<body>
{% for user in users %}
{{ user }}
{% endfor %}
</body>
</html>

@ -0,0 +1,15 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('<int:course_id>', views.details, name='details'),
path('register_form', views.register_form, name='register_form'),
path('register', views.register, name='register'),
path('login_form', views.login_form, name='login_form'),
path('login', views.login, name='login'),
path('courses', views.courses, name='courses'),
path('change_profile', views.change_profile, name='change_profile'),
path('profile', views.profile, name='profile'),
path('logout', views.logout, name='logout'),
]

@ -0,0 +1,23 @@
# Create indexes for the search feature
def create_index(redis_connection):
# Testing if the index is already created not to throw an exception when we launch the app multiple times (and i swear it was useful when I devlopped)
# Thanks to the great RediSearch module of Redis Stack (I'll repeat the Redis doc) I can implement a search feature on every property indexed (except on students list for confidentiality of course)
# So here, I'm indexing every member of my model because I want to expose every property to let user search in every property (except on students list for confidentiality of course)
# I'm using hset/hget... because it's my favorite one + it's a fast storage data type
redis_connection.execute_command('FT.DROPINDEX', 'idx:courses')
redis_connection.execute_command('FT.CREATE', 'idx:courses', 'ON', 'HASH', 'PREFIX', '1', 'course:',
'SCHEMA',
'title', 'TEXT',
'summary', 'TEXT',
'level', 'TEXT', # Found Tag here, it's for enums, when we know the possibility
'places', 'NUMERIC',
'teacher', 'TEXT', # ToString of the teacher because it's a primary key
)
# Same for persons
redis_connection.execute_command('FT.DROPINDEX', 'idx:persons')
redis_connection.execute_command('FT.CREATE', 'idx:persons', 'ON', 'HASH', 'PREFIX', '1', 'person:',
'SCHEMA',
'name', 'TEXT',
'role', 'TEXT'
)

@ -0,0 +1,200 @@
from django.shortcuts import render
from django.http import Http404
import redis
import uuid
from redis_app.utils.index import create_index
# This model only helps us the development part to set rules on objects (we do not use the django model to save objects in it)
from .models import Person
DEFAULT_EXPIRE_TIME = 120
EXPIRE_REFRESH_TIME = 60
personLoggedIn = ""
redis_connection = redis.Redis(host='localhost', port=6379, decode_responses=True)
create_index(redis_connection=redis_connection)
def home(request, person=''):
return render(request, 'home.html', {'person': person})
def details(request, course_id):
global redis_connection
course = redis_connection.hgetall(f"course:{course_id}")
if course is None:
raise Http404("Course does not exist")
return render(request, 'details.html', {'course': course})
# Handle error messages.
def register(request):
global personLoggedIn
global redis_connection
if request.method == 'POST':
person_name = request.POST.get('name')
person_role = request.POST.get('role')
query = f"@name:{person_name} @role:{person_role}"
results = redis_connection.execute_command('FT.SEARCH', 'idx:persons', query)
# First element = number of results
if results[0] > 0:
return render(request, 'register.html', {'person': Person(name="", role=""), "error_message": "This user already exists!"})
person_key = f"person:{uuid.uuid4()}"
redis_connection.hset(person_key, mapping={
'name': person_name,
'role': person_role
})
personLoggedIn = redis_connection.hgetall(person_key)
return home(request, personLoggedIn)
return render(request, 'register.html', {'person': Person(name="", role=""), "error_message": "The form has been wrongly filled!"})
def login(request):
global personLoggedIn
global redis_connection
if request.method == 'POST':
person_name = request.POST.get('name')
person_role = request.POST.get('role')
query = f"@name:{person_name} @role:{person_role}"
results = redis_connection.execute_command('FT.SEARCH', 'idx:persons', query)
if results[0] > 0:
person_key = results[1]
personLoggedIn = redis_connection.hgetall(person_key)
return home(request, personLoggedIn)
return render(request, 'login.html', {'person': Person(name="", role=""), "error_message": "No user found!"})
return login_form(request)
def register_form(request):
return render(request, 'register.html', {'person': Person(name="", role="")})
def login_form(request):
return render(request, 'login.html', {'person': Person(name="", role="")})
def logout(request):
global personLoggedIn
personLoggedIn = ""
return render(request, 'login.html', {'person': Person(name="", role="")})
def courses(request):
global personLoggedIn
if personLoggedIn == "":
return render(request, 'login.html', {'person': Person(name="", role=""), "error_message": "You must login!"})
person_id = getPersonId(personLoggedIn["name"], personLoggedIn["role"]).split(":")[1]
course_keys = redis_connection.keys(f"course:*")
courses = []
for key in course_keys:
course_data = redis_connection.hgetall(key)
if personLoggedIn['role'] == "Student":
if person_id in course_data.get("students", "").split(","):
course_id = getCourseId(course_data['title'], course_data['teacher'])
if course_id == False:
continue
course_data['id'] = course_id.split(":")[1]
courses.append(course_data)
else:
teacher_id = course_data["teacher"]
if teacher_id == person_id:
course_id = getCourseId(course_data['title'], course_data['teacher'])
if course_id == False:
continue
course_data['id'] = course_id.split(":")[1]
courses.append(course_data)
return render(request, 'courses.html', {'person': personLoggedIn, 'courses': courses})
def change_profile(request):
global personLoggedIn
if personLoggedIn == '':
return render(request, 'login.html', {'person': Person(name="", role=""), "error_message": "You must login!"})
if request.method == 'POST':
person_name = request.POST.get('name')
person_role = request.POST.get('role')
person_id = getPersonId(personLoggedIn["name"], personLoggedIn["role"])
if not person_id:
return render(request, 'profile.html', {'person': personLoggedIn, "error_message": "Internal error: No user found!"})
redis_connection.hmset(person_id, mapping={"name": person_name, "role": person_role})
personLoggedIn["name"] = person_name
personLoggedIn["role"] = person_role
return render(request, 'profile.html', {'person': personLoggedIn})
return login_form(request)
def profile(request):
global personLoggedIn
if personLoggedIn == '':
return render(request, 'login.html', {'person': Person(name="", role=""), "error_message": "You must login!"})
return render(request, 'profile.html', {'person': personLoggedIn})
def getPersonId(person_name, person_role):
query = f"@name:{person_name} @role:{person_role}"
results = redis_connection.execute_command('FT.SEARCH', 'idx:persons', query)
if results[0] > 0:
person_key = results[1]
return person_key
return False
def getCourseId(course_title, course_teacher):
query = f"@title:{course_title} @teacher:{course_teacher}"
results = redis_connection.execute_command('FT.SEARCH', 'idx:courses', query)
if results[0] > 0:
course_key = results[1]
return course_key
return False
def course_register(course_id, person_id):
course = redis_connection.hgetall(f"course:{course_id}")
person = redis_connection.hgetall(f"person:{person_id}")
if not course or not person:
return False
students = course.get('students', '')
if person_id in students.split(','):
return True
if students:
new_students = person_id
else:
new_students = students + "," + person_id
redis_connection.hset(f"course:{course_id}", "students", new_students)
return True
def course_unregister(course_id, person_id):
course = redis_connection.hgetall(f"course:{course_id}")
person = redis_connection.hgetall(f"person:{person_id}")
if not course or not person:
return False
students = course.get('students', '')
if person_id not in students.split(','):
return True
students_list = students.split(",")
if len(students_list) == 1:
new_students = ""
else:
new_students = ",".join([student for student in students_list if student != person_id])
redis_connection.hset(f"course:{course_id}", "students", new_students)
return True
def refresh_expire(course_id):
course = redis_connection.hgetall(f"course:{course_id}")
if not course:
return False
ttl = redis_connection.ttl(f"course:{course_id}")
if ttl <= 0:
return False
redis_connection.expire(f"course:{course_id}", ttl + EXPIRE_REFRESH_TIME)
return True
# Every id is only the number, not the course:number or person:number

@ -0,0 +1,22 @@
# Generated by Django 4.2.16 on 2024-10-19 09:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('redis', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='person',
name='courses',
),
migrations.AddField(
model_name='person',
name='courses',
field=models.ManyToManyField(blank=True, to='redis.course'),
),
]

@ -0,0 +1,25 @@
# Generated by Django 4.2.16 on 2024-10-19 09:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('redis', '0002_remove_person_courses_person_courses'),
]
operations = [
migrations.AddField(
model_name='course',
name='students',
field=models.ManyToManyField(blank=True, limit_choices_to={'role': 'Student'}, related_name='students', to='redis.person'),
),
migrations.AddField(
model_name='course',
name='teacher',
field=models.ForeignKey(default=3, limit_choices_to={'role': 'Teacher'}, on_delete=django.db.models.deletion.CASCADE, related_name='teacher', to='redis.person'),
preserve_default=False,
),
]

@ -0,0 +1,17 @@
# Generated by Django 4.2.16 on 2024-10-19 09:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('redis', '0003_course_students_course_teacher'),
]
operations = [
migrations.RemoveField(
model_name='course',
name='students',
),
]

@ -0,0 +1,22 @@
# Generated by Django 4.2.16 on 2024-10-19 09:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('redis', '0004_remove_course_students'),
]
operations = [
migrations.RemoveField(
model_name='person',
name='courses',
),
migrations.AddField(
model_name='course',
name='students',
field=models.ManyToManyField(blank=True, limit_choices_to={'role': 'Student'}, related_name='students', to='redis.person'),
),
]

@ -0,0 +1,68 @@
from django.db import models
# Utils function to truncate my string when it's too long (use in to string method)
def truncate_string(text):
if len(text) > 15:
return text[:15] + "..."
else:
return text
class Course(models.Model):
# Defining choices for the course level
BEGINNER = "B"
INTERMEDIATE = "I"
ADVANCED = "A"
LEVELS_CHOICES = [
(BEGINNER, "Beginner"),
(INTERMEDIATE, "Intermediate"),
(ADVANCED, "Advanced"),
]
# Defining our attributes which equal the Course table's columns
title = models.CharField(max_length=200)
summary = models.CharField(max_length=1000)
level = models.CharField(choices=LEVELS_CHOICES, default=BEGINNER, max_length=12)
places = models.IntegerField(default=0)
teacher = models.ForeignKey('Person', on_delete=models.CASCADE, related_name='teacher', limit_choices_to={'role': 'Teacher'})
students = models.ManyToManyField('Person', blank=True, related_name='students', limit_choices_to={'role': 'Student'})
# Utils function
def __str__(self):
return self.title + " " + truncate_string(self.summary)
def getLevel(self):
if (self.level == "B"):
return "Beginner"
if (self.level == "I"):
return "Intermediate"
return "Advanced"
# Student or teacher, what differs? For teachers, courses will be the courses taught, and for students, the courses followed.
# However, this only deferrs into a 'role'. If it's a teacher, then the courses are taught, else they are followed.
# All the logic can be simplified with the role attribute. Later, we'll also be able to check permission with this attribute.
class Person(models.Model):
# Defining choices for the course level
STUDENT = "Student"
TEACHER = "Teacher"
ROLE_CHOICES = [
(STUDENT, "Student"),
(TEACHER, "Teacher"),
]
# Defining our attributes which equal the Course table's columns
name = models.CharField(max_length=200)
role = models.CharField(choices=ROLE_CHOICES, default=STUDENT, max_length=7)
# Return the courses list for the Person
# If it's a teacher, returns all courses he teaches
# If it's a student, returns all courses he follows
@property
def courses(self):
if (self.role == "Student"):
return [course for course in Course.objects.all() if self in course.students.all()]
return Course.objects.filter(teacher=self)
# Utils function
def __str__(self):
return self.name + " is a " + self.role

@ -0,0 +1,12 @@
<html>
<body>
<h1>Courses for {{ person.name }}</h1>
{% if courses %}
{% for course in courses %}
<a href="{% url 'details' course.id %}">{{ course.title }}</a>
{% endfor %}
{% else %}
<p>No course yet</p>
{% endif %}
</body>
</html>

@ -0,0 +1,18 @@
<html>
<body>
{% if course %}
<h1>Welcome in the course {{ course.title }}!</h1>
<p>
{{ course.summary }}
</p>
<p>
This course is for {{ course.getLevel }} students
</p>
<p>
There's only {{ course.places }} places
</p>
{% else %}
<h1>No course found!</h1>
{% endif %}
</body>
</html>

@ -0,0 +1,10 @@
<html>
<body>
{% if person != '' %}
<h1>Welcome {{ person.name }}!</h1>
{% else %}
<h1>Welcome young padawan!</h1>
{% endif %}
<a href="{% url 'courses' %}">Courses</a>
</body>
</html>

@ -0,0 +1,19 @@
<html>
<body>
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<fieldset>
<legend><h1>Login</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<label for="name">Name</label><br>
<input name="name" id="name" value="{{ person.name }}"><br/>
<label for="role">Role</label><br>
<select name="role" id="role">
<option value="Student" {% if person.role == 'Student' %}selected{% endif %}>Student</option>
<option value="Teacher" {% if person.role == 'Teacher' %}selected{% endif %}>Teacher</option>
</select>
</fieldset>
<input type="submit" value="Login">
</form>
</body>
</html>

@ -0,0 +1,19 @@
<html>
<body>
<form action="{% url 'change_profil' %}" method="POST">
{% csrf_token %}
<fieldset>
<legend><h1>Profil</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<label for="name">Name</label><br>
<input name="name" id="name" value="{{ person.name }}"><br/>
<label for="role">Role</label><br>
<select name="role" id="role">
<option value="Student" {% if person.role == 'Student' %}selected{% endif %}>Student</option>
<option value="Teacher" {% if person.role == 'Teacher' %}selected{% endif %}>Teacher</option>
</select>
</fieldset>
<input type="submit" value="Update">
</form>
</body>
</html>

@ -0,0 +1,19 @@
<html>
<body>
<form action="{% url 'register' %}" method="POST">
{% csrf_token %}
<fieldset>
<legend><h1>Register</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<label for="name">Name</label><br>
<input name="name" id="name" value="{{ person.name }}"><br/>
<label for="role">Role</label><br>
<select name="role" id="role">
<option value="Student" {% if person.role == 'Student' %}selected{% endif %}>Student</option>
<option value="Teacher" {% if person.role == 'Teacher' %}selected{% endif %}>Teacher</option>
</select>
</fieldset>
<input type="submit" value="Register">
</form>
</body>
</html>

@ -0,0 +1,7 @@
<html>
<body>
{% for user in users %}
{{ user }}
{% endfor %}
</body>
</html>

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

@ -0,0 +1,15 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('<int:course_id>', views.details, name='details'),
path('register_form', views.register_form, name='register_form'),
path('register', views.register, name='register'),
path('login_form', views.login_form, name='login_form'),
path('login', views.login, name='login'),
path('courses', views.courses, name='courses'),
path('change_profil', views.change_profil, name='change_profil'),
path('profil', views.profil, name='profil'),
path('cached', views.cached, name='cached'),
]

@ -0,0 +1,103 @@
from django.shortcuts import render, get_object_or_404
from django.contrib.auth import get_user_model, authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.decorators.cache import cache_page
from .models import Course, Person
personLoggedIn = ""
def home(request, person=''):
return render(request, 'home.html', {'person': person})
def details(request, course_id):
course = get_object_or_404(Course, pk=course_id)
return render(request, 'details.html', {'course': course})
# Handle error messages.
def register(request):
global personLoggedIn
if request.method == 'POST':
person_name = request.POST.get('name')
person_role = request.POST.get('role')
try:
person = Person.objects.get(name=person_name, role=person_role)
return render(request, 'register.html', {'person': Person(name="", role=""), "error_message": "This user already exists!"})
except Person.DoesNotExist:
person = Person(name=person_name, role=person_role)
person.save()
personLoggedIn = person
return home(request, personLoggedIn)
return render(request, 'register.html', {'person': Person(name="", role=""), "error_message": "The form has been wrongly filled!"})
def login(request):
global personLoggedIn
if request.method == 'POST':
person_name = request.POST.get('name')
person_role = request.POST.get('role')
try:
person = Person.objects.get(name=person_name, role=person_role)
personLoggedIn = person
return home(request, personLoggedIn)
except:
return render(request, 'login.html', {'person': Person(name="", role=""), "error_message": "No user found!"})
return login_form(request)
def register_form(request):
return render(request, 'register.html', {'person': Person(name="", role="")})
def login_form(request):
return render(request, 'login.html', {'person': Person(name="", role="")})
def logout(request):
global personLoggedIn
personLoggedIn = ""
return render(request, 'login_form.html', {'person': Person(name="", role="")})
def courses(request):
global personLoggedIn
if personLoggedIn == "":
return render(request, 'login.html', {'person': Person(name="", role=""), "error_message": "You must login!"})
if personLoggedIn.role == "Student":
courses = Course.objects.filter(students=personLoggedIn)
else:
courses = Course.objects.filter(teacher=personLoggedIn)
if type(courses) == Course:
courses = [courses]
return render(request, 'courses.html', {'person': personLoggedIn, 'courses': courses})
def change_profil(request):
global personLoggedIn
if personLoggedIn == '':
return render(request, 'login.html', {'person': Person(name="", role=""), "error_message": "You must login!"})
if request.method == 'POST':
person_name = request.POST.get('name')
person_role = request.POST.get('role')
personLoggedIn.name = person_name
personLoggedIn.role = person_role
personLoggedIn.save()
return render(request, 'profil.html', {'person': personLoggedIn})
return login_form(request)
def profil(request):
global personLoggedIn
if personLoggedIn == '':
return render(request, 'login.html', {'person': Person(name="", role=""), "error_message": "You must login!"})
return render(request, 'profil.html', {'person': personLoggedIn})
@cache_page(60*15)
def cached(request):
user_model = get_user_model()
all_users = user_model.objects.all()
return render(request, 'test.html', {"users": all_users})
Loading…
Cancel
Save