Html форма регистрации через контакт. Создание HTML форм

23.09.18 6.8K

Мы составили список, состоящий из 60 бесплатных форм авторизации, которые вы можете использовать на своем WordPress-сайте, в блоге, на форуме и т.д. Каждая форма тщательно протестирована, чтобы можно было гарантировать ее работоспособность и доступность исходного кода.

WordPress Login Customizer

Формы из этого списка созданы с помощью HTML / CSS. Но в данном случае речь идет о лучшем плагине для настройки пользовательского интерфейса WordPress. Он поставляется с несколькими шаблонами, которые можно дополнительно настроить в соответствии с дизайном сайта. С помощью этого плагина вы сможете избавиться от скучной страницы входа в WordPress.

Creative Login Form

Простая, но креативная форма входа, созданная с помощью HTML и CSS3. Ее также можно использовать и как форму регистрации. Это наш любимый шаблон из представленных в этом списке.

Мы поискали в интернете действительно крутые формы авторизации, но найти такие оказалось непросто. Поэтому решили представить вам собственные. Вот 20 форм входа, разработанных нашей командой.

Форма авторизации №1

Простая, креативная и яркая форма входа с градиентным фоном. Вы можете использовать ее для любых целей, таких как авторизация в веб-сервисе, мобильном или десктопном приложении.

Скачать

Предварительный просмотр

Форма авторизации №2

Минималистичная и изысканная форма входа с кнопкой, градиентной заливкой, а также с анимацией и логотипом. Используйте ее, изменив необходимые элементы.

Скачать

Предварительный просмотр

Форма авторизации №3

Страница входа с фоновым изображением, тенью и эффектом наведения для кнопки входа в систему.

Скачать

Предварительный просмотр

Форма авторизации №4

Вы можете скачать эту веб-форму и использовать по своему усмотрению. Она является полностью адаптивной.

Скачать

Предварительный просмотр

Форма авторизации №5

Прекрасная и современная форма с опциями входа через Facebook или Google. Ее кнопки имеют красивые эффекты наведения, что позволяет предоставить пользователям прекрасный опыт взаимодействия.

Скачать

Предварительный просмотр

Форма авторизации №6

Если веб-страница аккуратная и красивая, форма входа не должна отличаться от ее дизайна. Вот форма, которая точно оправдает ваши ожидания.

Скачать

Предварительный просмотр

Форма авторизации №7

Форма с тремя вариантами входа в учетную запись: Facebook, Twitter или адрес электронной почты. А если у пользователя еще нет учетной записи, можно связать форму со страницей регистрации.

Скачать

Предварительный просмотр

Форма авторизации №8

Еще одна современная, модная и красивая форма входа в систему. Она особенно хорошо смотрится на мобильных устройствах.

Скачать

Предварительный просмотр

Форма авторизации №9

Если хотите уйти от чисто белого или одноцветного дизайна, вам стоит обратить внимание на эту форму. Она поддерживает добавления фонового изображения или наложения градиента. Также есть опция входа через Facebook или Google.

Скачать

Предварительный просмотр

Форма авторизации №10

Это полная противоположность предыдущему варианту. Она выглядит минималистично, но в то же время очень аккуратно.

Скачать

Предварительный просмотр

Форма авторизации №11

Вместо того чтобы создавать форму с нуля, вы можете использовать готовый к использованию великолепный шаблон — такой как этот.

Скачать

Предварительный просмотр

Форма авторизации №12

Фоновое изображение с наложением синей тени, имя с аватаром и поля ввода — это форма авторизации №12. Для кнопки входа в систему добавлен эффект наведения.

Скачать

Предварительный просмотр

Форма авторизации №13

Шаблон с разделением экрана, в котором одна половина предназначена для изображения, а другая — для формы.

Скачать

Предварительный просмотр

Форма авторизации №14

В этой подборке есть и простые, и более сложные формы входа. А шаблон №14 — из числа минималистичных.

Скачать

Предварительный просмотр

Форма авторизации №15

Довольно минималистичная форма, но в ее верхней части можно добавить баннер. Благодаря этой небольшой опции можно сделать форму более привлекательной.

Скачать

Предварительный просмотр

Форма авторизации №16

Это форма входа с полноэкранным изображением, поверх которого размещаются поля для ввода логина и пароля, а также кнопка с эффектом наведения.

Скачать

Предварительный просмотр

Форма авторизации №17

Чтобы сделать форму более персонализированной, можно использовать этот шаблон. Он включает в себя изображение, расположенное сбоку.

Скачать

Предварительный просмотр

Форма авторизации №18

Скачать

Предварительный просмотр

Форма авторизации №19

Яркая, энергичная и захватывающая — это все о данной форме входа. Она полностью адаптивная, оптимизирована под мобильные устройства и совместима со всеми основными веб-браузерами.

Скачать

Предварительный просмотр

Форма авторизации №20

Градиентный фон, черная кнопка с эффектом наведения, поля для ввода логина и пароля, а также раздел «Забыли пароль?» Все это есть в форме авторизации №20.

Скачать

Предварительный просмотр

Выпадающая форма авторизации

Скачать

Floating Sign Up Form

Разработано для форм подписки с использованием вкладок и меток.

Скачать

Простая форма авторизации

Что раньше останавливало людей, когда они хотели авторизоваться на WordPress -сайте так это слишком простой внешний вид. В этой форме сохранен популярный дизайн, но к нему добавлено цветовое оформление.

Скачать

Flat Login – Sign Up Form

Когда вы нажмете кнопку “Click me”, расположенную в правом верхнем углу, с помощью анимации форма входа будет преобразована в форму регистрации.

Скачать

Login With Self-Contained SCSS Form

Это форма, созданная с использованием SCSS. Расширение CSS, которое добавляет базовому языку новые возможности и элегантность. Оно позволяет использовать переменные, вложенные правила, встроенный импорт и многое другое.

Скачать

Animated Login Form

Это анимированная форма входа, а верхняя часть “Hey you, Login already” преобразуется в форму при нажатии кнопки.

Скачать

Login Form Using CSS3 And HTML5

Пример того, как создать простую форму входа в систему с помощью HTML5 и CSS3. В ней применяются псевдо элементы (:after и:before) для создания эффекта нескольких страниц. Эта форма использует HTML5, чтобы упростить валидацию и представление данных.

Скачать

Login With Shake Effect

Если вы ввели неправильный пароль, то будете уведомлены об этом с помощью красивого эффекта дрожания. Простое и эффективное решение.

Скачать

Boxy Login Form

Скачать

Animated Login Form

Аккуратная небольшая форма входа.Когда вы нажмете кнопку “LOGIN”, расположенную слева, будет отображена форма авторизации.

Скачать

Material Design Form

Скачать

Bootstrap Snippet Form

Скачать

Login With Flat UI

Скачать

Trendy UI Kits Form

Скачать

Creating a membership based site seems like a daunting task at first. If you ever wanted to do this by yourself, then just gave up when you started to think how you are going to put it together using your PHP skills, then this article is for you. We are going to walk you through every aspect of creating a membership based site, with a secure members area protected by password.

The whole process consists of two big parts: user registration and user authentication. In the first part, we are going to cover creation of the registration form and storing the data in a MySQL database. In the second part, we will create the login form and use it to allow users access in the secure area.

Download the code

You can download the whole source code for the registration/login system from the link below:

Configuration & Upload
The ReadMe file contains detailed instructions.

Open the source\include\membersite_config.php file in a text editor and update the configuration. (Database login, your website’s name, your email address etc).

Upload the whole directory contents. Test the register.php by submitting the form.

The registration form

In order to create a user account, we need to gather a minimal amount of information from the user. We need his name, his email address and his desired username and password. Of course, we can ask for more information at this point, but a long form is always a turn-off. So let’s limit ourselves to just those fields.

Here is the registration form:

Register

So, we have text fields for name, email and the password. Note that we are using the for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.

Handling the form submission

Now we have to handle the form data that is submitted.

Here is the sequence (see the file fg_membersite.php in the downloaded source):

function RegisterUser() { if(!isset($_POST["submitted"])) { return false; } $formvars = array(); if(!$this->ValidateRegistrationSubmission()) { return false; } $this->CollectRegistrationSubmission($formvars); if(!$this->SaveToDatabase($formvars)) { return false; } if(!$this->SendUserConfirmationEmail($formvars)) { return false; } $this->SendAdminIntimationEmail($formvars); return true; }

First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.

function SaveToDatabase(&$formvars) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } if(!$this->Ensuretable()) { return false; } if(!$this->IsFieldUnique($formvars,"email")) { $this->HandleError("This email is already registered"); return false; } if(!$this->IsFieldUnique($formvars,"username")) { $this->HandleError("This UserName is already used. Please try another username"); return false; } if(!$this->InsertIntoDB($formvars)) { $this->HandleError("Inserting to Database failed!"); return false; } return true; }

Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:

function CreateTable() { $qry = "Create Table $this->tablename (". "id_user INT NOT NULL AUTO_INCREMENT ,". "name VARCHAR(128) NOT NULL ,". "email VARCHAR(64) NOT NULL ,". "phone_number VARCHAR(16) NOT NULL ,". "username VARCHAR(16) NOT NULL ,". "password VARCHAR(32) NOT NULL ,". "confirmcode VARCHAR(32) ,". "PRIMARY KEY (id_user)". ")"; if(!mysql_query($qry,$this->connection)) { $this->HandleDBError("Error creating the table \nquery was\n $qry"); return false; } return true; }

The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.

function InsertIntoDB(&$formvars) { $confirmcode = $this->MakeConfirmationMd5($formvars["email"]); $insert_query = "insert into ".$this->tablename."(name, email, username, password, confirmcode) values ("" . $this->SanitizeForSQL($formvars["name"]) . "", "" . $this->SanitizeForSQL($formvars["email"]) . "", "" . $this->SanitizeForSQL($formvars["username"]) . "", "" . md5($formvars["password"]) . "", "" . $confirmcode . "")"; if(!mysql_query($insert_query ,$this->connection)) { $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"); return false; } return true; }

Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.

function SendUserConfirmationEmail(&$formvars) { $mailer = new PHPMailer(); $mailer->CharSet = "utf-8"; $mailer->AddAddress($formvars["email"],$formvars["name"]); $mailer->Subject = "Your registration with ".$this->sitename; $mailer->From = $this->GetFromAddress(); $confirmcode = urlencode($this->MakeConfirmationMd5($formvars["email"])); $confirm_url = $this->GetAbsoluteURLFolder()."/confirmreg.php?code=".$confirmcode; $mailer->Body ="Hello ".$formvars["name"]."\r\n\r\n". "Thanks for your registration with ".$this->sitename."\r\n". "Please click the link below to confirm your registration.\r\n". "$confirm_url\r\n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) { $this->HandleError("Failed sending registration confirmation email."); return false; } return true; }

Updates

9th Jan 2012
Reset Password/Change Password features are added
The code is now shared at GitHub .

Welcome back UserFullName(); ?>!

License


The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.

No related posts.

Comments on this entry are closed.

A tutorial on how to create a switching login and registration form with HTML5 and CSS3.

In this tutorial we are going to create two HTML5 forms that will switch between login and registration using the CSS3 pseudo class :target . We will style it using CSS3 and an icon font. The idea behind this demo is to show the user the login form and provide a link to “switch” to the registration form.

Note that this is for demo purpose only, it will only work in browser supporting the:target pseudo class, and you should not use this code on a live website without providing solid fallback.

In the following, we will be going through Demo 1.

The HTML

In the HTML, we will put both forms, hiding the second one with CSS. Here is the code, I’ll explain some of the interesting parts later.

Log in

Sign up

We’ve added some HTML5 goodness here and used some of the new inputs. The input type=password automatically hides what the user is typing and replaces it with dots (depending on browser). The input type=email enables the browser to check if what the user entered has the format of a valid email address. We’ve also used the require=required attribute; browsers that support this attribute will not let the user submit the form until this field is filled, no JavaScript required.
The autocomplete=on attribute will prefill values based on earlier user input. We also used some nice placeholders for the inputs that will show some guiding value when the input is not filled.

Now the two tricky parts. You might have noticed the two links at the top of the form. This is a little trick that will make our form behave nicely when playing with anchors, so that it won’t “jump” on long pages when we click on the switching link and trigger the:target pseudo-class.

The second little trick is related to the use of the icon font. We will be using a data-attribute to display the icons. By setting data-icon=”icon_character” with the according character in the HTML we will just need one CSS attribute selector to style all the icons. Read more about this technique on 24 Ways: Displaying Icons with Fonts and Data- Attributes .

The CSS

For the clearness of the code in this tutorial, I will omit all the vendor prefixes, but you will, of course, find them in the files. Once again, I’m using some pretty advanced CSS3 tricks that might not work in all browsers. Let’s get started.

Styling both forms using CSS3

First, let’s give our two forms some general styling for the container.

#subscribe, #login{ position: absolute; top: 0px; width: 88%; padding: 18px 6% 60px 6%; margin: 0 0 35px 0; background: rgb(247, 247, 247); border: 1px solid rgba(147, 184, 189,0.8); box-shadow: 0pt 2px 5px rgba(105, 108, 109, 0.7), 0px 0px 8px 5px rgba(208, 223, 226, 0.4) inset; border-radius: 5px; } #login{ z-index: 22; }

We’ve added a nice box shadow that’s made of two shadows: an inset one to create the inner blue glow, and an outside shadow. We’ll explain the z-index in a bit.

In the following we will style the header with some background clipping:

/**** general text styling ****/ #wrapper h1{ font-size: 48px; color: rgb(6, 106, 117); padding: 2px 0 10px 0; font-family: "FranchiseRegular","Arial Narrow",Arial,sans-serif; font-weight: bold; text-align: center; padding-bottom: 30px; } /** For the moment only webkit supports the background-clip:text; */ #wrapper h1{ background: -webkit-repeating-linear-gradient(-45deg, rgb(18, 83, 93) , rgb(18, 83, 93) 20px, rgb(64, 111, 118) 20px, rgb(64, 111, 118) 40px, rgb(18, 83, 93) 40px); -webkit-text-fill-color: transparent; -webkit-background-clip: text; } #wrapper h1:after{ content:" "; display:block; width:100%; height:2px; margin-top:10px; background: linear-gradient(left, rgba(147,184,189,0) 0%, rgba(147,184,189,0.8) 20%, rgba(147,184,189,1) 53%, rgba(147,184,189,0.8) 79%, rgba(147,184,189,0) 100%); }

Note that at this moment only webkit browsers support background-clip: text , so we will create a stripped background only for webkit here, and clip it to the text to add the stripes to the H1 title. Since the background-clip: text property currently only works in Webkit browsers, I decided to go only with the webkit prefix. That’s the reason why I split the CSS declaration into two parts, and use a webkit prefixed gradient only. Only using the –webkit- prefix is bad practice, it’s only for demo purpose, and you should never do this on real a website! That’s also where the -webkit-text-fill-color: transparent comes in handy: it enables us to only have a transparent background on the webkit browsers, all the other ones will ignore it and give us the provided text color fallback.

We also created a fading line under the title with the help of the:after pseudo-class. We use a 2px height gradient and fade the background to 0 opacity at both ends.

Now let’s style our inputs and give them a nicer look.

/**** advanced input styling ****/ /* placeholder */ ::-webkit-input-placeholder { color: rgb(190, 188, 188); font-style: italic; } input:-moz-placeholder, textarea:-moz-placeholder{ color: rgb(190, 188, 188); font-style: italic; } input { outline: none; }

First we style the inputs, and remove the outline. But be careful here; the outline helps the user know which input is focused, so if you remove it, you should provide some:active and:focus states for the inputs.

/* all the input except submit and checkbox */ #wrapper input:not(){ width: 92%; margin-top: 4px; padding: 10px 5px 10px 32px; border: 1px solid rgb(178, 178, 178); box-sizing: content-box; border-radius: 3px; box-shadow: 0px 1px 4px 0px rgba(168, 168, 168, 0.6) inset; transition: all 0.2s linear; } #wrapper input:not():active, #wrapper input:not():focus{ border: 1px solid rgba(91, 90, 90, 0.7); background: rgba(238, 236, 240, 0.2); box-shadow: 0px 1px 4px 0px rgba(168, 168, 168, 0.9) inset; }

Here we used the:not pseudo class, to style all inputs, except the checkbox. I provided a:focus and:active state, since I decided to remove the outline.

And now the fun part: the icon font. Since we can’t use:before and:after pseudo classes on inputs, we’ll have to cheat a little bit: we’ll add the icon to the label, and then place it in the input. I’m using the fontomas library which puts together some nice icons. You can rearrange them to set the icon to a specific letter. Remember the data-icon attribute? It’s where you should put the letter. I used data-icon=’u’ for user, ‘e’ for email, ‘p’ for password. Once I chose the letters, I downloaded the font, and used the fontsquirrel font generator to transform it into a @font-face compatible format.

@font-face { font-family: "FontomasCustomRegular"; src: url("fonts/fontomas-webfont.eot"); src: url("fonts/fontomas-webfont.eot?#iefix") format("embedded-opentype"), url("fonts/fontomas-webfont.woff") format("woff"), url("fonts/fontomas-webfont.ttf") format("truetype"), url("fonts/fontomas-webfont.svg#FontomasCustomRegular") format("svg"); font-weight: normal; font-style: normal; } /** the magic icon trick ! **/ :after { content: attr(data-icon); font-family: "FontomasCustomRegular"; color: rgb(106, 159, 171); position: absolute; left: 10px; top: 35px; width: 30px; }

Yeah, that’s it folks, you don’t need to have a class for each icon. We used content: attr(data-icon) to retrieve the letter from the data-icon attribute, so we only have to declare the font, choose a nice color and position it.

Now let’s style the submit button for both forms.

/*styling both submit buttons */ #wrapper p.button input{ width: 30%; cursor: pointer; background: rgb(61, 157, 179); padding: 8px 5px; font-family: "BebasNeueRegular","Arial Narrow",Arial,sans-serif; color: #fff; font-size: 24px; border: 1px solid rgb(28, 108, 122); margin-bottom: 10px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5); border-radius: 3px; box-shadow: 0px 1px 6px 4px rgba(0, 0, 0, 0.07) inset, 0px 0px 0px 3px rgb(254, 254, 254), 0px 5px 3px 3px rgb(210, 210, 210); transition: all 0.2s linear; } #wrapper p.button input:hover{ background: rgb(74, 179, 198); } #wrapper p.button input:active, #wrapper p.button input:focus{ background: rgb(40, 137, 154); position: relative; top: 1px; border: 1px solid rgb(12, 76, 87); box-shadow: 0px 1px 6px 4px rgba(0, 0, 0, 0.2) inset; } p.login.button, p.signin.button{ text-align: right; margin: 5px 0; }

The trick here is to use the box-shadow in order to create some extra borders. You can only use one border, but as many box-shadows as you want. We will use the length value to create a “fake” second white border, 3px wide, with no blur.

Then we’ll style the checkbox, nothing very special here:

/* styling the checkbox "keep me logged in"*/ .keeplogin{ margin-top: -5px; } .keeplogin input, .keeplogin label{ display: inline-block; font-size: 12px; font-style: italic; } .keeplogin input#loginkeeping{ margin-right: 5px; } .keeplogin label{ width: 80%; }

We will style the bottom of the form using repeating linear gradients to create a striped background.

P.change_link{ position: absolute; color: rgb(127, 124, 124); left: 0px; height: 20px; width: 440px; padding: 17px 30px 20px 30px; font-size: 16px ; text-align: right; border-top: 1px solid rgb(219, 229, 232); border-radius: 0 0 5px 5px; background: rgb(225, 234, 235); background: repeating-linear-gradient(-45deg, rgb(247, 247, 247) , rgb(247, 247, 247) 15px, rgb(225, 234, 235) 15px, rgb(225, 234, 235) 30px, rgb(247, 247, 247) 30px); } #wrapper p.change_link a { display: inline-block; font-weight: bold; background: rgb(247, 248, 241); padding: 2px 6px; color: rgb(29, 162, 193); margin-left: 10px; text-decoration: none; border-radius: 4px; border: 1px solid rgb(203, 213, 214); transition: all 0.4s linear; } #wrapper p.change_link a:hover { color: rgb(57, 191, 215); background: rgb(247, 247, 247); border: 1px solid rgb(74, 179, 198); } #wrapper p.change_link a:active{ position: relative; top: 1px; }

Now you’ll notice that we’ve got two nice forms, but we really want only one to show at a time. So now is time for some animations!!

Creating the switching animation

The first thing to do is to hide the second form by setting the opacity to 0:

#register{ z-index: 21; opacity: 0; }

Remember that our login form had a z-index of 22? We will give the second form a z-index of 21, to put it “under” the login form.

And now the really good part: switching the forms using the:target pseudo class. What you really have to understand about:target, is that we will use anchors to make the transition. The normal behavior of an anchor link, is to jump to the target in the page. But we don’t want to jump anywhere, we only want to switch the forms. And here comes our trick using the two links at the top of the page. Instead of directly linking to the second form, and risking getting a “jumping” effect, we actually put the two links at the top of the page and give them display: none . This will avoid any page jump. Credit where credit’s due: I found this trick on CSS3 create (in French).

#toregister:target ~ #wrapper #register, #tologin:target ~ #wrapper #login{ z-index: 22; animation-name: fadeInLeft; animation-delay: .1s; }

So this is what happens: when we click on the Join us button, we trigger the #toregister. We then do the animation, by using the sibling selector ~ to find our #register element. We use an animation called fadeInLeft . Since we “hide” the form using zero opacity, we will use an animation that fades in, to make it appear. We’ve also changed the z-index, to make it appear on top of the other form.
The same happens for the other form.

And here is the code for the animation. We are using the CSS3 animation framework from Dan Eden and adapted it for this tutorial.

Animate{ animation-duration: 0.5s; animation-timing-function: ease; animation-fill-mode: both; } @keyframes fadeInLeft { 0% { opacity: 0; transform: translateX(-20px); } 100% { opacity: 1; transform: translateX(0); } }

The form that is “disappearing” will have another animation which will make it fade out to the left:

#toregister:target ~ #wrapper #login, #tologin:target ~ #wrapper #register{ animation-name: fadeOutLeftBig; } @keyframes fadeOutLeft { 0% { opacity: 1; transform: translateX(0); } 100% { opacity: 0; transform: translateX(-20px); } }

You can now use other animations from Dan Eden’s animate.css: just adjust your .animate class and replace the animation names. You will also find some custom animations at the end of the animate-custom.css file.

Well, that’s it folks. I hope you enjoyed the tutorial!

Please note, that in some browsers background-clip: text is not supported. In Internet Explorer 9 the transitions and animations don’t work, so there will be no fancy form switching. In Internet Explorer 8 and below the:target pseudo-class is not supported, so it won’t work at all (you’ll just see the login form).

В данной статье будет описан процесс реализации возможности регистрации и аутентификации пользователей наиболее простейшим образом.

1. Регистрация

Начнём с регистрации. Django "из коробки" предоставляет форму создания пользователя UserCreationForm , которую мы и будет использовать для регистрации. Плюс ко всему, она автоматически делает все необходимые проверки. Например, зарегистрирован ли уже пользователь с данным именем. Построенное на основе данной формы представление будет иметь следующий вид:

From django.views.generic.edit import FormView from django.contrib.auth.forms import UserCreationForm class RegisterFormView(FormView): form_class = UserCreationForm # Ссылка, на которую будет перенаправляться пользователь в случае успешной регистрации. # В данном случае указана ссылка на страницу входа для зарегистрированных пользователей. success_url = "/login/" # Шаблон, который будет использоваться при отображении представления. template_name = "register.html" def form_valid(self, form): # Создаём пользователя, если данные в форму были введены корректно. form.save() # Вызываем метод базового класса return super(RegisterFormView, self).form_valid(form)

Как видно, зарегистрировать пользователя достаточно просто. Теперь необходимо добавить ссылку на представление в urls.py :

From django.conf.urls import patterns, include, url urlpatterns = patterns("", ... url(r"^register/$", views.RegisterFormView.as_view()), ...)

И тег {{ form }} в шаблон register.html :

Регистрация

{% csrf_token %} {{ form.as_p }}

Таким образом, перейдя на страницу ваш.сайт/register/ можно будет увидеть форму регистрации, которая, если повезёт, даже будет работать. Однако, выглядеть она будет страшновато. Как применить к ней форматирование и стили CSS можно догадаться из статьи или почитав документацию.

2. Аутентификация

Принципы реализации аутентификации абсолютно те же самые, но реализация немного сложнее (за счёт использования некоторых дополнительных функций). Без лишних слов, смотрим на код и читаем комментарии:

# Опять же, спасибо django за готовую форму аутентификации. from django.contrib.auth.forms import AuthenticationForm # Функция для установки сессионного ключа. # По нему django будет определять, выполнил ли вход пользователь. from django.contrib.auth import login class LoginFormView(FormView): form_class = AuthenticationForm # Аналогично регистрации, только используем шаблон аутентификации. template_name = "login.html" # В случае успеха перенаправим на главную. success_url = "/" def form_valid(self, form): # Получаем объект пользователя на основе введённых в форму данных. self.user = form.get_user() # Выполняем аутентификацию пользователя. login(self.request, self.user) return super(LoginFormView, self).form_valid(form)

Осталось, аналогично регистрации, добавить ссылку в urls.py и создать шаблон login.html (кстати говоря, подойдёт и представленный выше шаблон регистрации без каких-либо изменений).

3. Выход

Для полного счастья осталось добавить возможность выхода (для ещё большего счастья смену и восстановление пароля, но об этом ниже). Для выхода не требуется никаких форм и шаблонов, поэтому представление для него делается буквально в четыре строки: from django.http import HttpResponseRedirect from django.views.generic.base import View from django.contrib.auth import logout class LogoutView(View): def get(self, request): # Выполняем выход для пользователя, запросившего данное представление. logout(request) # После чего, перенаправляем пользователя на главную страницу. return HttpResponseRedirect("/")

4. Заключение

Скопировав и склеив всё это, можно получить минимальную систему "чтобы работало" с большим потенциалом для улучшения. Например, можно реализовать страницы восстановления и изменения пароля аналогичным образом на основе форм PasswordResetForm и PasswordChangeForm из django.contrib.auth.forms .

Please enable JavaScript to view the

DesignMaz have collected list of the best CSS /HTML Login Form Templates for Web Designers, Developers that they can download and use to create a form and most of them also have pre built HTML validation features as well as some option jQuery validation (like the Login /Register form with pass meter below).

Free Responsive Flat Login Form Widget Template

Free Responsive Flat New Login Form Widget Template for your websites. This Login form is designed using web technologies such as . It is completely free for download and can be use for your website or application sign in.

Forms Plus

PopForms

Flat Form with Bootstrap 3

This is a flat modern css3 design based on Booststrap 3 Framework. Responsive design with multi-color multipurpose web forms with pure css3.

Responsive Static Login Form HTML5 Template

Free Responsive Static Login Form HTML5 CSS3 Template. You can download this HTML CSS Sign In Widget which can be used in you web projects.

Free Responsive Flat and Clean Login Form Template

A Responsive Flat and Clean Login Form HTML Template designed using web technologies such as HTML5 and CSS3. You can free download and use for your website or application sign in.

Responsive Flat Purple Login Form Template

A free Responsive Flat Purple Login Form Template built with HTML5, and CSS3. It is completely free for download and can be used straight away in your website or app.

Bootstrap login with social buttons

Any Twitter Bootstrap developer will love these free Responsive Bootstrap login form template with social buttons . This Responsive Bootstrap login form template is a Simple and Clean login form website template base on Bootstrap 3.1.0 .

Easy to use the beautiful and colorful css login form for their own website. Simply insert into the existing CSS file and enjoy the new CSS login form . Created with rounded corners and nice look. It degrades nicely on older browsers, e.g. IE7 and IE8.

MetroLogin is a Windows 8’s Login form simulator that gives you this ability to make a login page for your website’s users or a login Page for your admin panel with a nice metro design.

Twitter Inspired Login Form – Jquery

This is a drop down login form similar to the one found on twitter. It comes complete with JavaScript , CSS and HTML . Just like Twitters login in form it comes with enhancements like tooltips and a compact login form and a clicked state button. It uses CSS3 to reduce the need for images and it degrades nicely in non CSS browsers. It has great browser support and works in most modern browsers and even older ones like Internet explorer 6 and 7.

This is clean and pleasant designed login & register HTML user interface with error handling and social buttons.

Clean and usable login & register form is for every developer. It’s very fast pure CSS . Error handling states, social buttons and forgotten password state is in there.

Zi-Popup Login Forms – Pure CSS3

Clean and usable login & register form is for every developer. It’s very fast CSS form with jQuery validation. Error handling, social buttons and forgotten password handling is in there. Bring to live with a jQuery.

Minimalistic Login/Register Form + Live Validation

Minimalistic Designed Login , Register and Forgot Template Forms Pack. Packed with jQuery Live Validation, 7 color styles, 3 different form size options, title animation, custom checkbox, tooltip hints and jQuery Error Handling.

Summer Forms – Login And Registration Forms

Summer Forms are coupled login and registration forms having a set of impressing effects bundled with the bright modern design. The flexibility of these responsive forms Summer Forms may be become the first brick of your new web site or may be just a replacement of your old forms . Every year the people get more exacting. The forms are well thought out and may satisfy any user.

Not so long ago, in order to achieve such effects, we used JS. But, now, CSS3 has all the necessary tools for making pop-up windows too.

Moon Forms – Login & Registration CSS Forms

Moon Forms are coupled login and registration forms having a modern design. The flexibility of these responsive forms allows placing it into any area on your site (like a widget, like a popup window, like a standalone page).

Tab and form developed by using only CSS3 , no javascript used. It is simple , clean and browser compatible. Very Easy to implement on any kind of website.

Features a large collection of form styles that are used regularly in websites. You get Search Forms , Login Forms , Contact Forms and General Form styles. Further all these forms are available in Dark and Light coloured versions, so you get a total of 224 form styles! The login , contact and general forms also have focus and validation error styles defined in the css.

Form Framework that strikes a balance between simplicity and elegance.CSS3 Responsive Forms kit is simple, clean and fresh modern form pack develop using bootstrap .

Day/Night Login Page

Day / Night Login Forms – has the net and unique design. In the kit you get 2 folder with 6 forms. In two colors white and dark. As in the kit includes 4 style buttons. Thanks to the Day / Night Login Forms developers can save time and money on developing the design. And the designers can see an example of the correct organization of layers.

Is a set of beautiful form elements. It has large amount of customized items, different color schemes, responsive grid system and allows you to create forms of any complexity and for any needs: login , registration , contacts , review , order , comment , checkout , etc.

Nice, clean and easy to use CSS3 login panel which 3 included color schemes.

Golden Forms – Responsive CSS3 Form Framework

Golden Forms is a simple and professional Form Framework that strikes a balance between simplicity and elegance. The framework is built with pure CSS3 + HTML5 (no images), features a clean consistent Form UI , responsive 12 column grid, and can be used to build any kind of Web Forms quickly whether simple or complex, without special CSS and coding knowledge.

– has a clean design and a powerfull 3D Flip Effect which give user a unique exprince and a fast way to complete the process . In the kit you get 1 psd file with 3 forms styes.

Responsive HTML5 – jQuery Sign In – Registration Form

Responsive HTML5 Sign In / Registration form , with jQuery effects and CSS3 customization.