示例#1
0
def register(request):	
	registered = False
	if request.method == "POST":
		user_form = UserForm(data=request.POST)
		profile_form = UserProfileForm(data=request.POST)
		print profile_form
		print request.FILES['picture']
		if user_form.is_valid() and profile_form.is_valid():
			
			user = user_form.save(commit=False)
			user.set_password(user.password)
			user.is_active=True
			user.save()
			profile = profile_form.save(commit=False)
			profile.user = user
			profile.lastLoginDate = datetime.now()
			profile.ipaddress=get_client_ip(request)
			if request.FILES['picture']:
				profile.picture = request.FILES['picture']
			profile.save()
			registered = True
		else:
			print user_form.errors, profile_form.errors
			messages.info(request,str(user_form.errors)+str(profile_form.errors))
	else:
		user_form = UserForm()
		profile_form = UserProfileForm()
	return render(request,'register.html',{'title':'Sign Up','current_page':'register',\
		'user_form':user_form,'profile_form':profile_form,'registered':registered})
示例#2
0
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(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():
            # Save the user's form data to the database.
            userid = request.POST['userid']
            print userid
            user = user_form.save()
            user.username = userid
            # 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
            profile.mode = random.randint(0,1)

            # Now we save the UserProfile model instance.
            profile.save()
            id_holder = Id.objects.get(userid=userid)
            id_holder.usedFlag = True
            id_holder.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_instance=RequestContext(request)
            )
示例#3
0
def registerM(request):
    context = RequestContext(request)

    registered = False

    if request.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:
            user_form = UserForm()
            profile_form = UserProfileForm()
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()
    return render_to_response(
        "registr.html", {"user_form": user_form, "profile_form": profile_form, "registered": registered}, context
    )
示例#4
0
def register(request):
    context = RequestContext(request)
    registered = False

    if request.POST:
        form = UserForm(request.POST)
        profile_form = UserProfileForm(request.POST)

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

            profile = profile_form.save(commit=False)
            profile.user = user          
            profile.save()
            registered = True
        else:
            form.errors, profile_form.errors

    else:
        form = UserForm()
        profile_form = UserProfileForm()

    return render_to_response('registration/register.html',{'form':form,'profile_form':profile_form,'registered':registered},context)
示例#5
0
    def post(self, request):
        organization_list = get_organizations_ordered_by_name()
        if organization_list:
            if request.method == 'POST':
                user_form = UserForm(request.POST, prefix="usr")
                administrator_form = AdministratorForm(
                    request.POST, prefix="admin")

                if user_form.is_valid() and administrator_form.is_valid():

                    ad_country = request.POST.get('admin-country')
                    ad_phone = request.POST.get('admin-phone_number')

                    if (ad_country and ad_phone):
                        if not validate_phone(ad_country, ad_phone):
                            self.phone_error = True
                            return render(
                                request,
                                'registration/signup_administrator.html', {
                                    'user_form': user_form,
                                    'administrator_form': administrator_form,
                                    'registered': self.registered,
                                    'phone_error': self.phone_error,
                                    'organization_list':
                                    self.organization_list,
                                })

                    user = user_form.save()
                    user.set_password(user.password)
                    user.save()

                    administrator = administrator_form.save(commit=False)
                    administrator.user = user

                    # if organization isn't chosen from dropdown,
                    # the organization_id will be 0
                    organization_id = request.POST.get('organization_name')
                    organization = get_organization_by_id(organization_id)

                    if organization:
                        administrator.organization = organization

                    administrator.save()
                    registered = True
                    messages.success(request,
                                     'You have successfully registered!')
                    return HttpResponseRedirect(reverse('home:index'))
                else:
                    print(user_form.errors, administrator_form.errors)
                    return render(
                        request, 'registration/signup_administrator.html', {
                            'user_form': user_form,
                            'administrator_form': administrator_form,
                            'registered': self.registered,
                            'phone_error': self.phone_error,
                            'organization_list': self.organization_list,
                        })
        else:
            return render(request, 'home/home.html', {'error': True})
示例#6
0
文件: views.py 项目: mjzac/intern
def registration_view(request):
    dict = {}
    if request.POST:
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.INFO, " You have successfully registered. You can sign in now.")
    	    redirect('/')
    else:
        form = UserForm()
    dict['form'] = form
    return render_to_response('registration/signup.html',dict,context_instance=RequestContext(request))
示例#7
0
 def test_user_form_password_error(self):
     photo = SimpleUploadedFile(
         content=(base64.b64decode(TEST_IMAGE)),
         name='tempfile.png',
         content_type='image/png',
     )
     form_data = dict(
         password1='123qweASD',
         password2='123qweASD1',
         login='******',
         email='*****@*****.**',
     )
     form = UserForm(data=form_data, files={'photo': photo})
     self.assertFalse(form.is_valid())
示例#8
0
文件: views.py 项目: Ads7/vms
def signup_volunteer(request):

    registered = False
    organization_list = get_organizations_ordered_by_name()

    if organization_list:
        if request.method == 'POST':
            #each form must have it's own namespace (prefix) if multiple forms are to be put inside one <form> tag
            user_form = UserForm(request.POST, prefix="usr")
            volunteer_form = VolunteerForm(request.POST, request.FILES, prefix="vol")

            if user_form.is_valid() and volunteer_form.is_valid():

                if 'resume_file' in request.FILES:
                    my_file = volunteer_form.cleaned_data['resume_file']
                    if not validate_file(my_file):
                        return render(request, 'registration/signup_volunteer.html', {'user_form' : user_form, 'volunteer_form' : volunteer_form, 'registered' : registered, 'organization_list' : organization_list,})

                user = user_form.save();

                user.set_password(user.password)
                user.save()
           
                volunteer = volunteer_form.save(commit=False)
                volunteer.user = user

                #if an organization isn't chosen from the dropdown, then organization_id will be 0
                organization_id = request.POST.get('organization_name')
                organization = get_organization_by_id(organization_id)

                if organization:
                    volunteer.organization = organization

                volunteer.save()
                registered = True

                return HttpResponseRedirect(reverse('home:index'))
            else:
                print user_form.errors, volunteer_form.errors
                return render(request, 'registration/signup_volunteer.html', {'user_form' : user_form, 'volunteer_form' : volunteer_form, 'registered' : registered, 'organization_list' : organization_list,})
        else:
            user_form = UserForm(prefix="usr")
            volunteer_form = VolunteerForm(prefix="vol") 

        return render(request, 'registration/signup_volunteer.html', {'user_form' : user_form, 'volunteer_form' : volunteer_form, 'registered' : registered, 'organization_list' : organization_list,})

    else:
        return render(request, 'organization/add_organizations.html')
示例#9
0
文件: views.py 项目: Ads7/vms
def signup_administrator(request):
    """
    This method is responsible for diplaying the register user view
    Register Admin or volunteer is judged on the basis of users 
    access rights.
    Only if user is registered and logged in and registered as an
    admin user, he/she is allowed to register others as an admin user
    """
    registered = False
    organization_list = get_organizations_ordered_by_name()
    
    if organization_list:
        #if request.user.username != '' and request.user.is_authenticated(
        #) and checkAdmin(request.user):
        if request.method == 'POST':
            user_form = UserForm(request.POST, prefix="usr")
            administrator_form = AdministratorForm(request.POST, prefix="admin")

            if user_form.is_valid() and administrator_form.is_valid():
                user = user_form.save();
                user.set_password(user.password)
                user.save()
                
                administrator = administrator_form.save(commit=False)
                administrator.user = user
                
                #if organization isn't chosen from dropdown, the organization_id will be 0
                organization_id = request.POST.get('organization_name')
                organization = get_organization_by_id(organization_id)
                
                if organization:
                    administrator.organization = organization
                    
                administrator.save()
                registered = True

                return HttpResponseRedirect(reverse('home:index'))
            else:
                print user_form.errors, administrator_form.errors
                return render(request, 'registration/signup_administrator.html', {'user_form' : user_form, 'administrator_form' : administrator_form, 'registered' : registered, 'organization_list' : organization_list,})
        else:
            user_form = UserForm(prefix="usr")
            administrator_form = AdministratorForm(prefix="admin")
                       
        return render(request, 'registration/signup_administrator.html', {'user_form' : user_form, 'administrator_form' : administrator_form, 'registered' : registered, 'organization_list' : organization_list,})

    else:
        return render(request, 'organization/add_organizations.html')
示例#10
0
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
    else:
        user_form = UserForm()

    context_dict = {'user_form': user_form, 'registered': registered}
    return render(request,
                  'registration/register.html', context_dict)
示例#11
0
 def get(self, request):
     user_form = UserForm(prefix="usr")
     administrator_form = AdministratorForm(prefix="admin")
     return render(
         request, 'registration/signup_administrator.html', {
             'user_form': user_form,
             'administrator_form': administrator_form,
             'registered': self.registered,
             'phone_error': self.phone_error,
             'organization_list': self.organization_list
         })
示例#12
0
 def get(self, request):
     user_form = UserForm(prefix="usr")
     volunteer_form = VolunteerForm(prefix="vol")
     return render(
         request, 'registration/signup_volunteer.html', {
             'user_form': user_form,
             'volunteer_form': volunteer_form,
             'registered': self.registered,
             'phone_error': self.phone_error,
             'organization_list': self.organization_list,
         })
示例#13
0
def changeUser(request):
    user = request.user
    if request.POST:
        form = UserForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            user.username = user.email
            user.is_active = True
            organization = set_organization(user, form.cleaned_data["organization"])
            user.organization_set.clear()
            user.organization_set.add(organization)
            user.save()
            return HttpResponseRedirect("/")
    else:
        organization = user.organization_set.all()
        form = UserForm(instance=user)
        if organization:
            organization = organization[0]
            form.fields["organization"].initial = organization.title

    return render_to_response("registration/edit_user.html", {"form": form}, context_instance=RequestContext(request))
示例#14
0
def UserSignUp(request):
    if (request.method == "POST"):
        form1 = UserForm(request.POST)
        if (form1.is_valid()):
            username = form1.cleaned_data['username']
            email = form1.cleaned_data['email']
            password = form1.cleaned_data['password']
            retype_password = form1.cleaned_data['confirm_password']
            User.objects.create_user(username=username,
                                     email=email,
                                     password=password,
                                     first_name="job_seeker")
            messages.success(request, 'user registration successful')
            usr = authenticate(username=username, password=password)
            login(request, usr)
            user_instance = UserModel(user=usr, accountType="job_seeker")
            user_instance.save()
            # return HttpResponseRedirect(reverse(UserDashBoard))
            return HttpResponseRedirect(reverse(HomePage))
    else:
        form1 = UserForm()
    return render(request, 'user_signup.html', {'reg_form': form1})
示例#15
0
文件: views.py 项目: Monal5031/vms
 def get(self, request):
     organization_list = get_organizations_ordered_by_name()
     user_form = UserForm(prefix="usr")
     administrator_form = AdministratorForm(prefix="admin")
     return render(
         request, 'registration/signup_administrator.html', {
             'user_form': user_form,
             'administrator_form': administrator_form,
             'registered': self.registered,
             'phone_error': self.phone_error,
             'match_error': self.match_error,
             'organization_list': organization_list,
             'country_list': self.country_list,
         })
示例#16
0
文件: views.py 项目: danecollins/tp
def newuser(request):
    if request.user.is_anonymous():
        form = UserForm(request.POST or None)
        if form.is_valid():
            form_data = form.save(commit=False)
            # if User.objects.filter(username=form_data.username) is None:
            u = User.objects.create_user(first_name=form_data.first_name,
                                         last_name=form_data.last_name,
                                         username=form_data.username,
                                         password=form_data.password,
                                         email=form_data.email)
            u.save()
            print('Created new user:{} with name {} {}'.format(form_data.username,
                                                        form_data.first_name,
                                                        form_data.last_name))
            user = authenticate(username=form_data.username,
                                password=form_data.password)
            login(request, user)
            return redirect('/')
        else:
            return render(request, 'registration/newuser.html', {'form': form})
    else:
        return render(request, 'registration/already_logged_on.html')
示例#17
0
def signup(request, template_name="signup.html"):
    if hasattr(request.user, 'pk'):
        HttpResponseRedirect(reverse('dashboard')) 
    if request.POST:
        form = UserForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                form.cleaned_data.get('username'),
                form.cleaned_data.get('email'),
                form.cleaned_data.get('password'),
            )
            user.first_name = form.cleaned_data.get('first_name')
            user.last_name = form.cleaned_data.get('last_name')
            user.save()
            return HttpResponseRedirect(reverse('after_signup')) 
    else:
        form = UserForm()
    return render_to_response(
        template_name,
        {
            'form': form,
        },
        context_instance=RequestContext(request)
    ) 
示例#18
0
文件: views.py 项目: averrin/zdev
def profile(request):
    """
        Edit mysql creds
    """
    cred = MysqlCreds.objects.get(user=request.user)
    saved = False
    mysql_form = MySQLCreds(instance=cred)
    user_form = UserForm(instance=request.user)
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        mysql_form = MySQLCreds(request.POST, instance=cred)
        _devs = utmGet("""SELECT login FROM __developers""")
        devs = []
        for dev in _devs:
            devs.append(dev[0])
        if user_form.is_valid() and mysql_form.is_valid():
            if mysql_form.cleaned_data['db_login'] in devs:
                user_form.save()
                mysql_form.save()
                saved = True
            else:
                from django.forms.util import ErrorList
                mysql_form._errors["db_login"] = ErrorList([u"Такой логин отсутствует в таблице __developers"])
    return {'form': mysql_form, 'saved': saved, 'user_form': user_form}
示例#19
0
 def get(self, request):
     if request.user.is_authenticated:
         return render(request, 'pages/user_is_logged_in.html')
     else:
         user_form = UserForm(prefix="usr")
         alumni_form = AlumniForm(prefix="alu")
         return render(
             request, 'registration/signup_alumni.html', {
                 'user_form': user_form,
                 'alumni_form': alumni_form,
                 'registered': self.registered,
                 'phone_error': self.phone_error,
                 'match_error': self.match_error,
                 'country_list': self.country_list,
                 'city_list': self.city_list,
                 'region_list': self.region_list,
             })
示例#20
0
文件: views.py 项目: mjzac/intern
def registration_view(request):
    dict = {}
    if request.POST:
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            messages.add_message(
                request, messages.INFO,
                " You have successfully registered. You can sign in now.")
            redirect('/')
    else:
        form = UserForm()
    dict['form'] = form
    return render_to_response('registration/signup.html',
                              dict,
                              context_instance=RequestContext(request))
示例#21
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)
        profile_form = UserProfileForm(data=request.POST)

        # If the the form is valid...
        if user_form.is_valid() and profile_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()

            profile = profile_form.save(commit=False)
            profile.user = user

            profile.save()
            # Update our variable to tell the template registration was successful.
            registered = True

            new_user = authenticate(
                username=user_form.cleaned_data['username'],
                password=user_form.cleaned_data['password'],
            )
            login(request, new_user)

            return HttpResponseRedirect('/')

        # 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()

    # Render the template depending on the context.
    return render(request, 'registration/register.html', {})
示例#22
0
def register(request):

    registered = False
    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            name = user_form.cleaned_data['firstname']
            subject = 'message from eshop'
            comment = 'Hi! I am a new user'
            message = '%s %s' % (comment, name)
            emailFrom = user_form.cleaned_data['email']
            emailTo = [settings.EMAIL_HOST_USER]
            send_mail(
                subject,
                message,
                emailFrom,
                emailTo,
                fail_silently=True,
            )

            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

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

            profile.save()

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

    return render(
        request, 'registration/register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })
示例#23
0
def register(request):
    registered = False
    flag = 1
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)
        User = get_user_model()
        if user_form.is_valid() and profile_form.is_valid():
            for User in User.objects.filter():
                if user_form.cleaned_data['email'] == User.email:
                    flag = 0
                    user_form.cleaned_data['username'] = "******"
                    print("This mail address already exists!")

            if flag == 1:
                user = user_form.save()
                print("user saved")
                user.set_password(user.password)
                user.save()

                profile = profile_form.save(commit=False)
                profile.user = user

                if 'profile_pic' in request.FILES:
                    print('found it')
                    profile.profile_pic = request.FILES['profile_pic']
                profile.save()
                registered = True
            else:
                print("not-saved")
        else:
            print(user_form.errors, profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()
    return render(
        request, 'registration/registration.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered,
            'flag': flag
        })
示例#24
0
文件: views.py 项目: kmcluskey/FlyMet
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)
    else:
        user_form = UserForm()

    context_dict = {'user_form': user_form, 'registered': registered}
    return render(request, 'registration/register.html', context_dict)
示例#25
0
def register(request):
    if request.method=='POST':
        form = UserForm(request.POST, instance=User())
        if form.is_valid():
            user=form.save()
            user.set_password(form.cleaned_data["password2"])
            user.save()
            
            #trying to authenticate user
            auth_user = authenticate(username=user.username, 
                                     password=form.cleaned_data["password2"])
            if auth_user:
                login(request,auth_user)
                return redirect("Mail_blacklist.views.home")
            
    else:
        form=UserForm(instance=User())
    
    return render(request, 'registration/register.html', locals() )
示例#26
0
def register(request):
    registered = False  #will be set true when the registration is successful
    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        #grab information from the raw form information
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        if user_form.is_valid() and profile_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 then 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

            # If user provided a profile picture we need to get it from the input form
            # and put it in the UserProfile model.
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']
                # Now we save the UserProfile model instance.
                profile.save()
                # Update our variable to indicate that registration was successful.
                registered = True
        else:
            #if form is invalid
            print(user_form.errors, profile_form.errors)
    else:  #Not a HTTP POST, so we render our blank form using two ModelForm instances
        user_form = UserForm()
        profile_form = UserProfileForm()
    # Render the template depending on the context.
    return render(
        request, 'registration/register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })
示例#27
0
def register(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, request.FILES)
        profile_form = UserProfileForm(request.POST, request.FILES)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)
            raw_password = user.password  # this will be used in logging in user later...see below
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()

            # logging in user after completing registration
            user = auth.authenticate(username=user.username,
                                     password=raw_password)
            auth.login(request, user)
            return HttpResponseRedirect(reverse('index'))
        else:
            print(user_form.errors)
            print(profile_form.errors)
            # it is happening for validation errors
            # and see we are not returning anything
            # may be django handles it itself
            # beacuse django retuns this form with telling error messages
            # if we show the validation error messages to user in the template
            # so that they may enter correct value
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    context = {
        'user_form': user_form,
        'profile_form': profile_form,
    }

    return render(request, 'registration/register.html', context=context)
示例#28
0
 def test_user_form_password2_label(self):
     form = UserForm()
     self.assertEqual(form.fields['password2'].label,
                      'Подтверждение пароля')
示例#29
0
 def test_user_form_password1_label(self):
     form = UserForm()
     self.assertEqual(form.fields['password1'].label, 'Пароль')
示例#30
0
文件: views.py 项目: dangerdak/chrapp
def register(request):
    registered = False

    # Messy to include profile stuff here
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)

        profile_form = ProfileForm(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
            unique_slugify(profile, user.username)
            profile.save()

            # Give user permission to view and edit own profile
            assign_perm('profiles.view_profile', user, profile)
            assign_perm('profiles.change_profile', user, profile)

            registered = True

            # Invitation stuff
            if 'invitation' in request.session:
                # Retrieve invitation object
                invitation = Invitation.objects.get(
                    id=request.session['invitation'])
                # Create membership of profile with group
                m = Membership(profile=profile, giftgroup=invitation.gift_group)
                m.save()


                # Delete the used invitation from the (database and) session
                # invitation.delete()
                del request.session['invitation']
            else:
                # If user was not invited
                profile.save()

            # Check if all invited people have registered
            invites = Invitation.objects.all()
            all_users = [u.username for u in User.objects.all()]
            for invite in invites:
                if invite.to_name in all_users:
                    pass
                else:
                    break
# User no longer has admin property
#            # Check if user is an admin
#            if user.profile.admin:
#                permission_invites = Permission.objects.get(
#                    codename='send_invites')
#                permission_assign = Permission.objects.get(
#                    codename='assign_pairs')
#                user.user_permissions.add(
#                    permission_invites,
#                    permission_assign
#                    )

            # Log user in after registration
            user = authenticate(
                username=request.POST['username'],
                password=request.POST['password'])
            login(request, user)

        else:
            print(user_form.errors, profile_form.errors)
    else:
        # TODO repetition checking for invite
        if 'invitation' in request.session:
            # Retrieve invitation object
            invitation = Invitation.objects.get(
                id=request.session['invitation'])

            user_form = UserForm(initial={
                'username': invitation.to_name,
                'email': invitation.to_email})
            user_form.fields['username'].widget.attrs['readonly'] = True
            user_form.fields['email'].widget.attrs['readonly'] = True
        else:
            user_form = UserForm()

        profile_form = ProfileForm()

    return render(request,
                  'registration/register.html',
                  {'user_form': user_form,
                   'profile_form': profile_form,
                   'registered': registered})
示例#31
0
文件: views.py 项目: ahmedsabie/vms
def signup_volunteer(request):

    registered = False
    organization_list = get_organizations_ordered_by_name()

    if organization_list:
        if request.method == "POST":
            # each form must have its own namespace (prefix) if multiple forms
            # are to be put inside one <form> tag
            user_form = UserForm(request.POST, prefix="usr")
            volunteer_form = VolunteerForm(request.POST, request.FILES, prefix="vol")

            if user_form.is_valid() and volunteer_form.is_valid():

                if "resume_file" in request.FILES:
                    my_file = volunteer_form.cleaned_data["resume_file"]
                    if not validate_file(my_file):
                        return render(
                            request,
                            "registration/signup_volunteer.html",
                            {
                                "user_form": user_form,
                                "volunteer_form": volunteer_form,
                                "registered": registered,
                                "organization_list": organization_list,
                            },
                        )

                user = user_form.save()

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

                volunteer = volunteer_form.save(commit=False)
                volunteer.user = user

                # if an organization isn't chosen from the dropdown,
                # then organization_id will be 0
                organization_id = request.POST.get("organization_name")
                organization = get_organization_by_id(organization_id)

                if organization:
                    volunteer.organization = organization

                volunteer.reminder_days = 1
                volunteer.save()
                registered = True

                messages.success(request, "You have successfully registered!")
                return HttpResponseRedirect(reverse("home:index"))
            else:
                print(user_form.errors, volunteer_form.errors)
                return render(
                    request,
                    "registration/signup_volunteer.html",
                    {
                        "user_form": user_form,
                        "volunteer_form": volunteer_form,
                        "registered": registered,
                        "organization_list": organization_list,
                    },
                )
        else:
            user_form = UserForm(prefix="usr")
            volunteer_form = VolunteerForm(prefix="vol")

        return render(
            request,
            "registration/signup_volunteer.html",
            {
                "user_form": user_form,
                "volunteer_form": volunteer_form,
                "registered": registered,
                "organization_list": organization_list,
            },
        )

    else:
        return render(request, "organization/add_organizations.html")
示例#32
0
def registration(request):
    """
         Функция регистрации профиля персоны
         user_form -  работает из админки и содержит поле username пользвоателя
         sms_form -  Нужна для обработки кода смс
    """
    global counter,mes

    user_form = UserForm()
    sms_form = SmsForm()
    disabled,disabled2 = "","disabled" # Параметры кнопок,которые передаются в html

    if request.is_ajax():
        # Ajax запрос для автоматического определения ошибок при ввода телефона пользователем
        user_form = UserForm(request.POST)
        if user_form.is_valid():
            return JsonResponse({'s': True})
        else:
            return JsonResponse({'error': user_form.errors})

    if request.method == "POST" and 'code' in request.POST or request.is_ajax():

        user_form = UserForm (request.POST)

        if user_form.is_valid():
            #  Отправка сообщения и валидация номера
            smsc = SMSC()
            phone = user_form.cleaned_data['username']
            mes = my_random_string(4)
            print(mes)
            # mes = "5"
            # counter = ['19', '1', '0.9', '194.4' ]
            # d = [ '-1' ]
            counter = smsc.send_sms(phones=phone, message=mes, sender="me") # Отправка смс с
            # введёными данными пользователя
            status_phone = smsc.get_status(phone=phone, id=counter[0])
            print(status_phone)

            if len(counter)<3 and status_phone[0] != "-1":
                #  Проверка статуса отправки сообщения сайтом
                messages.error(request, "Такого номера не существует    ")

            else:
                messages.success(request, "Код отправлен!")
                disabled = "disabled"
                disabled2 = ""

    if request.method == "POST" and 'reg' in request.POST:
        user_form = UserForm(request.POST)
        sms_form = SmsForm(request.POST)
        print(mes)#код отправки
        if user_form.is_valid () and sms_form.is_valid ():
            if mes == sms_form.cleaned_data['sms_mes']:# ПРоверка совпадает ли код пользователя и код отправленный ему
                # создание и аутентификаци персоны по введёным данным пользователя
                last_id = User.objects.latest('id').id   #  можно заменить на ваши модели
                # last_i = Person.objects.latest('id').id  #  можно заменить на ваши модели
                password = "******"
                #  сохранение новго пользователя и дальнейший его вход
                User.objects.create_user (**user_form.cleaned_data, id=int(last_id)+1, password=password)
                # create_person = Person(users_id = last_id+1, id = last_i+1)
                # print(create_person)
                # create_person.save()
                user = authenticate(
                    username=user_form.cleaned_data[ 'username' ],
                    password=password
                )
                login(request, user)
                messages.success (request, "Вы успешно зарегестрированы!")
                # return redirect('edit_person', id=last_i+1)
            else:
                messages.error(request, "Вы ввели неверный код!")
                disabled2 = ""


    return render (request, 'sign_ip.html',
                   {"user_form": user_form,
                    "sms_form": sms_form,
                    "id": id,
                    "disabled": disabled,
                    "disabled2":disabled2})
示例#33
0
    def post(self, request):
        organization_list = get_organizations_ordered_by_name()
        if organization_list:
            if request.method == 'POST':
                user_form = UserForm(request.POST, prefix="usr")
                volunteer_form = VolunteerForm(request.POST,
                                               request.FILES,
                                               prefix="vol")

                if user_form.is_valid() and volunteer_form.is_valid():
                    password1 = request.POST.get('usr-password')
                    password2 = request.POST.get('usr-confirm_password')
                    if not match_password(password1, password2):
                        self.match_error = True
                        return render(
                            request, 'registration/signup_volunteer.html', {
                                'user_form': user_form,
                                'volunteer_form': volunteer_form,
                                'registered': self.registered,
                                'phone_error': self.phone_error,
                                'match_error': self.match_error,
                                'organization_list': self.organization_list,
                            })

                    vol_country = request.POST.get('vol-country')
                    vol_phone = request.POST.get('vol-phone_number')
                    if (vol_country and vol_phone):
                        if not validate_phone(vol_country, vol_phone):
                            self.phone_error = True
                            return render(
                                request, 'registration/signup_volunteer.html',
                                {
                                    'user_form': user_form,
                                    'volunteer_form': volunteer_form,
                                    'registered': self.registered,
                                    'phone_error': self.phone_error,
                                    'organization_list':
                                    self.organization_list,
                                })

                    if 'resume_file' in request.FILES:
                        my_file = volunteer_form.cleaned_data['resume_file']
                        if not validate_file(my_file):
                            return render(
                                request, 'registration/signup_volunteer.html',
                                {
                                    'user_form': user_form,
                                    'volunteer_form': volunteer_form,
                                    'registered': self.registered,
                                    'phone_error': self.phone_error,
                                    'organization_list':
                                    self.organization_list,
                                })

                    user = user_form.save()

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

                    volunteer = volunteer_form.save(commit=False)
                    volunteer.user = user

                    # if an organization isn't chosen from the dropdown,
                    # then organization_id will be 0
                    organization_id = request.POST.get('organization_name')
                    organization = get_organization_by_id(organization_id)

                    if organization:
                        volunteer.organization = organization
                    else:
                        unlisted_org = request.POST.get(
                            'vol-unlisted_organization')
                        org = Organization.objects.create(
                            name=unlisted_org, approved_status=False)
                        org.save()
                        volunteer.organization = org

                    volunteer.reminder_days = 1
                    volunteer.save()
                    current_site = get_current_site(request)
                    mail_subject = 'Activate your account.'
                    message = render_to_string(
                        'registration/acc_active_email.html', {
                            'user': user,
                            'domain': current_site.domain,
                            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                            'token': account_activation_token.make_token(user),
                        })
                    to_email = volunteer_form.cleaned_data.get('email')
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
                    return render(request, 'home/email_ask_confirm.html')
                else:
                    return render(
                        request, 'registration/signup_volunteer.html', {
                            'user_form': user_form,
                            'volunteer_form': volunteer_form,
                            'registered': self.registered,
                            'phone_error': self.phone_error,
                            'organization_list': self.organization_list,
                        })
        else:
            return render(request, 'home/home.html', {'error': True})
示例#34
0
 def post(self, request, *args, **kwargs):
     form = UserForm(request.POST)
     return super(UserCreate, self).form_valid(form)
示例#35
0
 def post(self, request, *args, **kwargs):
     print("submitted form")
     form = UserForm(request.POST)
     return super(UserUpdate, self).form_valid(form)
示例#36
0
文件: views.py 项目: systers/vms
    def post(self, request):
        organization_list = get_organizations_ordered_by_name()
        if organization_list:
            if request.method == 'POST':
                user_form = UserForm(request.POST, prefix="usr")
                volunteer_form = VolunteerForm(
                    request.POST, request.FILES, prefix="vol")

                if user_form.is_valid() and volunteer_form.is_valid():
                    password1 = request.POST.get('usr-password')
                    password2 = request.POST.get('usr-confirm_password')
                    if not match_password(password1, password2):
                        self.match_error = True
                        return render(
                            request, 'registration/signup_volunteer.html', {
                                'user_form': user_form,
                                'volunteer_form': volunteer_form,
                                'registered': self.registered,
                                'phone_error': self.phone_error,
                                'match_error': self.match_error,
                                'organization_list': self.organization_list,
                            })

                    vol_country = request.POST.get('vol-country')
                    vol_phone = request.POST.get('vol-phone_number')
                    if (vol_country and vol_phone):
                        if not validate_phone(vol_country, vol_phone):
                            self.phone_error = True
                            return render(
                                request, 'registration/signup_volunteer.html',
                                {
                                    'user_form': user_form,
                                    'volunteer_form': volunteer_form,
                                    'registered': self.registered,
                                    'phone_error': self.phone_error,
                                    'organization_list':
                                    self.organization_list,
                                })

                    if 'resume_file' in request.FILES:
                        my_file = volunteer_form.cleaned_data['resume_file']
                        if not validate_file(my_file):
                            return render(
                                request, 'registration/signup_volunteer.html',
                                {
                                    'user_form': user_form,
                                    'volunteer_form': volunteer_form,
                                    'registered': self.registered,
                                    'phone_error': self.phone_error,
                                    'organization_list':
                                    self.organization_list,
                                })

                    user = user_form.save()

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

                    volunteer = volunteer_form.save(commit=False)
                    volunteer.user = user

                    # if an organization isn't chosen from the dropdown,
                    # then organization_id will be 0
                    organization_id = request.POST.get('organization_name')
                    organization = get_organization_by_id(organization_id)

                    if organization:
                        volunteer.organization = organization
                    else:
                        unlisted_org = request.POST.get('vol-unlisted_organization')
                        org = Organization.objects.create(name=unlisted_org, approved_status=False)
                        org.save()
                        volunteer.organization = org

                    volunteer.reminder_days = 1
                    volunteer.save()
                    current_site = get_current_site(request)
                    mail_subject = 'Activate your account.'
                    message = render_to_string(
                        'registration/acc_active_email.html', {
                            'user': user,
                            'domain': current_site.domain,
                            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                            'token': account_activation_token.make_token(user),
                        })
                    to_email = volunteer_form.cleaned_data.get('email')
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
                    return render(request, 'home/email_ask_confirm.html')
                else:
                    return render(
                        request, 'registration/signup_volunteer.html', {
                            'user_form': user_form,
                            'volunteer_form': volunteer_form,
                            'registered': self.registered,
                            'phone_error': self.phone_error,
                            'organization_list': self.organization_list,
                        })
        else:
            return render(request, 'home/home.html', {'error': True})
示例#37
0
文件: views.py 项目: systers/vms
    def post(self, request):
        organization_list = get_organizations_ordered_by_name()
        if organization_list:
            if request.method == 'POST':
                user_form = UserForm(request.POST, prefix="usr")
                administrator_form = AdministratorForm(
                    request.POST, prefix="admin")

                if user_form.is_valid() and administrator_form.is_valid():
                    password1 = request.POST.get('usr-password')
                    password2 = request.POST.get('usr-confirm_password')
                    if not match_password(password1, password2):
                        self.match_error = True
                        return render(
                            request, 'registration/signup_administrator.html',
                            {
                                'user_form': user_form,
                                'administrator_form': administrator_form,
                                'registered': self.registered,
                                'phone_error': self.phone_error,
                                'match_error': self.match_error,
                                'organization_list': self.organization_list,
                            })
                    ad_country = request.POST.get('admin-country')
                    ad_phone = request.POST.get('admin-phone_number')

                    if ad_country and ad_phone:
                        if not validate_phone(ad_country, ad_phone):
                            self.phone_error = True
                            return render(
                                request,
                                'registration/signup_administrator.html', {
                                    'user_form': user_form,
                                    'administrator_form': administrator_form,
                                    'registered': self.registered,
                                    'phone_error': self.phone_error,
                                    'match_error': self.match_error,
                                    'organization_list':
                                    self.organization_list,
                                })

                    user = user_form.save()
                    user.set_password(user.password)
                    user.save()

                    administrator = administrator_form.save(commit=False)
                    administrator.user = user

                    # if organization isn't chosen from dropdown,
                    # the organization_id will be 0
                    organization_id = request.POST.get('organization_name')
                    organization = get_organization_by_id(organization_id)

                    if organization:
                        administrator.organization = organization
                    else:
                        unlisted_org = request.POST.get('admin-unlisted_organization')
                        org = create_organization(unlisted_org)
                        administrator.organization = org

                    administrator.save()
                    registered = True
                    messages.success(request,
                                     'You have successfully registered!')
                    return HttpResponseRedirect(reverse('home:index'))
                else:
                    return render(
                        request, 'registration/signup_administrator.html', {
                            'user_form': user_form,
                            'administrator_form': administrator_form,
                            'registered': self.registered,
                            'phone_error': self.phone_error,
                            'match_error': self.match_error,
                            'organization_list': self.organization_list,
                        })
        else:
            return render(request, 'home/home.html', {'error': True})
示例#38
0
 def test_user_form_email_label(self):
     form = UserForm()
     self.assertEqual(form.fields['email'].label, 'Адрес электронной почты')
示例#39
0
 def test_user_form_photo_label(self):
     form = UserForm()
     self.assertEqual(form.fields['photo'].label, 'Аватарка')
示例#40
0
def register_clinician(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
	user_group = 'Clinician'

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

	# If it's a HTTP POST, we're interested in processing form data.
	if request.method == 'POST':

		user_form = UserForm(data=request.POST)
		user_profile_form = UserProfileForm(data=request.POST)
		clinical_profile_form = ClinicalUserProfileForm(data=request.POST)
		clinic_form = ClinicForm(data=request.POST)
		args['user_form'] = user_form

		# If the two forms are valid...
		if user_form.is_valid() and clinical_profile_form.is_valid() and clinic_form.is_valid() and user_profile_form.is_valid():
			# Save the user's form data to the database.
			user = user_form.save()
			username = user_form.cleaned_data['username']
			email = user_form.cleaned_data['email']
			user.set_password(user.password) # hash password
			user.is_active = False
			user.save()

			user_profile = user_profile_form.save(commit=False)
			user_profile.user = user
			user_profile.save()

			# save clinician profile
			clinical_profile = clinical_profile_form.save(commit=False)
			clinical_profile.userprofile = user_profile
			clinical_profile.save()

			# save clinic - need to check if user inputted the text himself/herself
			clinic = clinic_form.save(commit=False)
			clinical_profile.clinic_of_practice = clinic
			clinic.save()

			# Set user group - for this, we set it to 'User'
			g = Group.objects.get(name = user_group)
			g.user_set.add(user)

			# Update our variable to tell the template registration was successful.
			registered = True

			emailnotify("clinicianuser", username, email, "")

		else:
			print(user_form.errors, user_profile_form.errors, clinic_form.errors, clinical_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()
		user_profile_form = UserProfileForm()
		clinical_profile_form = ClinicalUserProfileForm()
		clinic_form = ClinicForm()

	# Render the template depending on the context.
	return render_to_response(
			'registration/doctor-signup.html',
			{'user_form': user_form, 'user_profile_form': user_profile_form, 'clinical_profile_form': clinical_profile_form, 'clinic_form': clinic_form, 'registered': registered},
			RequestContext(request))
示例#41
0
 def test_user_form_login_label(self):
     form = UserForm()
     self.assertEqual(form.fields['username'].label, 'Имя пользователя')
示例#42
0
def register_publicuser(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
	user_group = 'User'

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

	# 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)
		user_profile_form = UserProfileForm(data=request.POST)
		args['user_form'] = user_form

		# If the two forms are valid...
		if user_form.is_valid() and user_profile_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.
			username = user_form.cleaned_data['username']
			email = user_form.cleaned_data['email']
			user.set_password(user.password)
			user.is_active = False
			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 = user_profile_form.save(commit=False)
			profile.user = user

			# Generate activation key
			salt = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
			activation_key = hashlib.sha1((salt+email).encode('utf-8')).hexdigest()
			key_expires = datetime.datetime.today() + datetime.timedelta(2)

			profile = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires)
			# Now we save the UserProfile model instance.
			profile.save()

			# Set user group - for this, we set it to 'User'
			g = Group.objects.get(name = user_group)
			g.user_set.add(user)

			#Empty public user profile
			publicprofile = PublicUserProfile(userprofile = profile, allergies = "", height = 0, weight = 0)
			publicprofile.save()

			# Update our variable to tell the template registration was successful.
			registered = True

			emailnotify("publicuser", username, email, activation_key)

		# 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, user_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()
		user_profile_form = UserProfileForm()

	# Render the template depending on the context.
	return render_to_response(
			'registration/public-signup.html',
			{'user_form': user_form, 'user_profile_form': user_profile_form, 'registered': registered},
			RequestContext(request))
示例#43
0
def register(request):
    registered = False

    # Messy to include profile stuff here
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)

        profile_form = ProfileForm(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
            unique_slugify(profile, user.username)
            profile.save()

            # Give user permission to view and edit own profile
            assign_perm('profiles.view_profile', user, profile)
            assign_perm('profiles.change_profile', user, profile)

            registered = True

            # Invitation stuff
            if 'invitation' in request.session:
                # Retrieve invitation object
                invitation = Invitation.objects.get(
                    id=request.session['invitation'])
                # Create membership of profile with group
                m = Membership(profile=profile,
                               giftgroup=invitation.gift_group)
                m.save()

                # Delete the used invitation from the (database and) session
                # invitation.delete()
                del request.session['invitation']
            else:
                # If user was not invited
                profile.save()

            # Check if all invited people have registered
            invites = Invitation.objects.all()
            all_users = [u.username for u in User.objects.all()]
            for invite in invites:
                if invite.to_name in all_users:
                    pass
                else:
                    break


# User no longer has admin property
#            # Check if user is an admin
#            if user.profile.admin:
#                permission_invites = Permission.objects.get(
#                    codename='send_invites')
#                permission_assign = Permission.objects.get(
#                    codename='assign_pairs')
#                user.user_permissions.add(
#                    permission_invites,
#                    permission_assign
#                    )

# Log user in after registration
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password'])
            login(request, user)

        else:
            print(user_form.errors, profile_form.errors)
    else:
        # TODO repetition checking for invite
        if 'invitation' in request.session:
            # Retrieve invitation object
            invitation = Invitation.objects.get(
                id=request.session['invitation'])

            user_form = UserForm(initial={
                'username': invitation.to_name,
                'email': invitation.to_email
            })
            user_form.fields['username'].widget.attrs['readonly'] = True
            user_form.fields['email'].widget.attrs['readonly'] = True
        else:
            user_form = UserForm()

        profile_form = ProfileForm()

    return render(
        request, 'registration/register.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })
示例#44
0
def signup_administrator(request):
    """
    This method is responsible for diplaying the register user view
    Register Admin or volunteer is judged on the basis of users 
    access rights.
    Only if user is registered and logged in and registered as an
    admin user, he/she is allowed to register others as an admin user
    """
    registered = False
    organization_list = get_organizations_ordered_by_name()

    if organization_list:
        #if request.user.username != '' and request.user.is_authenticated(
        #) and checkAdmin(request.user):
        if request.method == 'POST':
            user_form = UserForm(request.POST, prefix="usr")
            administrator_form = AdministratorForm(request.POST,
                                                   prefix="admin")

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

                administrator = administrator_form.save(commit=False)
                administrator.user = user

                #if organization isn't chosen from dropdown, the organization_id will be 0
                organization_id = request.POST.get('organization_name')
                organization = get_organization_by_id(organization_id)

                if organization:
                    administrator.organization = organization

                administrator.save()
                registered = True

                return HttpResponseRedirect(reverse('home:index'))
            else:
                print user_form.errors, administrator_form.errors
                return render(
                    request, 'registration/signup_administrator.html', {
                        'user_form': user_form,
                        'administrator_form': administrator_form,
                        'registered': registered,
                        'organization_list': organization_list,
                    })
        else:
            user_form = UserForm(prefix="usr")
            administrator_form = AdministratorForm(prefix="admin")

        return render(
            request, 'registration/signup_administrator.html', {
                'user_form': user_form,
                'administrator_form': administrator_form,
                'registered': registered,
                'organization_list': organization_list,
            })

    else:
        return render(request, 'organization/add_organizations.html')
示例#45
0
文件: views.py 项目: ahmedsabie/vms
def signup_administrator(request):
    """
    This method is responsible for diplaying the register user view
    Register Admin or volunteer is judged on the basis of users
    access rights.
    Only if user is registered and logged in and registered as an
    admin user, he/she is allowed to register others as an admin user
    """
    registered = False
    organization_list = get_organizations_ordered_by_name()

    if organization_list:
        if request.method == "POST":
            user_form = UserForm(request.POST, prefix="usr")
            administrator_form = AdministratorForm(request.POST, prefix="admin")

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

                administrator = administrator_form.save(commit=False)
                administrator.user = user

                # if organization isn't chosen from dropdown,
                # the organization_id will be 0
                organization_id = request.POST.get("organization_name")
                organization = get_organization_by_id(organization_id)

                if organization:
                    administrator.organization = organization

                administrator.save()
                registered = True
                messages.success(request, "You have successfully registered!")
                return HttpResponseRedirect(reverse("home:index"))
            else:
                print(user_form.errors, administrator_form.errors)
                return render(
                    request,
                    "registration/signup_administrator.html",
                    {
                        "user_form": user_form,
                        "administrator_form": administrator_form,
                        "registered": registered,
                        "organization_list": organization_list,
                    },
                )
        else:
            user_form = UserForm(prefix="usr")
            administrator_form = AdministratorForm(prefix="admin")

        return render(
            request,
            "registration/signup_administrator.html",
            {
                "user_form": user_form,
                "administrator_form": administrator_form,
                "registered": registered,
                "organization_list": organization_list,
            },
        )

    else:
        return render(request, "organization/add_organizations.html")
示例#46
0
def signup_volunteer(request):

    registered = False
    organization_list = get_organizations_ordered_by_name()

    if organization_list:
        if request.method == 'POST':
            #each form must have it's own namespace (prefix) if multiple forms are to be put inside one <form> tag
            user_form = UserForm(request.POST, prefix="usr")
            volunteer_form = VolunteerForm(request.POST,
                                           request.FILES,
                                           prefix="vol")

            if user_form.is_valid() and volunteer_form.is_valid():

                if 'resume_file' in request.FILES:
                    my_file = volunteer_form.cleaned_data['resume_file']
                    if not validate_file(my_file):
                        return render(
                            request, 'registration/signup_volunteer.html', {
                                'user_form': user_form,
                                'volunteer_form': volunteer_form,
                                'registered': registered,
                                'organization_list': organization_list,
                            })

                user = user_form.save()

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

                volunteer = volunteer_form.save(commit=False)
                volunteer.user = user

                #if an organization isn't chosen from the dropdown, then organization_id will be 0
                organization_id = request.POST.get('organization_name')
                organization = get_organization_by_id(organization_id)

                if organization:
                    volunteer.organization = organization

                volunteer.save()
                registered = True

                return HttpResponseRedirect(reverse('home:index'))
            else:
                print user_form.errors, volunteer_form.errors
                return render(
                    request, 'registration/signup_volunteer.html', {
                        'user_form': user_form,
                        'volunteer_form': volunteer_form,
                        'registered': registered,
                        'organization_list': organization_list,
                    })
        else:
            user_form = UserForm(prefix="usr")
            volunteer_form = VolunteerForm(prefix="vol")

        return render(
            request, 'registration/signup_volunteer.html', {
                'user_form': user_form,
                'volunteer_form': volunteer_form,
                'registered': registered,
                'organization_list': organization_list,
            })

    else:
        return render(request, 'organization/add_organizations.html')
示例#47
0
def registerTeamMember(request, startupID='Default User'):

    registered = False

    startup = Startup.objects.get(uniqueID=startupID)

    if request.method == 'POST':

        # Get info from "both" forms
        # It appears as one form to the user on the .html page
        #        user_form = UserForm(data=request.POST)
        user_form = UserForm(request.POST, request.FILES)
        profile_form = TeamMemberProfileInfoForm(data=request.POST)

        # Check to see both forms are valid
        if user_form.is_valid() and profile_form.is_valid():

            # Save User Form to Database
            user = user_form.save(commit=False)

            #        group = user_form.save()

            # Hash the password
            user.set_password(user.password)
            user.is_Team_Leader = False
            user.is_Team_Member = True
            user.startupID = startup.uniqueID
            user.name_of_the_startup = startup.name_of_the_startup

            #        group.password(group.password)

            # Update with Hashed password

            # Now we deal with the extra info!

            # Can't commit yet because we still need to manipulate
            profile = profile_form.save(commit=False)

            # Set One to One relationship between
            # UserForm and IndividualProfileInfoForm
            profile.user = user
            profile.startupID = startup.uniqueID
            user.save()

            # we are getting the group

            group = Group.objects.get(name=user.name_of_the_startup)
            startup.group = group

            # we are adding the user to the group
            user.groups.add(startup.group)

            # Check if they provided a profile picture
            if 'profile_pic' in request.FILES:
                print('found it')
                # If yes, then grab it from the POST form reply
                user.profile_pic = request.FILES['profile_pic']

            profile.save()

            registered = True

            # Registration Successful!

        else:
            # One of the forms was invalid if this else gets called.
            print(
                user_form.errors,
                profile_form.errors,
            )

    else:
        # Was not an HTTP post so we just render the forms as blank.
        user_form = UserForm()
        profile_form = TeamMemberProfileInfoForm()

#    user_form = UserForm()

# This is the render and context dictionary to feed
# back to the registration.html file page.
    return render(
        request, 'registration/memberRegistration.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'startupID': startupID,
            'registered': registered
        })
示例#48
0
def user_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(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_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.is_active = False
            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

            # Now we save the UserProfile model instance.
            profile.save()

            # Update our variable to tell the template registration was successful.
            registered = True

            #send an Email
            send_to = request.POST['email']
            firstname = request.POST['firstname']
            lastname = request.POST['lastname']
            name = firstname+' '+lastname
            body = unicode(u'''
Hello %s!
             
Thank you for registering!

Greetings from BITS Pilani!

It gives me immense pleasure in inviting your institute to the 30th edition of BITS Open Sports Meet (BOSM), the annual national sports meet of Birla Institute of Technology & Science, Pilani, India. This year, BOSM will be held from September 18th to 22nd.             

Kindly go through the invite attached with this email and apply through our website www.bits-bosm.org. Applications close on 31st August 2015 at 1700 hrs.            

Please apply as soon as possible to enable us to confirm your participation at the earliest.             

We would be really happy to see your college represented at our sports festival.            

We look forward to seeing you at BOSM 2015.

P.S: THIS EMAIL DOES NOT CONFIRM YOUR PRESENCE AT BOSM 2015.

Regards,
Vinit Bhat
CoSSAcn (Head)
Dept. of Publications & Correspondence, BOSM 2015
BITS Pilani
Ph: +91 96605 77340
                ''') % name
            email = EmailMessage('Registration Confirmation', body, '*****@*****.**', [send_to])
            email.attach_file('/home/dvm/bosm/bosm2015/bosm2015/media/pdf/BOSM 2015 Invite.pdf')
            email.send()

        # 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(request, 'registration/register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})
示例#49
0
    def post(self, request):

        if request.method == 'POST':
            user_form = UserForm(request.POST, prefix="usr")
            alumni_form = AlumniForm(request.POST, request.FILES, prefix="alu")
            if user_form.is_valid() and alumni_form.is_valid():
                password1 = request.POST.get('usr-password')
                password2 = request.POST.get('usr-confirm_password')
                if not match_password(password1, password2):
                    self.match_error = True
                    return render(
                        request, 'registration/signup_alumni.html', {
                            'user_form': user_form,
                            'alumni_form': alumni_form,
                            'registered': self.registered,
                            'phone_error': self.phone_error,
                            'match_error': self.match_error,
                            'country_list': self.country_list,
                            'city_list': self.city_list,
                            'region_list': self.region_list,
                        })
                try:
                    alu_country_name = request.POST.get('current_country')
                    alu_country = Country.objects.get(name=alu_country_name)
                except ObjectDoesNotExist:
                    alu_country = None

                try:
                    alu_state_name = request.POST.get('current_state')
                    alu_state = Region.objects.get(name=alu_state_name)
                except ObjectDoesNotExist:
                    alu_state = None

                try:
                    alu_city_name = request.POST.get('current_city')
                    alu_city = City.objects.get(name=alu_city_name)
                except ObjectDoesNotExist:
                    alu_city = None

                alu_phone = request.POST.get('alu-phone_number')

                if alu_country and alu_phone:
                    if not validate_phone(alu_country, alu_phone):
                        self.phone_error = True
                        return render(
                            request, 'registration/signup_alumni.html', {
                                'user_form': user_form,
                                'alumni_form': alumni_form,
                                'registered': self.registered,
                                'phone_error': self.phone_error,
                                'match_error': self.match_error,
                                'country_list': self.country_list,
                                'city_list': self.city_list,
                                'region_list': self.region_list,
                            })

                user = user_form.save(commit=False)

                user.set_password(user.password)
                user.is_active = False
                user.save()

                alumni = alumni_form.save(commit=False)

                alumni.user = user
                alumni.country = alu_country
                alumni.city = alu_city
                alumni.state = alu_state
                alumni.save()

                print('nhi nhi yha pahooncha')

                current_site = get_current_site(request)
                mail_subject = 'Activate your account.'
                message = render_to_string(
                    'registration/acc_active_email.html', {
                        'user':
                        user,
                        'domain':
                        current_site.domain,
                        'uid':
                        force_text(urlsafe_base64_encode(force_bytes(
                            user.pk))),
                        'token':
                        account_activation_token.make_token(user),
                    })
                to_email = alumni_form.cleaned_data.get('email')
                send_mail(mail_subject, message, settings.EMAIL_HOST_USER,
                          [to_email])
                print('reached')
                return render(request, 'HomePage/email_ask_confirm.html')

            else:
                print('yha pahooncha kya')
                return render(
                    request, 'registration/signup_alumni.html', {
                        'user_form': user_form,
                        'alumni_form': alumni_form,
                        'registered': self.registered,
                        'phone_error': self.phone_error,
                        'match_error': self.match_error,
                        'country_list': self.country_list,
                        'city_list': self.city_list,
                        'region_list': self.region_list,
                    })
示例#50
0
def register(request):

    registered = False

    if request.method == 'POST':

        # Get info from "both" forms
        # It appears as one form to the user on the .html page
        user_form = UserForm(request.POST, request.FILES)
        profile_form = IndividualProfileInfoForm(data=request.POST)

        # Check to see both forms are valid
        if user_form.is_valid() and profile_form.is_valid():

            # Save User Form to Database
            user = user_form.save()

            # Hash the password
            user.set_password(user.password)
            user.is_Team_Leader = False
            user.is_Individual = True

            # Update with Hashed password

            # Now we deal with the extra info!

            # Can't commit yet because we still need to manipulate
            profile = profile_form.save(commit=False)

            # Set One to One relationship between
            # UserForm and IndividualProfileInfoForm
            profile.user = user

            # Check if they provided a profile picture
            if 'profile_pic' in request.FILES:
                print('found it')
                # If yes, then grab it from the POST form reply
                user.profile_pic = request.FILES['profile_pic']

            # Now save model
            user.save()

            profile.save()

            # Registration Successful!
            registered = True

        else:
            # One of the forms was invalid if this else gets called.
            print(user_form.errors, profile_form.errors)

    else:
        # Was not an HTTP post so we just render the forms as blank.
        user_form = UserForm()
        profile_form = IndividualProfileInfoForm()

    # This is the render and context dictionary to feed
    # back to the registration.html file page.
    return render(
        request, 'registration/registration.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })