Beispiel #1
0
def register(request):
    context = {}
    if request.method == 'GET':
        form = RegisterForm()
        context['form'] = form
    if request.method == 'POST':
        form = RegisterForm(request.POST)

        if form.is_valid():
            username = form.cleaned_data['name']
            email = form.cleaned_data['email']
            if User.objects.filter(username=username) or User.objects.filter(
                    email=email):
                form = RegisterForm()
                form.errors['注意:'] = (u"用户已存在,请更换用户名或邮箱注册")
            else:
                user = User()
                user.username = username
                user.email = email
                user.set_password(form.cleaned_data['password'])
                user.save()
                p = UserProfile(belong_to=user)
                p.name = username
                p.email = email
                p.save()
                return redirect(to='login')
        context['form'] = form
    return render(request, "register.html", context)
Beispiel #2
0
def saveprofile(request):
    user_id=request.POST.get('user_id',1)
    first_name=request.POST.get('first_name')
    last_name=request.POST.get('last_name')
    nickname=request.POST.get('nickname')
    email=request.POST.get('email')
    url=request.POST.get('url')
    yim=request.POST.get('yim')
    jabber=request.POST.get('jabber')
    description=request.POST.get('description')
    pass1 = request.POST.get('pass1')
    pass2 = request.POST.get('pass2')
    user = User.objects.get(id=user_id)
    try:
        profile=user.get_profile()
    except:
        profile=UserProfile(user=user)
    user.first_name=first_name
    user.last_name=last_name
    user.email=email
    profile.nickname=nickname
    profile.website=url
    profile.yim=yim
    profile.jabber=jabber
    profile.desc=description
    profile.save()
    user.save()
    return render_response(request,'admin/profile.html',{'user':user})
Beispiel #3
0
def signup(request):
	if request.method == 'POST':
		form = SignupForm(request.POST)
		print(form.data)
		print(form.is_valid())
		if form.is_valid():
			form.save()

			username = form.data['username']
			email = form.data['email']
			print(username,email)
			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(1)

			# Create and save user profile
			user = User.objects.get(email=email)
			new_profile = UserProfile(user=user, activation_key=activation_key,
				key_expires=key_expires)
			new_profile.save()

			# Send email with activation key
			email_subject = 'Account confirmation'
			email_body = "Hi %s, thanks for signing up. To activate your account, click this link within \
			48hours http://127.0.0.1:8000/confirm/%s" % (username, activation_key)
			send_mail(email_subject, email_body, '*****@*****.**',
				[email], fail_silently = False)
			return render(request, 'sign_up_success.html')
		else:
			return render(request, 'confirm_expired.html')
	else:
		return render(request, 'sign_up.html')
Beispiel #4
0
def register(request):
    data = dict()
    data["tags"] = th.get_information(None)
    if request.method == 'POST':  # 异步传输。。
        imf = {}
        username = (request.POST.get('username'))
        password1 = (request.POST.get('password1'))
        password2 = (request.POST.get('password2'))
        user = User.objects.filter(username=username)
        if user:
            imf["flag"] = "name"
            return HttpResponse(json.dumps(imf),
                                content_type='application/json')
        if password1 != password2:
            imf["flag"] = "pwd"
            return HttpResponse(json.dumps(imf),
                                content_type='application/json')
        user = User.objects.create_user(username=username, password=password1)
        user.save()
        profile = UserProfile()
        profile.user_id = user.id
        profile.save()
        imf["flag"] = "yes"
        user = authenticate(username=username, password=password1)
        if user is not None:
            auth_login(request, user)
        return HttpResponse(json.dumps(imf), content_type='application/json')
    return render_to_response('blog_register(1).html',
                              data,
                              context_instance=RequestContext(request))
Beispiel #5
0
def regist(request):
    regist_info = ''
    if request.method == 'GET':
        form = RegistForm()
        # context, content, contents are the same(变量名不影响使用)
        contents = {'form': form}

        # thise are the same
        return render(request, 'blog/regist.html', contents)
    else:
        form = RegistForm(request.POST, request.FILES)
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password1 = form.cleaned_data['password1']
            password2 = form.cleaned_data['password2']
            phone = form.cleaned_data['phone']
            userimg = form.cleaned_data['userimg']
            sex = form.cleaned_data['sex']
            if userimg and userimg.size > USER_IMG_MAX_SIZE:
                logger.info(userimg.size)
                regist_info = 'user img too big'
                return render_to_response("blog/regist.html", RequestContext(request, {'form': form, 'regist_info': regist_info}))
            if password1 == password2:
                user_filter_result = User.objects.filter(email=email)
                if user_filter_result :
                    regist_info = "邮箱已存在"
                    return render_to_response("blog/regist.html", RequestContext(request, {'form': form, 'regist_info': regist_info}))
                else:
                    user_profile = UserProfile()
                    user_profile.userimg = DEFAULT_USER_IMG
                    if userimg:
                        imgpath = os.path.join(USER_IMG_PATH, email)
                        with open(imgpath, 'wb') as img:
                            img.write(userimg.read())
                        user_profile.userimg = email

                    user = User.objects.create_user(
                        username=username, password=password1, email=email)
                    user_profile.user_id = user.id
                    user_profile.phone = phone
                    user_profile.sex = sex
                    user_profile.save()
                    regist_info = '注册成功'
                    user = auth.authenticate(
                        username=username, password=password1)
                    auth.login(request, user)
                    # 利用session传递信息给模板层
                    request.session['username'] = username
                    request.session['userimg'] = os.path.join(USER_IMG_URL, user_profile.userimg)
                    return HttpResponseRedirect('/')
                    return render_to_response('blog/regist.html', RequestContext(request, {'form': form, 'regist_info': regist_info}))
            else:
                regist_info = "两次输入的密码不一致!"
                return render_to_response("blog/regist.html", RequestContext(request, {'form': form, 'regist_info': regist_info}))
        else:
            regist_info = '输入有误'
            return render_to_response('blog/regist.html', RequestContext(request, {'form': form, 'regist_info': regist_info}))
Beispiel #6
0
def regist(request):
    regist_info = ''
    if request.method == 'GET':
        form = RegistForm()
        # context, content, contents are the same(变量名不影响使用)
        contents = {'form': form}

        # thise are the same
        return render(request, 'blog/regist.html', contents)
    else:
        form = RegistForm(request.POST, request.FILES)
        if form.is_valid():
            username = form.cleaned_data['username']
            password1 = form.cleaned_data['password1']
            password2 = form.cleaned_data['password2']
            nickname = form.cleaned_data['nickname']
            phone = form.cleaned_data['phone']
            userimg = form.cleaned_data['userimg']
            if password1 == password2:
                user_filter_result = User.objects.filter(username=username)
                nickname_filter_result = UserProfile.objects.filter(
                    nickname=nickname)
                if user_filter_result or nickname_filter_result:
                    regist_info = "邮箱或昵称已存在"
                    return render_to_response("blog/regist.html", RequestContext(request, {'form': form, 'regist_info': regist_info}))
                else:
                    user = User.objects.create_user(
                        username=username, password=password1)
                    # user.is_active=True
                    # user.save
                    user_profile = UserProfile()
                    user_profile.user_id = user.id
                    user_profile.phone = phone
                    user_profile.nickname = nickname
                    user_profile.userimg = '/media/uploads/userimg/defaultuser.png'
                    if userimg:
                        imgpath = os.path.join(UPLOADPATH, 'userimg', username)
                        with open(imgpath, 'wb') as img:
                            img.write(userimg.read())
                        user_profile.userimg = imgpath[(len(BASEPATH) + 5):]
                    user_profile.save()
                    regist_info = '注册成功'
                    user = auth.authenticate(
                        username=username, password=password1)
                    auth.login(request, user)
                    # 利用session传递信息给模板层
                    request.session['username'] = username
                    request.session['userimg'] = user.userprofile.userimg
                    return HttpResponseRedirect('/')
                    return render_to_response('blog/regist.html', RequestContext(request, {'form': form, 'regist_info': regist_info}))
            else:
                regist_info = "两次输入的密码不一致!"
                return render_to_response("blog/regist.html", RequestContext(request, {'form': form, 'regist_info': regist_info}))
        else:
            regist_info = '输入有误'
            return render_to_response('blog/regist.html', RequestContext(request, {'form': form, 'regist_info': regist_info}))
Beispiel #7
0
def register(request):
    context = RequestContext(request)
    registered = False
    error = 0
    if request.method == 'POST':

        username = request.POST['username']
        password1 = request.POST['password']
        cpassword1 = request.POST['cpassword']
        firstname = request.POST['firstname']
        lastname = request.POST['lastname']
        email = request.POST['email']
        phone = request.POST['phonenumber']
        dob = request.POST['dob']
        print request.POST
        profile = request.POST['img']
        print request.POST
        if password1 == cpassword1:
            user = User.objects.filter(username=username).count()
            if user == 0:
                temp = User.objects.create_user(username=username,
                                                password=password1,
                                                first_name=firstname,
                                                last_name=lastname,
                                                email=email)

                temp.save()
                y = User.objects.get(username=username)
                p = y.id

                temp1 = UserProfile(phone_number=phone,
                                    user_id=p,
                                    dob=dob,
                                    picture=profile)

                print temp1

                temp1.save()

                context = {
                    'sucess': "USer add sucessfully please login to continue"
                }
                return render(request, 'blog/index.html', context)
            else:
                error = "username exists"
                context = {'error': error}
                return render(request, 'blog/index.html', context)

        else:
            error = "Passwords do not match."
            context = {'error': error}
            return render(request, 'blog/index.html', context)
    else:
        return HttpResponseRedirect('/')
Beispiel #8
0
	def save(self):
        	user = User.objects.create_user(self.cleaned_data["username"],self.cleaned_data["email"],self.cleaned_data["password1"])
		user.is_active=False
		user.save()
		# Activation properties
		salt = sha.new(str(random.random())).hexdigest()[:5]
		activation_key = sha.new(salt+user.username).hexdigest()
		key_expires = datetime.datetime.today()+datetime.timedelta(2)
		new_user = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires)
		new_user.save()
		# sending an activation email
		email_subject = 'Your new account confirmation'
		email_body = 'Hello, %s, and thanks for registering for the blog \n To active your account, click following link within 48 hours: \n http://localhost:8000/confirm/%s' %(user.username, new_user.activation_key)
		send_mail(email_subject, email_body, '*****@*****.**', [user.email])
Beispiel #9
0
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)

        if form.is_valid():
            user = form.save()
            timelapse = datetime.today() + timedelta(2)
            salt = sha.new(str(random.random())).hexdigest()[:5]
            key= sha.new(salt+user.username).hexdigest()
            profile = UserProfile(user=user,key_expires=timelapse,activation_key=key)
            profile.save()
            send_confirmation(user.email,key)
            return redirect("blog.views.home")
    form = RegisterForm()
    return render(request, 'blog/register.html', {'form': form})
Beispiel #10
0
def socregUserCreate(user, profile, api):
    """
    This is the callback from the socialregistration app after a user has succuessfully connected their social network.
    I'm mainly using it here to add the user's profile picture.
    """
    
    info = {}
    
    # --------------------
    # Twitter API call
    # --------------------
    if hasattr(profile, 'twitter_id'):
        response = api.request("https://api.twitter.com/users/" + profile.twitter_id + ".json")
        
        #response is only a JSON string at the moment 
        details = json.loads(response)  
        
        info['picture'] = details['profile_image_url']
        info['username'] = details['screen_name']
           
    # --------------------
    # Facebook API call
    # --------------------
    else:
        info = api.graph.request(profile.uid, {'fields' : 'picture, username, first_name, last_name'})
    
    
    # Create the username for Django's User model
    if info['username']:
        user.username = info['username']
    else:
        #If there's no username slugify one from their real name
        user.username = slugify(info['first_name'] + info['lastname'])
    
    # Providing a dummy email allows us to automatically post comments,
    # by hiding all fields apart from the comment body
    user.email = '*****@*****.**'
    
    # The user doesn't actually exist in the DB yet.
    # Without persisting it UserProfile throws a wobbly :( 
    user.save()
    
    # Add the avatar
    up = UserProfile(avatar=info['picture'], user=user)
    up.save()
    
    # Return the username out of courtesy, it's not actually required
    return user.username
Beispiel #11
0
def UpdateUserInfo(request):
    """
    Update user info.
    """
    try:
        if not request.user.is_authenticated():
            return render_to_response("user/login.html", \
            RequestContext(request, {"WebSiteInfo" : WebSiteInfo}))

        user = User.objects.filter(id=request.user.id)[0]

        email = request.GET.get('email', '')
        if len(email) > 0:
            if email.find("@") <= 0:
                return HttpResponse("邮箱地址不正确")
            else:
                user.email = email
                user.save()

        mobile_phone = request.GET.get('mobile_phone', '')
        position = request.GET.get('position', '')
        title = request.GET.get('jobTitle', '')
        location = request.GET.get('location', '')

        if len(mobile_phone) > 0 or len(position) > 0 or len(title) > 0 or len(
                location) > 0:
            profile = UserProfile.objects.filter(user=request.user.id)

            editProfile = None
            if profile is None or len(profile) <= 0:
                editProfile = UserProfile()
            else:
                editProfile = profile[0]
            editProfile.user_id = request.user.id
            editProfile.mobile_phone = mobile_phone
            editProfile.position = JobPosition.objects.filter(
                job_title=position)[0]
            editProfile.job_title = JobTitle.objects.filter(job_title=title)[0]
            editProfile.location = location
            editProfile.website_level = WebSiteLevel.objects.get(id=1)
            editProfile.save()

        return HttpResponse("1")
    except Exception, e:
        return HttpResponse(e)
Beispiel #12
0
 def save(self):
     user = User.objects.create_user(self.cleaned_data["username"],
                                     self.cleaned_data["email"],
                                     self.cleaned_data["password1"])
     user.is_active = False
     user.save()
     # Activation properties
     salt = sha.new(str(random.random())).hexdigest()[:5]
     activation_key = sha.new(salt + user.username).hexdigest()
     key_expires = datetime.datetime.today() + datetime.timedelta(2)
     new_user = UserProfile(user=user,
                            activation_key=activation_key,
                            key_expires=key_expires)
     new_user.save()
     # sending an activation email
     email_subject = 'Your new account confirmation'
     email_body = 'Hello, %s, and thanks for registering for the blog \n To active your account, click following link within 48 hours: \n http://localhost:8000/confirm/%s' % (
         user.username, new_user.activation_key)
     send_mail(email_subject, email_body, '*****@*****.**', [user.email])
Beispiel #13
0
def register(request):
    '''
	用户注册界面逻辑实现
	author:陈思齐
	:param request:
	:return:
	'''
    context = {}
    errors = ''

    if request.method == "GET":
        form = RegisterForm
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            password = form.cleaned_data['password']
            email = form.cleaned_data['email']
            user = User.objects.create_user(username=email,
                                            password=password,
                                            email=email)
            if user:
                user.is_staff = True
                user.save()
                c = UserProfile(name=name, email=email, belong_to=user)
                c.save()
                login(request, user)
                # print (request.POST["referer"])
                if request.POST["referer"] and 'login' not in request.POST[
                        "referer"]:
                    return redirect(request.POST["referer"])
                else:
                    return redirect(to='home')
    if "HTTP_REFERER" in request.META:
        context["referer"] = request.META["HTTP_REFERER"]
        # print (context["referer"])
    else:
        context["referer"] = ""
    context['form'] = form
    context['errors'] = errors

    return render(request, "register.html", context)
Beispiel #14
0
def user_show(request, username):
    login_user = get_login_user(request)
    show_user = get_object_or_404(User, username=username)
    logging.info('用户: {}, IP: {}, 用户展示, 正在查看: {}'.format(
        login_user, get_remote_ip(request), show_user))
    if UserProfile.objects.filter(user=show_user):
        userprofile = UserProfile.objects.get(user=show_user)
    else:
        userprofile = UserProfile(user=show_user)
        userprofile.save()
    posts = Post.objects.filter(author=show_user).order_by('-created_time')
    context = {
        'show_user': show_user,
        'login_user': login_user,
        'posts': posts,
        'userprofile': userprofile,
        'is_current_user': False
    }
    if login_user == show_user:
        context['is_current_user'] = True
    return render(request, 'blog/user_show.html', context=context)
Beispiel #15
0
def register_profile(request):
    """
    用于展示目前登陆用户的信息,并且可以更新部分信息, 未完成
    """
    login_user = get_login_user(request)
    logging.info('用户: {}, IP: {}, 打开登陆用户信息编辑'.format(login_user,
                                                     get_remote_ip(request)))
    if UserProfile.objects.filter(user=login_user):
        userprofile = UserProfile.objects.get(user=login_user)
    else:
        logging.warn('用户: {}, IP: {}, 登陆用户信息详情暂无, 即将生成'.format(
            login_user, get_remote_ip(request)))
        userprofile = UserProfile(user=login_user)
        userprofile.save()
    userform = UserUpdateForm({
        'email': login_user.email,
        'website': userprofile.website
    })
    if request.method == 'POST':
        logging.info('用户: {}, IP: {}, 用户信息变更提交'.format(login_user,
                                                       get_remote_ip(request)))
        userform = UserUpdateForm(request.POST)
        if userform.is_valid():
            logging.info('用户: {}, IP: {}, 用户信息变更提交有效'.format(
                login_user, get_remote_ip(request)))
            login_user.email = userform.cleaned_data['email']
            login_user.save()
            userprofile.website = userform.cleaned_data['website']
        picture = request.FILES.get('avator')
        if picture:
            logging.info('用户: {}, IP: {}, 用户信息变更照片提交有效'.format(
                login_user, get_remote_ip(request)))
            userprofile.picture = picture
        userprofile.save()
    context = {
        'login_user': login_user,
        'userprofile': userprofile,
        'userform': userform
    }
    return render(request, 'blog/register_profile.html', context=context)
Beispiel #16
0
 def post(self, request):
     register_form = RegisterForm(request.POST)
     if register_form.is_valid():
         username = register_form.cleaned_data["username"]
         user = UserProfile.objects.filter(username=username).first()
         if user:
             err_allow = u"用户名已经存在"
             return render(request, "usercenter/register.html", locals())
         else:
             user = UserProfile()
             user.username = username
             user.password = make_password(
                 register_form.cleaned_data["password1"])
             user.email = register_form.cleaned_data["email"]
             user.gender = 0
             user.save()
             login(request, user)
             path = request.GET.get('next')
             if path == 'None':
                 return redirect(reverse("blog:index"))
             return redirect(path)
     else:
         return render(request, "usercenter/register.html", locals())
Beispiel #17
0
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        print(form.data)
        print(form.is_valid())
        if form.is_valid():
            form.save()

            username = form.data['username']
            email = form.data['email']
            print(username, email)
            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(1)

            # Create and save user profile
            user = User.objects.get(email=email)
            new_profile = UserProfile(user=user,
                                      activation_key=activation_key,
                                      key_expires=key_expires)
            new_profile.save()

            # Send email with activation key
            email_subject = 'Account confirmation'
            email_body = "Hi %s, thanks for signing up. To activate your account, click this link within \
			48hours http://127.0.0.1:8000/confirm/%s" % (username, activation_key)
            send_mail(email_subject,
                      email_body,
                      '*****@*****.**', [email],
                      fail_silently=False)
            return render(request, 'sign_up_success.html')
        else:
            return render(request, 'confirm_expired.html')
    else:
        return render(request, 'sign_up.html')
Beispiel #18
0
def regist(request):
    regist_info = ''
    if request.method == 'GET':
        form = RegistForm()
        # context, content, contents are the same(变量名不影响使用)
        contents = {'form': form}

        # thise are the same
        return render(request, 'blog/regist.html', contents)
    else:
        form = RegistForm(request.POST, request.FILES)
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password1 = form.cleaned_data['password1']
            password2 = form.cleaned_data['password2']
            phone = form.cleaned_data['phone']
            userimg = form.cleaned_data['userimg']
            sex = form.cleaned_data['sex']
            if userimg and userimg.size > USER_IMG_MAX_SIZE:
                logger.info(userimg.size)
                regist_info = 'user img too big'
                return render_to_response(
                    "blog/regist.html",
                    RequestContext(request, {
                        'form': form,
                        'regist_info': regist_info
                    }))
            if password1 == password2:
                user_filter_result = User.objects.filter(email=email)
                if user_filter_result:
                    regist_info = "邮箱已存在"
                    return render_to_response(
                        "blog/regist.html",
                        RequestContext(request, {
                            'form': form,
                            'regist_info': regist_info
                        }))
                else:
                    user_profile = UserProfile()
                    user_profile.userimg = DEFAULT_USER_IMG
                    if userimg:
                        imgpath = os.path.join(USER_IMG_PATH, email)
                        with open(imgpath, 'wb') as img:
                            img.write(userimg.read())
                        user_profile.userimg = email

                    user = User.objects.create_user(username=username,
                                                    password=password1,
                                                    email=email)
                    user_profile.user_id = user.id
                    user_profile.phone = phone
                    user_profile.sex = sex
                    user_profile.save()
                    regist_info = '注册成功'
                    user = auth.authenticate(username=username,
                                             password=password1)
                    auth.login(request, user)
                    # 利用session传递信息给模板层
                    request.session['username'] = username
                    request.session['userimg'] = os.path.join(
                        USER_IMG_URL, user_profile.userimg)
                    return HttpResponseRedirect('/')
                    return render_to_response(
                        'blog/regist.html',
                        RequestContext(request, {
                            'form': form,
                            'regist_info': regist_info
                        }))
            else:
                regist_info = "两次输入的密码不一致!"
                return render_to_response(
                    "blog/regist.html",
                    RequestContext(request, {
                        'form': form,
                        'regist_info': regist_info
                    }))
        else:
            regist_info = '输入有误'
            return render_to_response(
                'blog/regist.html',
                RequestContext(request, {
                    'form': form,
                    'regist_info': regist_info
                }))
Beispiel #19
0
def createUserProfile(user):
	profile=UserProfile(user=user)

	profile.nickname=user.username
	profile.save()