Exemplo n.º 1
0
def new_headmaster(request):
    if request.method == 'POST':
        registration_form = RegistrationForm(data=request.POST)
        headmaster_form = NewHeadMaster(data=request.POST)
        school_form = NewSchool(data=request.POST)
        address_form = NewAddress(data=request.POST)
        if registration_form.is_valid() and \
                headmaster_form.is_valid() and \
                school_form.is_valid() and address_form.is_valid():
            user = registration_form.save()
            headmaster = headmaster_form.save(commit=False)
            school = school_form.save(commit=False)
            address = address_form.save()
            school.address = address
            school.save()
            headmaster.school = school
            headmaster.user = user
            headmaster.save()
            return redirect('home')
    else:
        registration_form = RegistrationForm()
        headmaster_form = NewHeadMaster()
        address_form = NewAddress()
        school_form = NewSchool()
    return render(request, "new_headmaster.html",
                  {'form': registration_form,
                   'form1': headmaster_form,
                   'form3': address_form,
                   'form2': school_form})
Exemplo n.º 2
0
def registration(request):
    context = dict()
    context['form'] = RegistrationForm
    context.update(csrf(request))
    if request.POST:
        form = RegistrationForm(request.POST)
        context['form'] = form
        if form.is_valid():
            form.save()  # save user to database if form is valid

            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            salt = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
            salted_email = salt + email
            activation_key = hashlib.sha1(salted_email.encode('utf-8')).hexdigest()
            key_expires = datetime.datetime.today() + datetime.timedelta(2)

            # Get new user by username
            new_user = User.objects.get(username=username)

            # Create and save user profile
            new_profile = UserProfile(user=new_user, activation_key=activation_key, key_expires=key_expires)
            new_profile.save()

            # Send email with activation key
            email_subject = 'Account confirmation'
            email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \
            48hours http://127.0.0.1:8000/user/confirm/%s" % (username, activation_key)

            send_mail(email_subject, email_body, '*****@*****.**', [email], fail_silently=False)

            return redirect('user.views.login')
        else:
            context['form'] = form
    return render(request, "registration.html", context)
Exemplo n.º 3
0
    def create(self, request):
        success = False
        response = None

        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                form.cleaned_data['email'],
                password=form.cleaned_data['password'],
                phone_number=form.cleaned_data['phone_number'],
                user_type=request.data['user_type'])
            # user.phone_number =
            # email side
            password = form.cleaned_data['password']
            user.set_password(password)
            success = True
            user.save()
            response = JsonResponse({
                'success': success,
                'detail': 'User successfully created'
            })
            response.status = status.HTTP_201_CREATED
        else:
            response = JsonResponse({
                'success': success,
                'detail': form.errors
            })
            response.status = status.HTTP_400_BAD_REQUEST

        return response
Exemplo n.º 4
0
def register_user(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/profile/')
    if request.method == 'POST':
        reg_form = RegistrationForm(request.POST)
        if reg_form.is_valid():
            try:
                User.objects.get(username=reg_form.cleaned_data['username'])
            except User.DoesNotExist:
                try:
                    User.objects.get(email=reg_form.cleaned_data['email'])
                except User.DoesNotExist:
                    try:
                        RegularUser.objects.get(fb_email=reg_form.cleaned_data['email'])
                    except RegularUser.DoesNotExist:
                        if validate_password(reg_form):
                            return render_unvalid_password(request, reg_form)           
                        return create_regular_user(request, reg_form)
                return user_already_exists(request, reg_form, "email_match")
            return user_already_exists(request, reg_form, "name_match")
        else:
            context = {
                       'form': reg_form,
                       'msg': 'Невалидна форма! Моля, попълнете всички полета!'                    
                       }
            return render_to_response('registration.html', context, context_instance=RequestContext(request))
    else:
        reg_form = RegistrationForm()
        context = {'form': reg_form}
        return render_to_response('registration.html', context, context_instance=RequestContext(request))
Exemplo n.º 5
0
 def test_registration_data(self):
     form = RegistrationForm(data = {
         'username' : 'jkpour',
         'email' : '*****@*****.**',
         'password1' : 'mlkjhg1234',
         'password2' : 'mlkjhg1234'
     })
     self.assertTrue(form.is_valid())
Exemplo n.º 6
0
 def test_invalid_registration_form(self):
     data = {
         'email': '*****@*****.**',
         'password1': 'somepassword',
         'last_name': 'Newt'
     }
     form = RegistrationForm(data)
     self.assertFalse(form.is_valid())
Exemplo n.º 7
0
 def test_Registration_no_data(self):
     form = RegistrationForm(data = {
         'username' : '',
         'email' : '',
         'password1' : '',
         'password2' : ''
     })
     self.assertFalse(form.is_valid())
     self.assertEquals(len(form.errors), 3)
Exemplo n.º 8
0
    def test_registration_data(self):
        form = RegistrationForm(
            data={
                'username': '******',
                'email': '*****@*****.**',
                'password1': 'Secret123456',
                'password2': 'Secret123456',
            })

        self.assertTrue(form.is_valid())
def userRegiteration(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/thankYouRegister/')
    else:
        form = RegistrationForm()

        return render(request, "register.html", locals())
Exemplo n.º 10
0
 def test_registration_POST_form(self):
     form_data = {
         'username': '******',
         'email': '*****@*****.**',
         'password1': 'mlkjhg1234',
         'password2': 'mlkjhg1234'
     }
     form = RegistrationForm(data=form_data)
     self.assertTrue(form.is_valid())
     response = self.client.post(self.registration_url, form_data)
     self.assertRedirects(response, self.index_url, status_code=302)
Exemplo n.º 11
0
def signup():
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(form.password.data, salt)
        user = User(name=form.name.data,
                    email=form.email.data.lower(),
                    password=hashed_password)
        user.save()
        return redirect(url_for('user_page.login'))
    return render_template('user/signup.html', form=form)
Exemplo n.º 12
0
 def setUp(self):
     self.data = {
         'email': fake.email(),
         'firstname': fake.first_name(),
         'lastname': fake.last_name(),
         'password': password,
         'password2': password,
         'date_of_birth': fake.date_of_birth(),
         'phone': fake.numerify(text='080########'),
         'referral': fake.email(),
     }
     self.form = RegistrationForm(data=self.data)
Exemplo n.º 13
0
def signup():
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(form.password.data, salt)
        user = User(
            name=form.name.data,
            email=form.email.data,
            password=hashed_password
        )
        user.save()

        return '{} Signed up!'.format(form.name.data)
    return render_template('user/signup.html', form=form)
Exemplo n.º 14
0
def signup(request):
    print("WWWWWWWWWWWWww")
    print(request.method)
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        print(form)
        print(form.is_valid())
        print(form.is_bound)
        print(form.errors)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            print(username)
            password = form.cleaned_data.get('password')
            print(password)
            raw_password = form.cleaned_data.get('password1')
            print(raw_password)
            if password == raw_password:
                form.save()
                user = authenticate(username=username, password=raw_password)
                login(request, user)
                return redirect('user:get_user_info')
            else:
                messages.error(request, "Incorrect password.")
        else:
            messages.error(request, form.errors)
    else:
        form = RegistrationForm()
    return render(request, 'user/user_register.html', {'form': form})
Exemplo n.º 15
0
    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            form = RegistrationForm(request.POST)
            if form.is_valid():
                form.save()
                username = form.cleaned_data['username']
                password1 = form.cleaned_data['password1']
                user = authenticate(request,
                                    username=username,
                                    password=password1)
                login(request, user)

                return redirect("feed")
        return render(request, "user/home.html", context={'form': form})
Exemplo n.º 16
0
    def post(self, request, *args, **kwargs):
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password1 = form.cleaned_data['password1']
            user = authenticate(request, username=username, password=password1)
            login(request, user)

        return render(request,
                      "user/registrer.html",
                      context={
                          'form': RegistrationForm,
                      })
Exemplo n.º 17
0
def new_teacher(request):
    if request.method == 'POST':
        registration_form = RegistrationForm(data=request.POST)
        teacher_form = NewTeacher(data=request.POST)
        if registration_form.is_valid() and teacher_form.is_valid():
            user = registration_form.save()
            teacher = teacher_form.save(commit=False)
            teacher.user = user
            teacher.save()
            return redirect('home')
    else:
        registration_form = RegistrationForm()
        teacher_form = NewTeacher()
    return render(request, "new_teacher.html",
                  {'form': registration_form, 'form1': teacher_form})
Exemplo n.º 18
0
def signup():
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        salt = bcrypt.gensalt()
        hash_password = bcrypt.hashpw(form.password.data, salt)
        user = User(
            name=form.name.data,
            email=form.email.data,
            password=hash_password

        )
        user.save()
        flash("Registered successfully")

        #return '{} signup'.format(form.name.data)
        return redirect(url_for('user_page.login'))
    return render_template('user/signup.html', form =form)
Exemplo n.º 19
0
def registration_view(request):
    if request.POST:
        registration_form = RegistrationForm(request.POST)
        if registration_form.is_valid():
            login_user = registration_form.save()
            if login_user:
                login(request, login_user)
                return JsonResponse({
                    'response': "Good",
                    'result': 'success',
                    'url': reverse('main'),
                })
        else:
            response = render_template(
                'LoginRegistration/registration_form.html',
                {'registration_form': registration_form}, request)
            return JsonResponse({'response': response, 'result': 'error'})
Exemplo n.º 20
0
def signup():
    #instancia formulario de registro
    form = RegistrationForm(request.form)
    # si request es post y el formato ha sido validado registra el usuario
    if request.method == 'POST' and form.validate():
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(form.password.data, salt)   
        user = User(      
            name= form.name.data,
            lastname= form.lastname.data,
            city= form.city.data,
            email= form.email.data.lower(),
            password= hashed_password
        )
        user.save()
        return redirect(url_for('user_page.login'))
    return render_template('user/signup.html', form=form)
Exemplo n.º 21
0
def register(request):
    """return the register page"""
    form = RegistrationForm()
    context = {
        "register": "Inscription",
        "url_image": "user/assets/img/wheat-field-2554358_1920.jpg",
        "form": form,
    }

    if request.method == "POST":
        firstname = request.POST.get("firstname")
        lastname = request.POST.get("lastname")
        email = request.POST.get("email")
        password = request.POST.get("password_field")
        # create a form instance and populate it with data from the request:
        form = RegistrationForm(request.POST)

        if form.is_valid():
            print("form is valid")

            user = User.objects.filter(email=email)

            if not user.exists():
                # If a user is not registered, create a new one
                user = User.objects.create_user(
                    username=email,
                    first_name=firstname,
                    last_name=lastname,
                    email=email,
                    password=password,
                )
                user, created = PurBeurreUser.objects.get_or_create(user=user)
                print(created)
                return redirect("user:login")

            context.update({"message": "Votre compte existe déja"})
            return render(request, "user/register.html", context)

        print("form is not valid")
        print(form)
        context.update({"form": form})
        print("ERROR :", form.errors)
        print("CONTEXT :", context["form"].errors)

    print(context)
    return render(request, "user/register.html", context)
Exemplo n.º 22
0
def register(request):
    if request.method == "POST":
        # print(dir(request))
        form = RegistrationForm(request.POST)
        print(form)
        if form.is_valid():
            print('valid')
            form.save()
            message = "You have successfully created an account. Login to Get Investing!"
            args = {
                'rform': RegistrationForm(),
                'lform': AuthenticationForm(),
                'message': message
            }
            return render(request, 'user/login.html', args)
        else:
            print('not valid')
            error = 'The Username you have provided is already taken.'
            args = {
                'rform': RegistrationForm(),
                'message': error,
                'lform': AuthenticationForm()
            }
            return render(request, 'user/login.html', args)

    else:
        print('wrong request sent')
Exemplo n.º 23
0
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            #Save the user in the built-in auth database
            form.save()

            #Create and save the user in the custom UserDetails database
            newUser = {
                'username':
                form.cleaned_data.get('username'),
                'user_id_id':
                User.objects.get(
                    username=form.cleaned_data.get('username')).pk,
            }
            newUserRow = UserDetails(**newUser)
            newUserRow.save()

            #Login the user
            autoLogin = auth.authenticate(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
            )
            auth.login(request, autoLogin)
            return redirect('/user/profile/')
        else:
            return render(request, 'reg_form.html', {'form': form})

    else:
        #If request.method == 'GET', show the registration form'
        form = RegistrationForm()
        args = {'form': form}
        return render(request, 'reg_form.html', args)
Exemplo n.º 24
0
def register(request):
    if request.method == 'POST':
        user_form = RegistrationForm(request.POST)
        if user_form.is_valid():
            new_user = user_form.save(commit=False)
            new_user.set_password(user_form.cleaned_data['password'])
            if new_user.save() == 0:
                print('failed')
            #print (new_user.id)
            new_user_salt = UserSalt.objects.create(user_id=new_user.id)
            #assign_perm('view_user_profile', new_user, new_user_profile)
            #assign_perm('change_user_profile', new_user, new_user_profile)
            #assign_perm('view_salt', new_user, new_user_salt)
            return JsonResponse(CODE_MSG['success'])
        else:
            return JsonResponse(CODE_MSG['register_failed'])
    else:
        return JsonResponse(CODE_MSG['register_failed'])
Exemplo n.º 25
0
def register():
    form = RegistrationForm(request.form)
    if request.method == "POST" and form.validate():
        user = User()
        user.create_user(
            name=form.name,
            plaintext_password=form.password,
            email=form.email,
            title=form.title,
            secret_question=form.secret_question,
            plaintext_secret_answer=form.secret_answer,
            phone_number=form.phone_number,
            company=session["company"],
            authentication_level=form.authentication_level,
        )

        flash("Thanks for registering")
        return redirect(url_for("login"))
    return render_template("user/register.html")
Exemplo n.º 26
0
def home(request):
    if request.method == "POST":
        print('==============', request.user)
        form = AuthenticationForm(request.POST)
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request=request,
                            username=username,
                            password=password)
        print(user)
        if user is not None:
            login(request, user)
            args = {
                'user': request.user,
                'properties': Properties.properties.all()
            }

            return render(request, 'user/home.html', args)
        else:
            error = 'The Username and Password you have provided was not correct.'
            args = {
                'lform': form,
                'lError_message': error,
                'rform': RegistrationForm()
            }
            return render(request, 'user/login.html', args)

    if request.method == "GET":
        if request.user.is_authenticated():
            args = {
                'user': request.user,
                'properties': Properties.properties.all()
            }
            return render(request, 'user/home.html', args)
        else:
            error = 'You must first sign in to view that page. If you do not have an account then you must sign up.'
            args = {
                'rform': RegistrationForm(),
                'message': error,
                'lform': AuthenticationForm()
            }
            return render(request, 'user/login.html', args)
Exemplo n.º 27
0
 def test_form_email(self):
     data = {'email': self.email, 'password': "******"}
     form = RegistrationForm(data)
     self.assertTrue(form.is_valid())
     user = form.save()
     self.assertNotEqual(user.password, "test123")
     form = RegistrationForm(data)
     self.assertFalse(form.is_valid())
     self.assertEqual(list(form.errors.keys()), ['email'])
Exemplo n.º 28
0
def signup(request):
    forms = RegistrationForm()
    if request.method == 'POST':
        forms = RegistrationForm(request.POST)
        if forms.is_valid():
            firstname = forms.cleaned_data['firstname']
            lastname = forms.cleaned_data['lastname']
            email = forms.cleaned_data['email']
            username = forms.cleaned_data['username']
            password = forms.cleaned_data['password']
            confirm_password = forms.cleaned_data['confirm_password']
            if password == confirm_password:
                User.objects.create_user(username=username,
                                         password=password,
                                         email=email,
                                         first_name=firstname,
                                         last_name=lastname)
                return redirect('login')
    context = {'form': forms}
    return render(request, 'user/signup.html', context)
Exemplo n.º 29
0
def single_dish(request, dish_id):
	args={}
	choiceDish = list(Dish.objects.raw("SELECT * FROM food_dish WHERE id = {}".format(dish_id)))
	# print("choice dish",choiceDish)
	if len(choiceDish) == 0: # NOTE Change the following to reRoute to home page.
		error = "Dish was not found. Please try a different dish"
		args = {'lform':AuthenticationForm(),'lError_message':error, 'rform': RegistrationForm()}
		return render("user/login.html",args)
	else:
		args={"dishObj":choiceDish[0]}
		print(choiceDish[0].images)
		print(dir(choiceDish[0].images))
		return render(request, "food/singleFood.html",args)
Exemplo n.º 30
0
class TestUserRegistrationForm(TestCase):
    def setUp(self):
        self.data = {
            'email': fake.email(),
            'firstname': fake.first_name(),
            'lastname': fake.last_name(),
            'password': password,
            'password2': password,
            'date_of_birth': fake.date_of_birth(),
            'phone': fake.numerify(text='080########'),
            'referral': fake.email(),
        }
        self.form = RegistrationForm(data=self.data)

    def test_form_is_valid(self):
        print(self.form.errors)
        self.assertTrue(self.form.is_valid())
Exemplo n.º 31
0
def registrationView(request):
    form = RegistrationForm()

    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password1 = form.cleaned_data['password1']
            user = authenticate(request, username=username, password=password1)
            login(request, user)
            return redirect('index')
    context = {'form' : form}

    template = loader.get_template('user/registration.html')
    return HttpResponse(template.render(request=request, context=context))
Exemplo n.º 32
0
Arquivo: utils.py Projeto: wooshe/Shop
def getDataForNavBaR(ctx, request):
    cart_count = getUserCartCount(request)

    login_form = LoginForm()
    registration_form = RegistrationForm()
    password_reset_form = PasswordResetForm()

    notification_form = NotificationForm()
    category_menu = Category.objects.all()

    ctx.update({
        'cart_count': cart_count,
        'login_form': login_form,
        'registration_form': registration_form,
        'password_reset_form': password_reset_form,
        'notification_form': notification_form,
        'category_menu': category_menu,
    })
Exemplo n.º 33
0
def registration_view(request):
    context = {}
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            email = form.cleaned_data.get('email')
            raw_password = form.cleaned_data.get('password1')
            account = authenticate(email=email, password=raw_password)
            login(request, account)
            return redirect('home')
        else:
            context['registration_form'] = form
    else:  #get request
        form = RegistrationForm()
        context['registration_form'] = form
    return render(request, 'user/register.html', context)
Exemplo n.º 34
0
 def form_valid(self, form: RegistrationForm):
     address_params: dict = {
         k: self.request.POST.get(k)
         for k in AddressForm.base_fields if k != 'user'
     }
     with transaction.atomic():
         sid = transaction.savepoint()
         new_user: User = form.save()
         address_params['user'] = new_user.id
         address_form: AddressForm = AddressForm(address_params)
         if address_form.is_valid():
             new_user = self.register((new_user, form))
             address_form.save()
         else:
             transaction.savepoint_rollback(sid)
     if address_form.is_valid():
         return HttpResponseRedirect(self.get_success_url(new_user))
     else:
         return self.render_to_response(
             self.get_context_data(form=form, address_form=address_form))
Exemplo n.º 35
0
def registerUser(request):
    # checks if a user has inputted in the search field in the navbar
    if 'search_filter' in request.GET:
        return index(request)
    context = {}
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            email = form.cleaned_data.get('email')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(email=email, password=raw_password)
            login(request, user)
            return redirect('/user/account')
        else:
            context['registerForm'] = form

    else:
        form = RegistrationForm()
        context['registerForm'] = form
    return render(request, 'user/register.html', context)
Exemplo n.º 36
0
def user_register(request):
    if request.method == "POST":
        user_form = RegistrationForm(request.POST)
        user_profile = UserProfileForm(request.POST)
        if user_form.is_valid() and user_profile.is_valid():
            new_user = user_form.save(commit=False)
            new_user.password = user_form.cleaned_data["password1"]
            new_user.save()
            new_profile = user_profile.save(commit=False)
            new_profile.user = new_user
            new_profile.save()
            return HttpResponse("注册成功")
        else:
            print(user_form.is_valid())
            print(user_profile.is_valid())
            return HttpResponse("表单提交有误,注册失败")

    if request.method == "GET":
        user_form = RegistrationForm()
        user_profile = UserProfileForm()
        context = {"form": user_form, "profile": user_profile}
        return render(request, "user/register.html", context=context)