コード例 #1
0
def register(request):
    context = RequestContext(request)
    er1 = ""
    if request.POST:
        postform = UserForm(data=request.POST)

        if postform.is_valid():
            pwd = request.POST['password']
            rpwd = request.POST['password1']

            if pwd == rpwd:
                postform.save(commit=True)
                return HttpResponseRedirect('/index/')
            else:
                er1 = "Passwords don't match"
        else:
            print postform.errors
    else:
        postform = UserForm()

    context_dict = {
        'postform': postform,
        'er1': er1,
    }

    return render_to_response("register.html", context_dict, context)
コード例 #2
0
def djg_login(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            login(request, user)
            # 设置回话变量 姓名
            request.session['fname'] = request.user.first_name
            # 如果属于employee组, 就设置 device_permission 会话变量
            if Group.objects.get(name='employee') in user.groups.all():
                request.session['device_permission'] = True
            # 如果用户有'qyt_device.view_devicedb'权限, 就设置 device_permission 会话变量
            elif 'qyt_device.view_devicedb' in request.user.get_all_permissions(
            ):
                request.session['device_permission'] = True
            # 如果客户从其它页面重定向过来的, 就让它返回原始页面
            next_url = request.GET.get('next', '/')
            return HttpResponseRedirect(next_url)

        else:
            return render(request, 'registration/login.html', {
                'form': form,
                'error': '用户名或密码错误'
            })
    else:
        if request.user.is_authenticated:
            return HttpResponseRedirect('/')

        else:
            form = UserForm()
            return render(request, 'registration/login.html', {'form': form})
コード例 #3
0
def register(request):

    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        user_prof_form = UserProfForm(data=request.POST)
        if user_form.is_valid():
            if (user_prof_form.is_valid()):
                user = user_form.save(commit=False)
                user.set_password(user.password)
                user.is_active = False
                user.save()
                user_profile = user_prof_form.save(commit=False)
                user_profile.user = user
                user_profile.save()
                registered = True
            else:
                print user_prof_form.errors
        else:
            print user_form.errors
    else:
        user_form = UserForm()
        user_prof_form = UserProfForm()

    # Render the template depending on the context.
    return render(
        request, 'citadel/register.html', {
            'user_form': user_form,
            'user_prof_form': user_prof_form,
            'registered': registered
        })
コード例 #4
0
def register(request):
    if request.session.get('patient_mode'):
        return redirect('kiosk')
    # If there's a user logged in, require them to log out
    if request.user.is_authenticated():
        return redirect('manual_logout')
    # If it's post, the user has sent us their info and we need to try to set them up
    if request.method == 'POST':
        success = False
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            # Save the user and associate it with a new Doctor
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            doctor = Doctor()
            doctor.user = user
            doctor.save()
            success = True

        # Registration done, let's get out of here.
        # (note: I'm not actually sure whether it'd be more appropriate to
        # have a new view for the result and redirect to it. That sort of thing
        # seems common, but this seems simpler)
        return render(request, 'registration_report.html', {
            'success': success,
            'user_form': user_form
        })

    # Otherwise we diplay the form for them to fill out and post to us
    else:
        return render(request, 'register.html', {'user_form': UserForm()})
コード例 #5
0
def signup(request):
    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid():
            user = User(email=form.cleaned_data['email'])
            user.first_name = form.cleaned_data['firstName']
            user.last_name = form.cleaned_data['lastName']
            user.username = user.email
            user.set_password(form.cleaned_data['password'])
            user.is_active = False
            user.save()

            userProfile = UserProfile.objects.get_or_create(
                user=user,
                birthdate=form.cleaned_data['birthdate'],
                gender=form.cleaned_data['gender'],
                profilePhoto='images/default.png')
            registration = Registration.objects.create_registration(user)
            registration.send_activation_mail()
            return HttpResponseRedirect(reverse("login-user"))

    else:
        form = UserForm()

    data = {'form': form, 'title': 'SignUp'}
    return render_to_response("email_app/signup.html", data)
コード例 #6
0
def register_team(request):
    context = RequestContext(request)
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        team_form = TeamForm(request.POST, request.FILES)
        if user_form.is_valid():
            if team_form.is_valid():
                user = user_form.save()
                # do i need these two lines anymore? Django 1.5, i think, handles this automatically now.
                password = user.password
                user.set_password(password)
                user.save()
                t = team_form.save(commit=False)
                t.user = user
                t.save()
                registered = True
                user = authenticate(username=user.username, password=password)
                login(request, user)
                return HttpResponseRedirect('/showcase/team/' + str(t.id) +
                                            '/')
        else:
            print user_form.errors, team_form.errors
    else:
        user_form = UserForm()
        team_form = TeamForm()

    # Render the template depending on the context.
    return render_to_response('showcase/team_registration.html', {
        'user_form': user_form,
        'team_form': team_form,
        'registered': registered
    }, context)
コード例 #7
0
ファイル: views.py プロジェクト: mrdremack/Python02
def register(request):
	registered = False

	if request.method == 'POST':
		user_form = UserForm(data=request.POST)

		profile_form = UserProfileForm(data=request.POST)

		if user_form.is_valid() and profile_form.is_valid():
			user = user_form.save()
			user.set_password(user.password)
			user.save()

			profile = profile_form.save(commit=False)

			profile.user = user 

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

			profile.save()

			registered = True 

		else:
			print user_form.errors, profile_form.errors
	else:
		user_form = UserForm()
		profile_form = UserProfileForm()

	return render(request, 'register.html', { 'user_form': user_form,
											'profile_form':profile_form,
											'registered':registered }
											)
コード例 #8
0
def update_profile(request):
    if request.method == 'POST':
        member_form = MemberForm(request.POST)
        if not is_member(request.user):
            if member_form.is_valid(
            ) and member_form.cleaned_data['becomeMember']:
                group_name = models.SchoolYear.objects.current(
                ).get_member_group()
                g = Group.objects.get(name=group_name)
                g.user_set.add(request.user)
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, 'Your profile was successfully updated!')
            return redirect('/profile')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        member_form = MemberForm()
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(
        request, 'profile.html', {
            'member_form': member_form,
            'user_form': user_form,
            'profile_form': profile_form,
            'school_year': models.SchoolYear.objects.current()
        })
コード例 #9
0
def publisher_settings_users_add(request):
    ''' View to allow a Publisher the ability to create a new User '''
    from atrinsic.base.models import User, UserProfile
    from forms import UserForm
    print 'test5'
    if request.method == "POST":
        form = UserForm(request.POST)

        if form.is_valid():
            u = User()

            u.first_name = form.cleaned_data['first_name']
            u.last_name = form.cleaned_data['last_name']
            u.email = form.cleaned_data['email']
            u.username = u.email.replace('@', '-')

            u.set_password(form.cleaned_data['password'])
            u.save()

            up = UserProfile.objects.create(user=u)
            up.organizations.add(request.organization)

            return HttpResponseRedirect('/publisher/settings/users/')
    else:
        form = UserForm()

    return AQ_render_to_response(request,
                                 'publisher/settings/users-add.html', {
                                     'form': form,
                                 },
                                 context_instance=RequestContext(request))
コード例 #10
0
def edit_profile(request):
    user = get_object_or_404(User, username=request.user.username)
    if request.method == 'GET':
        user_form = UserForm(instance=user)
        profile_form = ProfileForm(instance=user.userprofile)
        equipment_form = EquipmentForm()
        context = {
            'user_form': user_form,
            'profile_form': profile_form,
            'equipment_form': equipment_form,
        }
        return render(request, 'accounts/profile_form.html', context)
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=user)
        profile_form = ProfileForm(request.POST, instance=user.userprofile)
        equipment_form = EquipmentForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            del (request.session['django_timezone'])
            messages.success(request, "Profile sucessfully updated")
            return redirect('profile', username=user.username)
        else:
            return render(
                request, 'accounts/profile_form.html', {
                    'user_form': user_form,
                    'profile_form': profile_form,
                    'equipment_form': equipment_form
                })
コード例 #11
0
def login_dl(request):

    if request.user.is_authenticated:
        return redirect('index')
    else:
        if request.method == 'GET':
            login_form = UserForm()

        if request.method == 'POST':
            login_form = UserForm(request.POST)
            if login_form.is_valid():
                username = login_form.cleaned_data['username']
                password = login_form.cleaned_data['password']
                user = authenticate(username=username, password=password)
                print 111111
                print username
                print password
                if user:
                    print 222222
                    login(request, user)
                    print 333333
                    return redirect('index')
                else:
                    return redirect('https://www.baidu.com/')
        return render(request, 'login.html', locals())
コード例 #12
0
def edit_account(request, name=None):
    if name and not has_role(request.user, ['staff', 'dev']):
        return redirect('edit_account')

    if name:
        user = McUser.objects.get(norm_name=normalize_name(name)).user
    else:
        user = request.user

    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=user, user=user)
        if user_form.is_valid():
            user_form.save()
            messages.add_message(request, messages.SUCCESS, 'Changes saved!')
            if name:
                return redirect('edit_other_account', name)
            return redirect('edit_account')
        else:
            messages.add_message(request, messages.WARNING,
                                 'Passwords do not match.')
            user_form = UserForm(instance=user, user=user)
    else:
        user_form = UserForm(instance=user, user=user)
    context = {
        'form': user_form,
    }
    if name:
        context['name'] = user.mcuser.get_full_name()
    return render(request, 'core/edit_account.html', context)
コード例 #13
0
ファイル: views.py プロジェクト: lantuzi/know_your_nyms
def signup(request):
    context = {'signup_failed': False, 'user_form': UserForm()}
    if request.method == 'GET':
        return render(request, 'signup.html', context=context)
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()
            login(request, user)
            return redirect('/')

        # Invalid form or forms - mistakes or something else?
        # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            context['signup_failed'] = True
            context['error'] = user_form.errors
            return render(request, 'signup.html', context)
コード例 #14
0
ファイル: views.py プロジェクト: kevinkiarie/djangoWebApp
def register(request):
	context = RequestContext(request)
	registered = False
	
	if request.method == 'POST':
		user_form = UserForm(data=request.POST)
		#prof_form = UserProfForm(data=request.POST)
		#validate form data
		if user_form.is_valid():# and prof_form.is_valid():
			user = user_form.save() #save the user form data to the database
			user.set_password(user.password)#hash the password
			if 'picture' in request.FILES:
				user.picture = request.FILES['picture']
			#profile.save() # save the user_prof instance
			user.save()
			registered = True #update the variable
			return HttpResponseRedirect("/main/signup_login/")
		else:
			print user_form.errors

	else:
		user_form = UserForm()
	return render_to_response(
			"registration/register.html",
			{"user_form": user_form, "registered":registered}, context)
コード例 #15
0
def register(request):
    # Like before, get the request's context.
    context = RequestContext(request)

    if request.user.is_authenticated:
        #return HttpResponseRedirect('/profile')

        #else:

        # A boolean value for telling the template whether the registration was successful.
        # Set to False initially. Code changes value to True when registration succeeds.
        registered = False

        # If it's a HTTP POST, we're interested in processing form data.
        if request.method == 'POST':
            user_form = UserForm(data=request.POST)
            profile_form = UserProfileForm(data=request.POST)
            validation_form = ValidationForm(data=request.POST)

            if user_form.is_valid() and profile_form.is_valid(
            ) and validation_form.is_valid():
                user = user_form.save()

                user.set_password(user.password)
                user.save()

                profile = profile_form.save(commit=False)
                profile.user = user
                profile.user_since = datetime.datetime.today()

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

                user_id = user.id
                if user_id % 2 is 0:
                    profile.condition = 1
                elif user_id % 2 is not 0:
                    profile.condition = 2

                profile.save()
                registered = True
                new_user = authenticate(username=request.POST['username'],
                                        password=request.POST['password'])
                login(request, new_user)

            else:
                print user_form.errors, profile_form.errors, validation_form.errors

        else:
            user_form = UserForm()
            profile_form = UserProfileForm()
            validation_form = ValidationForm()

        return render_to_response(
            'badsearch/register.html', {
                'user_form': user_form,
                'profile_form': profile_form,
                'validation_form': validation_form,
                'registered': registered
            }, context)
コード例 #16
0
ファイル: views.py プロジェクト: kelvinn/helomx
def upt_engineer_profile(request, slug):
    from forms import EngineerForm, UserForm
    from django.contrib.auth.models import Permission
    message = None
    engineer = Engineer.objects.get(user__username=slug)
    mailserver_list = get_mx_list(engineer.company)
    user_form = UserForm(instance=engineer.user)
    form = EngineerForm(instance=engineer)
    if request.method == 'POST':
        form = EngineerForm(data=request.POST, instance=engineer)
        user_form = UserForm(data=request.POST, instance=engineer.user)
        perm_form = EngineerPermForm(request.POST)
        if form.is_valid() and user_form.is_valid() and perm_form.is_valid():
            form.save()
            user_form.save()
            message = "Engineer updated successfully"

    company = engineer.company
    engineer_list = Engineer.objects.filter(company=company)

    return render_to_response("profiles/engineer.html", {
        'slug': slug,
        'engineer_form': form.as_ul(),
        'user_form': user_form.as_ul(),
        'mailserver_list': mailserver_list,
        'message': message,
        'company': company,
        'engineer_list': engineer_list,
    },
                              context_instance=RequestContext(request))
コード例 #17
0
def register_rater(request):
    context = RequestContext(request)
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            user = user_form.save()
            password = user.password
            user.set_password(user.password)
            user.save()
            r = Rater(user=user, active=True)
            r.save()
            registered = True
            user = authenticate(username=user.username, password=password)
            user.backend = "django.contrib.auth.backends.ModelBackend"
            login(request, user)
            return HttpResponseRedirect('/showcase/')
        else:
            print user_form.errors
    else:
        user_form = UserForm()

    # Render the template depending on the context.
    return render_to_response('showcase/rater_registration.html', {
        'user_form': user_form,
        'registered': registered
    }, context)
コード例 #18
0
ファイル: views.py プロジェクト: JoshuaKrma/bdneu_webserver
def register(request):  # 实现注册功能
    if request.method == "POST":
        uf = UserForm(request.POST)
        if uf.is_valid():
            #获取表单信息
            username = uf.cleaned_data['username']
            password1 = uf.cleaned_data['password1']
            password2 = uf.cleaned_data['password2']
            email = uf.cleaned_data['email']
            user = User.objects.filter(username=username)
            if user.exists():

                return render_to_response('register_fail.html',
                                          {'data': "用户名已被占用!请更换"})
            if password1 != password2:

                return render_to_response('register_fail.html',
                                          {'data': "前后密码不一致"})
            #将表单写入数据库
            user = User.objects.create_user(username=username,
                                            email=email,
                                            password=password2)
            '''user.username = username
            user.password = password2
            user.email = email'''
            user.save()
            #返回注册成功页面
            return render(request, 'register_success.html',
                          {'username': username})
    else:
        uf = UserForm()
    return render(request, 'register.html', {'uf': uf})
コード例 #19
0
ファイル: views.py プロジェクト: castaway2000/OpenStay
def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            registered = True
        else:
            print user_form.errors
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user.is_authenticated:
            login(request, user)
            profile = UserProfile(user_id=user.id)
            profile.save()
            return HttpResponseRedirect('../chooser')
        else:
            raise Exception("user is not authenticated")
    else:
        user_form = UserForm()
    return render(request, 'users/register.html', {
        'user_form': user_form,
        'registered': registered
    })
コード例 #20
0
ファイル: views.py プロジェクト: wcl19940217/disk
def regist(req):
    errors1 = []

    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():

            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            email = uf.cleaned_data['email']

            if User.objects.filter(username=username):
                errors1.append('用户名已经存在,请换一个啦')
                return render_to_response('index2.html', {'errors1': errors1},
                                          context_instance=RequestContext(req))
            else:
                User.objects.create(username=username, password=password)
                f = User.objects.get(username=username)
                create_time = timezone.now()
                modify_time = timezone.now()
                f.userinfo_set.create(email=email,
                                      tel='8888888',
                                      address='default')
                f.folder_set.create(folder_name='默认文件夹',
                                    create_time=create_time,
                                    modify_time=modify_time)
                return render_to_response('index2.html',
                                          context_instance=RequestContext(req))
    else:
        uf = UserForm()
    return render_to_response('index2.html', {'uf': uf},
                              context_instance=RequestContext(req))
コード例 #21
0
def my_profile(request):
    context = get_context(request)
    if not request.user.is_authenticated():
        return redirect('login')
    else:
        user_profile = UserProfile.objects.get(user=request.user)
        if request.method == "POST":
            user_form = UserForm(request.POST, instance=request.user)
            user_profile_form = UserProfileForm(request.POST,
                                                instance=user_profile)
            if user_form.is_valid() and user_profile_form.is_valid():
                user_form.save()
                user_profile_form.save()

            return redirect_after_profile_save(request, 'data')
        else:
            user_form = UserForm(instance=request.user)
            user_profile_form = UserProfileForm(instance=user_profile)
            user_form.helper.form_tag = False
            user_profile_form.helper.form_tag = False
            context['user_form'] = user_form
            context['user_profile_form'] = user_profile_form
            context['user_profile_page_form'] = UserProfilePageForm(
                instance=user_profile)
            context['user_cover_letter_form'] = UserCoverLetterForm(
                instance=user_profile)
            context['user_info_page_form'] = UserInfoPageForm(
                instance=user_profile.user_info)
            context['is_editing_profile'] = True
            context['title'] = u'Mój profil'

            return render(request, 'profile.html', context)
コード例 #22
0
def view_index(form=None):
    """ VIEW: Index page to handle registration, login and task creation """
    # Form selection
    if session.get('user_name'):
        if form:
            if form._prefix == 'log-':
                suite_form = _get_task_suite_form()
                form = (form, suite_form)
            elif form._prefix == 'suite-':
                log_form = _get_task_log_form()
                form = (log_form, form)
        else:
            log_form = _get_task_log_form()
            suite_form = _get_task_suite_form()

            form = (log_form, suite_form)
    else:
        # Render forms for registration/login if no session
        if form:  # Enables flash messages when called by another function
            if form._prefix == 'login-':
                form = (form, UserForm(prefix='register'))
            elif form._prefix == 'register-':
                form = (UserForm(prefix='login'), form)
        else:
            form = (UserForm(prefix='login'), UserForm(prefix='register'))

    return render_template('index.html',
                           form=form,
                           tasks=Task.query.order_by(
                               Task.time_created.desc()).limit(30).all(),
                           active='index')
コード例 #23
0
ファイル: views.py プロジェクト: weixwx/zyzxweb
def register(request):
    if request.method == 'POST':
        userform = UserForm(request.POST)
        if userform.is_valid():
            userid = userform.cleaned_data['userid']
            username = userform.cleaned_data['username']
            password1 = userform.cleaned_data['password1']
            password2 = userform.cleaned_data['password2']
            if password1 != password2:
                render(
                    request, 'register.html', {
                        'userform': userform,
                        'is_err': True,
                        'err_message': '再次输入的密码不一致'
                    })
            email = userform.cleaned_data['email']
            phone = userform.cleaned_data['phone']

            UserInfo.objects.create(userid=userid,
                                    username=username,
                                    password=password1,
                                    email=email,
                                    phone=phone)
            # obj_userinfo = UserInfo(userid=userid, username=username, password=password1, email=email, phone=phone)
            # obj_userinfo.save()

            return redirect(to='index')
    else:
        userform = UserForm()
    return render(request, 'register.html', {
        'userform': userform,
        'is_err': True,
        'err_message': '注册成功'
    })
コード例 #24
0
ファイル: views.py プロジェクト: aashitadutta/Q-Aforum
def register(request):
    # Like before, get the request's context.
    context = RequestContext(request)

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(request.POST,request.FILES)
       # p = UserProfileForm(data=request.FILES)
        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():# and p.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = profile_form.save(commit=False)
            profile.user = user

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model.
            if 'picture' in request.FILES:
               # p.picture = request.FILES['picture']
               # p.save()
               profile.picture = request.FILES['picture']
            # Now we save the UserProfile model instance.
            profile.save()
                
            # Update our variable to tell the template registration was successful.
            registered = True

        # Invalid form or forms - mistakes or something else?
        # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            print user_form.errors, profile_form.errors

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    # Render the template depending on the context.
    return render_to_response(
            'registration.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
            context)
コード例 #25
0
ファイル: views.py プロジェクト: opena11y/fae1-django
def my_account(request):
    user_data = {
        'first_name': request.user.first_name,
        'last_name': request.user.last_name,
        'email': request.user.email
    }

    try:
        profile_obj = request.user.get_profile()
    except ObjectDoesNotExist:
        profile_obj = UserProfile(user=request.user, acct_type=1)

    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=profile_obj)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            return HttpResponseRedirect('/')
    else:
        user_form = UserForm(initial=user_data)
        profile_form = ProfileForm(initial=get_profile_data(profile_obj))

    context = {
        'title': labels['profile'],
        'username': request.user.username,
        'user_form': user_form,
        'profile_form': profile_form,
    }

    # Return response
    t = get_template('my_account.html')
    html = t.render(RequestContext(request, context))
    return HttpResponse(html)
コード例 #26
0
def home(request):
    context = {}
    year = settings.CONSTITUENCY_YEAR
    constituencies = Constituency.objects.filter(year=year)
    count = CustomUser.objects\
            .aggregate(Count('constituencies',
                             distinct=True)).values()[0]
    total = constituencies.count()

    context['volunteers'] = CustomUser.objects.count()
    context['total'] = total
    context['count'] = count
    if total:
        context['percent_complete'] = int(float(count) / total * 100)
    else:
        context['percent_complete'] = 0
    if request.method == "POST":
        form = UserForm(request.POST, request.FILES)
        if form.is_valid():
            profile = form.save()
            user = authenticate(username=profile.user.email)
            login(request, user)
            return HttpResponseRedirect("/")
        else:
            context['form'] = form
    else:
        context['form'] = UserForm()
    return render_with_context(request, 'home.html', context)
コード例 #27
0
def register_view(request):
    if request.user.is_authenticated():
        print "user is authenticated"
        return HttpResponseRedirect(reverse('home_url'))
    if request.method=='POST':
        form = UserForm(request.POST)
        if form.is_valid():
            print "form is valid"
            email_exists = User.objects.filter(email=form.cleaned_data['email']).exists()
            if email_exists:
                print "email exists"
                return render(request, 'first/register.html', {'form':form, 'email_exists':True, 'fail':True})
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            email = form.cleaned_data['email']
            user = User.objects.create_user(username, email, password)
            user.last_name = last_name
            user.first_name = first_name
            user.save()
            user=authenticate(username=username, password=password)
            login(request, user)
            url = reverse('home_url')
            return HttpResponseRedirect(url)
        else:
            return render(request, 'first/register.html', {'form':form, 'fail':True})
    else:
        form = UserForm()
        return render(request, 'first/register.html', {'form':form, 'fail':False})
コード例 #28
0
    def post(self, request, user_id):
        form = UserForm(request.POST or None)
        hidden_form = CoursesForm(request.POST or None)

        if form.is_valid() and hidden_form.is_valid():
            data = form.cleaned_data
            user_courses = hidden_form.cleaned_data.get('courses')

            db = Database()
            db.update_records(user_id, user_courses)
            db.update_user(user_id=user_id, **data)

            all_courses = db.get_all_courses()
            user_courses = db.get_user_courses(user_id)

            template = loader.get_template('edit.html')
            all_courses = json.dumps(all_courses)
            user_courses = json.dumps(user_courses)
            form.fields['user_name'].widget.attrs['readonly'] = True
            context = dict(form=form, success=True, all_courses=all_courses, user_courses=user_courses)

            return HttpResponse(template.render(context, request))
        else:
            db = Database()
            all_courses = db.get_all_courses()
            user_courses = db.get_user_courses(user_id)

            template = loader.get_template('edit.html')
            form = UserForm(request.POST)
            hidden_form = CoursesForm(request.POST)
            form.fields['user_name'].widget.attrs['readonly'] = True
            context = dict(form=form, hidden_form=hidden_form, all_courses=all_courses, user_courses=user_courses)
            return HttpResponse(template.render(context, request))
コード例 #29
0
def register(request):

    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()

            user.set_password(user.password)
            user.save()

            profile = profile_form.save()

            profile.user = user
            profile.save()

            registered = True
        else:
            print user_form.errors, profile_form.errors
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    context_dict = {
        'user_form': user_form,
        'profile_form': profile_form,
        'registered': registered
    }

    return render(request, "register.html", context_dict)
コード例 #30
0
def register(request):

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        user_form = UserForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()


            # Update our variable to tell the template registration was successful.
            registered = True
            print "registered is true"

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = UserForm()

    # Render the template depending on the context.
    return render(request,'registration/form-1/index3.html', {'user_form': user_form,'registered': registered} )