コード例 #1
0
def create_account(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():

            user = User.objects.create_user(
                form.cleaned_data['email'],
                form.cleaned_data['email'],
                form.cleaned_data['password'],
            )
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.save()

            # Log in the new user. Note that Django requires that we call
            # authenticate() despite its apparent redundancy in this case
            user = authenticate(username=user.username,
                                password=form.cleaned_data['password'])
            login(request, user)

            return redirect(reverse('registration.views.create_account_done'))
    else:
        form = RegistrationForm()

    return render_to_response('registration/create_account.html',
                              RequestContext(request, {
                                  'form': form,
                              }))
コード例 #2
0
def signup(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()

            current_site = get_current_site(request)
            subject = 'Activate Your MySite Account'
            message = render_to_string(
                'prabhav/registration/account_activation_email.html',
                {
                    'user': user,
                    'domain': current_site.domain,
                    # 'uid':  urlsafe_base64_encode(force_bytes(user.pk)),
                    'uid': urlsafe_base64_encode(force_bytes(
                        user.pk)).decode(),
                    'token': account_activation_token.make_token(user),
                })
            from_email = [settings.EMAIL_HOST_USER]
            to_email = [user.email]
            send_mail(subject=subject,
                      from_email=from_email,
                      recipient_list=to_email,
                      message=message,
                      fail_silently=False)

            return redirect('account_activation_sent')
    else:
        form = RegistrationForm()
    return render(request, 'prabhav/registration/signup.html', {'form': form})
コード例 #3
0
def register(request, template_name='registration/register.html'):
    profile_url = settings.USER_PROFILE_URL % 'username'
    if request.method == 'GET':
        form = RegistrationForm()
    else:  # POST
        form = RegistrationForm(data=request.POST)
        if form.is_valid():
            hn_username = form.cleaned_data['hn_username']
            # user_data is a dict containing the users HN account creation
            # date, karma at query time, and HN profile
            user_data = retrieve_hn_user_data(hn_username)
            # form validation checks that hn_username matches what's provided
            # and that the "key" (a url) is in the profile
            temp_password = ''.join(random.sample(string.letters, 16))
            new_user = User.objects.create_user(username=hn_username,
                                                email='',
                                                password=temp_password)
            user = authenticate(username=new_user.username,
                                password=temp_password)

            if user is not None:
                login(request, user)
                messages.success(request,
                                 'That worked. Please provide a password.')
                return HttpResponseRedirect(reverse('set_password'))
    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))
コード例 #4
0
ファイル: views.py プロジェクト: Fak3/elections_network
def register(request):
    if request.user.is_authenticated():
        return redirect('current_profile')

    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']

            #new_user = RegistrationProfile.objects.create_inactive_user(username, email, password)
            #return redirect('registration_complete')

            user = User.objects.create_user(username, form.cleaned_data['email'], password)
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.save()

            user = auth.authenticate(username=username, password=password)

            assert user and user.is_authenticated()
            auth.login(request, user)

            # TODO: redirect to a message with confirmation
            return redirect(user.get_absolute_url())

    else:
        form = RegistrationForm()

    return render_to_response('users/register.html',
            context_instance=RequestContext(request, {'form': form}))
コード例 #5
0
    def handle_post(self, request):
        """
        Registers a user if it was a request to register a user
        and the registration form was correctly completed.

        """
        # Confirm that the requst is a post, and that this form is
        # the intended recipient of the posted data.
        if not request.POST or self.submit_btn_name() not in request.POST:
            return None
        form = RegistrationForm(request.POST, auto_id=False)
        if form.is_valid():
            # Create a user, log them in, and redirect based on the
            # success_url rules.
            user, created = User.objects.create_user(request=request,
                                                     send_email=True,
                                                     **form.cleaned_data)
            user_cache = authenticate(username=form.cleaned_data['email'],
                                      password=form.cleaned_data['password1'])
            expire_login(request, user_cache)

            response = HttpResponseRedirect(success_url(request))
            response.set_cookie('myguid',
                                user.user_guid,
                                expires=365 * 24 * 60 * 60,
                                domain='.my.jobs')
            return response
        return None
コード例 #6
0
ファイル: views.py プロジェクト: marichards/media-db
def user_profile_post(request, **kwargs):
    user=request.user
    form=RegistrationForm(request.POST)
    added_context={'registration_form': form}
    if not form.is_valid(user=user):
        form.reformat_errors()
#        log.debug('user %r not valid, aborting' % user.contributor)
        return render(request, 'registration/user_profile.html', added_context)
    
    user.first_name=form.cleaned_data['first_name']
    user.last_name=form.cleaned_data['last_name']
    user.email=form.cleaned_data['email']
    user.password=make_password(form.cleaned_data['password1'])
    user.contributor.lab.name=form.cleaned_data['lab']
    user.contributor.lab.url=form.cleaned_data['lab_url']
    try:
#        log.debug('about to save user: %r' % user.contributor)
        user.save()
        added_context['msgs']='Profile successfully updated'
    except Exception as e:
        msgs='Unable to save user information: %s' % e
        added_context['msgs']=msgs
#        log.debug(msgs)

    
    return render(request, 'registration/user_profile.html', added_context)
コード例 #7
0
ファイル: views.py プロジェクト: adsiiit/IIITM-Portal
def register(request):
	if request.user.is_authenticated():
		return HttpResponseRedirect('/profile/')
	if request.method == 'POST':
		form = RegistrationForm(request.POST)
		if form.is_valid():
			user = User.objects.create_user(username=form.cleaned_data['username'], email = form.cleaned_data['email'], password=form.cleaned_data['password'])
			user.save()

			registration = UserProfile(user=user, name = form.cleaned_data['name'],	address = form.cleaned_data['address'],
				contact = form.cleaned_data['contact'], stream = form.cleaned_data['stream'], age = form.cleaned_data['age'], 
				gender = form.cleaned_data['gender'], register_as = form.cleaned_data['register_as']
				)

			if form.cleaned_data['register_as']=='FY':
				facstat = FacultyStatus(username = form.cleaned_data['username'], name = form.cleaned_data['name'])
				facstat.save()

			if 'picture' in request.FILES:
				registration.picture = request.FILES['picture']

			registration.save()
			return HttpResponseRedirect('/profile')

		else:
			return render_to_response('registration/register.html',{'form':form, 're':"active"}, context_instance=RequestContext(request))


	else:
	 	form = RegistrationForm()
	   	context = {'form': form, 're':"active"}
	  	return render_to_response('registration/register.html', context, context_instance=RequestContext(request))
コード例 #8
0
ファイル: models.py プロジェクト: zeus911/MyJobs
    def handle_post(self, request):
        """
        Registers a user if it was a request to register a user
        and the registration form was correctly completed.

        """
        # Confirm that the requst is a post, and that this form is
        # the intended recipient of the posted data.
        if not request.POST or self.submit_btn_name() not in request.POST:
            return None
        form = RegistrationForm(request.POST, auto_id=False)
        if form.is_valid():
            # Create a user, log them in, and redirect based on the
            # success_url rules.
            user, created = User.objects.create_user(request=request,
                                                     send_email=True,
                                                     **form.cleaned_data)
            user_cache = authenticate(
                username=form.cleaned_data['email'],
                password=form.cleaned_data['password1'])
            expire_login(request, user_cache)

            response = HttpResponseRedirect(success_url(request))
            response.set_cookie('myguid', user.user_guid, expires=365*24*60*60,
                                domain='.my.jobs')
            return response
        return None
コード例 #9
0
ファイル: views.py プロジェクト: lty1/platform_django
def register(request,
             disallowed_url='registration_disallowed',
             template_name='registration/registration.html'):
    """用户注册
    """

    # 是否允许用户进行注册
    allow_register = getattr(settings, 'REGISTRATION_OPEN', False)

    if not allow_register:
        return redirect(disallowed_url)

    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        # 数据验证
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password1']        

            # 创建一个未激活的用户和默认的扩展属性
            act_key = TeamProfile.objects.create_inactive_user(username, email, password)

            # 直接将激活码作为链接发给用户
            to, args, kwargs = ('registration_activate',(), {'activation_key':act_key})
            return redirect(to, *args, **kwargs)
    else:
        form = RegistrationForm()
    
    context = RequestContext(request)

    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)
コード例 #10
0
ファイル: views.py プロジェクト: nava45/d
def edit(request):
    curr_user = request.user
    if request.method == 'POST':
        form = RegistrationForm(request.POST, user=curr_user)
        
        if form.is_valid():
            try:
                curr_user.account.first_name = form.cleaned_data['first_name']
                curr_user.account.middle_name = form.cleaned_data['middle_name']
                curr_user.account.last_name = form.cleaned_data['last_name']
                curr_user.account.mobile_no = form.cleaned_data['phone_number']
                #curr_user.account.email = form.cleaned_data['email']
                curr_user.account.save()
            except Account.DoesNotExist:
                return HttpResponse('The Account object does not exist for this user')
            
            return redirect('/register/success/')
    else:
        form = RegistrationForm(user=curr_user)
   
    return render(
                  request,
                  'registration/register.html',
                  {'form': form, 'title': 'Update Profile'}
                  )
コード例 #11
0
ファイル: views.py プロジェクト: nava45/d
def register(request):
    
    if not request.user.is_anonymous():
        return redirect('/home/')
    
    if request.method == 'POST':
        title = "Update Profile"
        form = RegistrationForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password1']
            user = User.objects.create(username=email_to_username(email),
                                       email=email)
            user.set_password(password)
            user.save()
            account = Account.objects.create(
                user=user,
                first_name=form.cleaned_data['first_name'],
                middle_name=form.cleaned_data['middle_name'],
                last_name=form.cleaned_data['last_name'],
                mobile_no=form.cleaned_data['phone_number'],
                email=form.cleaned_data['email']
            )
            return redirect('/register/success/')
    else:
        title = "Create New Profile"
        form = RegistrationForm()
   
    return render(
                  request,
                  'registration/register.html',
                  {'form': form, 'title': title}
                  )
コード例 #12
0
ファイル: views.py プロジェクト: benguillet/wmr-frontend
def create_account(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            
            user = User.objects.create_user(
                form.cleaned_data['email'],
                form.cleaned_data['email'],
                form.cleaned_data['password'],
            )
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.save()
            
            # Log in the new user. Note that Django requires that we call
            # authenticate() despite its apparent redundancy in this case
            user = authenticate(username=user.username, password=form.cleaned_data['password'])
            login(request, user)
            
            return redirect(reverse('registration.views.create_account_done'))
    else:
        form = RegistrationForm()
    
    return render_to_response('registration/create_account.html', RequestContext(request, {
        'form': form,
    }))
コード例 #13
0
ファイル: views.py プロジェクト: Rocket-Listings/Rocket-2013
def register(request, extra_context=None):

    if not getattr(settings, 'REGISTRATION_OPEN', True):
        return redirect('registration_disallowed')
    if request.method == 'POST':
        form = RegistrationForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            username, email, password = form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password1']
            site = Site.objects.get_current() if Site._meta.installed else RequestSite(request)
            new_user = RegistrationProfile.objects.create_inactive_user(username, email, password, site)
            signals.user_registered.send(sender=None, user=new_user, request=request)

            profile = UserProfile.objects.get(user=new_user)
            seller_type = form.cleaned_data['seller_type']
            phone = form.cleaned_data['phone']
            profile.seller_type = seller_type
            profile.phone = phone
            profile.save()
            gravatar_task.delay(new_user, new_user.pk)

            success_url = request.GET.get('next','')
            if success_url:                    
                return redirect(success_url)
            else:
                return redirect('registration_complete')
    else:
        form = RegistrationForm()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response('static_pages/index.html', {'register_form': form}, context_instance=context)
コード例 #14
0
ファイル: views.py プロジェクト: agentultra/hnofficehours
def register(request, template_name='registration/register.html'):
    profile_url = settings.USER_PROFILE_URL % 'username'
    if request.method == 'GET':
        form = RegistrationForm()
    else: # POST
        form = RegistrationForm(data=request.POST)
        if form.is_valid():
            hn_username = form.cleaned_data['hn_username']
            # user_data is a dict containing the users HN account creation
            # date, karma at query time, and HN profile
            user_data = retrieve_hn_user_data(hn_username)
            # form validation checks that hn_username matches what's provided
            # and that the "key" (a url) is in the profile
            temp_password = ''.join(random.sample(string.letters, 16))
            new_user = User.objects.create_user(username=hn_username,
                                                email='',
                                                password=temp_password)
            user = authenticate(username=new_user.username,
                                password=temp_password)
            
            if user is not None:
                login(request, user)
                messages.success(request, 'That worked. Please provide a password.')
                return HttpResponseRedirect(reverse('set_password'))
    return render_to_response(template_name, locals(),
                              context_instance=RequestContext(request))
コード例 #15
0
ファイル: views.py プロジェクト: Nervosa/Sit_test
def login(request):

    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('')
        else:
            return render(request, 'registration/login.html')
コード例 #16
0
ファイル: views.py プロジェクト: taha7ussein007/BotlerChat
def index(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('registration/registered')
    else:
        form = RegistrationForm()
        args = {'form': form}
        return render(request, 'registration/index.html', args)
コード例 #17
0
ファイル: views.py プロジェクト: DominykasP/Python
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('pvm_forms:index')
    else:
        form = RegistrationForm()

    return render(request, 'registration/register.html', {'form': form})
コード例 #18
0
ファイル: views.py プロジェクト: nweinthal/afs_swat
def createUser(request):
    if request.method == 'POST': # If the form has been submitted...
        form = RegistrationForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            try:
                form.save()
            except ValidationError, err:
                error = unicode(err)
                return render(request, 'createuser.html', {'form': form, 'error': error})
            return HttpResponseRedirect('/thanks/') # Redirect after POST
コード例 #19
0
ファイル: views.py プロジェクト: mikpanko/elections_network
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():
            user = form.save()
            return redirect('registration_completed')
    else:
        form = RegistrationForm()

    return TemplateResponse(request, 'registration/register.html', {'form': form})
コード例 #20
0
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST, request.FILES)
        if form.is_valid():
            user = form.save()
            login(request, user)
            user.verify_email()
            return render(request, "reg/check_email.html")
    else:
        form = RegistrationForm()
    return render(request, "reg/reg.html", context={"form": form})
コード例 #21
0
ファイル: views.py プロジェクト: dellsystem/agora-octave
def login_register(request):
    form = None
    next_url = None

    if request.method == 'POST':
        action = request.POST.get('action')
        next_url = request.GET.get('next') or reverse('login')

        if action == 'login':
            username = request.POST.get('username', '')
            password = request.POST.get('password1', '')

            if username and password:
                user = authenticate(username=username, password=password)

                if user is not None:
                    login(request, user)
                    return redirect(next_url)

                # Could not authenticate
                form = {
                    'username': {
                        'errors': 'Your username and password did not match.',
                    }
                }
            else:
                form = {
                    'password1': {
                        'errors': 'Please enter a username and password.',
                    },
                }
        elif action == 'register':
            form = RegistrationForm(request.POST)

            if form.is_valid():
                username = form.cleaned_data['username']
                email = form.cleaned_data['email']
                password = form.cleaned_data['password1']

                User.objects.create_user(username, email, password)
                user = authenticate(username=username, password=password)
                login(request, user)
                return redirect(next_url)
        else:
            # The action is not set. Malicious submission?
            pass

    context = {
        'next_url': next_url,
        'form': form,
    }

    return render(request, 'login.djhtml', context)
コード例 #22
0
ファイル: views.py プロジェクト: marichards/media-db
def register_new_user(request):
    form=RegistrationForm(request.POST)
#    log.debug('hi, prospective new user')
    if not form.is_valid():       # try again
#        log.debug('form invalid, try again')
        form.reformat_errors()
        return render(request, 'registration/login.html', {'registration_form': form})

    # check for previously existing user of that name:
    try:
        username=form.cleaned_data['username']
        user=User.objects.get(username=username)
        form.errors['username']='******' % username
#        log.debug('username %s already taken' % username)
        form.reformat_errors()
        return render(request, 'registration/login.html', {'registration_form': form})
    except User.DoesNotExist:
#        log.debug('no user %s, proceeding' % username)
        pass

    # create User:
    log.info('attempting to create new user %s' % form.cleaned_data['username'])
    username=form.cleaned_data['username']
    first_name=form.cleaned_data['first_name']
    last_name=form.cleaned_data['last_name']
    password1=form.cleaned_data['password2']
    password2=form.cleaned_data['password1']
    email=form.cleaned_data['email']
    lab_name=form.cleaned_data['lab']
    lab_url=form.cleaned_data['lab_url']

    user=User.objects.create_user(username, email, password1)
    user=auth.authenticate(username=username, password=password1)
    auth.login(request, user)
    log.info('new user %s logged in' % user.username)

    # create lab and contributor:
    try:
        lab=Lab.objects.get(name=lab_name)
    except Lab.DoesNotExist:
        lab=Lab(name=lab_name, url=lab_url)
        lab.save()
#    log.debug('new user: lab is %s' % lab)

    try:
        contributor=Contributor.objects.get(user=user)
    except Contributor.DoesNotExist:
        contributor=Contributor(user=user, first_name=first_name, last_name=last_name, lab=lab)
        contributor.save()
#    log.debug('contributor is %s' % contributor)

    url=reverse('user_profile', args=(user.username,))
    return redirect(url)
コード例 #23
0
def _register_all(trial_run, email_func):
    if trial_run:
        def trial_email(subject, body, from_, addresses, fail_silently):
            print "-" * 60
            print "Would send this mail:"
            print "To: %s" % ", ".join(addresses)
            print "From: %s" % from_
            print "Subject: %s" % subject
            print
            print body
            print '-' * 60
        email_func = trial_email

    anon_racks = Rack.objects.filter(user=u'')
    addrs = set([rack.email.strip() for rack in anon_racks])
    names_seen = set()
    current_site = Site.objects.get(id=settings.SITE_ID)
    for email in addrs:
        name = email.split('@', 1)[0]
        import re
        name = re.sub(r'[^!A-Za-z0-9_-]', '_', name)
        if name in names_seen:
            raise ValueError("Oh crap, already saw name %r" % name)
        names_seen.add(name)
        password = randpass()  # Just so we always have a non-empty password.
        data = {'username': name, 'email': email,
                'password1': password, 'password2': password,}
        template_args = {'name': name, 'email': email, 'domain': current_site.domain,
                         'password': password,
                         'activation_days': settings.ACCOUNT_ACTIVATION_DAYS,
                         }
        form = RegistrationForm(data=data)
        if form.is_valid():
            # Register an inactive account and get the key.
            template = register_email_txt
            user = form.save()
            reg_profile = RegistrationProfile.objects.filter(user=user)[0]
            template_args['key'] = reg_profile.activation_key
            # We also need to provide a way to set your password.
            template_args['password_reset_token'] = default_token_generator.make_token(user)
            template_args['uidb36'] = int_to_base36(user.id)
            if trial_run:
                user.delete(); reg_profile.delete()
        else:
            if form.errors.get('username', [''])[0].count(u'already taken'):
                # Send an email without the link to the predetermined username.
                template = register_email_name_taken_txt
            else:
                print "Problem with address %s:" % email
                import pprint
                pprint.pprint(form.errors)
                continue
        send_email(template, trial_run, email_func=email_func, **template_args)
コード例 #24
0
ファイル: views.py プロジェクト: manolisn/Farm-Subsidy
def login(request):
    #grab the redirect URL if set
    if request.POST.get('next'):
        redirect = request.POST.get('next')
    elif request.POST.get('redirect'):
        redirect = request.POST.get('redirect')
    elif request.GET.get('next'):
        redirect = request.GET.get('next')
    else:
        redirect = request.META.get('HTTP_REFERER', '/')
        if redirect.endswith("login"):
            redirect = "/myaccount"
    
    
    login_form = AuthenticationForm()
    registration_form = RegistrationForm()

    if request.POST:
    
        login_form = AuthenticationForm(request.POST)
        registration_form = RegistrationForm(request.POST)

        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        user = auth.authenticate(username=username, password=password)
    
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                return HttpResponseRedirect(redirect)
        if registration_form.is_valid():
            u = User(username=request.POST['username'],
                                    email=request.POST['email'],
                                     )
            u.set_password(request.POST['password1'])
            u.is_active = True
            u.save()
            p = Profile(user=u)
            p.save()
            user = auth.authenticate(username=request.POST['username'], password=request.POST['password1'])

            auth.login(request, user)
            return HttpResponseRedirect(redirect)
  
    return render_to_response('login.html', 
    {
        'login_form': login_form, 
        'registration_form': registration_form,
        'redirect' : redirect,
    }, 
    context_instance = RequestContext(request)
    )
コード例 #25
0
ファイル: views.py プロジェクト: WeTut/weTut
def subscribe(request):
	if request.method == 'POST':
		form = RegistrationForm(request.POST)
		if form.is_valid():
			user = User.objects.create_user(
			username=form.cleaned_data['username'],
			password=form.cleaned_data['password1'],
			email=form.cleaned_data['email']
			)
			return HttpResponseRedirect('/')
	else:
		form = RegistrationForm()
	return render(request, 'general/signup.html',{'form': RegistrationForm()})
コード例 #26
0
def createUser(request):
    if request.method == 'POST':  # If the form has been submitted...
        form = RegistrationForm(request.POST)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            try:
                form.save()
            except ValidationError, err:
                error = unicode(err)
                return render(request, 'createuser.html', {
                    'form': form,
                    'error': error
                })
            return HttpResponseRedirect('/thanks/')  # Redirect after POST
コード例 #27
0
ファイル: views.py プロジェクト: Astarael/unswfingr
def register(request):
    if request.POST:
        # load up the form with data from the POST request
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(username=form.cleaned_data['email'], email=form.cleaned_data['email'],
                                            password=form.cleaned_data['password'])
            return render(request, 'register_result.html', {'email': user.username})
        else:
            print form.errors
    else:
        form = RegistrationForm()

    return render(request, 'register.html', {'form': form})
コード例 #28
0
ファイル: views.py プロジェクト: ShiMenIT/SinoRPC
def cal(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        result = 0
        if form.is_valid():
            result = 1
            Line = form.cleaned_data['LineCode']
            Machine = form.cleaned_data['MachineCode']
            Product = form.cleaned_data['ProductCode']
            result = OEEcal(Line, Machine, Product)
    return render(request, 'production/index.html', {
        'result': result,
        'te': 1
    })
コード例 #29
0
    def test_registration_form(self):
        """
        Test that ``RegistrationForm`` enforces username constraints
        and matching passwords.

        """
        # Create a user so we can verify that duplicate usernames aren't
        # permitted.
        User.objects.create_user(**{
            'email':'*****@*****.**', 'password1':'5UuYquA@'})

        invalid_data_dicts = [
            # Already-existing username.
            {'data': {'email': '*****@*****.**',
                      'password1': '5UuYquA@',
                      'password2': '5UuYquA@'},
            #__all__ refers to a form level error.
            'error': [['__all__', [u"A user with that email already exists."]]]},
            # Mismatched passwords.
            {'data': {'email': '*****@*****.**',
                      'password1': '5UuYquA@',
                      'password2': 'bar'},
            'error': [['password1', [u"The new password fields did not match."]],
                     ['password2', [u"The new password fields did not match."]]]},
            ]

        for invalid_dict in invalid_data_dicts:
            form = RegistrationForm(data=invalid_dict['data'])
            self.failIf(form.is_valid())

            self.assertEqual(form.errors[invalid_dict['error'][0][0]],
                             invalid_dict['error'][0][1])

        form = RegistrationForm(data={'email': '*****@*****.**',
                                      'password1': '5UuYquA@',
                                      'password2': '5UuYquA@'})
        self.failUnless(form.is_valid())
コード例 #30
0
def index(request):

    success = False

    if request.method == 'POST':
        f = RegistrationForm(request.POST)
        if f.is_valid():
            success = True
            f.instance.is_active = False

            #print f.cleaned_data

            f.save()
            # присоединяем пользователя к группе зарегистрированных пользователей
            g = Group.objects.get(pk=1)
            f.instance.groups.add(g)
            # отправляем письмо с данными учетной записи пользователю
            mail_template = MailTemplate.objects.get(
                code__exact='USERREGISTRATION')
            body = mail_template.body.replace('###hostname###',
                                              request.get_host())
            body = body.replace('###username###', request.POST.get('username'))
            body = body.replace('###password###', request.POST.get('password'))
            body = body.replace(
                '###activation_link###', 'http://' + request.get_host() +
                '/registration/activate/{0}/'.format(
                    request.POST.get('username')))

            email = EmailMessage(mail_template.subject,
                                 body,
                                 mail_template.from_email, [
                                     request.POST.get('email').strip(),
                                 ],
                                 mail_template.copy_emails.split(';'),
                                 headers={
                                     'Reply-To': mail_template.from_email,
                                     'From': mail_template.from_name
                                 })

            email.content_subtype = "html"
            email.send()
            return redirect('registration_success')

    else:
        f = RegistrationForm()

    context = {'form': f, 'success': success}
    return render(request, 'registration/index.html', context)
コード例 #31
0
def register(request):
    is_registered = False
    if request.method == 'POST':
        form = RegistrationForm(data=request.POST)
        if form.is_valid():
            backend = DefaultBackend()
            new_user = backend.register(request, **form.cleaned_data)
            is_registered = True
        else:
            is_registered = False
    else:
        is_registered = False

    result = {"Status": is_registered}
    response = json.dumps(result)
    return HttpResponse(response)
コード例 #32
0
ファイル: views.py プロジェクト: sverrejoh/chishop
def create_user(request, post_data, files):
    """Create new user from a distutil client request"""
    form = RegistrationForm({"username": post_data["name"],
                             "email": post_data["email"],
                             "password1": post_data["password"],
                             "password2": post_data["password"]})
    if not form.is_valid():
        # Dist Utils requires error msg in HTTP status: "HTTP/1.1 400 msg"
        # Which is HTTP/WSGI incompatible, so we're just returning a empty 400.
        return HttpResponseBadRequest()

    backend = get_backend("registration.backends.default.DefaultBackend")
    if not backend.registration_allowed(request):
        return HttpResponseBadRequest()
    new_user = backend.register(request, **form.cleaned_data)
    return HttpResponse("OK\n", status=200, mimetype='text/plain')
コード例 #33
0
def home(request, template_name="registration/register.html"):
    """Home view"""

    # NOTE: Only using the actual 'django form' on the POST side b/c we could
    # be running split tests on the actual form elements (some are shown and
    # some aren't, etc.).  So, it's just easier to render the form ourselves on
    # the template side.

    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if not form.is_valid():
            return render(request, template_name,
                                {'test_choice': int(request.POST['choice']),
                                 'form': form})

        if form.cleaned_data['choice'] > 0:
            choice = form.cleaned_data['choice']

            try:
                result = TestResult.objects.get(pk=choice)
            except TestResult.DoesNotExist:
                result = _create_result_object(choice)

            if result is not None:
                result.conversions += 1
                result.save()

        # NOTE: The data could easily be saved here into the standard django
        # User model or a custom one.  However, the point of this app is just
        # to demonstrate A/B split testing, not saving user information.

        return HttpResponseRedirect('/register/thanks')
    else:
        # See if there's a test running for this url
        choice = _get_choice_for_split_test('registration.views.home')
        if choice > 0:
            try:
                result = TestResult.objects.get(pk=choice)
            except TestResult.DoesNotExist:
                result = _create_result_object(choice)

            if result is not None:
                result.visitors += 1
                result.save()

    return render(request, template_name, {'test_choice': choice})
コード例 #34
0
 def post(self, request, *args, **kwargs):
     form = RegistrationForm(request.POST or None)
     if form.is_valid():
         new_user = form.save(commit=False)
         username = form.cleaned_data['username']
         password = form.cleaned_data['password']
         new_user.set_password(password)
         password_check = form.cleaned_data['password_check']
         # phone = form.cleaned_data['phone']
         email = form.cleaned_data['email']
         new_user.save()
         UserAccount.objects.create(
             user=User.objects.get(username=new_user.username),
             email=new_user.email)
         return HttpResponseRedirect('/')
     context = {'form': form}
     return render(self.request, self.template, context)
コード例 #35
0
ファイル: views.py プロジェクト: jpaezsa/MyJobs
def register(request):
    """
    Registration form. Creates inactive user (which in turn sends an activation
    email) and redirect to registration complete page.

    """
    form = RegistrationForm()
    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            new_user = User.objects.create_inactive_user(**form.cleaned_data)
            username = form.cleaned_data['email']
            password = form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            expire_login(request, user)
            return HttpResponseRedirect('/accounts/register/complete/')
    return HttpResponse(json.dumps({'errors': form.errors.items()}))
コード例 #36
0
def register(request):
    """
    Registration form. Creates inactive user (which in turn sends an activation
    email) and redirect to registration complete page.

    """
    form = RegistrationForm()
    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            new_user = User.objects.create_inactive_user(**form.cleaned_data)
            username = form.cleaned_data['email']
            password = form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            expire_login(request, user)
            return HttpResponseRedirect('/accounts/register/complete/')
    return HttpResponse(json.dumps({'errors': form.errors.items()}))
コード例 #37
0
ファイル: views.py プロジェクト: joelbrady/unswfingr
def register(request):
    if request.POST:
        # load up the form with data from the POST request
        form = RegistrationForm(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            user = create_fingr_user(form.cleaned_data['email'], form.cleaned_data['password'], first_name=first_name,
                                     last_name=last_name)

            verification(form.cleaned_data['email'], user, request)

            return render(request, 'register_result.html', {'email': user.username})
    else:
        form = RegistrationForm()

    return render(request, 'register.html', {'form': form})
コード例 #38
0
def create_user(request, post_data, files, backend_name=DEFAULT_BACKEND):
    """Create new user from a distutil client request"""
    form = RegistrationForm({
        "username": post_data["name"],
        "email": post_data["email"],
        "password1": post_data["password"],
        "password2": post_data["password"]
    })
    if not form.is_valid():
        # Dist Utils requires error msg in HTTP status: "HTTP/1.1 400 msg"
        # Which is HTTP/WSGI incompatible, so we're just returning a empty 400.
        return HttpResponseBadRequest()

    backend = get_backend(backend_name)
    if not backend.registration_allowed(request):
        return HttpResponseBadRequest()
    new_user = backend.register(request, **form.cleaned_data)
    return HttpResponse("OK\n", status=200, mimetype='text/plain')
コード例 #39
0
def register(request, template_name='static_pages/splash.html'):
    if request.method == 'POST':
        form = RegistrationForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            username = form.cleaned_data['email'].split('@')[0]
            email = form.cleaned_data['email']
            password = form.cleaned_data['password1']
            if Site._meta.installed:
                site = Site.objects.get_current()
            else:
                site = RequestSite(request)
            new_user = RegistrationProfile.objects.create_inactive_user(username,
                                                                        email,
                                                                        password,
                                                                        site)
            signals.user_registered.send(sender=RegistrationProfile,
                                         user=new_user,
                                         request=request)
            profile = UserProfile.objects.get(user=new_user)
            profile.save()

            # Check if the email matches a professor in the db
            try:
                professor = Professor.objects.get(email=email)
                profile.professor_assoc = professor
                profile.save()
            except Professor.DoesNotExist:
                # Not a professor in our db, but user came from
                # professor registration page
                if request.POST.get('is_professor', False):
                    # is_professor field is only for validation
                    return redirect('prof_reg_error')
                # else drop down to normal registration

            messages.add_message(request, messages.INFO,
                                 "Thanks for signing up! Check your email for an activation link.")
            success_url = request.GET.get('next')
            if success_url:
                return redirect(success_url)
            else:
                return redirect('index')
    else:
        form = RegistrationForm()
    return TemplateResponse(request, template_name, {'form': form})
コード例 #40
0
ファイル: views_admin.py プロジェクト: perng/42learning-sis
def school_info(request):
  if request.method == 'POST':
    # adminForm.clean()

    try:
      form = SchoolForm(request.POST, instance=request.session['school'])
    except:
      new = True
      request.session['school'] = School()
      form = SchoolForm(request.POST, instance=request.session['school'])

    # sem.school=request.session['school']
    if 'password1' in request.POST:
      adminForm = RegistrationForm(request.POST)
    else:
      adminForm = None

    if adminForm and adminForm.is_valid():
      admin = User.objects.create_user(username=adminForm.cleaned_data['email'],
                                       email=adminForm.cleaned_data['email'],
                                       password=adminForm.cleaned_data[
                                         'password1'])
      role = Role(user=admin, is_admin=True)
      role.save()

    if form.is_valid():
      request.session['school'].admin = admin
      form.instance
      form.save()

      return HttpResponseRedirect('/')
    else:
      print  'form not valid', dir(form)
  else:  # GET
    try:
      form = SchoolForm(instance=request.session['school'])
    except:
      new = True
      request.session['school'] = School()
      form = SchoolForm(instance=request.session['school'])
    if not request.session['school'].admin:  # admin is in
      adminForm = RegistrationForm()

  return my_render_to_response(request, 'school_info.html', locals())
コード例 #41
0
def professor_register(request, template_name='cr_registration/professor_registration_form.html'):
    # if request.user.is_authenticated():
        # return redirect('index')
    if request.method == 'POST':
        form = RegistrationForm(data=request.POST)
        if form.is_valid():
            try:
                # professor = Professor.objects.get(email=form.cleaned_data['email'])
                return register(request,
                                template_name='cr_registration/professor_registration_form.html')
            except Professor.DoesNotExist:
                return redirect('prof_reg_error')

        else:
            return TemplateResponse(request, template_name, {'form': form})

    else:
        form = RegistrationForm()
    return TemplateResponse(request, template_name, {'form': form})
コード例 #42
0
ファイル: views.py プロジェクト: eserge/elections_network
def register(request):
    if request.user.is_authenticated():
        return redirect('edit_profile')

    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():
            user = form.save()

            #user = auth.authenticate(username=username, password=password)
            #assert user and user.is_authenticated()
            #auth.login(request, user)

            return redirect('registration_completed')
    else:
        form = RegistrationForm()

    return TemplateResponse(request, 'registration/register.html', {'form': form})
コード例 #43
0
ファイル: views.py プロジェクト: olia88/resume
def register(request):
    member_form = MemberForm(request.POST or None)
    registration_form = RegistrationForm(request.POST or None)

    if request.method == 'POST':
        member_form = MemberForm(request.POST, request.FILES)
        registration_form = RegistrationForm(request.POST)
        if member_form.is_valid() and registration_form.is_valid():
            member_form.save()
            registration_form.save()
            registration_form.new_person_form = member_form
            registration_form.save()
        else:
            member_form = member_form
            registration_form = registration_form
    return render(request, 'registration/registration_form.html', {
        'member_form': member_form,
        'registration_form': registration_form,
    })
コード例 #44
0
ファイル: views.py プロジェクト: olia88/resume
def register(request):
    member_form=MemberForm(request.POST or None)
    registration_form=RegistrationForm(request.POST or None)

    if request.method == 'POST':
        member_form = MemberForm(request.POST, request.FILES)
        registration_form = RegistrationForm(request.POST)
        if member_form.is_valid() and registration_form.is_valid():
            member_form.save()
            registration_form.save()
            registration_form.new_person_form = member_form
            registration_form.save()
        else:
            member_form = member_form
            registration_form = registration_form
    return render(request, 'registration/registration_form.html', {
        'member_form': member_form,
        'registration_form': registration_form,
        })
コード例 #45
0
ファイル: views.py プロジェクト: ryhan000/MMS
def index(request):

    register_list = Registration.objects.all()
    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            try:
                form.save()

                return redirect('/registration')

            except:
                pass
    else:
        form = RegistrationForm()

    return render(request, 'registration/index.html', {
        'form': form,
        'register_list': register_list
    })
コード例 #46
0
ファイル: views.py プロジェクト: sam9312/ita_lab6
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
                email=form.cleaned_data['email'],
                first_name=form.cleaned_data['firstname'],
                last_name=form.cleaned_data['lastname'],
                is_active=False,
            )
            return HttpResponseRedirect('success/')
    else:
        form = RegistrationForm()
    variables = RequestContext(request, {'form': form})

    return render_to_response(
        'registration/register.html',
        variables,
    )
コード例 #47
0
ファイル: views.py プロジェクト: xRowe/platform_django
def register(request,
             disallowed_url='registration_disallowed',
             template_name='registration/registration.html'):
    """用户注册
    """

    # 是否允许用户进行注册
    allow_register = getattr(settings, 'REGISTRATION_OPEN', False)

    if not allow_register:
        return redirect(disallowed_url)

    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        # 数据验证
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password1']

            # 创建一个未激活的用户和默认的扩展属性
            act_key = TeamProfile.objects.create_inactive_user(
                username, email, password)

            # 直接将激活码作为链接发给用户
            to, args, kwargs = ('registration_activate', (), {
                'activation_key': act_key
            })
            return redirect(to, *args, **kwargs)
    else:
        form = RegistrationForm()

    context = RequestContext(request)

    return render_to_response(template_name, {'form': form},
                              context_instance=context)
コード例 #48
0
ファイル: views.py プロジェクト: YuppieCC/freenote
def register(request):
	if request.method == 'POST':
		user_form = RegistrationForm(request.POST)
		if user_form.is_valid():
			username = user_form.cleaned_data.get('username')
			email = user_form.cleaned_data.get('email')
			password = user_form.cleaned_data.get('password1')
			user = User.objects.create_user(username=username, password=password, email=email)
			user.is_active = False
			user.save()
			token = token_confirm.generate_validate_token(username)

			subject = u'欢迎加入<FreeNote>'
			link = '/'.join([settings.DOMAIN, 'activate', token])
			html_content = u'<p>{0}, 欢迎加入 FreeNote ,请访问该链接,完成用户验证:</p>\
				<br><a href="{1}">点击链接完成验证</a>'.format(username, link)
			to_list = []
			to_list.append(email)
			send_html_email(subject, html_content, to_list)
			return render(request, 'site/message.html', {'message': u'请登录你的邮箱按提示进行操作'})
	else:
		user_form = RegistrationForm()
	context_dict = {'form': user_form}
	return render(request, 'registration/registration_form.html', context_dict)
コード例 #49
0
    def post(self, request):
        form = RegistrationForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get('username')
            passw = form.cleaned_data.get('password')
            user = User.objects.create_user(username=name, password=passw)
            phone = form.cleaned_data['phone']

            UserProfileModel.objects.create(user=user, phone=phone)

            group = Group.objects.get(name='clients')
            group.user_set.add(user)
            name = form.cleaned_data.get('username')
            passw = form.cleaned_data.get('password')
            auth_user = authenticate(username=name, password=passw)
            if auth_user is not None:
                login(request, auth_user)

                return redirect('/reg/changeTable/')
            return HttpResponse('<h1>ошибка авторизации</h1>')

        else:
            data = {'form': form, 'error': form.errors}
            return render(request, 'registration/registration.html', data)
コード例 #50
0
def home(request):
    """
    The home page view receives 2 separate Ajax requests, one for the
    registration form and another for the initial profile information form. If
    everything checks out alright and the form saves with no errors, it returns
    a simple string, 'valid', as an HTTP Response, which the front end
    recognizes as a signal to continue with the account creation process. If an
    error occurs, this triggers the jQuery to update the page. The form
    instances with errors must be passed back to the form template it was
    originally from.

    """
    registration_form = RegistrationForm(auto_id=False)
    login_form = CustomAuthForm(auto_id=False)

    name_form = InitialNameForm(prefix="name")
    education_form = InitialEducationForm(prefix="edu")
    phone_form = InitialPhoneForm(prefix="ph")
    work_form = InitialWorkForm(prefix="work")
    address_form = InitialAddressForm(prefix="addr")
    nexturl = request.GET.get('next')
    title_template = get_title_template(nexturl)
    if nexturl:
        nexturl = urllib2.unquote(nexturl)
        nexturl = urllib2.quote(nexturl.encode('utf8'))

    last_ms = request.COOKIES.get('lastmicrosite')
    site_name = ''
    logo_url = ''
    show_registration = True
    if last_ms:
        try:
            last_ms = get_domain(last_ms)
            custom_page = CustomHomepage.objects.get(domain=last_ms)
            logo_url = custom_page.logo_url
            show_registration = custom_page.show_signup_form
            site_name = custom_page.name

        except CustomHomepage.DoesNotExist:
            pass

    data_dict = {
        'num_modules': len(settings.PROFILE_COMPLETION_MODULES),
        'registrationform': registration_form,
        'loginform': login_form,
        'name_form': name_form,
        'phone_form': phone_form,
        'address_form': address_form,
        'work_form': work_form,
        'education_form': education_form,
        'nexturl': nexturl,
        'logo_url': logo_url,
        'show_registration': show_registration,
        'site_name': site_name,
        'logo_template': title_template,
    }

    if request.method == "POST":
        if request.POST.get('action') == "register":
            registration_form = RegistrationForm(request.POST, auto_id=False)
            if registration_form.is_valid():
                new_user, created = User.objects.create_user(
                    request=request,
                    send_email=True,
                    **registration_form.cleaned_data)
                user_cache = authenticate(
                    username=registration_form.cleaned_data['email'],
                    password=registration_form.cleaned_data['password1'])
                expire_login(request, user_cache)
                ctx = {}
                ctx['success'] = True
                response = HttpResponse(json.dumps(ctx))
                response.set_cookie('myguid',
                                    new_user.user_guid,
                                    expires=365 * 24 * 60 * 60,
                                    domain='.my.jobs')
                response.delete_cookie('loggedout')
                return response
            else:
                return HttpResponse(
                    json.dumps({'errors': registration_form.errors.items()}))

        elif request.POST.get('action') == "login":
            login_form = CustomAuthForm(data=request.POST)
            if login_form.is_valid():
                expire_login(request, login_form.get_user())

                url = request.POST.get('nexturl')

                # Boolean for activation login page to show initial forms
                # again or not
                has_units = False
                if len(login_form.get_user().profileunits_set.all()) > 0:
                    has_units = True

                response_data = {
                    'validation':
                    'valid',
                    'url':
                    url,
                    'units':
                    has_units,
                    'gravatar_url':
                    login_form.get_user().get_gravatar_url(size=100)
                }
                response = HttpResponse(json.dumps(response_data))
                response.set_cookie('myguid',
                                    login_form.get_user().user_guid,
                                    expires=365 * 24 * 60 * 60,
                                    domain='.my.jobs')
                response.delete_cookie('loggedout')
                return response
            else:
                return HttpResponse(
                    json.dumps({'errors': login_form.errors.items()}))

        elif request.POST.get('action') == "save_profile":
            name_form = InitialNameForm(request.POST,
                                        prefix="name",
                                        user=request.user)
            if not name_form.changed_data:
                name_form = InitialNameForm(prefix="name")

            education_form = InitialEducationForm(request.POST,
                                                  prefix="edu",
                                                  user=request.user)
            if not education_form.changed_data:
                education_form = InitialEducationForm(prefix="edu")

            phone_form = InitialPhoneForm(request.POST,
                                          prefix="ph",
                                          user=request.user)
            if not phone_form.changed_data:
                phone_form = InitialPhoneForm(prefix="ph")

            work_form = InitialWorkForm(request.POST,
                                        prefix="work",
                                        user=request.user)
            if not work_form.changed_data:
                work_form = InitialWorkForm(prefix="work")

            address_form = InitialAddressForm(request.POST,
                                              prefix="addr",
                                              user=request.user)
            if not address_form.changed_data:
                address_form = InitialAddressForm(prefix="addr")

            forms = [
                name_form, education_form, phone_form, work_form, address_form
            ]
            valid_forms = [form for form in forms if form.is_valid()]
            invalid_forms = []
            for form in forms:
                if form.changed_data and not form.is_valid():
                    invalid_forms.append(form)

            if not invalid_forms:
                for form in valid_forms:
                    if form.changed_data:
                        form.save(commit=False)
                        form.user = request.user
                        form.save_m2m()
                return HttpResponse('valid')
            else:
                return render_to_response(
                    'includes/initial-profile-form.html', {
                        'name_form': name_form,
                        'phone_form': phone_form,
                        'address_form': address_form,
                        'work_form': work_form,
                        'education_form': education_form
                    },
                    context_instance=RequestContext(request))

    return render_to_response('index.html', data_dict, RequestContext(request))
コード例 #51
0
def registration(request, uuid):
    print('Get FORM')
    event = get_object_or_404(Event, event_uuid=uuid)
    if request.method == 'POST':
        print('Form POST')
        form = RegistrationForm(request.POST, event_uuid=uuid)

        if form.is_valid():
            print('HERE VALID')
            last_name = form.cleaned_data['last_name']
            first_name = form.cleaned_data['first_name']
            school = form.cleaned_data['school']
            shs_track = form.cleaned_data['shs_track']
            # projected_course = form.cleaned_data['projected_course']
            email = form.cleaned_data['email']
            date_of_birth = form.cleaned_data['date_of_birth']
            gender = form.cleaned_data['gender']
            mobile = form.cleaned_data['mobile']
            print(form.cleaned_data['projected_course'])
            print(form.cleaned_data['grade_level'])
            if form.cleaned_data['projected_course'] == 'OTHER':
                print('OTHER')
                projected_course = form.cleaned_data['other']
                print(projected_course)
            else:
                projected_course = form.cleaned_data['projected_course']

            if form.cleaned_data['grade_level'] == 0:
                print('OTHER')
                grade_level = form.cleaned_data['otherGrade']
                print(grade_level)
            else:
                grade_level = form.cleaned_data['grade_level']

            student = Student()
            student.last_name = last_name
            student.first_name = first_name
            student.school = school
            student.shs_track = shs_track
            student.projected_course = projected_course
            student.email = email
            student.date_of_birth = date_of_birth
            student.gender = gender
            student.mobile = mobile
            student.registered_event = event
            student.grade_level = grade_level
            student.save()

            html_message = render_to_string('email_template.html',
                                            context={
                                                'last_name': student.last_name,
                                                'first_name':
                                                student.first_name,
                                                'school': student.school
                                            })

            msg = EmailMessage(subject='Thank You',
                               body=html_message,
                               from_email=settings.DEFAULT_FROM_EMAIL,
                               to=[student.email],
                               cc=[
                                   settings.EMAIL_CC,
                               ])

            msg.attach(student.qr_code.name, student.qr_code.read(),
                       'image/png')
            # change
            msg.content_subtype = 'html'

            try:
                msg.send(fail_silently=False)
            except Exception as e:
                connection = get_connection(
                    host=settings.EMAIL_HOST_BACKUP,
                    port=settings.EMAIL_PORT,
                    username=settings.EMAIL_HOST_USER_BACKUP1,
                    password=settings.EMAIL_HOST_USER_BACKUP_PASSWORD,
                )
                msg.connection = connection
                msg.send(fail_silently=False)

            return render(request,
                          'success.html',
                          context={
                              'student': student,
                              'event_name': event.name,
                              'event_id': event.id,
                              'event_logo': event.logo,
                              'event_uuid': event.event_uuid,
                              'qr': student.qr_code.url
                          })
    else:
        form = RegistrationForm(event_uuid=uuid)

    is_expired = date.today() > event.end_date

    context = {
        'event_uuid': event.event_uuid,
        'event_name': event.name,
        'event_id': event.id,
        'event_logo': event.logo,
        'event_start_date': event.start_date,
        'event_end_date': event.end_date,
        'form': form,
        'is_expired': is_expired,
        'courses': sorted(COURSES),
        'grade_level': GRADE_LEVEL
    }

    return render(request, 'registration.html', context=context)