Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
441 changes: 408 additions & 33 deletions AlumniConnect/forms.py

Large diffs are not rendered by default.

9 changes: 5 additions & 4 deletions AlumniConnect/urls.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""AlumniConnect URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Expand Down Expand Up @@ -37,13 +36,15 @@
#path('account/reset_password/', views.ResetPasswordRequestView.as_view(), name="reset_password"),
path('logout/', LogoutView.as_view(), name='logout'),
path('register/', views.register, name='register'),
path('newregister/', views.new_register, name='new_register'),
path('profilecompletion/',views.profile_completion, name='profile_completion'),
# path('newregister/', views.new_register, name='new_register'),
path('signup/', views.signup, name='signup'),
re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'),
path('confirm/', TemplateView.as_view(template_name='AlumniConnect/confirm_email.html'), name = 'confirm'),
path('success/', TemplateView.as_view(template_name='AlumniConnect/account_success.html'), name = 'success'),
re_path('^', include('django.contrib.auth.urls')),
path('password/', views.change_password, name='change_password'),
re_path(r'^profileedit/(?P<id>[0-9]+)/$', views.profileedit, name='profileedit'),
re_path(r'^profileedit/(?P<id>[0-9A-Za-z]+)/$', views.profileedit, name='profileedit'),
path('profile/', include('applications.alumniprofile.urls')),
path('members/', include('applications.members.urls')),
path('events/', include('applications.events_news.urls')),
Expand Down Expand Up @@ -72,4 +73,4 @@

admin.site.site_header = "IIITDMJ Alumni Association"
admin.site.site_title = "Alumni Association"
admin.site.index_title = "Alumni Association Admin"
admin.site.index_title = "Alumni Association Admin"
153 changes: 110 additions & 43 deletions AlumniConnect/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,24 @@
from django.db.models import Count
from django.contrib.auth.views import LoginView
from django.contrib.messages.views import SuccessMessageMixin

from .forms import RegisterForm, ProfileEdit, NewRegister
from django.conf import settings
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.html import strip_tags
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from .forms import RegisterForm, ProfileEdit, Alumni_NewRegister, Student_NewRegister, SignUp
from .token import account_activation_token
from applications.events_news.models import Event, Attendees
from applications.alumniprofile.models import Profile, Constants
from applications.alumniprofile.models import Batch, Profile, Constants
from applications.news.models import News
from applications.gallery.models import Album
from applications.geolocation.views import addPoints
import datetime
from django.utils import timezone
from itertools import chain
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import send_mail


# Create your views here.
Expand All @@ -49,7 +56,8 @@ def index(request):
news = News.objects.filter().order_by('-date')
# messages.success(request, 'Your password was successfully updated!')
events_to_display = list(chain(events, events_completed))[:3]
albums_list = Album.objects.order_by('-created').annotate(images_count=Count('albumimage'))[:3]
albums_list = Album.objects.order_by(
'-created').annotate(images_count=Count('albumimage'))[:3]
return render(request, "AlumniConnect/index.html",
{'name': sname, 'events': events_to_display, 'news': news, 'albums': albums_list})

Expand Down Expand Up @@ -84,7 +92,8 @@ def register(request):
batch = form.cleaned_data.get('batch')
branch = form.cleaned_data.get('branch')
programme = form.cleaned_data.get('programme')
l = Profile.objects.filter(batch=batch, programme=programme, branch=branch)
l = Profile.objects.filter(
batch=batch, programme=programme, branch=branch)
print('Testing output\n')
print(l)
check = True
Expand All @@ -95,9 +104,12 @@ def register(request):


def reg_no_gen(degree_, spec_, year):
degree = {"B.Tech": "1", "B.Des": '2', "M.Tech": '3', "M.Des": '4', "PhD": '5'}
spec = {"NA": '00', "CSE": "01", "ECE": "02", "ME": "03", "MT": "04", "NS": "05", "DS": "06"}
last_reg_no = Profile.objects.filter(year_of_admission=year).order_by('user__date_joined').last()
degree = {"B.Tech": "1", "B.Des": '2',
"M.Tech": '3', "M.Des": '4', "PhD": '5'}
spec = {"NA": '00', "CSE": "01", "ECE": "02",
"ME": "03", "MT": "04", "NS": "05", "DS": "06", "SM": "07"} # Added SM Branch
last_reg_no = Profile.objects.filter(
year_of_admission=year).order_by('user__date_joined').last()
# print(last_reg_no)
new_reg_no = (int(str(last_reg_no.reg_no)[-4:]) + 1) if last_reg_no else 1
return degree[degree_] + spec[spec_] + str(year)[2:] + str(convert_int(new_reg_no, 4))
Expand All @@ -107,41 +119,51 @@ def convert_int(number, decimals):
return str(number).zfill(decimals)


def new_register(request):
def signup(request):
if request.method == 'POST':
form = NewRegister(request.POST, request.FILES)
# print (request.POST)
form = SignUp(request.POST)
if form.is_valid():
try:
first_name, last_name = request.POST['name'].split(' ', 1)
except:
first_name = request.POST['name']
last_name = ""
# print (form.cleaned_data.get('date_of_joining'))
profile = form.save(commit=False)
profile.reg_no = reg_no_gen(profile.programme, profile.branch, profile.year_of_admission)
profile.country = request.POST['country']
profile.state = request.POST['state']
profile.city = request.POST['city']
password = User.objects.make_random_password(length=10)
# password = '12345678'
user = User.objects.create_user(
username=str(form.cleaned_data.get('roll_no')),
first_name=first_name,
last_name=last_name,
email=str(form.cleaned_data.get('email')),
password=password,
is_active=True

# CREATING THE USER FROM THE MODEL FORM DATA
user = form.save(commit=False)
user.username = form.cleaned_data.get('username')
user.email = str(form.cleaned_data.get('email'))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess you do not need to do this (above two lines). It is already taken care of by django forms. So, if you keep is_active=False as default, you can just do form.save() here?

user.is_active = False
user.save()
# THEN CREATING THE PROFILE INSTANCE AND SAVING THE USER AND USER_TYPE
profile = Profile.objects.create(
roll_no=form.cleaned_data.get('username'),
email=form.cleaned_data.get('email'),
user_type=form.cleaned_data.get('user_type'),
batch = Batch(2009),
user=user,
)
profile.user = user
profile.save()
mappt = addPoints({'city': str(request.POST['city']), 'state': str(request.POST['state']),
'country': str(request.POST['country'])})
print('Adding Map Point Status: ' + str(mappt))
# Send Account Activation Email
current_site = get_current_site(request)

from_email = settings.DEFAULT_FROM_EMAIL
to = [user.email]
subject = '[noreply] SAC Account Activation'
html_message = render_to_string('AlumniConnect/acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
plain_message = strip_tags(html_message)
send_mail(
subject, plain_message, from_email, to,
fail_silently=False, html_message=html_message,
)
messages.success(
request, f'Your account has been created! You are now able to log in')
return render(request, 'AlumniConnect/confirm_email.html')

# return HttpResponseRedirect('/')
else:
form = NewRegister()
return render(request, 'AlumniConnect/profileedit.html', {'form': form, 'edit': False})
form = SignUp()
return render(request, 'AlumniConnect/signup.html', {'form': form})


@login_required
Expand All @@ -163,21 +185,65 @@ def profileedit(request, id):
return HttpResponseRedirect('/')


@login_required
def profile_completion(request):
profile = Profile.objects.get(roll_no=request.user.username)
if request.method == 'POST':
if profile.user_type == 'A':
form = Alumni_NewRegister(
request.POST, request.FILES, instance=profile)
else:
form = Student_NewRegister(
request.POST, request.FILES, instance=profile)
# print (request.POST)
if form.is_valid():
try:
first_name, last_name = request.POST['name'].split(' ', 1)
except:
first_name = request.POST['name']
last_name = ""
# print (form.cleaned_data.get('date_of_joining'))
profile = form.save(commit=False)
profile.reg_no = reg_no_gen(
profile.programme, profile.branch, profile.year_of_admission)
profile.country = request.POST['country']
profile.state = request.POST['state']
profile.city = request.POST['city']
profile.user.first_name = first_name
profile.user.last_name = last_name
request.user.first_name = first_name
request.user.last_name = last_name
request.user.is_active = False
profile.save()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of adding all this information manually, why not just do form.save() here?? You can use reg_no_gen first thing after if request.method == 'POST', something like request.POST['reg_no'] = reg_no_gen(...).

request.user.save()
mappt = addPoints({'city': str(request.POST['city']), 'state': str(request.POST['state']),
'country': str(request.POST['country'])})
print('Adding Map Point Status: ' + str(mappt))
return HttpResponseRedirect('/')
else:
user_type = 'Alumni' if profile.user_type == 'A' else 'Student'
if profile.user_type == 'A':
form = Alumni_NewRegister()
else:
form = Student_NewRegister()
return render(request, 'AlumniConnect/profileedit.html', {'form': form, 'edit': False})


def activate(request, uidb64, token):
print('inside activate')
try:
uid = urlsafe_base64_decode(uidb64)
print(uid)
u = User.objects.get(username=uid)
u = User.objects.get(pk=uid)
print(u)
except(TypeError, ValueError, OverflowError):
u = None
if u is not None and account_activation_token.check_token(u, token):
if u is not None and account_activation_token.check_token(u, token) and not u.first_name:
u.is_active = True
u.save()
login(request, u)
# login(request, u)
# return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
return HttpResponseRedirect('/password/')
return HttpResponseRedirect('/profilecompletion/')
else:
return HttpResponse('Activation link is invalid!')
return redirect('/')
Expand All @@ -190,10 +256,11 @@ def change_password(request):
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user) # Important!
messages.success(request, 'Your password was successfully updated!')
messages.success(
request, 'Your password was successfully updated!')
return redirect('home')
else:
messages.error(request, 'Please correct the error below.')
else:
form = PasswordChangeForm(request.user)
return render(request, 'AlumniConnect/change_password.html', {'form': form})
return render(request, 'AlumniConnect/change_password.html', {'form': form})
27 changes: 16 additions & 11 deletions applications/alumniprofile/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@


class Constants:
USER_TYPE = (
('S','Student'),
('A','Alumni')
)
SEX_CHOICES = (
('M', 'Male'),
('F', 'Female'),
Expand All @@ -28,6 +32,7 @@ class Constants:
('CSE', 'Computer Science and Engineering'),
('ECE', 'Electronics and Communication Engineering'),
('ME', 'Mechanical Engineering'),
('SM', 'Smart Manufacturing'),
('NS', 'Natural Sciences'),
('MT', 'Mechatronics'),
('DS', 'Design'),
Expand All @@ -41,11 +46,11 @@ class Constants:
)

YEAR_OF_ADDMISSION = tuple((n, str(n)) for n in range(2005, datetime.datetime.now().year))


class Batch(models.Model):
# batch = models.IntegerField(primary_key=True,choices=Constants.BATCH_OF,default=2009)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove this commented line.

batch = models.IntegerField(primary_key=True)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't remove newlines like this. It reduces readability of the code.

def __str__(self):
return str(self.batch)

Expand All @@ -57,24 +62,24 @@ def upload_photo(instance, filename):

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
roll_no = models.IntegerField(primary_key=True)
email = models.EmailField(null=False, default="")
alternate_email = models.EmailField(null=True, blank=True)
roll_no = models.CharField(primary_key=True,max_length=8)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't assume that the max_length will always be 8 only, keep it 10 or 15

email = models.EmailField(unique=True,default="")
alternate_email = models.EmailField(null=True)
year_of_admission = models.IntegerField(null=True, choices=Constants.YEAR_OF_ADDMISSION)
batch = models.ForeignKey(Batch, on_delete=models.CASCADE)
name = models.CharField(max_length=1000, default="", null=False)
name = models.CharField(max_length=1000, default="", null=True)
fathers_name = models.CharField(max_length=1000, default="")
husbands_name = models.CharField(null=True, blank=True, max_length=1000, default="")
programme = models.CharField(max_length=1000, choices=Constants.PROG_CHOICES, null=False)
branch = models.CharField(choices=Constants.BRANCH, max_length=1000, null=False)
spouse_name = models.CharField(null=True, blank=True, max_length=1000, default="")
programme = models.CharField(max_length=1000, choices=Constants.PROG_CHOICES)
branch = models.CharField(choices=Constants.BRANCH, max_length=1000)
sex = models.CharField(max_length=2, choices=Constants.SEX_CHOICES, default='M')
date_of_birth = models.DateField(default=datetime.date(1970, 1, 1))
current_address = models.TextField(max_length=1000, default="")
permanent_address = models.TextField(max_length=1000, blank=True, null=True)
mobile1 = models.BigIntegerField(null=True)
mobile2 = models.BigIntegerField(null=True, blank=True)
phone_no = models.BigIntegerField(null=True, blank=True)
working_status = models.CharField(max_length=1000, choices=Constants.WORKING_STATUS, default='1', null=False)
working_status = models.CharField(max_length=1000, choices=Constants.WORKING_STATUS, default='1')
current_position = models.CharField(max_length=1000, null=True, blank=True)
current_organisation = models.CharField(max_length=1000, null=True, blank=True)
past_experience = models.IntegerField(null=True, blank=True)
Expand All @@ -94,7 +99,7 @@ class Profile(models.Model):
mail_sent = models.BooleanField(default=False)
verify = models.BooleanField(null=True)
mail_sent_tracker = FieldTracker(fields=['verify'])

user_type = models.CharField(max_length=2, choices=Constants.USER_TYPE, default='A')
def __str__(self):
return self.name

Expand Down
2 changes: 1 addition & 1 deletion applications/alumniprofile/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
app_name = 'profile'

urlpatterns = [
re_path(r'^(?P<username>[0-9]{6,8})/$', views.profile, name='profile'),
re_path(r'^(?P<username>[0-9A-Za-z]{6,8})/$', views.profile, name='profile'),
]
15 changes: 10 additions & 5 deletions templates/AlumniConnect/acc_active_email.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
{% autoescape off %}
Hi {{ l.name }},
Please click on the link to confirm your registration,
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}

<h3>Your current default Passwords is your Roll No. It is HIGHLY RECOMMENDED to change it after activating your account.</h3>
Hi {{ user }},<br>
<br>
Your account has successfully created. Please click below link to activate your account...<br>
Username : {{ user }}<br>
<br>
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}<br>
<br>
<br>
Regards,<br>
SAC
{% endautoescape %}
2 changes: 1 addition & 1 deletion templates/AlumniConnect/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ <h1 class="text-uppercase mt-4">
<div class="alert alert-primary m-4 text-center" role="alert" >
Please Sign In to Continue! Don't have an Account?
<h5 class="pt-2 m-0">
<a class="d-inline-block" href="{% url 'new_register' %}">
<a class="d-inline-block" href="{% url 'signup' %}">
<span class="badge badge-pill badge-primary p-2">Register! &nbsp;<i class="fas fa-external-link-alt"></i></span>
</a>
</h5>
Expand Down
Loading