def atom(request, cat_id, atom_id, class_id=None): r""" This is the view for both the ``atom`` view and the ``base_atom`` view (``/class/<class_id>/category/<cat_id>/atom/<atom_id>`` and ``/category/<cat_id>/atom/<atom_id>``). It generates the content that is contained in the atom. """ if class_id is not None: template = 'web/home/class/category.html' class_object = get_object_or_404(Class, id=class_id) category_object = get_object_or_404(ClassCategory, id=cat_id) # Check if user is allowed to see this page if has_class_access(class_object, request.user): return HttpResponseRedirect(reverse('class_index')) # Redirect else: template = 'web/home/base/category.html' class_object = None category_object = get_object_or_404(BaseCategory, id=cat_id) atom_object = get_object_or_404(Atom, id=atom_id) context = get_navbar_context(category_object, class_object) context.update( # Add the breadcrumbs to the context get_breadcrumbs(request.path, web_breadcrumb_dict) ) context.update( # Add the atom specific content to the context get_context_for_atom(atom_object) ) context.update({ 'atom_object': atom_object, 'class_object':class_object, 'forum': Forum.objects.get(atom=atom_object), }) return render(request, template, context)
def metrics(request): user=request.user stat_set=[] maxPossible=0 achieved=0 for a in user.owned_assignments.all(): stats=AssignmentStats(); stats.assignmentName=a.title stats.assignmentid=a.id #Generate data data=[] for i in a.instances.all(): maxPossible = i.max_score achieved = i.score stats.numinstances += 1 if maxPossible>0: data.append((achieved/maxPossible)*100) stats.data=data if(stats.numinstances > 0): #Calculate average stats.average = np.average(stats.data)#can add weighting #Calculate std deviation stats.deviation = np.std(stats.data) #Number completed? #Min, Max stats.minimum=np.amin(stats.data) stats.maximum=np.amax(stats.data) #median stats.median=np.median(stats.data) stat_set.append(stats) context = get_breadcrumbs(request.path) context["user"]=request.user context["stat_set"]=stat_set return render(request, 'assignment/metrics.html', context)
def category(request, cat_id, class_id=None): r""" This is the view for category and base_category (``/class/<class_id>/category/<cat_id>`` and ``/category/<cat_id>``). It generates the category page which has a table of all the content in all of its ``child_atoms`` and all of the ``child_atoms`` in all categories under it. """ if class_id is not None: template = 'web/home/class/category.html' category_object = get_object_or_404(ClassCategory, id=cat_id) class_object = get_object_or_404(Class, id=class_id) # Check if user is allowed to see this page if has_class_access(class_object, request.user): return HttpResponseRedirect(reverse('class_index')) # Redirect else: template = 'web/home/base/category.html' category_object = get_object_or_404(BaseCategory, id=cat_id) class_object = None # We aren't in a class context = get_navbar_context(category_object, class_object) context.update( # Add the breadrumbs to the context get_breadcrumbs(request.path, web_breadcrumb_dict) ) context.update( # Add the category specific content to the context get_context_for_category(category_object) ) context.update({ 'class_object':class_object, 'category_object':category_object, }) return render(request, template, context)
def deleteQ(request): #Delete specified questions if request.method == "POST": for entry in request.POST: if entry =="csrfmiddlewaretoken": continue try: question = Question.objects.get(id=entry) except: break #Delete data entries in assignments for a in question.assigned_to.all(): data = json.loads(a.data) while str(question.id) in json.dumps(data): for q in data: if int(q['id']) == int(question.id): data.remove(q) a.data = json.dumps(data) a.save() copy = question.copy.all()[0] if not copy.owners.all().exists(): copy.delete() else: copy.original = None copy.save() question.delete() context = get_breadcrumbs(request.path) context['question_list'] = request.user.owned_questions.filter(isCopy=False) if request.method == "POST": context['messages'] = ['Question(s) deleted'] return render(request, 'question/delete.html', context)
def previewTemplate(request, a): assignment = Assignment.objects.get(pk=a) question_list=[] data = json.loads(assignment.data) for question in data: qdat = { 'title': '', 'text':'', 'choices': '', } qdat['title'] = question['title'] q=Question.objects.get(id=question['id']).data q=json.loads(q) q['choices']=json.loads(q['choices']) exec q['code'] solution=eval(q['solution']) #q text formatted here local_dict = dict(locals()) qdat['text'] = Template(q['text']).substitute(local_dict) qdat['choices'] = [] for choice in q['choices']: answer = eval(choice) qdat['choices'].append(answer) if len(q['choices']) > 0: qdat['choices'].append(solution) shuffle(qdat['choices']) question_list.append(qdat) context = get_breadcrumbs(request.path) context['question_list']=question_list context['assignment']=assignment return render(request, 'assignment/preview.html', context)
def assign(request, messages=[]): context = get_breadcrumbs(request.path) context["users"] = User.objects.all() context["assignments"] = request.user.owned_assignments.all() context["class_list"] = request.user.allowed_classes.all() | request.user.classes_authored.all() context["messages"] = messages return render(request, "assignment/assign.html", context)
def main(request, messages=[]): assignment_list = request.user.assignmentInstances.all() context = get_breadcrumbs(request.path) context["assignment_list"] = assignment_list context["user"] = request.user context["messages"] = messages return render(request, "assignment_nav.html", context)
def editQ(request, id): question = get_object_or_404(Question, id=id) #Generate list of variables variable_list = [] varCode = json.loads(question.data)['code'].split('#CUSTOM')[0].replace('\r\n', '\n') if varCode.find('#var:') >= 0: for content in varCode.split('#var')[1:]: variable={ 'vartype':'', 'varname':'', 'vardata':dict(), } variable['vartype'] = content.split('\n')[0].split('_')[0] variable['varname'] = content.split('\n')[0].split('_')[1] for line in content.split('#Template Code\n')[0].split('\n')[1:-1]: variable['vardata'][line.split('=')[0]] = line.split('=')[1] variable_list.append(variable) #Get code code = json.loads(question.data)['code'].split('#CUSTOM')[1] context=get_breadcrumbs(request.path) context['qdata'] = json.loads(question.data) context['code'] = code context['variable_list'] = variable_list context['question'] = question context['type_list'] = Variable.objects.all() context['atom_list'] = web.models.Atom.objects.all() return render(request, 'question/addQ.html', context)
def deleteA(request): #Delete specified assignment if request.method == "POST": for entry in request.POST: if entry =="csrfmiddlewaretoken": continue try: assignment = Assignment.objects.get(id=entry) except: break for question in assignment.questions.all(): #See if we need to remove ownership from a copy if question.isCopy: removeOwner = True for a in request.user.owned_assignments.all(): if a.id != assignment.id and a.questions.filter(id=question.id).exists(): removeOwner=False break #remove ownership of copy, see if copy should be deleted if removeOwner: question.owners.remove(request.owner) #Copy has no owners and original has been changed if question.owners.all.count() == 0 and question.original == None: question.delete() assignment.delete() #deletes assigned instances as well context = get_breadcrumbs(request.path) context['assignment_list'] = request.user.owned_assignments.all() if request.method == "POST": context['messages']=['Assignment(s) deleted'] return render(request, 'assignment/delete.html', context)
def register(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse('home')) if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): email_exists = User.objects.filter( email=form.cleaned_data['email'] ).exists() if email_exists: messages.warning(request, _('Could not register you. Email is ' 'already registered.') ) if (form.cleaned_data['password'] != form.cleaned_data['password_confirmation']): messages.warning(request, _('Passwords did not match. Please ' 'try again.') ) elif not email_exists: user = User.objects.create_user( form.cleaned_data['email'], form.cleaned_data['email'], form.cleaned_data['password'] ) user.first_name = form.cleaned_data['firstname'] user.last_name = form.cleaned_data['lastname'] user.username = form.cleaned_data['username'] user.is_active = False user.save() m = hashlib.md5() m.update(user.email + str(user.date_joined).split('.')[0]) send_mail( subject=_('KnoAtom Registration'), message=(_('You have successfully registered at ' 'knoatom.eecs.umich.edu with the username ') + user.username + _('. Please validate your account by going to ')+ request.build_absolute_uri('validate')+'?email='+ user.email + '&validation=' + m.hexdigest() + _(' . If you did not process this registration, ' 'please contact us as soon as possible.\n\n-- The ' 'Management') ), from_email='*****@*****.**', recipient_list=[user.email, settings.EMAIL_HOST_USER], fail_silently=False ) messages.success(request, _('You have been registered. Please ' 'login to continue.') ) return HttpResponseRedirect(reverse('login')) messages.warning(request, _('Could not register you. Try again.')) else: # Request is GET form = RegisterForm() context = get_breadcrumbs(request.path, web_breadcrumb_dict) context.update({'register_form':form}) return render(request, 'web/account/register.html', context)
def get_context_data(self, **kwargs): context = super(CreateClassView, self).get_context_data(**kwargs) context.update( get_navbar_context() ) context.update( get_breadcrumbs(self.request.path, web_breadcrumb_dict) ) return context
def class_list(request): r"""This is the view for the class list.""" context = get_navbar_context() context.update( get_breadcrumbs(request.path, web_breadcrumb_dict) ) context.update({ 'class_list': Class.objects.all() }) return render(request, 'web/home/class_list.html', context)
def editA(request, id): assignment = Assignment.objects.get(pk=id) context = get_breadcrumbs(request.path) if assignment.owners.filter(id=request.user.id).exists(): context["isCopy"] = False else: context["isCopy"] = True context["assignment"] = assignment context["question_list"] = Question.objects.filter(isCopy=False) context["assign_data"] = json.loads(assignment.data) return render(request, "assignment/addAssignment.html", context)
def list_videos(request): if not request.user.is_staff: return HttpResponseRedirect(reverse('home')) top_ranked_videos = cache.get('top_ranked_videos') # Load from cache if top_ranked_videos is None: # If there is no cached version top_ranked_videos = Video.objects.all().order_by('-votes')[:5] cache.set('top_ranked_videos', top_ranked_videos, 60*10) # Set cache context = get_breadcrumbs(request.path, web_breadcrumb_dict) context.update({'top_ranked_videos':top_ranked_videos}) return render(request, 'web/admin/videos.html', context)
def instanceDetail(request, pk, id): assignmentInstance = request.user.assignmentInstances.get(pk=pk) question = assignmentInstance.questions.get(pk=id) context = get_breadcrumbs(request.path) context['user']=request.user context['question_selected']=question context['q']=question context['assignment_selected']=assignmentInstance context['text']=question.text context['choices']=question.choiceInstances.all() return render(request, 'question/instance.html', context)
def classes(request, class_id): r""" This is the view for the class home page. It shows the class summary. """ class_object = get_object_or_404(Class, id=class_id) # Check if user is allowed to see this page if has_class_access(class_object, request.user): return HttpResponseRedirect(reverse('class_index')) # If not redirect context = get_navbar_context(None, class_object) context.update( # Add breadcrumbs to context get_breadcrumbs(request.path, web_breadcrumb_dict) ) context.update({ # Add the class_objet to the context 'class_object': class_object }) return render(request, 'web/home/class/index.html', context)
def detail(request, id): assignment = get_object_or_404(AssignmentInstance, pk=id) # check if assignment was published if not assignment.was_published(): return Http404 # check if assignment was due if assignment.was_due(): assignment.can_edit = False assignment.save() question_list = assignment.questions.all() context = get_breadcrumbs(request.path) context["user"] = request.user context["assignment_list"] = request.user.assignmentInstances.all() context["assignment_selected"] = assignment context["question_list"] = question_list return render(request, "assignment/detail.html", context)
def previewAssignment(request): assignment = json.loads(request.POST['previewdata']) question_list=[] test = '' for question in assignment['questions']: q=Question.objects.get(id=question) data = json.loads(q.data) data['solution']= data['solution'].replace('<br>', '\n') data['solution']= data['solution'].replace(' ', '\t') exec data['code'] try: data['solution']=eval(data['solution']) except: pass #q text formatted here local_dict = dict(locals()) data['text'] = Template(data['text']).safe_substitute(local_dict) #format choices choices = json.loads(data['choices']) data['choices'] = [] for choice in choices: try: answer = eval(choice) except: answer=choice data['choices'].append(answer) if len(data['choices']) > 0: data['choices'].append(data['solution']) data['title']=q.title question_list.append(data) if test!='': return HttpResponse(test) context = get_breadcrumbs(request.path) context['question_list']=question_list context['assignment']=assignment return render(request, 'assignment/preview.html', context)
def batch_add(request): if not request.user.is_staff: return HttpResponseRedirect(reverse('home')) if request.method == 'POST': form = BatchAddUsersForm(request.POST) if form.is_valid(): users_added = 0 for u in form.cleaned_data['users'].split('\n'): u = u.strip() if u == '': continue user_exists = User.objects.filter( Q(email=u)|Q(username=u)).exists() if not re.match('[a-z]*@umich\.edu', u) or user_exists: messages.warning(request, 'Could not add ' + u + '. Username or email are already in the database, or ' 'email is not [email protected].' ) continue password = ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in range(10)) user = User.objects.create_user(email=u, username=u) user.set_password(password) user.save() users_added += 1 send_mail( subject='KnoAtom New Account', message='You have been registered at ' 'knoatom.eecs.umich.edu. Your information is as ' 'follows:\n\nUsername: '******'\nPassword: '******'\n\nPlease login and change your ' 'password as soon as you can (click on your username ' 'at the bottom of the left sidebar).\n\nThank ' 'you\n\n-- The Management', recipient_list=[u, '*****@*****.**'] ) messages.success(request, str(users_added) + ' users have been ' 'added.') else: messages.warning(request, 'Could not add users. Did you have the ' 'format correct?') else: form = BatchAddUsersForm() context = get_breadcrumbs(request.path, web_breadcrumb_dict) context.update({'form':form}) return request(render, 'web/admin/batch_add.html', context)
def practice(request, id): context = get_breadcrumbs(request.path) question_list = Atom.objects.get(id=id).related_questions.filter(isCopy=False) count = question_list.count() if count==0: messages = ['No Questions related to that atom!'] return choose_atom(request, messages) question = question_list[randint(0,count-1)] #generate question qdat = detail(request, question.id, True) #load page context['qid'] = question.id context['atomid'] = id context['title'] = question.title context['text'] = qdat['text'] context['answer'] = qdat['answer'] context['choices'] = qdat['choices'] return render(request, 'question/practice.html', context)
def exposition_submit(request, pk): r""" This is the view for the exposition submit feature. """ success_url = request.GET.get('next', None) if 'add-another' in request.POST: success_url = reverse('expo_submit') context = get_navbar_context() context.update( get_breadcrumbs(request.path, web_breadcrumb_dict) ) form_kwargs = {'user':request.user} if pk: exposition = get_object_or_404(Exposition, pk=pk) form_kwargs.update({'instance':exposition}) else: exposition = None if request.method == 'POST': # If the form has been submitted... form = ExpositionForm(request.POST, request.FILES, **form_kwargs) if form.is_valid(): # All validation rules pass obj = form.save() messages.success( request, _('The exposition has been submitted correctly.') ) if success_url is not None: return HttpResponseRedirect(success_url) else: return HttpResponseRedirect(obj.get_absolute_url()) else: messages.warning(request, _('Error submitting the exposition.')) else: form = ExpositionForm(**form_kwargs) context.update({ 'object':exposition, 'form':form, 'success_url':success_url }) return render(request, 'web/home/expo_submit.html', context)
def video_submit(request, pk): """ This is the view for video submission. """ success_url = request.GET.get('next', None) # Redirection URL if 'add-another' in request.POST: success_url = reverse('video_submit') context = get_navbar_context() context.update( get_breadcrumbs(request.path, web_breadcrumb_dict) ) form_kwargs = {'user': request.user} if pk: video = get_object_or_404(Video, pk=pk) form_kwargs.update({'instance':video}) else: video = None if request.method == 'POST': form = VideoForm(request.POST, **form_kwargs) if form.is_valid(): obj = form.save() messages.success( request, _('The video has been submitted correctly.') ) if success_url is not None: return HttpResponseRedirect(success_url) else: return HttpResponseRedirect(obj.get_absolute_url()) else: messages.warning(request, _('Error submitting the video.')) else: form = VideoForm(**form_kwargs) context.update({ 'object':video, 'form':form, 'success_url':success_url }) return render(request, 'web/home/video_submit.html', context)
def login(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse('home')) if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): logging.debug('Trying to log in %s: %s' % (form.cleaned_data['email'], form.cleaned_data['password']) ) users = User.objects.filter( email=form.cleaned_data['email'].strip() ) if users.count() == 1: u = users[0] user = authenticate( username=u.username, password=form.cleaned_data['password'] ) if user is not None: logging.debug('Trying to log in user %s' % user) if user.is_active == 0: messages.warning(request, _('Please activate your ' 'account before you log in. Contact ' '[email protected] if you need further ' 'assistance.') ) return HttpResponseRedirect(reverse('login')) else: auth_login(request, user) if form.cleaned_data['redirect']: return HttpResponseRedirect( form.cleaned_data['redirect'] ) else: return HttpResponseRedirect(reverse('home')) logging.debug('Could not find account %s' % form.cleaned_data['email']) messages.warning(request, _('Could not authenticate you. Try again.')) else: # Request is GET form = LoginForm(initial={'redirect':request.GET.get('next', None)}) context = get_breadcrumbs(request.path, web_breadcrumb_dict) context.update({'login_form':form}) return render(request, 'web/account/login.html', context)
def detail(request, id, practice=False): q=Question.objects.get(id=id) data=json.loads(q.data) test = '' try: exec data['code'] except Exception as ex: test += "Error in code section:<br>"+str(ex)+"<br>" try: solution = eval(data['solution']) except: solution = data['solution'] text = data['text'] local_dict = dict(locals()) text = Template(text).safe_substitute(local_dict) # #choices formatted here choices = [] for choice in json.loads(data['choices']): choice = Template(choice).safe_substitute(local_dict) try: choices.append(eval(choice)) except Exception as ex: choices.append(choice) if len(choices) > 0: try: choices.append(eval(solution)) except Exception as ex: choices.append(solution) shuffle(choices) if not test=='': return HttpResponse(test) context = get_breadcrumbs(request.path) context['text']=text context['answer']=solution context['choices']=choices if practice: return context return render(request, 'question/detail.html', context)
def forgot_password(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse('home')) if request.method == 'POST': form = ForgotPasswordForm(request.POST) if form.is_valid(): user_check = User.objects.filter(email=form.cleaned_data['email']) if user_check.count() == 1: user = User.objects.get(email=form.cleaned_data['email']) if user: logging.debug('Changing password for %s' % user) new_password = ''.join(random.choice( string.ascii_uppercase + string.digits + string.ascii_lowercase ) for x in range(10)) send_mail( subject=_('KnoAtom Password Reset'), message=_('You requested to reset your password at ' 'knoatom.eecs.umich.edu. Here is your new ' 'password: '******'\n\nIf you did ' 'not request this change, contact us ' 'immediatly.\n\n--The Management'), from_email='*****@*****.**', recipient_list=[user.email, EMAIL_HOST_USER] ) user.set_password(new_password) user.save() logging.debug('Successfully changed password for %s: %s' % (user, new_password) ) messages.success(request, _('If we have your email on file, you ' 'should expect a password reset within a couple minutes to ' 'appear in your inbox.') ) return HttpResponseRedirect(reverse('login')) else: form = ForgotPasswordForm() context = get_breadcrumbs(request.path, web_breadcrumb_dict) context.update({ 'login_form': form }) return render(request, 'web/account/forgot_password.html', context)
def index(request): user_rate = UserRating.objects.get(user=request.user) if request.method == 'POST': if request.POST.get('action') == 'password': # Password form processing password_form = ChangePasswordForm(request.POST) username_form = ChangeUsernameForm() delete_account_form = DeleteAccountForm() if (password_form.is_valid() and password_form.cleaned_data['new_password'] == password_form.cleaned_data['new_password_confirm']): if not authenticate(username=request.user.username, password=password_form.cleaned_data['current_password'] ): messages.warning( request, _('Please supply your current password') ) else: user = User.objects.get(pk=request.user.id) if user: user.set_password( password_form.cleaned_data['new_password'] ) user.save() messages.success( request, 'Your password has been changed.' ) return HttpResponseRedirect(reverse('account')) else: messages.warning( request, _('Could not change your password. Make sure you type the ' 'same password twice in the form below') ) elif request.POST.get('action') == 'username':#Username form processing username_form = ChangeUsernameForm(request.POST) password_form = ChangePasswordForm() delete_account_form = DeleteAccountForm() if username_form.is_valid(): user = User.objects.get(pk=request.user.id) list_with_username = User.objects.filter( username=username_form.cleaned_data['new_username'] ).exists if User.objects.filter( username=username_form.cleaned_data['new_username'] ).exists(): messages.warning( request, _('The display name %s is currently in use. Please ' 'choose a different display name.' % username_form.cleaned_data['new_username'] ) ) elif user: user.username = username_form.cleaned_data['new_username'] user.save() messages.success( request, _('Your display name has been changed.') ) return HttpResponseRedirect(reverse('account')) else: messages.warning( request, _('Could not change your display name.') ) elif request.POST.get('action') == 'delete_account':#delete form delete_account_form = DeleteAccountForm(request.POST) password_form = ChangePasswordForm() username_form = ChangeUsernameForm() if delete_account_form.is_valid(): user = User.objects.get(pk=request.user.id) if (user and delete_account_form.cleaned_data['confirmation'] == 'KnoAtom'): user.delete() auth_logout(request) messages.success(request, _('Your account has been ' 'deleted. Thank for your time! --KnoAtom Staff') ) return HttpResponseRedirect(reverse('home')) else: messages.warning(request, _('The confirmation was not ' 'correct, or we could not find your account. Sorry, ' 'try again.') ) else: messages.warning(request, _('We could not delete your ' 'account.') ) else: # Request is not POST password_form = ChangePasswordForm() username_form = ChangeUsernameForm() delete_account_form = DeleteAccountForm() context = get_breadcrumbs(request.path, web_breadcrumb_dict) context.update({ 'password_form': password_form, 'username_form': username_form, 'delete_account_form': delete_account_form, 'user_rate': user_rate, }) return render(request, 'web/account/index.html', context)
def editQlist(request): context = get_breadcrumbs(request.path) context['question_list'] = request.user.owned_questions.filter(isCopy=False) return render(request, 'question/list.html', context)
def addQ(request): context = get_breadcrumbs(request.path) context['type_list']= Variable.objects.all() context['atom_list']= Atom.objects.all() return render(request, 'question/addQ.html', context)
def selectInstance(request, messages=[]): context = get_breadcrumbs(request.path) context['assignments']=request.user.owned_assignments.all() context['messages']=messages return render(request, 'assignment/select.html', context)
def viewStudent(request): user = request.user context = get_breadcrumbs(request.path) context['class_list']=user.classes_authored.all() | user.allowed_classes.all() context['user']=user return render(request, 'assignment/students.html', context)