when I insert username and password, it doesn't redirect to home page and stays on the login page, and its URL displays such messages
http://localhost:8000/login/?csrfmiddlewaretoken=B6RMXDzgZjnk2QzbmbcesMqsRUOtVH3Q1FBaS1HCB6CXXujpbOziiHLH8VR1oLzC&username=admin&password=laughonloud24
in Powershell, it shows like this
System check identified no issues (0 silenced).
May 25, 2018 - 11:50:07
Django version 2.0.5, using settings 'a.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[25/May/2018 11:50:10] "GET /login/?csrfmiddlewaretoken=B6RMXDzgZjnk2QzbmbcesMqsRUOtVH3Q1FBaS1HCB6CXXujpbOziiHLH8VR1oLzC&username=admin&password=laughonloud24 HTTP/1.1" 200 446
Performing system checks...
there is no error though, but it doesn't behave the way i want it to..
models.py
from django.db import models
# Create your models here.
class login_model(models.Model):
username = models.CharField(max_length=200)
password = models.CharField(max_length=200)
forms.py
from django import forms
from .models import login_model
class LoginForm(forms.ModelForm):
class Meta:
model = login_model
fields = ['username','password']
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('login/',views.login_view,name = 'login_url' ),
path('',views.home, name = 'home_url'),
]
views.py
from django.shortcuts import render,redirect
from .forms import LoginForm
from django.contrib.auth import authenticate,login
# Create your views here.
def home(request):
return render(request,'home.html')
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST or None)
if form.is_valid():
uusername = form.cleaned_data.get('username')
ppassword = form.cleaned_data.get('password')
user = authenticate(request,username=uusername,password=ppassword)
if user is None:
login(request,user)
return redirect('home url')
else:
print('Error')
else:
form = LoginForm()
return render(request,'login.html',{'form':form})
templates
login.html
<form>
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Login">
</form>
home.html
{% if user.is_authenticated %}
<h1>Hi {{user.username}} </h1>
{% else %}
<h1> Hi Ola Amigo </h1>
<p>Please Login Login </p>
{% endif %}
You should set form's method as POST, otherwise it's GET by default:
<form action="" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Login">
</form>
Related
Login cannot be done in my app.I wrote in views.py
from django.shortcuts import render,redirect
from django.urls import reverse
from app.forms import RegisterForm,LoginForm
from app.models import Data
from app.forms import DataForm
from django.db.models import Q
def index(request):
data = Data.objects.order_by('-created_at')
form = RegisterForm()
loginform = LoginForm()
dataform = DataForm()
return render(request, 'index.html',{'data':data,'form':form,'loginform':loginform,'dataform':dataform,'user': request.user})
in index.html
<section id="top">
{% if user and not user.is_anonymous %}
<p>Hello</p>
<h3>{{ user.username }}</h3>
{% else %}
<form action="{% url 'app:index' %}" method="POST">
{{ loginform.non_field_errors }}
{% for field in loginform %}
{{ field }}
{{ field.errors }}
{% endfor %}
<button type="submit">LOGIN</button>
{% csrf_token %}
</form>
{% endif %}
</section>
in forms.py
from django import forms
from django.contrib.auth.forms import (
AuthenticationForm
)
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
field.widget.attrs['placeholder'] = field.label
in child's app's urls.py
from django.urls import include, path
from . import views
from django.contrib.auth.views import login
app_name = 'app'
urlpatterns = [
path('index', views.index,name='index'),
]
in parent's app's urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('app/',include('app.urls') ),
]
When I login from loginform,if statement of {% if user and not user.is_anonymous %} did not become true.But when I login in admin site, the statement become true.When I put LOGIN button, no error happens.I really cannot understand what is wrong.How should I fix this?
Your index view doesn't do anything when a POST request is submitted. It just initialises empty forms and returns them. You need to actually process the data that is submitted, authenticate the user and call the login method:
def index(request):
if request.method == 'POST':
loginform = LoginForm(request, data=request.POST)
if loginform.is_valid(): # this authenticates the user
user = loginform.get_user()
# redirect to success view or just render index.html
return render(request, 'index.html', {'user': user})
# else not needed, we go to the end and return the form with errors
else: # request method is 'GET'
loginform = LoginForm()
dataform = ...
...
return render(request, 'index.html',{'data':data,'form':form,'loginform':loginform,'dataform':dataform,'user': request.user})
I have hard time with such a easy thing (I guess).
My aim is to create two subpages with 2 different forms yet connected with the same user model:
/account/register.html - page only to manage registration (create user with login,email,password)
/account/questionnaire.html - page for UPDATING the same user information such as age,weight,height etc.
I've got 'POST' communicates in server log but nothing appears when I'm checking up django admin site.
models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
age = models.PositiveIntegerField(blank=False)
weight = models.PositiveIntegerField(blank=False)
height = models.PositiveIntegerField(blank=False)
forms.py
from django import forms
from django.core import validators
from django.contrib.auth.models import User
from account.models import UserProfile
class RegisterUserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ('username','email','password')
class RegisterUserInfoForm(forms.ModelForm):
class Meta():
model = UserProfile
fields = ('age','weight','height')
views.py
from django.shortcuts import render
from account.forms import RegisterUserForm, RegisterUserInfoForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
def register(request):
registered = False
if request.method == 'POST':
user_form = RegisterUserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = RegisterUserForm()
return render(request,'account/register.html',{
'user_form':user_form,
'registered':registered,
})
#login_required
def questionnaire(request):
if request.method == 'POST':
profile_form = RegisterUserInfoForm(request.POST, instance=request.user)
if profile_form.is_valid():
profile_form.save()
else:
print(profile_form.errors)
else:
profile_form = RegisterUserInfoForm(instance=request.user)
return render(request,'account/questionnaire.html',{
'profile_form':profile_form,
})
register.html
{% extends 'base.html' %}
{% block body_block %}
<div class="container">
<h1>Register</h1>
<form method="post">
{% csrf_token %}
{{ user_form.as_p }}
<input type="submit" name="btn btn-primary" value="Save">
</form>
</div>
{% endblock %}
questionnaire.html
{% extends 'base.html' %}
{% block body_block %}
<div class="container">
<h1>questionnaire</h1>
<form method="post">
{% csrf_token %}
{{ profile_form.as_p }}
<input type="submit" name="" value="Save">
</form>
</div>
{% endblock %}
Your view doesn't receive a POST request because you didn't provide an action attribute to your form tag. So, your form passes your POST request nowhere. Try it like this:
<form action="" method="post">
{% csrf_token %}
{{ user_form.as_p }}
<input type="submit" name="btn btn-primary" value="Save">
</form>
Also, you should definitely check django's built-in generic views: CreateView and UpdateView. They serve exactly for such purposes and makes almost everything for you.
I am new to Django. i am unable to store the user input values into the postgres DB. I have created a tables using Models.py file and create a user interface using template file .How can i pass the vaues to the database using view.py file . someone help me plsz
For simple log-in
in users/views.py
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, logout,login
from django.http import HttpResponse, HttpResponseRedirect
def user_login(request):
if request.method == "POST":
phone = request.POST.get('phone')
password = request.POST.get('password')
user = authenticate(username=phone, password=password)
if user:
login(request,user)
return HttpResponseRedirect('/users/home')
else:
error = " Sorry! Phone Number and Password didn't match, Please try again ! "
return render(request, 'login/index.html',{'error':error})
else:
return render(request, 'login/index.html')
and in template login/index.html
<html>
<body>
{% if error %}
{{ error }}
{% endif %}
<form method="post" action="/users/login/">{% csrf_token %}
<input type=text placeholder="PhoneNo" name="phone">
<input type=password placeholder="Password" name="password">
<input type="submit" value="login">
</body>
</html>
for registration
login/signup.html
<html>
<body>
<form method=post action="users/signup/">{% csrf_token %}
<input type="text" name="phone" placeholde="Phone No">
<input type="text" name="email" placeholde="Email">
<input type="text" name="password1" placeholde="Password">
<input type="text" name="password2" placeholde="Password Again">
<input type="submit" value="signup">
</form>
</body>
</html>
in users/views.py
def users_signup(request):
if request.method == 'POST':
email = request.POST.get('email')
phone = request.POST.get('phone')
pass_1 = request.POST.get('password1')
pass_2 = request.POST.get('password2')
if pass_1 == pass_2:
user = User.objects.create_user(
username=phone,
email=email,
password=pass_1,
)
return HttpResponseRedirect("/")
else:
error = " Password Mismatch "
return render(request, 'login/signup.html',{"error":error})
else:
return render(request, 'login/signup.html')
main urls.py in main project folder where there is settings.py file would be
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^users/', include('users.urls')),
]
also url.py of app say "users"
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^login/', "users.views.user_login", name='login_url'),
url(r'^signup/', "users.views.user_signup", name='signup_url'),
)
Assuming your UI is based on a form, all you need to do in view.py is to handle a POST request which is sent from client when this form is submitted. So you define a method (say signup) which would get passed a request and possibly other parameters if needed. In it you do necessary validation (i.e. check if this user already exists) and return either new page with error messages via render() or a redirect to the next page if all is good.
More details in official tutorial which is quite good as correctly pointed out by #anuragal
I am new to Django (1.5) and got stucked at assumingly basic stuff. I try to create a User using following code.
VIEW:
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib import auth
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
def sign_up(request):
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = User.objects.create_user(username=username, password=password)
user.save()
return HttpResponseRedirect(reverse('account:login'))
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
return render_to_response('account/sign_up.html', args, context_instance=RequestContext(request))
ACCORDANT TEMPLATE:
<html>
...
<div id="sign_up"> {% block extension1 %}
</form action="/account/sign_up/" method="post"> {% csrf_token %}
{{ form }} <br/>
<input type="submit" value="Sign up"/>
</form> {% endblock %}
</div>
If I hit the 'Sign up' button just nothing happens. What basic thing am I missing. I would appreaciate a tiny lesson about this. Thanks.
I have an app with name account which contain all the models, views, and forms to be used in registering and signing in users.
I have a template that is located outside the app folder that suppose to contain all the forms in account app.
I am having problem trying to get the forms showing in the template.
Can someone help me?
Here are some snippet of codes:
accounts/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# Safe from injection, etc.
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField(required = True)
first_name = forms.CharField(max_length=30, required=True)
last_name = forms.CharField(max_length=30, required=True)
class Meta:
model = User
fields = ('username','email','password1', 'password2','first_name','last_name')
def save(self, commit=True):
user = super(UserRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
accounts/view.py
from forms import UserRegistrationForm
def register_user(request):
if request.POST:
form = UserRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
form = UserRegistrationForm()
args = {}
# prevent forgery
args.update(csrf(request))
# empty form
args['form'] = form
return render_to_response('signup.html', args)
def register_success(request):
return render_to_response('signup_success.html')
and finally the template, which is not in account folder. It's in the same folder as settings.py
signup.html
{% extends "base.html" %}
{% block content %}
<form action="" method="post"> {% csrf_token %}
<ul>
{{accounts.form.as_ul}}
</ul>
<input type="submit" name="submit" value="Register">
</form>
{% endblock %}
UPDATE
Upon obtaining permission to move the template from the project manager, I moved it to accounts/template, and changed the render to response address.
I have new problem of form not submitting now.
OMG what's going on??
The template should not be in the same directory as settings.py.
It should be in a directory within the accounts app: accounts/templates/signup/html.
If you've configured your Django project correctly then Django should pickup the template after restarting the web server.
as I see you are passing form variable to template,
but you are trying to use accounts.form.
Hope this helps.
Ok the problem lies on my signup.html file. It should have script for onclick and the form should have an id.
{% extends "base.html" %}
{% block content %}
<form action="" method="post" id="form"> {% csrf_token %}
<ul>
{{accounts.form.as_ul}}
</ul>
<input type="submit" name="submit" value="Register" onclick="submit()">
</form>
<script>
function submit() {document.forms["form"].submit();}
</script>
{% endblock %}