Skip to content

Commit

Permalink
routing prototype finish
Browse files Browse the repository at this point in the history
  • Loading branch information
DrRicx committed Apr 6, 2024
1 parent 17ca290 commit 8486b3e
Show file tree
Hide file tree
Showing 10 changed files with 160 additions and 131 deletions.
27 changes: 12 additions & 15 deletions chat/admin.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
# admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from .models import Profile, UserSession
from django.contrib.auth.admin import UserAdmin
from .models import *


class ProfileInline(admin.StackedInline):
model = Profile
class AccountInline(admin.StackedInline):
model = Account
can_delete = False
verbose_name_plural = 'Profile'
verbose_name_plural = 'Accounts'


class CustomUserAdmin(UserAdmin):
inlines = (ProfileInline,)
class CustomizeUserAdmin(UserAdmin):
inlines = (AccountInline,)


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)


class ProfileAdmin(admin.ModelAdmin):
list_display = ['user', 'middle_name'] # Display fields in the admin list view

admin.site.register(Profile, ProfileAdmin)
admin.site.register(User, CustomizeUserAdmin)

admin.site.register(UserSession)
admin.site.register(Channels)
admin.site.register(Subchannels)
1 change: 0 additions & 1 deletion chat/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from channels.db import database_sync_to_async
from django.db import close_old_connections


class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
# Close old database connections to prevent usage outside of async context
Expand Down
35 changes: 25 additions & 10 deletions chat/forms.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,30 @@
from django.forms import ModelForm, inlineformset_factory
from django import forms
from django.contrib.auth.models import User
from .models import *
from .models import Account

class CombinedAccountCreationForm(forms.ModelForm):
username = forms.CharField(max_length=150)
email = forms.EmailField()
password1 = forms.CharField(widget=forms.PasswordInput)
# Additional fields from AccountCreationFormAdd
gender = forms.CharField(max_length=6, widget=forms.Select(choices=[('MALE', 'male'), ('FEMALE', 'female')]))
student_number = forms.CharField(max_length=12)
middle_name = forms.CharField(max_length=12)

class profileForm(ModelForm):
class Meta:
model = Profile
fields = '__all__'


class userForm(ModelForm):
class Meta:
model = User
fields = ['first_name', 'last_name', 'email']
fields = ['username', 'email', 'password1']

def save(self, commit=True):
user = super(CombinedAccountCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
# Save additional fields into Account model
account = Account.objects.create(
user=user,
gender=self.cleaned_data['gender'],
student_number=self.cleaned_data['student_number'],
middle_name=self.cleaned_data['middle_name']
)
return user, account
30 changes: 18 additions & 12 deletions chat/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,28 @@
from django.contrib.auth.models import User


# Create your models here.
class Profile(models.Model):
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
student_number = models.CharField(null=True, blank=True, max_length=11)
middle_name = models.CharField(null=True, blank=True, max_length=100)
gender = models.CharField(
max_length=6,
choices=[('MALE', 'male'), ('FEMALE', 'female')]
)
student_number = models.CharField(max_length=12, null=True, blank=True)
middle_name = models.CharField(max_length=12, null=True, blank=True)

def __str__(self):
return f"{self.user.username} Profile"
return self.user.username

class Channels(models.Model):
host = models.ForeignKey(User, on_delete=models.CASCADE)
channel_name = models.CharField(max_length=12, null=True, blank=True)
def __str__(self):
return self.channel_name

from django.contrib.auth.models import User

class UserSession(models.Model):
host = models.ForeignKey(User, on_delete=models.CASCADE, null = True)
session_key = models.CharField(max_length=40, unique=True)
room_name = models.CharField(max_length=100)
class Subchannels(models.Model):
subchannel_root = models.ForeignKey(Channels, on_delete=models.CASCADE)
subchannel_name = models.CharField(max_length=12, null=True, blank=True)
members = models.ManyToManyField(User, related_name='members', blank=True)

def __str__(self):
return f"{self.host.username}'s session ({self.session_key})"
return self.subchannel_name
2 changes: 1 addition & 1 deletion chat/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
from . import consumers

websocket_urlpatterns = [
re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()),
re_path(r"ws/chat/(?P<channel_name>\w+)/(?P<subchannel_name>\w+)/$", consumers.ChatConsumer.as_asgi()),
]
36 changes: 21 additions & 15 deletions chat/templates/chat/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,29 @@
</head>
<body>
What chat room would you like to enter?<br>
<input id="room-name-input" type="text" size="100"><br>
<input id="room-name-submit" type="button" value="Enter">

<input type="text" id="search" name="search" placeholder="Search Users">
{% for channel in channels %}
<a href="{% url 'channels' channel.channel_name%}">{{ channel.channel_name }} </a><br>
{% endfor %}

<script>
document.querySelector('#room-name-input').focus();
document.querySelector('#room-name-input').onkeyup = function(e) {
if (e.key === 'Enter') { // enter, return
document.querySelector('#room-name-submit').click();
}
};

document.querySelector('#room-name-submit').onclick = function(e) {
var roomName = document.querySelector('#room-name-input').value;
window.location.pathname = '/chat/' + roomName + '/';
};
</script>
{# <input id="room-name-input" type="text" size="100"><br>#}
{# <input id="room-name-submit" type="button" value="Enter">#}
{##}
{# <input type="text" id="search" name="search" placeholder="Search Users">#}
{##}
{# <script>#}
{# document.querySelector('#room-name-input').focus();#}
{# document.querySelector('#room-name-input').onkeyup = function(e) {#}
{# if (e.key === 'Enter') { // enter, return#}
{# document.querySelector('#room-name-submit').click();#}
{# }#}
{# };#}
{##}
{# document.querySelector('#room-name-submit').onclick = function(e) {#}
{# var roomName = document.querySelector('#room-name-input').value;#}
{# window.location.pathname = '/chat/' + roomName + '/';#}
{# };#}
{# </script>#}
</body>
</html>
47 changes: 31 additions & 16 deletions chat/templates/chat/register_login.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,42 @@
</form>
</div>
{% else %}
<div>
<form action="" method="POST">
{% csrf_token %}
<label>First name:</label>
<input type="text" name="first_name" placeholder="Enter first name"/>
<div>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

<label>Middle name:</label>
<input type="text" name="middle_name" placeholder="Enter middle name"/>
<form action="" method="POST">
{% csrf_token %}

<label>Last name:</label>
<input type="text" name="last_name" placeholder="Enter last name"/>
<label for="id_username">Username:</label><br>
<input type="text" id="id_username" name="username"><br><br>

<label>Username:</label>
<input type="text" name="username" placeholder="Enter username"/>
<label for="id_email">Email:</label><br>
<input type="email" id="id_email" name="email"><br><br>

<label>Password:</label>
<input type="password" name="password" placeholder="Enter password"/>
<label for="id_gender">Gender:</label><br>
<select id="id_gender" name="gender">
<option value="MALE">Male</option>
<option value="FEMALE">Female</option>
</select><br><br>

<button type="submit">Submit</button>
</form>
</div>
<label for="id_student_number">Student Number:</label><br>
<input type="text" id="id_student_number" name="student_number"><br><br>

<label for="id_middle_name">Middle Name:</label><br>
<input type="text" id="id_middle_name" name="middle_name"><br><br>

<label for="id_password1">Password:</label><br>
<input type="password" id="id_password1" name="password1"><br><br>

<button type="submit">Register</button>
</form>
</div>
{% endif %}


Expand Down
5 changes: 3 additions & 2 deletions chat/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
from . import views

urlpatterns = [
path("", views.index, name="index"),
path("index/", views.index, name="index"),
path("<str:channel_name>/", views.channels, name="channels"),
path("<str:channel_name>/<str:sub_channel_name>/", views.subchannels, name="subchannels"),
path("home/", views.home, name="home"),
path("login/", views.loginPage, name="login"),
path("register/", views.registerPage, name="register"),
path("<str:room_name>/", views.room, name="room"),
]
107 changes: 48 additions & 59 deletions chat/views.py
Original file line number Diff line number Diff line change
@@ -1,86 +1,75 @@
# chat/views.py
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from .forms import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from .models import *
from .forms import *


def home(request):
return render(request, "chat/splash-page.html")


def index(request):
users_all = User.objects.all()
context={'users_all':users_all}
return render(request, "chat/index.html",context)
channels = Channels.objects.all()
context = {'channels': channels}
return render(request, 'chat/index.html', context)


def channels(request, channel_name):
channel = get_object_or_404(Channels, channel_name=channel_name)
subchannels = Subchannels.objects.all()
context = {'channel': channel, 'subchannel': subchannels}
return render(request, 'chat/channel.html', context)


def subchannels(request, channel_name, sub_channel_name):
channel = get_object_or_404(Channels, channel_name=channel_name)
subchannels = Subchannels.objects.filter(subchannel_name=sub_channel_name)
context = {'subchannel': subchannels, 'channel_name': channel}
return render(request, 'chat/subchannel.html', context)


def loginPage(request):
page = 'login'

context = {'page': page}

if request.method == 'POST':
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
# Authenticate the user with the provided username and password
user = authenticate(username=username, password=password)

if user is None:
# Display an error message if authentication fails (invalid password)
messages.error(request, "Invalid Password")
return redirect('login')
else:
# Log in the user and redirect to the home page upon successful login
login(request, user)
# Create a new session for the user
request.session.create()
# Redirect to a success page or home page
return redirect('index')
else:
# Handle invalid login credentials
return render(request, 'chat/register_login.html', {'error': 'Invalid username or password'})
else:
# Render the login form
return render(request, 'chat/register_login.html', context)

# if request.method == "POST":
# username = request.POST.get('username')
# password = request.POST.get('password')
# # Authenticate the user with the provided username and password
# user = authenticate(username=username, password=password)
#
# if user is None:
# # Display an error message if authentication fails (invalid password)
# messages.error(request, "Invalid Password")
# return redirect('login')
# else:
# # Log in the user and redirect to the home page upon successful login
# login(request, user)
# return redirect('index')

def registerPage(request):
if request.method == 'POST':
first_name = request.POST.get('first_name')
middle_name = request.POST.get('middle_name') # Retrieve middle name field
last_name = request.POST.get('last_name')
username = request.POST.get('username')
password = request.POST.get('password')

user = User.objects.create_user(
first_name=first_name,
last_name=last_name,
username=username
)

profile = Profile.objects.create(
user=user,
middle_name=middle_name
)
return render(request, 'chat/register_login.html', context)

user.set_password(password)
user.save()

return redirect('login')

return render(request, 'chat/register_login.html')

def registerPage(request):
if request.method == 'POST':
form = CombinedAccountCreationForm(request.POST)
if form.is_valid():
form.save()
# Redirect to a success page or login page
return redirect('login')
else:
# Form is invalid, render back to the user with error messages
for field, errors in form.errors.items():
for error in errors:
messages.error(request, f"Error in {field}: {error}")
else:
form = CombinedAccountCreationForm()

def room(request, room_name):
return render(request, "chat/room.html", {"room_name": room_name})
context = {'form': form}
return render(request, 'chat/register_login.html', context)
Loading

0 comments on commit 8486b3e

Please sign in to comment.