def add(self, user=None, sharedfile=None, body=None): """ Creates a comment and returns it, or returns None if some conditions are not met. Sets a user to be restricted if they exhibit spammy behavior. """ if not user or not sharedfile or not body: return None if user.restricted: return None body = body.strip() if len(body) == 0: return None now = datetime.utcnow() if user.created_at > (now - timedelta(hours=24)): if user.sharedfiles_count() == 0 and user.likes_count() == 0: if Comment.where_count("user_id = %s", user.id) >= 1: user.restricted = 1 user.save() all_comments = Comment.where('user_id=%s', user.id) for this_comment in all_comments: this_comment.delete() comment = Comment(user_id=user.id, sharedfile_id=sharedfile.id, body=body) comment.save() return comment
def sign(): if request.method == 'POST': userdata = request.form.to_dict() print 'sign - userdata : ', userdata # user.save(userdata) # 把新注册用户写入数据库(在实际中,会利用js 在页面里过滤不合法的 用户名和密码,然后直接把数据放进去) # users = user.load(user_db_file) users = user.load() for ur in users: # if userdata['username'] == ur['name']: if userdata['username'] == ur[1]: return '<h1> User name already exists </h1>' if len(userdata['name']) <= 2: return '<h1> User name should be more than 2 bytes.</h2>' # 应该弹出 提示框 if userdata['password1'] == userdata['password']: del userdata['password1'] # 两个密码相同,只需要存一个好了,所以把另一个删掉 user.save(userdata) return '<h1> sign OK </h1>' else: return '<h1>前后密码不匹配,请重新输入密码</h1>' # 应该弹出 提示框 return render_template('sign.html')
def register(request): context = RequestContext(request) registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() registered = True else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() return render_to_response( 'register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, context)
def signup(request): if request.method == 'POST': # If the form has been submitted... form = SignUpForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data username = form.cleaned_data["username"] password = form.cleaned_data["password"] email = form.cleaned_data["email"] first_name = form.cleaned_data["first_name"] last_name = form.cleaned_data["last_name"] # At this point, user is a User object that has already been saved # to the database. You can continue to change its attributes # if you want to change other fields. user = User.objects.create_user(username, email, password) user.first_name = first_name user.last_name = last_name # Save new user attributes user.save() return HttpResponseRedirect('/') # Redirect after POST else: form = SignUpForm() data = { 'form': form, } return render_to_response('modulo12/registro.html', data, context_instance=RequestContext(request))
def update_information(self, update): __mt_gl = sniff.get_keys_and_values_from_gitlab(self, update) __mt_rd_id = sniff.get_keys_from_redis(self, update) __mt_gl_id = __mt_gl.keys() # Generate difference and intersection metadata __mt_diff = set(__mt_gl_id).difference(set(__mt_rd_id)) __mt_int = set(__mt_gl_id).intersection(set(__mt_rd_id)) __mt_mod = list(__mt_diff.union(__mt_int)) __mt_del = list(set(__mt_rd_id).difference(set(__mt_gl_id))) # Print alert if config.DEBUGGER: config.print_message("- [ %s ] New or possible updates: %d | Deleted: %d" % (update, len(__mt_mod), len(__mt_del))) # Insert / Modify Information for i in __mt_mod: if update == "users": util_user.save(self, i, __mt_gl[i]) elif update == "groups": util_group.save(self, i, __mt_gl[i]) elif update == "projects": util_project.save(self, i, __mt_gl[i]) # Delete Information for i in __mt_del: if update == "users": util_user.delete(self, i) elif update == "groups": util_group.delete(self, i) elif update == "projects": util_project.delete(self, i)
def register(request): #if we have a post to the url then populate the registration form with the request.POST information if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): try: customer = stripe.Customer.create( email = form.cleaned_data['email'], card = form.cleaned_data['stripe_id'], plan = 'REG_MONTHLY', ) except stripe.error.CardError, e: messages.error(request, "Your (valid) card was declined!") if customer: user = form.save() user.stripe_id = customer.id user.subscription_end = arrow.now().replace(weeks=+4).datetime user.save() user = auth.authenticate(email=request.POST.get('email'), password = request.POST.get('password1')) if user: auth.login(request,user) messages.success(request, "You have successfully registered. Your customer id number is") return redirect(reverse('profile')) else: messages.error(request,'Unable to log you in at this time!') else: messages.error(request, "We were unable to take a payment with that card!")
def change_password(request): if request.method == 'POST': form = ChangepasswordForm(request.POST) if form.is_valid(): if check_password(form.cleaned_data['Old_password'], request.user.password): if form.cleaned_data['New_password'] == form.cleaned_data[ 'Confirm_Newpassword']: user = request.user user.set_password(form.cleaned_data['New_password']) user.save() logout(request) messages.success( request, 'your password is updated successfully. ') return redirect('/queries/login/') else: messages.error(request, 'password must be same') form = ChangepasswordForm() return render(request, 'change_password.html', {'form': form}) else: messages.error( request, 'you enterd old password is wrong. please give correct details' ) form = ChangepasswordForm() return render(request, 'change_password.html', {'form': form}) else: form = ChangepasswordForm() return render(request, 'change_password.html', {'form': form})
def test_populate(request): if settings.DEBUG: if not Module.objects.filter(name="Umit Project"): _create_fake_module("Umit Project", "This is our main website.", "passive", "www.umitproject.org", "http://www.umitproject.org") if not Module.objects.filter(name="Trac"): _create_fake_module("Trac", "This is our old development site, based on Trac.", "passive", "trac.umitproject.org", "http://trac.umitproject.org") if not Module.objects.filter(name="Redmine"): _create_fake_module("Redmine", "This is our new development site, based on Redmine.", "passive", "dev.umitproject.org", "http://dev.umitproject.org") if not Module.objects.filter(name="Git"): _create_fake_module("Git", "This is our git repository.", "passive", "git.umitproject.org", "http://git.umitproject.org") if not Module.objects.filter(name="Blog"): _create_fake_module("Blog", "This is our blog.", "passive", "blog.umitproject.org", "http://blog.umitproject.org") # Create test user if not User.objects.filter(username='******'): user = User.objects.create_user('admin', '*****@*****.**', 'test') user.is_staff = True user.is_superuser = True user.is_active = True user.save() # Create Twitter Account if not TwitterAccount.objects.filter(login='******'): twitter_account = TwitterAccount() twitter_account.login = '******' twitter_account.api_key = '' twitter_account.api_secret = '' twitter_account.post_tweet_automatically = True twitter_account.monitor_stream = True twitter_account.monitor_stream_terms = '' twitter_account.save() return home(request, 'Test Populate OK') raise Http404
def create_user(request): username = request.POST.get('username', '') password = request.POST.get('password', '') email = request.POST.get('email','') print username +""+password+""+email user = User.objects.create_user(username = username ,password = password ,email = email) user.save() return HttpResponseRedirect('success/register')
def save(self, commit=True): user=super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user
def test_save(self): newuser = {"firstName": "Stefan", "lastName": "Agner", "eMail": self.testmail, "password": "******"} newuser2 = newuser.copy() useridsave = user.save(newuser) with self.assertRaises(DuplicateKeyError): user.save(newuser2) userdata = user.get(self.testmail) user.remove(self.testmail) self.assertTrue(self.testmail == userdata["eMail"])
def create_user(request): if request.method == 'POST': user = user(uin=request.POST.get('uin'), name=request.POST.get('name'), headurl=request.POST.get('headurl'), sex=request.POST.get('sex')) user.save() serializer = UserSerializer(user) return Response(serializer.data)
def do_GET(s): query = s.path if not re.match("^\/iptv.*$", query): s.send_error(404) return data = dict(re.findall("[\?\&](\w+)=([^&]+)", query)) if 'hash' not in data: s.send_error(400) return if not public.iptvChangeRequest: s.send_error(400) return checkhash = data['hash'] if checkhash not in public.iptvChangeRequest: s.send_error(400) return uid = public.iptvChangeRequest[checkhash] del public.iptvChangeRequest[checkhash] user = users.get(uid) if not user: s.send_error(400) return oldIp = user.ip newIp = s.client_address[0] if not oldIp: result = iptv.insertAddress(newIp) else: result = iptv.changeAddress(newIp, oldIp) if not result: s.send_error(500) return user.ip = newIp user.save() s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() s.wfile.write("<html>") s.wfile.write("<head>") s.wfile.write("<title>IP changed!</title>") s.wfile.write("</head>") s.wfile.write("<body>") s.wfile.write("<p><h2>IP changed!</h2></p>") s.wfile.write("<p>Old IP: %s</p>" % (oldIp,)) s.wfile.write("<p>New IP: %s</p>" % (newIp,)) s.wfile.write("</body>") s.wfile.write("</html>")
def do_GET(s): query = s.path if not re.match("^\/iptv.*$", query): s.send_error(404) return data = dict(re.findall("[\?\&](\w+)=([^&]+)", query)) if 'hash' not in data: s.send_error(400) return if not public.iptvChangeRequest: s.send_error(400) return checkhash = data['hash'] if checkhash not in public.iptvChangeRequest: s.send_error(400) return uid = public.iptvChangeRequest[checkhash] del public.iptvChangeRequest[checkhash] user = users.get(uid) if not user: s.send_error(400) return oldIp = user.ip newIp = s.client_address[0] if not oldIp: result = iptv.insertAddress(newIp) else: result = iptv.changeAddress(newIp, oldIp) if not result: s.send_error(500) return user.ip = newIp user.save() s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() s.wfile.write("<html>") s.wfile.write("<head>") s.wfile.write("<title>IP changed!</title>") s.wfile.write("</head>") s.wfile.write("<body>") s.wfile.write("<p><h2>IP changed!</h2></p>") s.wfile.write("<p>Old IP: %s</p>" % (oldIp, )) s.wfile.write("<p>New IP: %s</p>" % (newIp, )) s.wfile.write("</body>") s.wfile.write("</html>")
def add_charge_payment_done(plan, payment): payment.done = True payment.save() from user.views import get_user payment_items = payment.items.get('list', []) for item in payment_items: user = get_user(item['uid']) user.charge += plan.charge if user.status == -300: user.status = 100 user.save()
def test_user_bind_save_get(self): Dashboard.add_dashboard([User]) request = [("User[name]", "sample"), ("User[email]", "*****@*****.**")] user = connection.User() user.bind_form(request) user.save() collection = DbConn.get_db("User") filter = {} filter["_id"] = user["_id"] obj = collection.find_one(filter) assert obj["name"] == "sample" assert obj["email"] == "*****@*****.**"
def test_dbref(self): Dashboard.add_dashboard([User, Group]) group = connection.Group() group["name"] = "sampleGroup" group["creation_date"] = datetime.utcnow() group.save() user = connection.User() user["name"] = "sampleUser" user["email"] = "*****@*****.**" user["groups"] = [group] user.save() assert group["_id"] == user["groups"][0]["_id"]
def test_save(self): newuser = { "firstName": "Stefan", \ "lastName": "Agner", \ "eMail": self.testmail, \ "password": "******" \ } newuser2 = newuser.copy() useridsave = user.save(newuser) with self.assertRaises(DuplicateKeyError): user.save(newuser2) userdata = user.get(self.testmail) user.remove(self.testmail) self.assertTrue(self.testmail == userdata["eMail"])
def get(self, request, user_id, *args, **kwargs): profileInstance = get_object_or_404(Profile, id=user_id) user = get_object_or_404(User, pk=profileInstance.user.id) if user.is_superuser and request.user.is_superuser == False: return render(request,'users/authentication_message.html') user.is_active = False user.save() messages.add_message(self.request, messages.INFO, 'User Archived Successfully' ) return HttpResponseRedirect( self.get_success_url() )
def test_bind_with_dbref(self): Dashboard.add_dashboard([User]) group = connection.Group() group["name"] = "sampleGroup" group["creation_date"] = datetime.utcnow() group.save() request = [("User[groups][0]", str(group["_id"]))] user = connection.User() user["name"] = "sampleUser" user["email"] = "*****@*****.**" user.save() user.bind_form(request) user.save() assert group["_id"] == user["groups"][0]["_id"]
def find_by_activation_key(self, activation_key): if ACTIVATION_KEY_PATTERN.search(activation_key): try: member = self.get(activation_key=activation_key) except self.model.DoesNotExist: return False if not member.is_activation_key_expired(): user = member.user user.is_active = True user.save() member.activation_key = self.model.ACTIVATED member.save() return member return False
def update_user(request): if request.method == 'POST': user = user.objects.get(uin=request.POST.get('uin')) if user: user.name = request.objects.get('name') user.headurl=request.objects.get('headurl') user.sex=request.objects.get('sex') user.update_time = timezone.localtime() user.save() serializer = UserSerializer(user) return Response(serializer.data) else: return JsonResponse({})
def save(self, commit=True): ob = super(UserProfileForm, self).save(commit=False) ob.description = self.cleaned_data['description'] ob.city = self.cleaned_data['city'] ob.website = self.cleaned_data['website'] ob.phone = self.cleaned_data['phone'] ob.experience = self.cleaned_data['experience'] ob.skills = self.cleaned_data['skills'] ob.image=self.cleaned_data['image'] if commit: user.save() return ob
def get(self, request, user_id, *args, **kwargs): profileInstance = get_object_or_404(Profile, id=user_id) user = get_object_or_404(User, pk=profileInstance.user.id) if user.is_superuser and request.user.is_superuser == False: return render(request, 'users/authentication_message.html') user.is_active = False user.save() messages.add_message(self.request, messages.INFO, 'User Archived Successfully') return HttpResponseRedirect(self.get_success_url())
def editPassword(request): if request.method == "POST": form = EditPasswordForm(request.POST) if form.is_valid(): password = form.cleaned_data['password'] user = User.objects.get(username=request.user.username) user.set_password(password) user.save() messages.add_message(request, messages.INFO, 'Your password has been changed') return HttpResponseRedirect("/yaas/") else: form = EditPasswordForm(request.POST) return render_to_response("editPass.html", {'form': form},context_instance= RequestContext(request))
def editPassword(request): if request.method == "POST": form = EditPasswordForm(request.POST) if form.is_valid(): password = form.cleaned_data['password'] user = User.objects.get(username=request.user.username) user.set_password(password) user.save() messages.add_message(request, messages.INFO, 'Your password has been changed') return HttpResponseRedirect("/yaas/") else: form = EditPasswordForm(request.POST) return render_to_response("editPass.html", {'form': form}, context_instance=RequestContext(request))
def post(self, request): user = request.user form = User(request.POST or None) if request.method == 'POST': user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] # user.email = request.POST['email'] # user.birth_data = request.POST['birth_data'] user.educations = request.POST['educations'] user.about_me = request.POST['about_me'] if request.method == 'POST': user.save() context = {"form": form} return render(request, 'user/edit_profile.html', context) return render(request, 'user/edit_profile.html', {'user': request.user})
def register(): print ("in register_page") try: form = RegistrationForm(request.form) # allows us to render the form if request.method == "POST" and form.validate(): # if user hit register button and form is complete # logout any logged in user logout_user() username = form.username.data # refers to username from RegistrationForm class email = form.email.data pass_hash = generate_password_hash(form.password.data, method='pbkdf2:sha256') # hash the user's pw # prepare User user = User(username,email,pass_hash) if user.save(): if login_user(user, remember="no"): flash("Thank you for registering! Logged in!") return redirect(url_for('questions')) else: flash("unable to log you in") else: flash("Username already taken. Please choose another.") return render_template('register.html', form=form) return render_template('register.html', form=form) except Exception as e: return(str(e))
def test_objectdbref(self): Dashboard.add_dashboard([User]) group = connection.Group() group["name"] = "sampleGroup" group["creation_date"] = datetime.utcnow() group.save() request = [("User[groups][0]", str(group["_id"]))] user = connection.User() user["name"] = "sampleUser" user["email"] = "*****@*****.**" user["groupRef"] = group["_id"] renderer = User.get_renderer("groupRef") assert renderer.is_object_id == True renderer.set_reference(Group) user.save() assert group["_id"] == user["groupRef"] assert isinstance(user["groupRef"], ObjectId)
def user_center(request): user = request.user if request.method == 'GET': return render(request, 'user/center.html', context={'user': user}) else: username = request.POST.get('username') email = request.POST.get('email') mobile = request.POST.get('mobile') icon = request.FILES.get('icon') #更新用户 user.username = username user.email = email user.mobile = mobile user.icon = icon #ImageField(upload_to='') user.save() return render(request, 'user/center.html', context={'user': user})
def loadFileWithUsers(abspath): with db.connect() as cnn: with db._create_cursor(cnn) as cursor: try: counterLines = 0 with codecs.open(abspath, "r", "utf-8") as myfile: for line in myfile: counterLines += 1 if counterLines == 1: continue line = line.strip() if line == '': continue parts = line.split(',') if len(parts) != 4: error = 'La linea %d no tiene cuatro columnas.' % ( counterLines, ) raise ValueError(error) rol = parts[3].lower() if not (rol == 'usuario' or rol == 'administrador'): error = 'La linea %d no contiene un rol valido.' % ( counterLines, ) raise ValueError(error) rolid = 1 if rol == 'usuario': rolid = 2 objUser = { 'username': parts[1], 'name': parts[0], 'role': rolid, 'email': parts[2], } user.save(objUser, cursor) #end-file cnn.commit() print 'Se registraron %d usuarios' % (counterLines, ) except Exception as e: cnn.rollback() print 'Error, no se guardo ningun usuario.' print e
def subscriptions_webhook(request): #turn our request.body in to a dictionary so we can easily pull out the values from the file event_json = json.loads(request.body) #Verify the event by fetching it from Stripe try: #firstly verify this is a real event generated by Stripe.com, if it is then assign it to the variable 'event' event = stripe.Event.retrieve(event_json["id"]) #get our user by the customer string (this pulls the User class defined in our models which looks for the inputted stripe_id from the form that was input. user = User.objects.get(stripe_id=event_json["data"]["object"]["customer"]) if user and event_json ['type']=="invoice.payment_succeeded": user.subscription_end = arrow.now().replace(weeks=+4).datetime user.save() except stripe.InvalidRequestError, e: return HttpResponse(status=404)
def add_user(): username = request.cookies.get('username') if username == 'admin': if request.methods == 'POST': userdata = request.form.to_dict() if userdata['password'] == userdata['password1']: del userdata['password1'] user.save(userdata) print "add user OK : ", userdata usersdata = user.load() return render_template('user_list.html', users_info=usersdata) # FIXME 添加成功后,进入 user_list 页面,查看资料 else: return render_template('user_add.html', tips="<h1>输入密码前后不一致,请重新设置</h1>") return render_template('user_add.html') # return flask.redirect(flask.url_for('login')) return "<h1> 当前用户无权限查看该页面</h1>"
def create_with_inactive_user(self, email, password, nickname=''): def generate_activation_key(email): salt = sha_constructor(str(random.random())).hexdigest()[:8] activation_key = sha_constructor(salt+email).hexdigest() return activation_key user = User() user.username = email user.email = email user.set_password(password) user.is_active = True user.save() activation_key = generate_activation_key(email) member = self.model(user=user, nickname=nickname, activation_key=activation_key) member.save() member.send_activation_email() return member
def loadFileWithUsers(abspath): with db.connect() as cnn: with db._create_cursor(cnn) as cursor: try: counterLines = 0 with codecs.open(abspath, "r", "utf-8") as myfile: for line in myfile: counterLines += 1 if counterLines == 1: continue line = line.strip() if line == '': continue parts = line.split(',') if len(parts) != 4: error = 'La linea %d no tiene cuatro columnas.' % (counterLines,) raise ValueError(error) rol = parts[3].lower() if not (rol == 'usuario' or rol == 'administrador'): error = 'La linea %d no contiene un rol valido.' % (counterLines,) raise ValueError(error) rolid = 1 if rol == 'usuario': rolid = 2 objUser = { 'username': parts[1], 'name': parts[0], 'role': rolid, 'email': parts[2], } user.save(objUser, cursor) #end-file cnn.commit() print 'Se registraron %d usuarios' % (counterLines,) except Exception as e: cnn.rollback() print 'Error, no se guardo ningun usuario.' print e
def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] # profile.user.kills = 0 # profile.user.survival = 0 profile.save() registered = True else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() return render( request, 'zombieGame/register.html', { 'user_form': user_form, 'profile_form': profile_form, 'registered': registered })
def user_entry(): account = login.loginuser() if account is None: return False while True: operating = raw_input(prompt.user_option).strip() if operating == '1': user.shopping(account) elif operating == '2': user.save(account) elif operating == '3': user.withdraw(account) elif operating == '4': user.inquire(account) elif operating == '5': user.genbill(account) elif operating == '0': break else: continue
def add_user(): username = request.cookies.get('username') if username == 'admin': if request.method == 'POST': userdata = request.form.to_dict() if userdata['password'] == userdata['password1']: del userdata['password1'] print userdata for i in userdata: userdata[i] = userdata[i].encode('utf-8') user.save(userdata) print "add user OK : ", userdata usersdata = user.load() return flask.redirect(flask.url_for('settings/user/list')) # FIXME 添加成功后,进入 user_list 页面,查看资料 else: return render_template('user_add.html', tips="<h1>输入密码前后不一致,请重新设置</h1>") return render_template('user_add.html') # return flask.redirect(flask.url_for('login')) return "<h1> 当前用户无权限查看该页面</h1>"
def createUser(request): if request.method == 'POST': form =CreateUserForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] email = form.cleaned_data["email"] first_name = form.cleaned_data["first_name"] last_name = form.cleaned_data["last_name"] user = User.objects.create_user(username, email, password) user.first_name = first_name user.last_name = last_name user.save() return HttpResponseRedirect("/yaas/loginuser/") else: form =CreateUserForm() return render_to_response("newUser.html", {'form': form},context_instance= RequestContext(request))
def create_with_inactive_user(self, email, password, nickname=''): def generate_activation_key(email): salt = sha_constructor(str(random.random())).hexdigest()[:8] activation_key = sha_constructor(salt + email).hexdigest() return activation_key user = User() user.username = email user.email = email user.set_password(password) user.is_active = True user.save() activation_key = generate_activation_key(email) member = self.model(user=user, nickname=nickname, activation_key=activation_key) member.save() member.send_activation_email() return member
def update_pwd(request): if request.method == 'GET': c = request.GET.get('c') return render(request, 'user/update_pwd.html', context={'c': c}) else: code = request.POST.get('code') uid = request.session.get(code) user = UserProfile.objects.get(pk=uid) #获取密码 pwd = request.POST.get('password') repwd = request.POST.get('repassword') if pwd == repwd and user: pwd = make_password(pwd) user.password = pwd user.save() return render(request, 'user/update_pwd.html', context={'msg': '用户密码更新成功!'}) else: return render(request, 'user/update_pwd.html', context={'msg': '更新失败!'})
def createUser(request): if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] email = form.cleaned_data["email"] first_name = form.cleaned_data["first_name"] last_name = form.cleaned_data["last_name"] user = User.objects.create_user(username, email, password) user.first_name = first_name user.last_name = last_name user.save() return HttpResponseRedirect("/yaas/loginuser/") else: form = CreateUserForm() return render_to_response("newUser.html", {'form': form}, context_instance=RequestContext(request))
def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] # profile.user.kills = 0 # profile.user.survival = 0 profile.save() registered = True else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() return render(request, 'zombieGame/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
def add_user(email, passwd): """ Args: email: email of the suer passwd: passof the user Returns: True if the user was added. """ callback = request.args.get('callback') user = User(email, passwd) result = user.save() return str(callback) + "(" + str({"result": result}) + ")"
def reset_password(request, token): if not UserToken.objects.filter(token=token): return redirect(reverse("index")) else: if request.method == "GET": form = ForgotForm() return render(request, "forgot.html", { "form": form, "token": token }) elif request.method == "POST": form = ForgotForm(request.POST) if form.is_valid(): passw = form.cleaned_data["password"] passw2 = form.cleaned_data["confirm_password"] if (passw == passw2): user = UserToken.objects.get(token=token).user user.set_password(passw) user.save() user2 = authenticate(username=user.username, password=passw) login(request, user2) return redirect(reverse("index"))
def user_center1(request): user = request.user if request.method == 'GET': return render(request, 'user/center.html', context={'user': user}) else: username = request.POST.get('username') email = request.POST.get('email') mobile = request.POST.get('mobile') icon = request.FILES.get('icon') user.username = username user.email = email user.mobile = mobile # user.icon = icon # ImageField(upload_to='') # user.save() #上传图片到七牛云 # icon1=str(user.icon) # save_path=upload_image(icon,icon1) save_path = upload_image(icon) user.yunicon = save_path user.save() return render(request, 'user/center.html', context={'user': user})
def post(self, request): if not request.user.is_staff: return HttpResponse( "دسترسی مجاز نیست") # TODO: redirect to error page uid = request.POST.get('id', None) charge = request.POST.get('charge', None) errors = [] if not uid: errors.append('لطفا یک یوزر انتخاب کنید.') elif not charge: errors.append('لطفا شارژ موردنظرتان را وارد کنید.') from user.views import get_user user = get_user(uid) if not user: errors.append('یوزر انتخاب شده معتبر نیست.') if len(errors) == 0: user.charge = charge if user.status == -300: user.status = 100 user.save() users = User.objects.all() return render(request, 'client/manageUserCharges.html', { 'instagramUsers': users, 'errors': errors })