def ajax_register(request): """ AJAX regsiter procedure """ if request.method != 'POST': return HttpResponse("NOTFOUND") reg_form = RegistrationForm(request.POST) if reg_form.is_valid(): username = reg_form.cleaned_data['username'] email = reg_form.cleaned_data['email'] password = reg_form.cleaned_data['password'] user_type = reg_form.cleaned_data['user_type'] if User.objects.filter( username=username).exists() or User.objects.filter( email=email).exists(): #checking for existing emails and usernames return HttpResponse("EXISTS") user = User.objects.create_user(username, email, password) user_profile = UserProfile(account=user, user_type=user_type) user.save() user_profile.save() return HttpResponse("OK") else: return HttpResponse("NOTVALID")
def test_that_user_profile_can_be_created(self): """Ensure that user profile can be created """ user_profile = UserProfile(bio="Some bio info", age=24, user=self.user) user_profile.save() test_user_profile = UserProfile.objects.get(user=self.user) self.assertEqual(test_user_profile.id, user_profile.id)
def invited(self, userdata): user = User.objects.get(id=userdata['userid']) try: new_userprofile = UserProfile(belong_to=user) user.profile.role = 'author' new_userprofile.save() except: user.profile.role = 'author' user.save() return user
def create(self, userdata): user = User(username=userdata['username']) # print(user) user.set_password(userdata['password']) user.save() new_user_profile = UserProfile(belong_to=user) user.profile.role = userdata['role'] new_user_profile.save() # print(userdata['role']) return user
def register(request): try: context = {} if request.user.is_authenticated(): auth.logout(request) context.update(csrf(request)) if request.POST: user_email = str(request.POST['email']) username = user_email password = request.POST['password_1'] password_repeat = request.POST['password_2'] email_check = User.objects.filter(email=user_email) if email_check: context['email_error'] = "Такой пользователь уже существует" return render_to_response('register.html', context) elif password == password_repeat and len(password) != 0: user = User.objects.create_user(username, user_email, password) user.is_active = False user.save() activation_key = key(user_email)['activation_key'] key_expires = key(user_email)['key_expires'] email_subject = 'Подтверждение регистрации' email_body = "Hey %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) try: send_mail(email_subject, email_body, '*****@*****.**', [user_email], fail_silently=False) user = User.objects.get(username=user_email) new_profile = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires) new_profile.save() context[ 'ok'] = "На указанную Вами почту отправленно сообщение для завершения регистрации" except SMTPRecipientsRefused: context['email_error'] = "Почта не существует" except SMTPDataError: context['email_error'] = "Почта не существует" else: context['password_error'] = "Пароли не совпадают" else: context['post'] = "post" return render_to_response('register.html', context) except: raise Http404
def signup(request): if request.method == "POST": first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] birthday = request.POST['birthday'] created_at = datetime.datetime.now() phone_number = request.POST['phone_number'] converted = datetime.datetime.strptime(birthday, '%Y-%m-%d') gender = request.POST['gender'] if password1 != password2: messages.error(request, 'Passwords do not match.') return redirect('signup') if len(password1) < 8: messages.error(request, 'password does not less than 8 characters') return redirect('signup') if converted.year > created_at.year: messages.error(request, 'Invalid birthday date') return redirect('signup') if email and User.objects.filter(email=email).exclude(username=username).exists(): messages.error(request, 'Email is already exist in the system.') return redirect('signup') if User.objects.filter(username=username).exists(): messages.error(request, 'Username is already exist in the system. Please enter a different username') return redirect('signup') user = User.objects.create_user( first_name=first_name, last_name=last_name, username=username, email=email, password=password1) profile = UserProfile(gender=gender, birthday=birthday, phone_number=phone_number, user=user) profile.save() user = authenticate(request, username=username, password=password1) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'username or password not correct') return redirect('signup') else: return render(request, 'registration/signup.html')
def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): if User.objects.filter(email=form.cleaned_data['email']): form._errors['email'] = ['Email exist'] + form._errors.get('email', []) return render(request, 'website/register.html', {'form': form}) username = form.cleaned_data['email'].split('@')[0] user = User(username=username) user.set_password(form.cleaned_data['password']) user.email = form.cleaned_data['email'] user.save() userProfile = UserProfile(user=user, name=form.cleaned_data['name'], userType=form.cleaned_data['type']) userProfile.save() return redirect('login') else: form = RegisterForm() return render(request, 'website/register.html', {'form': form})
def hello_view(request): if request.method == "POST": name = request.POST.get("name") email = request.POST.get("email") mobile_no = request.POST.get("pn_no") place = request.POST.get("place") data_dict = dict() data_dict["name"] = name data_dict["place"] = place data_dict["mobile_no"] = mobile_no data_dict["email"] = email up = UserProfile(**data_dict) up.save() ups = UserProfile.objects.all()[:10] return render(request, "home.html", locals())
def change_user(request, id): user = User.objects.get(id=id) if request.method == 'PUT': try: print(request.data['role']) user.profile.role = request.data['role'] user.profile.save() print(user.profile.role) return Response(status=status.HTTP_201_CREATED) except: new_userprofile = UserProfile(belong_to=user) new_userprofile.role = request.data['role'] print(new_userprofile) new_userprofile.save() print(new_userprofile) return Response(status=status.HTTP_201_CREATED) elif request.method == 'DELETE': user.delete() return Response({'msg': 'Delete-OK'}, status=status.HTTP_201_CREATED)
def listing(request): context = {} if request.method == "POST": uf = UserForm(request.POST, request.FILES) if request.user.username and uf.is_valid(): #username = uf.cleaned_data['username'] user_upload_file = uf.cleaned_data['user_upload_file'] #写入数据库 profile = UserProfile() profile.username = request.user.username profile.user_upload_file = user_upload_file profile.save() file_name = request.FILES.get('user_upload_file').name path = "C:\\Users\\K\\Desktop\\excel-upload-sqlite3\\mins\\upload\\upload\\" #C:\Users\K\Desktop\excel - upload - sqlite3\excel - upload - sqlite3\mins\upload\upload\华泰大赛参赛私募基金数据填报模板.xlsx filefullpath = path + file_name #print(filefullpath) if user_upload_file: b = xlrd.open_workbook(filefullpath) #count = len(b.sheets())#不需要,sheet数都是固定的 for sheet in range(1, 5): if sheet == 1: row_name = "公司资料简介" df_to_sql_T_1(filefullpath, sheet, row_name) if sheet == 2: row_name = "基金简介" df_to_sql_T_2(filefullpath, sheet, row_name) if sheet == 3: row_name = "人员简介" df_to_sql_T_3(filefullpath, sheet, row_name) if sheet == 4: row_name = "基金简称" df_to_sql_4(filefullpath, sheet, row_name) return HttpResponse('upload ok!') else: return redirect(to='login') else: uf = UserForm() context['uf'] = uf return render(request, 'website/templates/listing.html', context)
def register_view(request): '''Registration view Register users, by default makes them Students If registertion is successful, it show button to log in Keyword arguments: request -- request from client ''' data = request.POST if request.POST else None form = RegisterForm(data) registered = False if request.method == 'POST': if form.is_valid(): user = form.save() user.set_password(user.password) user.save() user_profile = UserProfile() user_profile.user = user user_profile.role = UserProfile.STUDENT user_profile.save() registered = True return render(request, 'register.html', locals())
class PostTests(APITestCase): def setUp(self): self.crowd = Crowd(name='test_crowd') self.crowd.save() self.user = UserProfile(username='******', email='*****@*****.**', password='******', crowd=self.crowd) self.user.save() # Include an appropriate `Authorization:` header on all requests. self.token = Token(user=self.user) self.token.save() self.category = Category(created_by=self.user, name='test_category', color='red', crowd=self.crowd) self.category.save() self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) self.viewset = PostViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) def _get_response(self, urllib_mock, content_type): urllib_mock.headers.get.return_value = content_type return urllib_mock @mock.patch('website.models.Post._new_post_email') @mock.patch('urllib3.PoolManager') def test_create_text_post(self, urllib_mock, new_post_mock): urllib_mock = self._get_response(urllib_mock, 'text/html') url = reverse('post-list') data = {'category': self.category.id, 'title': 'test post'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual('text', response.data['type']) self.assertEqual(self.crowd.id, response.data['crowd']['id']) self.assertEqual(self.user.id, response.data['user']['id']) # Ensure we can get the post back get_response = self.client.get('{}{}/'.format(url, response.data['id'])) self.assertEqual(get_response.status_code, status.HTTP_200_OK) self.assertEqual(self.crowd.id, get_response.data['crowd']['id']) self.assertEqual(self.user.id, get_response.data['user']['id']) @mock.patch('website.models.Post._new_post_email') @mock.patch('urllib3.PoolManager') def test_create_url_post(self, urllib_mock, new_post_mock): urllib_mock = self._get_response(urllib_mock, 'text/html') url = reverse('post-list') data = { 'category': self.category.id, 'title': 'test post', 'url': 'http://google.com/' } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual('link', response.data['type']) self.assertEqual('http://google.com/', response.data['url'])
class DeutchMitSpassLoggedInStudent(TestCase): def setUp(self): self.username = '******' self.email = '*****@*****.**' self.password = '******' self.test_user = User.objects.create_user( self.username, self.email, self.password) self.test_user_profile = UserProfile() self.test_user_profile.user = self.test_user self.test_user_profile.role = UserProfile.STUDENT self.test_user_profile.save() login = self.client.login( username=self.username, password=self.password) self.assertEqual(login, True) def test_doexercises(self): resp = self.client.get('/website/doexercises') self.assertEqual(resp.status_code, 200) self.assertTrue('username' in resp.context) self.assertEqual(resp.context['username'], 'test') def test_dotranslations(self): resp = self.client.get('/website/dotranslations') self.assertEqual(resp.status_code, 200) self.assertTrue('translation_exercises' in resp.context) self.assertTrue('username' in resp.context) self.assertEqual(resp.context['username'], 'test') def test_dotranslations_exercise_correct(self): exercise = TranslationExercise() exercise.translated_example = 'very good' exercise.example = 'sehr gut' exercise.save() self.assertEquals(len(TranslationExercise.objects.all()), 1) resp = self.client.post('/website/dotranslations', { 'answer': 'sehr gut', 'id': '1'}) self.assertEquals(resp.content, b'correct') def test_docorrections(self): resp = self.client.get('/website/docorrections') self.assertEqual(resp.status_code, 200) self.assertTrue('correcting_exercises' in resp.context) self.assertTrue('username' in resp.context) self.assertEqual(resp.context['username'], 'test') def test_docorrection_exercise_correct(self): exercise = CorrectingExercise() exercise.correct_sentence = 'nicht schlecht' exercise.wrong_sentence = 'nein schlecht' exercise.save() self.assertEquals(len(CorrectingExercise.objects.all()), 1) resp = self.client.post('/website/docorrections', { 'answer': 'nicht schlecht', 'id': '1'}) self.assertEquals(resp.content, b'correct') def test_dofillin_exercise_correct(self): exercise = FillInExercise() exercise.example = 'test *** test' exercise.correct_answer = 'ja' exercise.wrong_answer = 'nein' exercise.second_wrong_answer = 'nein nein' exercise.save() self.assertEquals(len(FillInExercise.objects.all()), 1) resp = self.client.post('/website/dofillins', { 'answer': 'ja', 'id': '1'}) self.assertEquals(resp.content, b'correct') wrong_resp = self.client.post('/website/dofillins', { 'answer': 'ja', 'id': '1'}) self.assertEquals(wrong_resp.content, b'correct') def test_doreadings(self): resp = self.client.get('/website/doreading') self.assertEqual(resp.status_code, 200) self.assertTrue('reading_exercises' in resp.context) self.assertTrue('username' in resp.context) self.assertEqual(resp.context['username'], 'test') def test_access_exercises(self): resp = self.client.get('/website/exercises') self.assertEqual(resp.status_code, 200) self.assertTrue('role' in resp.context) self.assertTrue('username' in resp.context) self.assertEqual(resp.context['username'], 'test') self.assertEqual(resp.context['role'], 'Student') def test_access_add_corrections(self): resp = self.client.get('/website/correction') self.assertEqual(resp.status_code, 200) self.assertTrue('role' in resp.context) self.assertEqual(resp.context['role'], 'Student') self.client.post('/website/correction', { 'correct_sentence': 'should not add', 'second_correct_sentence': 'should not add', 'wrong_sentence': 'should not be added'}) # student should not add exercises self.assertEqual(len(CorrectingExercise.objects.all()), 0) def test_access_add_translations(self): resp = self.client.get('/website/translation') self.assertEqual(resp.status_code, 200) self.assertTrue('role' in resp.context) self.assertEqual(resp.context['role'], 'Student') self.client.post('/website/translation', { 'example': 'should not add', 'translated_example': 'should not add'}) # student should not add exercises self.assertEqual(len(TranslationExercise.objects.all()), 0) def test_access_add_readings(self): resp = self.client.get('/website/reading') self.assertEqual(resp.status_code, 200) self.assertTrue('role' in resp.context) self.assertEqual(resp.context['role'], 'Student') self.client.post('/website/reading', { 'text': 'Lorem ipsum .......................', 'question': 'Ist das text ohne Wert', 'first_choise': 'Ja', 'first_is_correct': '1', 'second_choise': 'Nein', 'second_is_correct': '0', 'third_choise': 'Nein', 'third_is_correct': '0', 'fourt_choise': 'Nein', 'fourt_is_correct': '0' }) # student should not add exercises self.assertEqual(len(ReadingExercise.objects.all()), 0) def test_access_add_fillin(self): resp = self.client.get('/website/fillin') self.assertEqual(resp.status_code, 200) self.assertTrue('role' in resp.context) self.assertEqual(resp.context['role'], 'Student') self.client.post('/website/fillin', { 'example': 'Du *** gut', 'correct_answer': 'bist', 'wrong_answer': 'ist', 'second_wrong_answer': 'hast' }) # student should not add exercises self.assertEqual(len(FillInExercise.objects.all()), 0) def test_access_add_ordering(self): resp = self.client.get('/website/ordering') self.assertEqual(resp.status_code, 200) self.assertTrue('role' in resp.context) self.assertEqual(resp.context['role'], 'Student') self.client.post('/website/ordering', { 'description': 'test', 'first': 'test1', 'second': 'test2', 'third': 'test3', 'fourt': 'test4', 'first_match': 'test11', 'second_match': 'test22', 'third_match': 'test33', 'fourt_match': 'test44', }) # student should not add exercises self.assertEqual(len(OrderingExercise.objects.all()), 0)
class PostTests(APITestCase): def setUp(self): self.crowd = Crowd(name='test_crowd') self.crowd.save() self.user = UserProfile(username='******', email='*****@*****.**', password='******', crowd=self.crowd) self.user.save() # Include an appropriate `Authorization:` header on all requests. self.token = Token(user=self.user) self.token.save() self.category = Category(created_by=self.user, name='test_category', color='red', crowd=self.crowd) self.category.save() self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) self.viewset = PostViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) def _get_response(self, urllib_mock, content_type): urllib_mock.headers.get.return_value = content_type return urllib_mock @mock.patch('website.models.Post._new_post_email') @mock.patch('urllib3.PoolManager') def test_create_text_post(self, urllib_mock, new_post_mock): urllib_mock = self._get_response(urllib_mock, 'text/html') url = reverse('post-list') data = {'category': self.category.id, 'title': 'test post'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual('text', response.data['type']) self.assertEqual(self.crowd.id, response.data['crowd']['id']) self.assertEqual(self.user.id, response.data['user']['id']) # Ensure we can get the post back get_response = self.client.get( '{}{}/'.format(url, response.data['id'])) self.assertEqual(get_response.status_code, status.HTTP_200_OK) self.assertEqual(self.crowd.id, get_response.data['crowd']['id']) self.assertEqual(self.user.id, get_response.data['user']['id']) @mock.patch('website.models.Post._new_post_email') @mock.patch('urllib3.PoolManager') def test_create_url_post(self, urllib_mock, new_post_mock): urllib_mock = self._get_response(urllib_mock, 'text/html') url = reverse('post-list') data = {'category': self.category.id, 'title': 'test post', 'url': 'http://google.com/'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual('link', response.data['type']) self.assertEqual('http://google.com/', response.data['url'])
def register_view(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] birthdate = request.POST['date'] createdat = datetime.datetime.now() faculty = request.POST['Bölüm'] gender = request.POST['gender'] converted = datetime.datetime.strptime(birthdate, '%Y-%m-%d') if str(email).split('@')[1] != 'isik.edu.tr': messages.error( request, 'Güvenliğiniz için sadece Işık mailiniz ile kayıt olabilirsiniz.' ) return redirect('register') if password1 != password2: messages.error(request, 'İki şifre eşleşmiyor.') return redirect('register') if len(password1) < 8: messages.error(request, 'Şifre 8 karakterden küçük olamaz.') return redirect('register') if converted.year > createdat.year: messages.error(request, 'Geçersiz doğum tarihi.Geçerli bir tarih giriniz.') return redirect('register') if email and User.objects.filter(email=email).exclude( username=username).exists(): messages.error( request, 'Email sistemde kayıtlı.Lütfen başka bir email giriniz.') return redirect('register') if User.objects.filter(username=username).exists(): messages.error( request, 'Kullanıcı adı sistemde kayıtlı.Lütfen başka bir kullanıcı adı giriniz.' ) return redirect('register') user = User.objects.create_user(username=username, email=email, password=password1) profile = UserProfile(gender=gender, faculty=faculty, user=user, birthdate=birthdate, createdat=createdat) # user_test = UserProfile.objects.get(pk=13) profile.save() subject = 'Aramıza hoşgeldin - The Insider Sight' current_site = get_current_site(request) message = render_to_string( 'account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, 'Onay maili belirttiğiniz maile gönderildi.') return redirect('register') else: return render(request, 'register.html')