def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():

            form.save()

            user = auth.authenticate(email=request.POST.get('email'),
                                     password=request.POST.get('password1'))

            if user:
                auth.login(request, user)
                messages.success(request, "You have successfully registered")
                return redirect(reverse('profile'))

            else:
                messages.error(request, "unable to log you in at this time!")

    else:
        today = datetime.date.today()
        form = UserRegistrationForm()

    args = {'form': form}
    args.update(csrf(request))

    return render(request, 'register.html', args)
예제 #2
0
def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            user = auth.authenticate(email=request.POST.get('email'),
                                     password=request.POST.get('password1'))

            if user:
                auth.login(request, user)
                messages.success(request, "You have successfully registered")
                return redirect(reverse('profile'))

            else:
                messages.error(request, "unable to log you in at this time!!!")
        else:
            return render(request, 'register.html', {'form': form})

    else:
        args = {}
        args.update(csrf(request))

        args['form'] = UserRegistrationForm()

        return render(request, 'register.html', args)
예제 #3
0
def register(request):
    """This view handles user registration."""
    form = UserRegistrationForm(request.POST or None)
    if form.is_valid():
        user = User.objects.create_user(username=form.cleaned_data["username"],
                                        email=form.cleaned_data["email"],
                                        password=form.cleaned_data["password1"],
                                        )
        user.first_name = form.cleaned_data["first_name"]
        user.last_name = form.cleaned_data["last_name"]
        user.save()
        # XXX: email i18n?!
        email_subject = "Registration for %s" % settings.SITE_NAME
        email_body = ("A new user has registered for %s.\n"
                      "username: %s\n"
                      "email: %s\n"
                      "first_name: %s\n"
                      "last_name: %s\n" % \
                      (settings.SITE_NAME, form.cleaned_data["username"], form.cleaned_data["email"],
                       form.cleaned_data["first_name"], form.cleaned_data["last_name"]))
        email_message = EmailMessage(subject=email_subject, body=email_body, from_email=settings.WEB_EMAIL, 
                                     to=[admin[1] for admin in settings.ADMINS], 
                                     headers={"Reply-To":settings.NOREPLY_EMAIL})
        email_message.send()
        return redirect("/register_success")
    
    c = {"form":form}
    c.update(csrf(request))
    c.update(locals())
    return render_to_response("register.html", c, context_instance=RequestContext(request))
예제 #4
0
def user_register(request, template_name="users/user_registration.html"):
    registration_form = UserRegistrationForm()
    if request.method == 'POST':
        registration_form = UserRegistrationForm(request.POST)
        if registration_form.is_valid():
            user = registration_form.save()
            # generate random activation code
            random.seed()
            code = random.getrandbits(128)
            activation = UserActivationCode(user=user, code=code)
            activation.save()
            
            code_url = reverse('user_activation', args=[code])
            activation_url = "http://%s%s" % (SITE_DOMAIN, code_url)
            send_mail(ACTIVATION_MAIL_SUBJECT,
                      ACTIVATION_MAIL_CONTENT % activation_url,
                      GAE_MAIL_ACCOUNT, [user.email])
            
            return direct_to_template(request,
                        "users/user_registration_confirm.html")
    extra_context = {
        'registration_form': registration_form
    }
    return direct_to_template(request, template_name,
                              extra_context=extra_context)
예제 #5
0
파일: views.py 프로젝트: LeeGeonU/hive
def register_userinfo_page(request, key):
    if request.method != "POST" :
        return HttpResponseRedirect('/')
    else:
        userinfo_form = UserRegistrationForm(request.POST)
        
        if userinfo_form.is_valid():
            try:
                user = EmailActivation.objects.get(activation_key=key)
                
                userinfo_form.clean_username()
                userinfo_form.clean_password2()
                new_user = userinfo_form.save()
                
                # Enroll Email
                new_user.email = user.email
                
                if User.objects.all().count() is 1:
                    new_user.is_staff = True
                    new_user.is_superuser = True
                
                new_user.save()
                # Delete Activation Key 
                user.delete() 
                
                # Self-Following
                UserProfile.objects.create(user=new_user)
                Following.objects.create(followee=new_user,
                                         followee_str = new_user.username,
                                         follower=new_user,
                                         follower_str = new_user.username)
            except ObjectDoesNotExist:
                return HttpResponseRedirect('/')    
                        
        return HttpResponseRedirect('/')            
예제 #6
0
def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            # Create a new user object but avoid saving it yet
            new_user = form.save(commit=False)
            # Set the chosen password                 
            new_user.set_password(
                form.cleaned_data['password'])
            # Save the User object
            new_user.save()
            profile = Profile(user=new_user)
            profile.save()
            # 記錄系統事件
            if is_event_open(request) :   
                log = Log(user_id=new_user.id, event='註冊帳號成功')
                log.save()                
        
            # create Message
            title = "請洽詢任課教師課程名稱及選課密碼"
            url = "/student/classroom/add"
            message = Message.create(title=title, url=url, time=timezone.now())
            message.save()                        
                    
            # message for group member
            messagepoll = MessagePoll.create(message_id = message.id,reader_id=new_user.id)
            messagepoll.save()               
            return render(request,
                          'account/register_done.html',
                          {'new_user': new_user})
    else:
        form = UserRegistrationForm()
    return render(request,
                  'account/register.html',
                  {'form': form})
예제 #7
0
def add_user(request):
    username = request.POST.get("username")
    email = request.POST.get("emailid")
    password = request.POST.get("password")
    fname = request.POST.get("fname")
    lname = request.POST.get("lname")
    address = request.POST.get("address")
    phone = request.POST.get("phone")
    tech = request.POST.get("tech")
    print('.........address........', address)
    if request.method == 'GET':
        print('get here')
        form = UserRegistrationForm()  # object creation
    else:
        print('form in post')
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            print('user registration from valid')
            user = User.objects.create_user(username, email, password)
            user.first_name = fname
            user.last_name = lname
            user.save()
            a = UserProfile(user_id=user.id,
                            address=address,
                            phone=phone,
                            tech=tech)
            a.save()
            print('saved')
            return HttpResponseRedirect('/homepage/')
    return render(request, 'registration.html', {
        'form': form,
    })
예제 #8
0
 def test_registration_form(self):
     form = UserRegistrationForm({
         'email': '*****@*****.**',
         'password1': 'tester33',
         'password2': 'tester33',
     })
     self.assertTrue(form.is_valid())
예제 #9
0
def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            # Create a new user object but avoid saving it yet
            new_user = form.save(commit=False)
            # Set the chosen password
            new_user.set_password(form.cleaned_data['password'])
            # Save the User object
            new_user.save()
            profile = Profile(user=new_user)
            profile.save()
            # 記錄系統事件
            if is_event_open(request):
                log = Log(user_id=new_user.id, event='註冊帳號成功')
                log.save()

            # create Message
            title = "請洽詢任課教師課程名稱及選課密碼"
            url = "/student/classroom/add"
            message = Message.create(title=title, url=url, time=timezone.now())
            message.save()

            # message for group member
            messagepoll = MessagePoll.create(message_id=message.id,
                                             reader_id=new_user.id)
            messagepoll.save()
            return render(request, 'account/register_done.html',
                          {'new_user': new_user})
    else:
        form = UserRegistrationForm()
    return render(request, 'account/register.html', {'form': form})
예제 #10
0
def user_register(request, template_name="users/user_registration.html"):
    registration_form = UserRegistrationForm()
    if request.method == 'POST':
        registration_form = UserRegistrationForm(request.POST)
        if registration_form.is_valid():
            user = registration_form.save()
            # generate random activation code
            random.seed()
            code = random.getrandbits(128)
            activation = UserActivationCode(user=user, code=code)
            activation.save()
            
            code_url = reverse('user_activation', args=[code])
            activation_url = "http://%s%s" % (settings.SITE_DOMAIN, code_url)
            send_mail(ACTIVATION_MAIL_SUBJECT,
                      ACTIVATION_MAIL_CONTENT % activation_url,
                      settings.ACTIVATION_FROM_EMAIL, [user.email])
            
            return direct_to_template(request,
                        "users/user_registration_confirm.html")
    extra_context = {
        'registration_form': registration_form
    }
    return direct_to_template(request, template_name,
                              extra_context=extra_context)
예제 #11
0
 def test_registration_form_success(self):
     form = UserRegistrationForm({
         'email': '*****@*****.**',
         'public_name': 'test name 1',
         'password1': 'testpassword1',
         'password2': 'testpassword1'
     })
     self.assertTrue(form.is_valid())
예제 #12
0
    def test_registration_form(self):
        form = UserRegistrationForm({
            'username': '******',
            'email': '*****@*****.**',
            'password1': 'letmein1',
            'password2': 'letmein1',
        })
 
        self.assertTrue(form.is_valid())
예제 #13
0
 def test_registration_form_missing_email(self):
     form = UserRegistrationForm({
         'password1': 'test35',
         'password2': 'test35',
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Please enter your email address",
                              form.full_clean())
예제 #14
0
 def test_registration_form_password_missing(self):
     form = UserRegistrationForm({
         'email': '*****@*****.**',
         'password1': 'tester40',
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Second Password is missing",
                              form.full_clean())
예제 #15
0
 def test_registration_form_fails_with_missing_password2(self):
     form = UserRegistrationForm({
         'email': '*****@*****.**',
         'public_name': 'test name 4',
         'password1': 'testpassword1'
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Passwords do not match", form.full_clean())
예제 #16
0
 def test_registration_form_passwords_not_matching(self):
     form = UserRegistrationForm({
         'email': '*****@*****.**',
         'password1': 'tester38',
         'password2': 'tester39',
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Passwords do not match", form.full_clean())
예제 #17
0
 def test_registration_form_fails_with_missing_public_name(self):
     form = UserRegistrationForm({
         'email': '*****@*****.**',
         'password1': 'testpassword1',
         'password2': 'testpassword1'
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Please fill in this field",
                              form.full_clean())
예제 #18
0
 def test_registration_form_fails_with_missing_password(self):
     form = UserRegistrationForm({
         'username': '******',
         'email': '*****@*****.**',
         'password1': 'letmein1',
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                             "please enter both passwords",
                             form.full_clean())
 def test_registration_form_fails_wih_passwords_that_dont_match(self):
     form = UserRegistrationForm({
         'username': '******',
         'email': '*****@*****.**',
         'password1': 'testing1',
         'password2': 'testing2'
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Passwords do not match", form.full_clean())
예제 #20
0
파일: views.py 프로젝트: meerstein/rbtm
def registration_view(request):
    if request.method == 'POST':
        user_form = UserRegistrationForm(request.POST)
        userprofile_form = UserProfileRegistrationForm(request.POST)
        if user_form.is_valid() and userprofile_form.is_valid():
            user = user_form.save(commit=False)
            user.is_active = False
            new_profile = userprofile_form.save(commit=False)

            #attempt = try_user_sending(request, u'Невозможно завершить регистрацию', settings.STORAGE_CREATE_USER_HOST,
            #                           user=user)

            #if attempt:  # if something went wrong
            #    return attempt

            user.save()

            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            activation_key = hashlib.sha1(salt + user.email).hexdigest()
            new_profile.user = user
            new_profile.activation_key = activation_key
            activation_link = u'{}/accounts/confirm/{}'.format(request.get_host(), activation_key)
            email_subject = '[Томограф] Подтверждение регистрации'
            email_body = u"Приветствуем Вас на сайте Robo-Tom, {}!\n\
             Для активации аккаунта пройдите по следующей ссылке: {}".format(user.username, activation_link)

            try:
                send_mail(email_subject, email_body, '*****@*****.**',
                          [user.email], fail_silently=False)
            except BaseException as e:
                import traceback
                main_logger.error(traceback.print_exc()) 
                main_logger.error(e)  
                messages.warning(request,
                                 'Произошла ошибка при отправке письма о подтверждении регистрации. Попробуйте \
                                 зарегистрироваться повторно, указав корректный email')
            else:
                messages.success(request,
                                 'На указанный Вами адрес было отправлено письмо. Для завершения регистрации и \
                                 подтверждения адреса перейдите по ссылке, указанной в письме')
            new_profile.save()
            userprofile_form.save_m2m()
            return redirect(reverse('main:done'))
        else:
            return render(request, 'registration/registration_form.html', {
                'user_form': user_form,
                'userprofile_form': userprofile_form,
                'caption': 'Регистрация'
            })

    return render(request, 'registration/registration_form.html', {
        'user_form': UserRegistrationForm(),
        'userprofile_form': UserProfileRegistrationForm(),
        'caption': 'Регистрация'
    })
예제 #21
0
def registration_view(request):
    if request.method == 'POST':
        user_form = UserRegistrationForm(request.POST)
        userprofile_form = UserProfileRegistrationForm(request.POST)
        if user_form.is_valid() and userprofile_form.is_valid():
            user = user_form.save(commit=False)
            user.is_active = False
            new_profile = userprofile_form.save(commit=False)

            #attempt = try_user_sending(request, u'Невозможно завершить регистрацию', settings.STORAGE_CREATE_USER_HOST,
            #                           user=user)

            #if attempt:  # if something went wrong
            #    return attempt

            user.save()

            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            activation_key = hashlib.sha1(salt + user.email).hexdigest()
            new_profile.user = user
            new_profile.activation_key = activation_key
            activation_link = u'{}/accounts/confirm/{}'.format(request.get_host(), activation_key)
            email_subject = '[Томограф] Подтверждение регистрации'
            email_body = u"Приветствуем Вас на сайте Robo-Tom, {}!\n\
             Для активации аккаунта пройдите по следующей ссылке: {}".format(user.username, activation_link)

            try:
                send_mail(email_subject, email_body, '*****@*****.**',
                          [user.email], fail_silently=False)
            except BaseException as e:
                import traceback
                main_logger.error(traceback.print_exc()) 
                main_logger.error(e)  
                messages.warning(request,
                                 'Произошла ошибка при отправке письма о подтверждении регистрации. Попробуйте \
                                 зарегистрироваться повторно, указав корректный email')
            else:
                messages.success(request,
                                 'На указанный Вами адрес было отправлено письмо. Для завершения регистрации и \
                                 подтверждения адреса перейдите по ссылке, указанной в письме')
            new_profile.save()
            userprofile_form.save_m2m()
            return redirect(reverse('main:done'))
        else:
            return render(request, 'registration/registration_form.html', {
                'user_form': user_form,
                'userprofile_form': userprofile_form,
                'caption': 'Регистрация'
            })

    return render(request, 'registration/registration_form.html', {
        'user_form': UserRegistrationForm(),
        'userprofile_form': UserProfileRegistrationForm(),
        'caption': 'Регистрация'
    })
예제 #22
0
 def test_form_is_valid(self):
     form = UserRegistrationForm({
         'username': '******',
         'email': '*****@*****.**',
         'password1': 'letmein1',
         'password2': 'letmein1',
         'first_name': 'test',
         'last_name': 'test',
         'company': 'test'
     })
     self.assertTrue(form.is_valid())
예제 #23
0
def register_view(request):
    if request.method == "POST":
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            new_user = User.objects.create_user(**form.cleaned_data)
            username = request.POST.get('username')
            password = request.POST.get('password')
            print "username:"******"password", password
            return login_user(request, username, password)
    else:
        form = UserRegistrationForm()
    return render(request, 'ncqs/register.html', {'form': form})
예제 #24
0
 def test_form_fails_when_missing_password2(self):
     form = UserRegistrationForm({
         'username': '******',
         'email': '*****@*****.**',
         'password1': 'letmein1',
         'first_name': 'test',
         'last_name': 'test',
         'company': 'test'
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Please confirm your password")
예제 #25
0
def register_view(request):
    if request.method=="POST":
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            new_user = User.objects.create_user(**form.cleaned_data)
            username = request.POST.get('username')
            password = request.POST.get('password')
            print "username:"******"password",password
            return login_user(request, username, password)
    else:
        form = UserRegistrationForm()
    return render(request, 'ncqs/register.html', {'form':form})
예제 #26
0
def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            form = None
    else:
        form = UserRegistrationForm()

    return render_to_response(
        'users/register.html',
        RequestContext(request, { 'form': form,
                                  'page': 'register' })
        )
예제 #27
0
 def test_form_fails_when_password_not_letters(self):
     form = UserRegistrationForm({
         'username': '******',
         'email': '*****@*****.**',
         'password1': '12345678',
         'password2': '12345678',
         'first_name': 'test',
         'last_name': 'test',
         'company': 'test'
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Password must contain at least 1 letter")
예제 #28
0
def register_user(request):
  if request.method == 'POST':
    form = UserRegistrationForm(request.POST)
    if form.is_valid():
      form.save()
      return HttpResponseRedirect('/register_success')

  args = {}
  args.update(csrf(request))

  args['form'] = UserRegistrationForm()

  return render_to_response('register.html', args)
예제 #29
0
파일: views.py 프로젝트: fcharming/bookmark
def register(request):
    if request.method == "POST":
        user_form = UserRegistrationForm(request.POST)
        if user_form.is_valid():
            new_user = user_form.save(commit=False)
            new_user.set_password(user_form.cleaned_data['password'])
            new_user.save()
            profile = Profile.objects.create(user=new_user)
            create_action(new_user,'has created an account')
            return render(request,'account/register_done.html',{'new_user':new_user})
    else:
        user_form = UserRegistrationForm()
    return render(request,'account/register.html',{'user_form': user_form})
예제 #30
0
    def test_registration_form(self):
        form = UserRegistrationForm({
            'email': '*****@*****.**',
            'password1': 'letmein1',
            'password2': 'letmein1',
            'stripe_id': settings.STRIPE_SECRET,
            'credit_card_number': 4242424242424242,
            'cvv': 123,
            'expiry_month': 1,
            'expiry_year': 2033
        })

        self.assertTrue(form.is_valid())
예제 #31
0
 def test_form_fails_when_password_too_short(self):
     form = UserRegistrationForm({
         'username': '******',
         'email': '*****@*****.**',
         'password1': 'letme',
         'password2': 'letme',
         'first_name': 'test',
         'last_name': 'test',
         'company': 'test'
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Password must be at least 8 characters long")
예제 #32
0
 def test_form_fails_when_password_dont_match(self):
     form = UserRegistrationForm({
         'username': '******',
         'email': '*****@*****.**',
         'password1': 'letmein1',
         'password2': 'letmein2',
         'first_name': 'test',
         'last_name': 'test',
         'company': 'test'
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Passwords do not match")
예제 #33
0
파일: views.py 프로젝트: potray/TFM-Web
def registration(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            # Hash the password.
            print form.cleaned_data
            newUser = form.instance
            newUser.password = make_password(newUser.password)
            newUser.email = newUser.username
            newUser.save()
            return HttpResponseRedirect('/')
    else:
        form = UserRegistrationForm()
    return render(request, 'registration.html', {'form': form})
예제 #34
0
 def test_registration_form_fails_wih_passwords_that_dont_match(self):
     form = UserRegistrationForm({
         'email': '*****@*****.**',
         'password1': 'letmein1',
         'password2': 'letmein2',
         'stripe_id': settings.STRIPE_SECRET,
         'credit_card_number': 4242424242424242,
         'cvv': 123,
         'expiry_month': 1,
         'expiry_year': 2033
     })
     self.assertFalse(form.is_valid())
     self.assertRaisesMessage(forms.ValidationError,
                              "Passwords do not match", form.full_clean())
예제 #35
0
def register(request):
    if request.method == 'POST':
        urf = UserRegistrationForm(request.POST)
        if(urf.is_valid()):
            urf.save()
            return redirect('home')
        else:
            print(urf.errors)
            context = RequestContext(request)
            context['urf'] = urf
            return render_to_response('register.html', context)
            
    else:
        return HttpResponseNotAllowed('POST requests only')
예제 #36
0
    def test_registration_form_fails_with_missing_password(self):
        form = UserRegistrationForm({
            'email': '*****@*****.**',
            'password1': 'letmein1',
            'stripe_id': settings.STRIPE_SECRET,
            'credit_card_number': 4242424242424242,
            'cvv': 123,
            'expiry_month': 1,
            'expiry_year': 2033
        })

        self.assertFalse(form.is_valid())
        self.assertRaisesMessage(forms.ValidationError,
                                 "Please re-type your password",
                                 form.full_clean())
예제 #37
0
파일: views.py 프로젝트: bxm156/ServicePad
def register(request, **kwargs):
    if request.POST:
        new_data = request.POST.copy()
        #Create form with user data

        account_type = int(new_data['form_type'])
        if account_type is UserProfile.ACCOUNT_VOLUNTEER:
            registration = UserRegistrationForm(new_data)
        elif account_type is UserProfile.ACCOUNT_ORGANIZATION:
            registration = OrganizationRegistrationForm(new_data)
        else:
            raise InvalidRegistrationRequest

        #Process data
        if registration.is_valid():
            #Create user
            new_user = registration.save()

            try:
                activation_key = get_object_or_404(ActivationKey,
                                                   user=new_user)
            except MultipleObjectsReturned:
                return render_to_response('confirm.djhtml', {'success': False})

            #Activation URL
            url = request.get_host() + "/register/confirm/%u/%s" % (
                new_user.id, activation_key.activation_key)
            #Send email
            send_email(new_user.username, "Activation Email", url)
            return render_to_response('register_thankyou.djhtml', {'url': url})
        else:
            context = RequestContext(request, {
                'errors': registration.errors,
                'form': registration
            })
            return render_to_response('register_manual.djhtml', context)

    #Show new form
    if kwargs['type'] == UserProfile.ACCOUNT_VOLUNTEER:
        registration = UserRegistrationForm()
    elif kwargs['type'] == UserProfile.ACCOUNT_ORGANIZATION:
        registration = OrganizationRegistrationForm()
    else:
        registration = UserRegistrationForm()
    context = RequestContext(request, {'form': registration})
    return render_to_response('register_manual.djhtml', context)
예제 #38
0
파일: views.py 프로젝트: Apothys/ServicePad
def register(request,**kwargs):    
    if request.POST:
        new_data = request.POST.copy()
        #Create form with user data
        
        account_type = int(new_data['form_type'])
        if account_type is UserProfile.ACCOUNT_VOLUNTEER:
            registration = UserRegistrationForm(new_data)
        elif account_type is UserProfile.ACCOUNT_ORGANIZATION:
            registration = OrganizationRegistrationForm(new_data)
        else:
            raise InvalidRegistrationRequest
        
        #Process data
        if registration.is_valid():
            #Create user
            new_user = registration.save()
            
            try:
                activation_key = get_object_or_404(ActivationKey,user=new_user)
            except MultipleObjectsReturned:
                return render_to_response('confirm.djhtml',{'success':False})
            
            #Activation URL
            url = request.get_host() + "/register/confirm/%u/%s" % (new_user.id,activation_key.activation_key)
            #Send email
            send_email(new_user.username,"Activation Email",url)
            return render_to_response('register_thankyou.djhtml',{'url':url})
        else:
            context = RequestContext(request,
                                     {'errors':registration.errors,
                                     'form':registration})
            return render_to_response('register_manual.djhtml', context)
    
    #Show new form
    if kwargs['type'] == UserProfile.ACCOUNT_VOLUNTEER:
        registration = UserRegistrationForm()
    elif kwargs['type'] == UserProfile.ACCOUNT_ORGANIZATION:
        registration = OrganizationRegistrationForm()
    else:
        registration = UserRegistrationForm()
    context = RequestContext(request,
           {'form':registration}
    )
    return render_to_response('register_manual.djhtml', context)
예제 #39
0
def userRegistration(request):
    
    if request.method == 'POST':
        
        form = UserRegistrationForm(request.POST)
        
        if form.is_valid():
            try:
                user = form.save()
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                login(request, user)
                return HttpResponseRedirect("/tasks")
                
            except Exception as error:
                return HttpResponseRedirect('/?error='+str(error)[1:-1])
            return HttpResponseRedirect('/')
        return HttpResponseRedirect('/?error=invalid_input')
	return HttpResponse(403)
예제 #40
0
def register(request):
    is_post = request.method == 'POST'

    if is_post:
        form = UserRegistrationForm(request.POST)

        if form.is_valid():
            form.save()
            data = create_user_json(request)

            return HttpResponse(data, mimetype='application/json')

        return HttpResponse(status=401)

    args = {}
    args.update(csrf(request))
    args['form'] = UserRegistrationForm()

    return render_to_response('users/register.html', args)
예제 #41
0
def register(request):
  is_post = request.method == 'POST'

  if is_post:
    form = UserRegistrationForm(request.POST)

    if form.is_valid():
      form.save()
      data = create_user_json(request)

      return HttpResponse(data, mimetype='application/json')

    return HttpResponse(status=401)

  args = {}
  args.update(csrf(request))
  args['form'] = UserRegistrationForm()

  return render_to_response('users/register.html', args)
예제 #42
0
    def test_form_fails_when_email_not_unique(self):

        self.user = User.objects.create(username='******',
                                        email='*****@*****.**',
                                        password='******',
                                        first_name='test', last_name='test',
                                        company='test')
        self.user.save()

        form = UserRegistrationForm({
            'username': '******',
            'email': '*****@*****.**',
            'password1': 'letmein1',
            'password2': 'letmein1',
            'first_name': 'test',
            'last_name': 'test',
            'company': 'test'
        })
        self.assertFalse(form.is_valid())
        self.assertRaisesMessage(forms.ValidationError,
                                 "That email address is already registered")
예제 #43
0
def registerUser(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            user = authenticate(username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'])
            if form.cleaned_data['choice'] == 'advertiser':
                folderPath = ADVERTISERS_ROOT + 'user_' + str(user.id)
                advertisersGrp = Group.objects.get(name='Advertisers')
                advertisersGrp.user_set.add(user)
                advertisersGrp.save()
                user.is_staff = True
                user.save()
                os.mkdir(folderPath)

            login(request,user)
            return redirect(reverse('index'))
    else:
        form = UserRegistrationForm()
    return render(request, 'oglasnik/userRegistration.html', {'form': form})
예제 #44
0
def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            username = cd['username']
            password = cd['password']
            if not (User.objects.filter(username=username).exists()):
                user = User.objects.create_user(username=username,
                                                password=password)
                profile = Profile(user=user)
                profile.save()
                logsin(request, user)
                return redirect('index')
    else:
        form = UserRegistrationForm()
        return render(request, 'register.html', {
            'form': form,
            'user': request.user
        })
    return render(request, 'register.html', {
        'form': form,
        'user': request.user
    })
예제 #45
0
def registration(request):   
    if request.method == 'POST': # If the form has been submitted...
        form = UserRegistrationForm(request.POST) # A form bound to the POST data
        if form.is_valid():
            if request.user.is_authenticated():
                user = User.objects.get(username__exact=request.user.username)
                if(user.check_password(form.cleaned_data['passw'])):
                    if(form.cleaned_data['year'] != None) and (form.cleaned_data['month'] != None) and (form.cleaned_data['day'] != None):
                            try:
                                user.get_profile().birthday = datetime.date(int(form.cleaned_data['year']), int(form.cleaned_data['month']), int(form.cleaned_data['day']))
                            except:
                                pass
                    if(form.cleaned_data['bio'] != None): 
                            user.get_profile().bio = form.cleaned_data['bio']          
                    if 'photo' in request.FILES:
                            user.get_profile().photo = request.FILES['photo']
                            im = Image.open(user.get_profile().photo)
                    else:
                        user.get_profile().photo = 'media/unknown_user.gif'
                    if(form.cleaned_data['gender'] != None): 
                            user.get_profile().gender = form.cleaned_data['gender']   
                    if(form.cleaned_data['firstname'] != None):
                            user.get_profile().firstname = form.cleaned_data['firstname']
                    if(form.cleaned_data['lastname'] != None):
                            user.get_profile().lastname = form.cleaned_data['lastname']
                    if(form.cleaned_data['uemail'] != None):
                            user.email = form.cleaned_data['uemail']
                    user.get_profile().save()
                    context = RequestContext(request)
                    return render_to_response('users/profile.html', context)
        
            if not request.user.is_authenticated():
                    #First initialize a basic user
                    user = User.objects.create_user(form.cleaned_data['usern'], form.cleaned_data['uemail'], form.cleaned_data['passw'])
                    user = authenticate(username=form.cleaned_data['usern'], password=form.cleaned_data['passw'])
                    login(request, user)
                   
                    #Set up extended user profile
                    user.profile.firstname = form.cleaned_data['firstname']
                    user.get_profile().firstname = request.POST['firstname']
                    user.get_profile().lastname = request.POST['lastname']
                    
                    if 'photo' in request.FILES:
                        user.get_profile().photo = request.FILES['photo']
                        im = Image.open(user.get_profile().photo)
                    else:
                        user.get_profile().photo = 'media/unknown_user.gif'
                        
                    user.get_profile().gender = form.cleaned_data['gender']
                    print form.cleaned_data['year']
                    print form.cleaned_data['month']
                    print form.cleaned_data['day']
                    if((form.cleaned_data['year'] is not '') and (form.cleaned_data['month'] is not '') and (form.cleaned_data['day'] is not '')):
                            try:
                                user.get_profile().birthday = datetime.date(int(form.cleaned_data['year']), int(form.cleaned_data['month']), int(form.cleaned_data['day']))
                            except:
                                pass
                    user.get_profile().bio = request.POST['bio']
                    user.get_profile().save()
                        
                    #Set up context
                    context = RequestContext(request)
                    context['Success'] = True
                    context['UserName'] = form.cleaned_data['usern']
                    context['FirstName'] = form.cleaned_data['firstname']
                    context['LastName'] = form.cleaned_data['lastname']
                    context['Email'] =form.cleaned_data['uemail']
                    context['Bio']= form.cleaned_data['bio']
                    context['Gender']= form.cleaned_data['gender']
                    context['Birthday']= user.get_profile().birthday
                    context['Photo'] = user.get_profile().photo
                    return render_to_response('users/registration.html', context)
            else:
                    context = RequestContext(request) 
                    context['form'] = form 
        else:
            context = RequestContext(request) 
            context['form'] = form 
                
     # Populate the form if the user is logged in
    elif request.user.is_authenticated():
        user = request.user
        form = UserRegistrationForm(initial={'usern': user.username,
                                             'firstname':user.get_profile().firstname ,
                                             'lastname': user.get_profile().lastname,
                                             'uemail': user.email,
                                             'gender': user.get_profile().gender,
                                             'birthday': user.get_profile().birthday,
                                             'bio': user.get_profile().bio,
                                             'photo': user.get_profile().photo,
                                             'passw': user.password,
                                             'passwr': user.password,})    
        context = RequestContext(request) 
        context['form'] = form 
          
    else:
        form = UserRegistrationForm()
        context = RequestContext(request) 
        context['form'] = form 
    
    return render_to_response('users/registration.html', context)
예제 #46
0
def reg(request, token):
    if request.user.is_authenticated():
        return render(request, 'index.html')
    else:
        try:
            activation = Activation.objects.get(token=token)
        except Activation.DoesNotExist:
            raise Exception("Неверный код")
        if activation.status == activation.REGISTERED:
            return render(request, 'login.html')
        elif activation.status == activation.EMAIL_SENT:
            raise Exception("Сначала подтвердите емейл")
        context = dict()
        email = Activation.objects.get(token=token).email
        shortcut = lambda: render(request, 'reg.html', context)

        if 'code' in request.GET and not 'vkuserid' in request.POST:
            code = request.GET['code']
            try:
                access_token, user_id = vkontakte.auth_code(code, request.path)
            except vkontakte.AuthError as e:
                messages.warning(request, 'Ошибка авторизации')
                context['form'] = UserRegistrationForm(request.POST)
                return shortcut()
            if User.objects.filter(vkuserid=user_id).count() == 0:
                vkuser = vkontakte.api(access_token, 'users.get', fields=['sex', 'bdate', 'city',
                                                                          'photo_max', 'contacts'])[0]
                vkdata = dict()
                vkdata['vkuserid'] = user_id

                vkdata['first_name'] = vkuser['first_name']
                vkdata['last_name'] = vkuser['last_name']

                if 'mobile_phone' in vkuser:
                    vkdata['phone'] = vkuser['mobile_phone']
                elif 'home_phone' in vkuser:
                    vkdata['phone'] = vkuser['home_phone']
                else:
                    vkdata['phone'] = None

                if vkuser['sex']:
                    if vkuser['sex'] == 2:
                        vkdata['sex'] = 'm'
                    elif vkuser['sex'] == 1:
                        vkdata['sex'] = 'f'
                else:
                    vkdata['sex'] = None

                if 'bdate' in vkuser:
                    if len(vkuser['bdate']) >= 8:
                        vkdata['bdate'] = vkuser['bdate']
                    elif vkuser['bdate'] != '':
                        messages.warning(request, 'Неполная дата')
                        vkdata['bdate'] = vkuser['bdate']
                else:
                    vkdata['bdate'] = ''

                if 'photo_max' in vkuser:
                    url = vkuser['photo_max']
                    vkdata['avatar'] = url
                    context['avatar_url'] = url

                context['vkdata'] = vkdata
                context['vkuserid'] = user_id

                initial = {'email': email,
                           'sex': vkdata['sex'],
                           'first_name': vkdata['first_name'],
                           'last_name': vkdata['last_name'],
                           'phone': vkdata['phone'],
                           'bdate': vkdata['bdate'],
                           'vkuserid': user_id,
                           'avatar': vkdata['avatar']
                           }

                context['form'] = UserRegistrationForm(initial=initial)
                return shortcut()
            else:
                messages.warning(request, 'Такой пользователь уже зарегестрирован в системе')

        if request.method == 'POST':
            form = UserRegistrationForm(request.POST)
            if form.is_valid():
                print form.cleaned_data
                user = form.save(commit=False)
                user.set_password(user.password)
                activation = Activation.objects.get(email=user.email)
                activation.status = activation.REGISTERED
                activation.save()
                user.save()
                newuser = auth.authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password'])
                auth.login(request, newuser)
                return redirect('index')
            else:
                context['form'] = form
                messages.success(request, "Form is not valid!")
                return shortcut()
        context['form'] = UserRegistrationForm(initial={'email': email})
        return shortcut()