def update(self, request, event, registration): form = RegistrationForm(event, data=request.POST, instance=registration) if request.GET['role'] == 'cm-admin': # POSTing the form as an chairman administrating the event request.user.check_admin_of(event.committee) if form.is_valid(): form.save(registration.participant) messages.success(request, _("Inschrijving bijgewerkt!")) return redirect('event-edit', event.pk) else: # Render previous page with validation errors registration_view = RegistrationView(self.route, self.request) return registration_view.edit(self.request, event.pk, form=form) elif request.GET['role'] == 'user': # POSTing the form as an user updating their own registration self.check_user(registration.participant) # Make sure deadline hasn't passed and event is open if event.is_expired() or not event.is_published(): raise PermissionDenied if form.is_valid(): form.save(request.user) messages.success(request, _("Inschrijving bijgewerkt!")) return redirect('event-detail', event.pk) else: # Render previous page with validation errors event_view = EventView(self.route, self.request) return event_view.show(self.request, event.pk, form=form)
def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] user = User.objects.create_user(email, #email is username email, #email password) user.first_name = first_name user.last_name = last_name user.save() up = UserProfile(user=user) up.save() #request.session['next'] = '/' return authenticate(request, email, password) else: form = RegistrationForm() return render_to_response("login.html", { 'form': form, }, context_instance = RequestContext(request) )
def signup_view(request): # функция регистрации template = 'app/signup.html' # шаблон для регистрации msg = None if request.method == 'POST': # если послываем данные на сервер form = RegistrationForm( request.POST) # используем форму для регистрации if form.is_valid( ): # проверяет данные формы и возвращает True, если данные корректны first_name = form.cleaned_data[ 'first_name'] # правильно обрабатывает введенные в поле данные email = form.cleaned_data['username'] username = form.cleaned_data['username'] password = form.cleaned_data['password1'] User.objects.create_user( first_name=first_name, username=username, email=email, password=password) # создать пользователя и добавить в таблицу user = authenticate( username=username, password=password) # проверить наборв учетных данных login(request, user) # залогиниить пользователя return redirect('main') # вернуть на главную страницу else: # если форма не валидна form = RegistrationForm() # возвращает пустую форму msg = 'Пользователь с таким Email уже зарегистрирован либо ваши пароли не совпадают. Повторите попытку' # возвращается сообщение, которое выведтся рядом с формой else: # если метод не POST form = RegistrationForm() # возвращает пустую форму context = { 'form': form, # возвращает форму 'msg': msg # возвращает сообщение } return render( request, template, context) # страница просто перезагружается и возвращает сообщение
def registration_view(request): form = RegistrationForm(request.POST or None) context = {} context['form'] = form if form.is_valid(): new_user = form.save(commit=False) email = form.cleaned_data['email'] password = form.cleaned_data['password'] new_user.set_password(password) new_user.first_name = form.cleaned_data['first_name'] new_user.last_name = form.cleaned_data['last_name'] new_user.email = email new_user.company = form.cleaned_data['company'] new_user.position = form.cleaned_data['position'] new_user.second_name = form.cleaned_data['second_name'] new_user.save() login_user = authenticate(email=email, password=password) if login_user: login(request, login_user) return HttpResponseRedirect(reverse('main_page')) return HttpResponseRedirect(reverse('main_page')) return render(request, 'app/registration.html', context)
def register(request): status = 200 if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): logger.debug('Registering user email=%s' % form.cleaned_data['email']) user = form.save() registration.send('app.views.auth.register', user=user) return render(request, 'registration/check_inbox.html', status=201) else: errors = {field: error[0] for field, error in form.errors.items()} logger.debug('Registration failed ' + str(errors)) status = 400 else: form = RegistrationForm() return render(request, 'registration/register.html', {'form': form}, status=status)
def post(self, request): f = RegistrationForm(request.POST) if f.is_valid(): user = f.save() login(request, user) return redirect('home') else: return render(request, 'registration.html', context={'form': f})
def SignUp(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/app') else: form = RegistrationForm() args = {'form': form} return render(request, 'app/signup.html', args)
def home(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() username = request.POST['username'] messages.success(request, f'User created successfully for user {username}') return HttpResponseRedirect('/home/') else: form = RegistrationForm() return render(request, 'app/home.html', {'form': form})
def register(request): if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): new_user = User() new_user.username = form.cleaned_data["username"] new_user.set_password(form.cleaned_data["password"]) new_user.email = form.cleaned_data["email"] new_user.save() return HttpResponseRedirect("/thanks") else: form = RegistrationForm() return render(request, "app/register.html", {"form": form})
def test_register_form_mobile_number_missing(self): form_data = { 'username': '******', 'password1': '1234', 'mobile_number': '', 'email': '*****@*****.**', 'alias': '', 'gender': '', 'year_of_birth': '1989', 'identity': '', 'tos': True } form = RegistrationForm(data=form_data) self.assertEqual(form.is_valid(), True)
def test_register_form_email_incorrect(self): form_data = { 'username': '******', 'password1': '1234', 'mobile_number': '0712341113', 'email': 'an', 'alias': '', 'gender': '', 'year_of_birth': '1989', 'identity' : '', 'tos': True } form = RegistrationForm(data=form_data) self.assertEqual(form.is_valid(), False)
def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() args = { 'title': 'Sign Up Selection', 'year': datetime.now().year, } return render(request, app / about.html, args) else: form = RegistrationForm() args = {'form': form} return render(request, 'app/register.html', args)
def register(request): if request.method == "POST": form = RegistrationForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Registration Successful") return render_to_response('register.html', {'form': RegistrationForm}, context_instance=RequestContext(request)) else: messages.error(request, "Some Error Occured") return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request)) else: return render_to_response('register.html', {'form': RegistrationForm}, context_instance=RequestContext(request))
def sing_up(request): form = RegistrationForm(request.POST or None) if form.is_valid(): new_user = form.save() email = form.cleaned_data['email'] password = form.cleaned_data['password'] username = form.cleaned_data['username'] new_user.username = username new_user.email = email new_user.set_password(password) new_user.save() user = authenticate(username=username, password=password) if user: auth_login(request, user) return HttpResponseRedirect(reverse('index')) context = {'form': form} return render(request, 'sing_up.html', context)
def signup(request): tags = Tag.objects.get_popular() if request.method == 'GET': form = RegistrationForm() else: form = RegistrationForm(data=request.POST, files=request.FILES) if form.is_valid(): user = User.objects.create_user(form.cleaned_data["username"], form.cleaned_data["email"], form.cleaned_data["password"]) Profile.objects.create(user=user) return redirect('/login') return render(request, 'signup.html', { 'form': form, 'tags': tags, })
def register_view(request): """ Displays a registration form and runs user registration. name: accounts:registration URL: /accounts/register """ form = RegistrationForm(request.POST or None) if form.is_valid(): username = form.cleaned_data['username'] user = User.objects.create_user(username, password=form.cleaned_data['password']) code = form.cleaned_data['code'] UserX.objects.create(user=user, code=code) RegistrationCode.objects.filter(code=code).delete() return redirect('accounts:login', username) return render(request, 'accounts/registration.html', {'form': form})
def registration_view(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') account = authenticate(username=username, password=raw_password) login(request, account) return redirect('home') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form return render(request, 'app/register.html', context)
def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): # Save account user = form.save() # Login under new account login(request, user) # Go to account home return redirect('account_home') else: form = RegistrationForm() ctx = {'form': form} return render(request, 'auth/register.html', ctx)
def my_register(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = RegistrationForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # some actions user = User.objects.create_user( username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password')) login(request, user) return HttpResponseRedirect('/') # if a GET (or any other method) we'll create a blank form else: form = RegistrationForm() return render(request, 'register.html', {'form': form})
def registration(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.verified = False user.save() my_password = form.cleaned_data.get('password1') user = auth.authenticate(username=user.username, password=my_password) auth.login(request, user) logger.info( log_username(request) + " зарегистрировался, пароль: {0}".format(my_password)) return redirect('home') else: form = RegistrationForm() return render(request, 'app/registration.html', {'form': form})
def get_registrationform(request): if(request.method=='POST'): form=RegistrationForm(request.POST) if form.is_valid(): username=form.cleaned_data['username'] email=form.cleaned_data['email'] hotel=form.cleaned_data['hotel'] location=form.cleaned_data['location'] password1=form.cleaned_data['password1'] password2=form.cleaned_data['password2'] if password1==password2: u=User.objects.create_superuser(username,email,password1) r=Restaurant(name=hotel,location=location,user=u) r.save() return HttpResponseRedirect("/restaurants/lists/") else: form=RegistrationForm() return render(request,'registration/registration.html',{'form':form},)
def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db( ) # load the profile instance created by the signal user.profile.age = form.cleaned_data.get('age') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, firstname=user.first_name, lastname=user.last_name, password=raw_password) login(request, user) #return redirect('dashboard') return redirect('register') else: form = RegistrationForm() return render(request, 'register.html', {'form': form})
def register(request): """Handles user registration.""" assert isinstance(request, HttpRequest) form = RegistrationForm(request.POST or None) if (request.method == 'POST' and form.is_valid()): user = User.objects.create_user( form.cleaned_data['reg_email'], form.cleaned_data['reg_email'], form.cleaned_data['reg_password'], first_name=form.cleaned_data['reg_firstname'], last_name=form.cleaned_data['reg_lastname']) login(request, user) return HttpResponseRedirect('/') else: return render( request, 'app/login.html', { 'signin_title': 'Login', 'signup_title': 'Sign Up', 'form': BootstrapAuthenticationForm, 'signup_form': form })
def signup_view(request): template = 'app/signup.html' msg = None if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] email = form.cleaned_data['username'] username = form.cleaned_data['username'] password = form.cleaned_data['password1'] User.objects.create_user(first_name=first_name, username=username, email=email, password=password) user = authenticate(username=username, password=password) login(request, user) return redirect('main') else: form = RegistrationForm() msg = 'Пользователь с таким Email уже зарегистрирован либо ваши пароли не совпадают. Повторите попытку' else: form = RegistrationForm() context = {'form': form, 'msg': msg} return render(request, template, context)
def register(request: HttpRequest): """ Регистрация """ Visit.make(request, '/register') error = None if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): name = form.cleaned_data['nickname'] password = form.cleaned_data['password1'] User.objects.create_user( username=name, password=password, ) else: error = form.errors['__all__'][0] return render( request, 'login.html', { 'registration_form': RegistrationForm, 'form': BootstrapAuthenticationForm, 'name': 'login', 'title': 'Вход', 'year': datetime.now().year, 'error': error })
def registration(request): msg = '' registration_error = -1 created = False form = RegistrationForm(request.POST or None) if request.method == "POST": if form.is_valid() and form.cleaned_data['location_lat'] != '' and form.cleaned_data['location_lng'] != '' and \ form.cleaned_data['location_name'] != '': try: Scientist.objects.get(email=form.cleaned_data['email'], ci=form.cleaned_data['ci']) msg = f"Investigador con email {form.cleaned_data['email']} y cédula de identidad " \ f"{form.cleaned_data['ci']} ya existente" registration_error = 1 except Scientist.DoesNotExist: # Save institution data inst_dict = { 'latitude': form.cleaned_data['location_lat'], 'longitude': form.cleaned_data['location_lng'], 'name': form.cleaned_data['location_name'] } inst_obj = __create_update_institution(inst_dict) # Remove institution data from form object del form.cleaned_data['location_lat'] del form.cleaned_data['location_lng'] del form.cleaned_data['location_name'] # Get/Create Scientist scientist_obj = Scientist.objects.create(**form.cleaned_data) scientist_obj.save() logger.info(f"Scientist {scientist_obj} created!") affiliation_obj, created = Affiliation.objects.get_or_create( scientist=scientist_obj, institution=inst_obj, defaults={ 'scientist': scientist_obj, 'institution': inst_obj }) msg = f"Registro exitoso! Luego de su aprobación, los datos podrán ser " \ f"visualizados en el mapa de investigadores." form = RegistrationForm() registration_error = 0 else: if form.cleaned_data['location_name'] == '' or form.cleaned_data['location_lat'] == '' or \ form.cleaned_data['location_lng'] == '': msg = f"Datos de registro incompletos, favor indique una institución" logger.info( f"Registration Error: Missing institution. Form details {form}" ) else: msg = "Datos inválidos, favor compruebe los errores" logger.info( f"Registration Error: The form is not valid. Form details {form}" ) registration_error = 1 context = { 'form': form, 'msg': msg, 'edit': 0, 'institution': json.dumps(None), 'registration_result': registration_error } if created: logger.info(f"Affiliation {affiliation_obj} created!") return render(request, 'register.html', context)
def store(self, request, event): if request.GET['role'] == 'cm-committee': # Bulk registration of whole committee by chairman # Get committee that was POSTed and check if user is chairman committee = Committee.objects.get(name=request.POST['committee']) self.check_user(committee.chairman) # Register all members for event committee.enroll(Mailer(settings.DEFAULT_FROM_EMAIL), event, request) messages.success( request, _("Commissie {} geregistreerd!").format(committee.name)) return redirect('event-detail', event.pk) elif request.GET['role'] == 'cm-admin': # Bulk registration of users as staff administrating the event request.user.check_staff() # Create list of tuples from three lists of inputs rows = list( zip_longest(request.POST.getlist('username'), request.POST.getlist('note'), request.POST.getlist('date'))) # Build list of forms forms = [ RegistrationsForm(event, data={ 'username': username, 'note': note, 'date': date }) for username, note, date in rows ] count = 0 with Mailer(settings.DEFAULT_FROM_EMAIL) as mailer: for form in forms: if form.is_valid(): form.save(mailer, request) count += 1 else: messages.error(request, form.errors) if count > 0: messages.success( request, _("{} inschrijvingen toegevoegd!").format(count)) return redirect('event-edit', event.pk) elif request.GET['role'] == 'user': form = RegistrationForm(event, data=request.POST) # Make sure deadline hasn't passed and event is open if event.is_expired() or not event.is_published(): raise PermissionDenied if form.is_valid(): form.save(request.user) messages.success(request, _("Inschrijving geregistreerd!")) return redirect('event-detail', event.pk) else: # Render previous page with validation errors event_view = EventView(self.route, self.request) return event_view.show(self.request, event.pk, form=form)