How to make a success ulr for my contact page - django

I want the client to be redirected to another HTML page as a successfully sent message in my contact form. But I don't know exactly what is wrong here. I can't redirect to my success page but the form works.
#my main app's url.py
urlpatterns = [
path('^contact/', include('contactus.urls')),
]
#my contact app url.py
from __future__ import unicode_literals
from django.conf.urls import url
from django.views.generic import TemplateView
from .views import ContactUsView
urlpatterns = [
url(r'^$', ContactUsView.as_view(), {}, 'contactus'),
url(r'^success/$', TemplateView.as_view(),
{}, 'contactus-success'),
]
#contact app view.py
from __future__ import unicode_literals
from django.conf import settings
from django.core.mail import EmailMessage
from django.template import loader
from django.views.generic.edit import FormView
from contactus.forms import ContactUsForm
class ContactUsView(FormView):
template_name = 'contactus/contact.html'
email_template_name = 'contactus/contact_notification_email.txt'
form_class = ContactUsForm
success_url = "/contact/success/"
subject = "Contact Us Request"
def get_initial(self):
initial = super(ContactUsView, self).get_initial()
if not self.request.user.is_anonymous:
initial['name'] = self.request.user.get_full_name()
initial['email'] = self.request.user.email
return initial
def form_valid(self, form):
form_data = form.cleaned_data
if not self.request.user.is_anonymous:
form_data['username'] = self.request.user.username
# POST to the support email
sender = settings.SERVER_EMAIL
recipients = (getattr(settings, 'CONTACT_US_EMAIL'),)
reply_to = form_data.get('email') or sender
tmpl = loader.get_template(self.email_template_name)
email = EmailMessage(
self.subject,
tmpl.render(form_data),
sender,
recipients,
reply_to=[reply_to],
)
email.send()
return super(ContactUsView, self).form_valid(form)
#contact app forms.py
from __future__ import unicode_literals
from django import forms
class ContactUsForm(forms.Form):
name = forms.CharField(required=True, max_length=512)
email = forms.EmailField(required=True)
subject = forms.CharField(required=True, max_length=512)
description = forms.CharField(
widget=forms.Textarea(attrs={'class': "form-control"}),
required=True)
def clean(self):
cleaned_data = super(ContactUsForm, self).clean()
return cleaned_data
#Contact.html
{% extends 'website/base.html' %}
{% load static %}
{% block main %}
<!-- ======= Breadcrumbs ======= -->
<section id="breadcrumbs" class="breadcrumbs">
<div class="container">
<div class="d-flex justify-content-between align-items-center">
<h2>Contact</h2>
<ol>
<li>Home</li>
<li>Contact</li>
</ol>
</div>
</div>
</section><!-- End Breadcrumbs -->
<section id="contact" class="contact">
<div class="container">
<div class="row mt-5 justify-content-center" data-aos="fade-up">
<div class="col-lg-10">
<form action="." method="post" role="form" class="php-email-form">{% csrf_token %}
<div class="row">
<div class="col-md-6 form-group {% if form.name.errors %}has-error{% endif %}">
<input type="text" name="name" class="form-control"
data-rule="minlen:4" data-msg="Please enter at least 4 chars"
id="id_name" placeholder="Your Name"
value="{% if form.data.name %}{{form.data.name}}{% else%} {{form.initial.name}}{% endif %}" />
<div class="validate"></div>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0 {% if form.email.errors %}has-error{% endif %}">
<input class="form-control" type="email" name="email"
id="email" data-rule="email" data-msg="Please enter a valid email"
id="id_email" placeholder="Your Email"
value="{% if form.data.email %}{{form.data.email}}{% else %}{{form.initial.email}}{% endif %}" />
<div class="validate"></div>
</div>
</div>
<div class="form-group mt-3 {% if form.subject.errors %}has-error{% endif %}">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject"
data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
<div class="validate"></div>
</div>
<div class="form-group mt-3 {% if form.description.errors %}has-error{% endif %}">
<textarea class="form-control" name="description" rows="5" data-rule="required"
data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
</div>
</div>
</section><!-- End Contact Section -->
{% endblock %}

The error could be from the view.
try:
success_url = "/success/"
or you could leave your view like that and change the url in urls.py to:
url(r'^contact/success/$',......),

Related

How do I use Django generic updateviews to update my model using individual form field values?

models.py:
from django.db import models
class Location(models.Model):
name = models.CharField(max_length=20)
is_source = models.BooleanField(default=False)
is_destination = models.BooleanField(default=False)
def __str__(self):
return self.name
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views import generic
from .models import Location
class LocationsListView(generic.ListView):
model = Location
template_name = 'locations/list.html'
context_object_name = 'locations'
class LocationUpdateView(generic.edit.UpdateView):
model = Location
fields = ['name', 'is_source', 'is_destination']
context_object_name = 'location'
template_name = 'locations/update.html'
success_url = reverse_lazy('locations:list')
class LocationDeleteView (generic.edit.DeleteView):
model = Location
template_name = 'locations/confirm_delete.html'
context_object_name = 'location'
success_url = reverse_lazy('locations:list')
locations/update.html
{% extends 'base.html' %}
{% block title %}Location Update{% endblock %}
{% block content %}
<section>
<div class="container">
<h1>Location Update</h1>
<div class="form-container">
<form method="post">
{% csrf_token %}
{% if form.errors %}
<div class="p-3 mb-3 border border-danger border-3 rounded">{{ form.errors }}</div>
{% endif %}
<div class="mb-3">
<label for="" class="form-label">Name</label>
<input type="text" class="form-control" value="{{ form.name.value }}">
</div>
<div class="mb-3">
<input type="checkbox" class="form-check-input" {% if form.is_source.value %} checked {% endif %}>
<label for="">Source</label>
</div>
<div class="mb-3">
<input type="checkbox" class="form-check-input" {% if form.is_destination.value %} checked {% endif %}>
<label for="">Destination</label>
</div>
<input type="submit" class="btn btn-success mb-3" value="Save">
</form>
</div>
</div>
</section>
{% endblock %}
locations.urls.py
from django.urls import path
from . import views
app_name = 'locations'
urlpatterns = [
path('', views.LocationsListView.as_view(), name='list'),
path('update/<int:pk>/', views.LocationUpdateView.as_view(), name='update'),
path('delete/<int:pk>/', views.LocationDeleteView.as_view(), name='delete'),
]
When I try to update my model, individually rendering the form fields using {{form.name.value}}, I get an error that my name field is required, and yet it is filled. I do not get the error if I render the form as a whole using {{form.as_p}} for example. What am I doing wrong?
I tried using {{form.as_p}} and it worked. But I need individual field rendering so I can style my form.
You need to provide the name attribute for each of your field <input> tags. The field's html_name attribute should be used if rendering manually
<input name="{{ form.name.html_name }}" type="text" class="form-control" value="{{ form.name.value }}">

Why customized django login form thows takes 1 positional argument but 2 were given

I was trying to customized django login form. but it throws error like this TypeError at /login/ __init__() takes 1 positional argument but 2 were given. I have created my own form and not using django built in forms. My Project structure looks like this
project_name
apps
app1
app2
static
templates
app1
login.html
app2
app1 contains the basic home, login, signup template file
url.py file inside app1 looks like this
from django.urls import path
from .views import home
from django.contrib.auth import views as auth_views
app_name = "basics"
urlpatterns = [
path('home/', home, name="home_page"),
path('login/', auth_views.LoginView,{'template_name': 'basics/login.html'}, name="login")
]
login.html file resides under templates/app1/login.html and its template looks like this.
{% extends 'basics/home.html' %}
{% block body %}
{% load static %}
<script src="{% static 'js/login.js' %}"></script>
<div class="container">
<div class="row">
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
<div class="card card-signin my-5">
<div class="card-body" style="background-color: azure">
<h3 class="card-title text-center">Log In</h3>
<br>
<br>
<p class="text-center">How did you signup?</p>
{{ error }}
<div class="main" id="mainForm">
<br>
<form class="form form-group" method="POST" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<input name ="username" class="form-control" placeholder="Enter Username" required="required">
</br>
<input name="password" class="form-control" placeholder="Enter Password" type="password"
required="required">
</br>
<button class="btn btn-block btn-dark btn-sm" type="submit">Submit</button>
<br>
back
</form>
</div>
<div class="dummybutton">
</br>
<button class="btn btn-sm btn-block emailbutton" style="background-color: skyblue">Email</button>
<button class="btn btn-sm btn-block facebookbutton" style="background-color:aqua">Facebook</button>
</br>
</div>
<br>
<br>
<br>
</div>
</div>
<p class="text-center">Dont have a Profile? Sign up now</p>
</div>
</div>
</div>
{% endblock body %}
view.py file looks like this
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login as login_check
def home(request):
result = {}
return render(request, 'basics/home.html', result)
def login(request):
result = {'error': 'No error'}
if request.method == "POST":
username = request.POST["username"]
password = request.POST["passsword"]
user = authenticate(request, username=username, password=password)
if user is not None:
login_check(request, user)
redirect('home/')
else:
result = {'error':'Invalid User'}
return render(request, 'basics/home.html', result)
return render(request, 'basics/home.html', result)
You use the LoginView the wrong way, you need to add .as_view() to convert the class-based view to a function, like:
app_name = 'basics'
urlpatterns = [
path('home/', home, name="home_page"),
path('login/', auth_views.LoginView.as_view(template_name='basics/login.html'), name="login")
]

How can I deal with error message when not using {{form}} in Django template?

I implemented Login and it works good except error message.
If I used {{ form.as_p }}, it shows error message.
<form id="loginform" class="form-horizontal" role="form" method="post" action="{% url 'users:login' %}">
{% csrf_token %}
<!-- id / pw -->
{{ form.as_p }}
<div class="form-group">
<!-- Button -->
<div class="btn-controls">
<div class="row">
<input id="btn-login" class="btn btn-success" type="submit" name="login_submit" value="로 그 인" />
<input type="hidden" name="next" value={{ request.GET.next}} />
<a id="btn-fblogin" href="{% url 'social:begin' backend='facebook' %}" class="btn btn-primary col-xs-12"><i class="icon-facebook"></i> 1초만에 페이스북으로 로그인 </a>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div class="signup">
아직 차차다방 회원이 아니세요? &nbsp
가입하기
</div>
<div class="forget">
비밀번호를 잊어버리셨나요?
</div>
</div>
</div>
</form>
But when I change template like this, it doesn't show any error when I type wrong id or pw...
<form id="loginform" class="form-horizontal" role="form" method="post" action="{% url 'users:login' %}">
{% csrf_token %}
<div class="input-group">
<span class="input-group-addon"><i class="icon-user"></i></span>
<input id="id_username" type="text" class="form-control" name="username" value="" placeholder="username">
</div>
<div class="input-group">
<span class="input-group-addon"><i class="icon-lock"></i></span>
<input id="id_password" type="password" class="form-control" name="password" placeholder="password">
</div>
<div class="form-group">
<!-- Button -->
<div class="btn-controls">
<div class="row">
<input id="btn-login" class="btn btn-success" type="submit" name="login_submit" value="로 그 인" />
<input type="hidden" name="next" value={{ request.GET.next}} />
<a id="btn-fblogin" href="{% url 'social:begin' backend='facebook' %}" class="btn btn-primary col-xs-12"><i class="icon-facebook"></i> 1초만에 페이스북으로 로그인 </a>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div class="signup">
아직 차차다방 회원이 아니세요? &nbsp
가입하기
</div>
<div class="forget">
비밀번호를 잊어버리셨나요?
</div>
</div>
</div>
</form>
How can I make it show error message even if I don't user {{ form.xx }} ?
Here is my LoginView.
from django.utils.http import is_safe_url
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import FormView
from users.forms import MyUserCreationForm
class LoginView(FormView):
form_class = AuthenticationForm
redirect_field_name = REDIRECT_FIELD_NAME
# template_name is fake one.
# This view only process POST request from users/login_signup.html
template_name = "users/login_signup.html"
#method_decorator(sensitive_post_parameters('password'))
#method_decorator(csrf_protect)
#method_decorator(never_cache)
def dispatch(self, request, *args, **kwargs):
# Sets a test cookie to make sure the user has cookies enabled
request.session.set_test_cookie()
return super(LoginView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
auth_login(self.request, form.get_user())
# If the test cookie worked, go ahead and
# delete it since its no longer needed
if self.request.session.test_cookie_worked():
self.request.session.delete_test_cookie()
return super(LoginView, self).form_valid(form)
def get_context_data(self, *args, **kwargs):
context = super(LoginView, self).get_context_data(*args, **kwargs)
return context
def get_success_url(self):
return self.request.POST.get("next")
I didn't get what exactly your question is, and also don't know if it is your answer or not, but i just say it!
You should use your django form that you passed from view in your template to be able to validate the form after the submission of form.
and if your concern is how to show the form properly in they way you want, it has another solution. you can represent the form in the way you want like something below:
{% for field in form %}
<div class="input-group">
{% if field.name=="username" %}
<span class="input-group-addon"><i class="icon-user"></i></span>
<input id="id_username" type="text" class="form-control" name="username" value="" placeholder="username">
{% endif %}
{% if field.name=="password" %}
<span class="input-group-addon"><i class="icon-lock"></i></span>
<input id="id_password" type="password" class="form-control" name="password" placeholder="password">
{% endif %}
{% for error in field.errors %}
{{ error }}
{% endfor %}
</div>
{% endfor %}
As you can see, you can access the error of fields via field.errors and check the name of field with field.name!

Django - 405 POST not allowed

I have a form like so:
{% extends "interface/base.html" %}
{% load subscribertags %}
{% block title %}{{ object }}{% endblock %}
{% block center %}
<div class="page-header">
<h1>Редактирование меню <small>{% operator_name object.operator %}: {{ object }} ({{ object.slug }})</small></h1>
</div>
<!-- Modal -->
<div class="modal fade" id="itemModal" tabindex="-1" role="dialog" aria-labelledby="itemModalTitle" aria-hidden="true">
<form method="post">{% csrf_token %}
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="itemModalTitle">Добавить пункт</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="item_name">Действие</label>
<select class="form-control" name="action">
<option value="">----------</option>
{% for value, action in actions %}
<option value="{{ value }}">{{ action }}</option>
{% endfor %}
</select>
</div>
<div class="checkbox">
<label>
<input id='is_hidden' type="checkbox" name='is_hidden' > Спрятать
</label>
</div>
<div class="checkbox">
<label>
<input id='allow_back' type="checkbox" name='allow_back' > Пункт назад
</label>
</div>
<div class="form-group">
<label for="label">Метка</label>
<input type="text" class="form-control" id="label" placeholder="Название метки" name='slug'>
</div>
<div class="form-group">
<label for="params">Доп параметры</label>
<textarea type="text" class="form-control" id="params" placeholder="Дополнительные параметры" name='params'></textarea>
</div>
{% for code, language in languages %}
<div class="form-group">
<h5>{{ language }}</h5>
{% if code = object.default_language %}
<label for="text">Текст</label>
<input type="text" class="form-control" id="text" placeholder="Текст" name='text'>
<label for="result_text">Текст результата</label>
<input type="text" class="form-control" id="result_text" placeholder="Текст результата" name='result_text'>
{% else %}
<label for="text-{{ code }}">Текст</label>
<input type="text" class="form-control" id="text-{{ code }}" placeholder="Текст" name='text-{{ code }}'>
<label for="result_text-{{ code }}">Текст результата</label>
<input type="text" class="form-control" id="result_text-{{ code }}" placeholder="Текст результата" name='result_text-{{ code }}'>
{% endif %}
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="subbmit" class="btn btn-primary">Сохранить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</form>
</div><!-- /.modal -->
<div class="tree">
{% if object.item_set.count %}
<ul>
{% with object.item_set.all.0 as item %}
{% include "interactive/interface/menu_item.html" %}
{% endwith %}
</ul>
{% endif %}
</div>
{% endblock %}
SECOND PART:
{% load interactivetags %}
<li class="element-interactive-item{% if not item.is_visible %} i-hidden{% endif %}">
<span data-toggle="tooltip" title="{{ item.params }}" class='name'><i class="glyphicon glyphicon-{% item_icon item %}"></i> ({{ item.id }}) {{ item }} {% if item.slug %}({{ item.slug }}){% endif %}
<a class='tool item-tool' data-values='{% item_to_json item %}' data-toggle="modal" data-target="#itemModal" data-label="Редактировать: {{ item }}" href="#" data-href="{% url "interactive.views.item_update" pk=item.pk %}"><i class="glyphicon glyphicon-edit"></i></a>
<a class='tool item-tool' data-toggle="modal" data-target="#itemModal" data-label="Добавить пункт" href="#" <data-href="{% url "interactive.views.item_create" pk=object.pk parent_pk=item.pk %}"><i class="glyphicon glyphicon-plus"></i></a>
{% if item.is_leaf_node and not item.is_root_node%}
<a class='tool confirm' href="{% url "interactive.views.item_delete" pk=item.pk %}"><i class="glyphicon glyphicon-remove"></i></a>
{% endif %}
<a class='tool confirm' href="{% url "interactive.views.item_up" pk=item.pk %}"><i class="glyphicon glyphicon-arrow-up"></i></a>
<a class='tool confirm' href="{% url "interactive.views.item_down" pk=item.pk %}"><i class="glyphicon glyphicon-arrow-down"></i></a>
</span>
<ul>
{% for item in item.get_children %}
{% include "interactive/interface/menu_item.html" %}
{% endfor %}
</ul>
</li>
When I hit the Save/Сохранить button data isn't updated in the database for this form and I get
"POST /interactive/1/ HTTP/1.1" 405 0
Code that handles the request:
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseRedirect
from interactive.models import Menu, Item
from interactive.forms import UpdateItemForm
from interface.views import InterfaceMixin
from interactive.processors import ProcessorManager
from subscribers.models import Subscriber
from languages.models import Translate
class MenuList(InterfaceMixin, ListView):
model = Menu
name = u'Интерактивные меню'
index = MenuList.as_interface_view(template_name='interactive/interface/index.html')
class MenuItem(InterfaceMixin, DetailView):
""" Редактирование интерактивного меню """
model = Menu
def get_context_data(self, **kwargs):
kwargs['actions'] = ProcessorManager.actions()
kwargs['languages'] = Subscriber.LANGUAGES
return super(MenuItem, self).get_context_data(**kwargs)
menu = MenuItem.as_interface_view(item=MenuList, template_name='interactive/interface/item.html')
class ItemMixin:
#classmethod
def update_language(cls, attribute, text, context):
if text:
o, _ = Translate.objects.get_or_create(attribute=attribute, **context)
o.text = text
o.save()
class CreateItemView(ItemMixin, InterfaceMixin, CreateView):
menu = None
parent = None
model = Item
form_class = UpdateItemForm
auth = False
def get_success_url(self):
return reverse("interactive.views.menu", kwargs={'pk': self.menu.pk})
def post(self, request, *args, **kwargs):
pk = kwargs.get('pk')
parent_pk = kwargs.get('parent_pk')
self.menu = Menu.objects.get(pk=pk)
self.parent = Item.objects.get(pk=parent_pk)
return super(CreateItemView, self).post(request, *args, **kwargs)
def form_valid(self, form):
form.instance.menu = self.menu
form.instance.insert_at(self.parent, position='last-child')
form.instance.save()
ct = ContentType.objects.get_for_model(form.instance)
for code, _ in Subscriber.LANGUAGES:
text = self.request.POST.get('text-%s' % code)
result_text = self.request.POST.get('result_text-%s' % code)
context = dict(content_type=ct, object_id=form.instance.pk, language=code, operator=self.menu.operator)
self.update_language('text', text, context)
self.update_language('result_text', result_text, context)
return super(CreateItemView, self).form_valid(form)
def form_invalid(self, form):
return super(CreateItemView, self).form_valid(form)
item_create = CreateItemView.as_view()
class UpdateItemView(ItemMixin, InterfaceMixin, UpdateView):
""" Изменение пункта меню """
model = Item
form_class = UpdateItemForm
auth = False
def get_success_url(self):
return reverse("interactive.views.menu", kwargs={'pk': self.object.menu.pk})
def form_valid(self, form):
ct = ContentType.objects.get_for_model(self.object)
for code, _ in Subscriber.LANGUAGES:
text = self.request.POST.get('text-%s' % code)
result_text = self.request.POST.get('result_text-%s' % code)
context = dict(content_type=ct, object_id=self.object.pk, language=code)
self.update_language('text', text, context)
self.update_language('result_text', result_text, context)
return super(UpdateItemView, self).form_valid(form)
def form_invalid(self, form):
return super(UpdateItemView, self).form_valid(form)
item_update = UpdateItemView.as_view()
class DeleteItemView(InterfaceMixin, DeleteView):
model = Item
auth = False
def get_success_url(self):
return reverse("interactive.views.menu", kwargs={'pk': self.object.menu.pk})
def get(self, request, *args, **kwargs):
return self.delete(request, *args, **kwargs)
item_delete = DeleteItemView.as_view()
class UpDownItemVew(DetailView):
action = None
model = Item
auth = False
def get(self, request, *args, **kwargs):
item = self.get_object()
if self.action == 'left':
other = item.get_previous_sibling()
else:
other = item.get_next_sibling()
item.move_to(other, position=self.action)
return HttpResponseRedirect(reverse("interactive.views.menu", kwargs={'pk': item.menu.pk}))
item_up = UpDownItemVew.as_view(action='left')
item_down = UpDownItemVew.as_view(action='right')
URL patterns:
urlpatterns = patterns(
'interactive.views',
(r'^(?P<pk>\d+)/(?P<parent_pk>\d+)/additem/$', "item_create"),
(r'^item/(?P<pk>\d+)/delete/$', "item_delete"),
(r'^item/(?P<pk>\d+)/up/$', "item_up"),
(r'^item/(?P<pk>\d+)/down/$', "item_down"),
(r'^item/(?P<pk>\d+)/$', "item_update"),
(r'^(?P<pk>\d+)/$', "menu"),
(r'^$', 'index'),
)
This code perfectly work on a production server, but wasn't uploaded by me and uses nginx as http server.
I am running it on local server using python manage.py runserver

Using Django registration with a Flat UI template

I have created a template design for signup page using Flat UI. Now i want to use Django registration to register a user. I have goggled various resources but they are very complex and using Django inbuilt form to create a form.
I need simple steps that i can follow
signup.html(home/django/mysite/templates)
{% extends "base.html" %}
{% block title %}Signup page{% endblock %}
{% block content %}
<div class="container" style="width:500px">
<h3 style="margin-top:100px">Sign Up</h3>
<hr>
<div class="login-form">
<form action="" method="post">
<div class="control-group span3" style="width:400px" >
<input type="text" value="" placeholder="Enter your name" id="name" style="width:400px;padding-bottom:15px;margin-bottom:10px" >
<i class="input-icon fui-user" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px" >
<input type="text" value="" placeholder="Your E-mail" id="email" style="width:400px;padding-bottom:15px;margin-bottom:10px" >
<i class="input-icon fui-mail" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px">
<input type="password" value="" placeholder="Password" id="pass" style="width:400px;padding-bottom:15px;margin-bottom:10px">
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div class="control-group span3" style="width:400px">
<input type="password" value="" placeholder="Confirm Password" id="login-pass" style="width:400px;padding-bottom:15px;margin-bottom:10px">
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div style="text-align:center">
<a class="btn btn-hg btn-primary btn-wide" href="#">Sign Up</a>
<!--<a class="login-link" href="#">Lost your password ?</a> -->
</div>
</form>
</div><!-- /login-form -->
</div> <!-- /container -->
{% endblock content %}
views.py
def signup(request):
return render(request, 'signup.html')
urls.py
urlpatterns = patterns('',
url(r'^signup/$', views.signup),)
What i should write in views.py or models.py to register a user using django registration.
You can use django registration together with custom html/css through django forms. Here are the steps:
Provided you have included relevant imports, your urls.py looks fine so no changes needed.
Create a forms.py file in the same folder as your views.py and add the following code into forms.py:
from django import forms
class Signup_form(forms.Form):
# CSS styles should not be inline. i've moved your style contents under a 'form-control' class
name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'type':'text', 'placeholder':'Enter your name', 'id':'name', 'name':'name', 'class' : 'form-control'}))
email = forms.EmailField(label="Email address", widget=forms.TextInput(attrs={'type':'text', 'placeholder':'Your E-mail', 'id':'email', 'name':'email', 'class' : 'form-control'}))
pass1 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Password', 'id':'pass1', 'name':'pass1', 'class' : 'form-control'}))
pass2 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Confirm Password', 'id':'pass2', 'name':'pass2', 'class' : 'form-control'}))
3.In your views.py file, you have to link pass the Signup_form to your views layer. Change your views.py file to the following:
from forms import Signup_form
def signup(request):
form = Signup_form()
name = request.POST.get('name','')
email = request.POST.get('email', '')
pass1 = request.POST.get('pass1', '')
pass2 = request.POST.get('pass2', '')
# Do some validations here
user = User.objects.create_user(name, email, pass2)
if user:
user.save()
return render(request, 'signup.html', {'form': form})
4.Now that you have passed your Signup_form object in views layer, you can use django template tags to display them in your signup.html page. Here's how your signup.html could look like:
{% extends "base.html" %}
<link rel="stylesheet" href="{% static 'css/custom.css' %}">
{% block title %}Signup page{% endblock %}
{% block content %}
<div class="container" style="width:500px">
<h3 style="margin-top:100px">Sign Up</h3>
<hr>
<div class="login-form">
<form action="" method="post"> {% csrf_token %}
<div class="control-group span3" style="width:400px" >
{{ form.name.errors }}
{{ form.name }}
<i class="input-icon fui-user" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px" >
{{ form.email.errors }}
{{ form.email }}
<i class="input-icon fui-mail" for="login-name"></i>
</div>
<div class="control-group span3" style="width:400px">
{{ form.pass1.errors }}
{{ forms.pass2 }}
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div class="control-group span3" style="width:400px">
{{ form.pass2.errors }}
{{ forms.pass2 }}
<i class="input-icon fui-lock" for="login-pass"></i>
</div>
<div style="text-align:center">
<input type="submit" class="btn btn-hg btn-primary btn-wide" value="Sign Up">
<!--<a class="login-link" href="#">Lost your password ?</a> -->
</div>
</form>
</div><!-- /login-form -->
</div> <!-- /container -->
{% endblock content %}
5.Since i have earlier moved your CSS styles(in point 2) into a 'form-control' class, now we will place it back by adding your styles in a external custom.css file. Create a custom.css file in the directory static/css/custom.css and add the following into it:
.form-control {
width:400px;
padding-bottom:15px;
margin-bottom:10px;
}
In your Views.py
from django.contrib.auth.models import User
def signup(request):
username = request.POST.get("name","")
password = request.POST.get("pass","")
login_pass = request.POST.get("login-pass","")
email = request.POST.get("email","")
if username != "" or password != "" or login_pass != "":
#do some validations
user = User.objects.create_user(username, email, password)
if user:
user.is_active = True
user.save()
return render(request, 'signup.html')
Above code will register a new user into system
If you would have use Django forms then all the validations will be done by Django.
Note: Please add name attribute to your HTML fields required for getting vaLues in request.POST. Also point your HTMl form action to "signup" view