Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/signup #75

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
298 changes: 104 additions & 194 deletions AlumniConnect/forms.py

Large diffs are not rendered by default.

10 changes: 6 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,16 @@
#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('confirmprofile/', TemplateView.as_view(template_name='AlumniConnect/confirm_profile.html'), name = 'confirmprofile'),
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 +74,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"
148 changes: 106 additions & 42 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, ProfileNewRegister, 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,50 @@ 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()
user.is_active = False
user.save()
# THEN CREATING THE PROFILE INSTANCE AND SAVING THE USER AND user_role
profile = Profile.objects.create(
roll_no=form.cleaned_data.get('username'),
email=form.cleaned_data.get('email'),
user_role=form.cleaned_data.get('user_role'),
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! Complete your profile to log in')
return render(request, 'AlumniConnect/confirm_email.html')

return render(request, 'AlumniConnect/signup.html', {'form': form})
# 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 +184,63 @@ def profileedit(request, id):
return HttpResponseRedirect('/')


@login_required
def profile_completion(request):
profile = Profile.objects.get(roll_no=request.user.username)
if profile.name:
return HttpResponseRedirect('/')
if request.method == 'POST':

form = ProfileNewRegister(
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.batch = Batch(request.POST['batch'])
request.user.first_name = first_name
request.user.last_name = last_name
request.user.is_active = False
request.user.save()
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))
return HttpResponseRedirect('/confirmprofile/')
else:
form = ProfileNewRegister()

batches = list(Batch.objects.all().order_by('batch'))
context = {'form': form, 'edit': False, 'programmes': Constants.PROG_CHOICES, 'user_role': profile.user_role,'branches': Constants.BRANCH, 'batch_year': batches, 'year_of_admission': Constants.YEAR_OF_ADDMISSION}
return render(request, 'AlumniConnect/profileedit.html', context)

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)
# 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 +253,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})
3 changes: 2 additions & 1 deletion applications/adminportal/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,13 @@ def registrations_index(request):
send_verification_email(request, profile)
profile.mail_sent = True
profile.verify = True
profile.user.is_active = True
messages.add_message(request, messages.SUCCESS, "Registration Success, Mail sent to {}".format(profile.name))

elif 'decline' in request.POST:
profile.verify = False
messages.add_message(request, messages.SUCCESS, "Registration Declined for {}".format(profile.name))

profile.user.save()
profile.save()
except Exception:
print(Exception)
Expand Down
31 changes: 18 additions & 13 deletions applications/alumniprofile/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@


class Constants:
USER_ROLE = (
('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 @@ -37,15 +42,15 @@ class Constants:
WORKING_STATUS = (
('Is Working', 'Is Working'),
('Is Pursuing Higher Studies', 'Is Pursuing Higher Studies'),
('Is Self Employed', 'Is Self Employed')
('Is Self Employed', 'Is Self Employed'),
('Student', 'Student')
)

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



class Batch(models.Model):
class Batch(models.Model):
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=15)
email = models.EmailField(unique=True,default="")
alternate_email = models.EmailField(null=True,blank=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, blank=True,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_role = models.CharField(max_length=2, choices=Constants.USER_ROLE, 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'),
]
Loading