I'm making a sign up page.
html
{{message}}
<form action="{% url 'signup' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input class="form-control" autofocus type="text" name="username" placeholder="Username">
</div>
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="Email Address">
</div>
<div class="form-group">
<input class="form-control" type="password" name="password" placeholder="Password">
</div>
<div class="form-group">
<input class="form-control" type="password" name="confirmation" placeholder="Confirm Password">
</div>
<input class="btn btn-primary" type="submit" value="Register">
</form>
django
def signup(request):
if request.method == 'POST':
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
confirmation = request.POST['confirmation']
if password != confirmation:
return render(request, 'lms/signup.html', {
'message': 'Passwords must match.'
})
else:
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, 'lms/signup.html', {
'message': 'Username already taken.'
})
return HttpResponseRedirect(reverse('index'))
else:
return render(request, 'lms/signup.html')
When I submit the form, I get this error:
OperationalError at /signup
no such table: lms_user
I've already done the migrations command. I also deleted tried deleting migrations and pycache folder's content and db.sqlite3 file and did the migrations again but that didn't help either.
Related
So, I've tried a couple of times to register and back to login. Always failed to log in except for superuser or admin. Already checked in Django admin that the user that I have registered already there.
There is no error message in the terminal when login or register a user. Except for the error message that I've created in views.py if log in unsuccessful.
So, let's take a look into my code. First views.py
from django.contrib.auth import authenticate, login, logout
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
# Check if authenticate successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
context = {
"message": "Invalid username and/or password"
}
return render(request, "page/login.html", context)
else:
return render(request, "page/login.html")
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches with password confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
context = {
"message": "Both password must match"
}
return render(request, "page/register.html", context)
# Attempt to create new user
try:
user = User.objects.create_user(username)
user.save()
except IntegrityError:
context = {
"message": "Username already exist"
}
return render(request, "page/register.html", context)
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "page/register.html")
And below is the template both for log in and register.
<!-- Logintemplate -->
<div class="login-register">
<div class="head">
Log in to Explore
</div>
<form action="{% url 'login' %}" method="post">
{% csrf_token %}
<div class="form-floating mb-3">
<input type="text" class="form-control" id="username" name="username" placeholder="Username"">
<label for="username">Username</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
<label for="password">Password</label>
</div>
<div class="d-grid gap-2">
<input class="btn btn-outline-success" type="submit" value="Login">
</div>
<div id="log-reg">
Sign Up
</div>
</form>
{% if message %}
<div class="alert alert-danger mt-4" role="alert">
{{ message }}
</div>
{% endif %}
</div>
<!-- Register template -->
<div class="login-register">
<div class="head">
Create your account
</div>
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
<div class="form-floating mb-3">
<input type="text" class="form-control" autofocus type="text" name="username" id="username" placeholder="Username">
<label for="username">Username</label>
</div>
<div class="form-floating mb-3">
<input type="email" class="form-control" name="email" id="email" placeholder="name#example.com">
<label for="email">Email address</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
<label for="password">Password</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="confirmation" name="confirmation" placeholder="Confirm Password">
<label for="confirmation">Password Confirmation</label>
</div>
<div class="d-grid gap-2">
<input class="btn btn-outline-success" type="submit" value="Register">
</div>
<div id="log-reg">
Already have an account? Log In here.
</div>
</form>
{% if message %}
<div class="alert alert-danger mt-4" role="alert">
{{ message }}
</div>
{% endif %}
</div>
Is there something I missed or action that I need to perform?
You create the user as follows:
user = User.objects.create_user(username)
This creates a user without a password which means your user would not be able to login. pass the username and password both to the create_user method:
user = User.objects.create_user(username=username, password=password)
Note: Use a form class to make forms in Django to perform validation and cleaning. For making a user use the
UserCreationForm
I have a problem with updating an existing user object in my database. When I update and change the user object it saves and everything is looking ok but when I change the user and I want to login this user does not authenticate. Here is my code:
def profile_edit(request):
user = request.user
profile = request.user.profile
context = {
'user': user
}
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
email = request.POST.get('email')
user.profile.address = request.POST.get('address')
user.profile.phone = request.POST.get('phone')
user.set_password('password')
user.username = username
user.save()
user.profile.save()
authenticate(user)
context = {
'profile': profile
}
return render(request, 'helpdesk/profile.html', context)
return render(request, 'helpdesk/profile_edit.html', context)
and login view:
def login_view(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
profile = request.user.profile
context = {
'profile': profile
}
return render(request, 'helpdesk/user_desk.html', context)
else:
context = {
'username': username,
'error': 'user not find!'
}
else:
context = {}
return render(request, 'helpdesk/login.html', context)
When updating the password you are actually setting the string 'password' as password and not the submitted password. Change user.set_password('password') to user.set_password(password) to correct this.
<form action="" style="font-size: 2cm" method="post">
{% csrf_token %}
<div class="row" style="margin: 7px">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="username" id="first_name" class="form-control input-sm" placeholder="username:{{ request.user.username }}">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="address" id="last_name" class="form-control input-sm" placeholder="address:{{ request.user.address }}">
</div>
</div>
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control input-sm" placeholder="email: {{ request.user.email }}">
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-sm" placeholder="Password">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="phone" id="password_confirmation" class="form-control input-sm" placeholder="phone:{{ request.user.phone }}">
</div>
</div>
</div>
<input type="submit" value="EDIT" class="btn btn-info btn-block" style="background-color: #0d0d0d; border-color: #0d0d0d">
</form>
i started to learn django,
im getting The view lessons.views.login didn't return an HttpResponse object. It returned None instead.
i dont know where i'm making mistake.
my HTML codes
<div class="formBx">
<form method="POST">
{% csrf_token %}
<h2>Sign In</h2>
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" name="" value="Login">
<p class="signup">Don't have an Account?Sign Up.</p>
</form>
</div>
</div>
<div class="user signUpBx">
<div class="formBx">
<form method="POST">
{% csrf_token %}
<h2>Create an account</h2>
<input type="text" name="username1" placeholder="Username">
<input type="email" name="email" placeholder="E-mail">
<input type="password" name="password1" placeholder="Create Password">
<input type="password" name="confirm" placeholder="Confirm Password">
<input type="submit" name="" value="Register">
<p class="signup">Already Have an Account?Sign In.</p>
</form>
</div>
<div class="imgBx"><img src="{% static 'img/logbg2.jpg' %}"></div>
</div>
</div>
My views.py codes
def login(request):
if request.method == "GET":
return render( request,"login.html")
if request.method == "POST":
if request.POST.get("submit") == "Login":
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(username = username,password=password)
if user is None:
messages.info(request,"Username or password is incorrect")
return render(request,"login.html")
messages.success("Logged In")
login(request,user)
return render(request,"index.html")
elif request.POST.get("submit") == "Register":
if request.method == "POST":
username = request.POST["username1"]
email = request.POST["email"]
password = request.POST["password1"]
confirm = request.POST["confirm"]
if password and confirm and password != confirm:
newUser = (User.objects.create_user(username,email,password))
newUser.save()
login(request,newUser)
return render(request,"login.html")
return render(request,"login.html")
so how can i solve this problem?
After POST method signup page always redirects to same page without printing any message or redirecting to homepage or login page but I am tracing it in every steps by printing something to check how it is working. But I can signup a new user using python shell.
Terminal is giving me only this:
[28/Nov/2019 15:36:26] "GET / HTTP/1.1" 200 2574
[28/Nov/2019 15:36:46] "POST / HTTP/1.1" 200 2574
def signup(request):
if request.user.is_authenticated:
return render(request,'/',{})
form = UserForm(request.POST or None)
if request.method == 'POST':
print("step 2")
if form.is_valid():
user = form.save(commit= False)
username= form.cleaned_data['username']
password= form.cleaned_data['password']
user.set_password(password)
user.save()
authenticate(username= username, password= password)
Profile.objects.create(
user= user,
full_name=form.cleaned_data['full_name'],
codeforces_id= form.cleaned_data['codeforces_id'],
Uva_Id = form.cleaned_data['Uva_Id'],
points = 0,
department= form.cleaned_data['department']
)
if user is not None:
if user.is_active:
login(request,user)
return redirect('/')
return render(request, 'signup.html',{'msg':'Invalid'})
else:
error = form.errors
print("error step")
return render(request, 'signup.html',{'msg':error})
else:
return render(request,'signup.html',{})
forms.py:
class UserForm(forms.ModelForm):
password = forms.CharField(widget= forms.PasswordInput)
full_name = forms.CharField(required= True)
codeforces_id = forms.CharField(required= True)
Uva_Id = forms.CharField(required= True)
department = forms.CharField(required= True)
class Meta:
model = User
fields=('username','email','password','full_name','codeforces_id','Uva_Id','department')
signup.html:
<body>
<div class="wrapper">
<div class="inner" style="width: 500px;">
{% block content %}
<form action="" method="post" style="padding-top: 40px; padding-bottom: 50px">
{% csrf_token %}
<h3 style="margin-bottom: 20px">New Account?</h3>
<div class="form-group">
<label for="username" class="control-label">Username</label>
<input type="text" class="form-control" name="username" placeholder="username">
</div>
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input type="text" class="form-control" name="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password" class="control-label">password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group">
<label for="full_name" class="control-label">fullname</label>
<input type="text" class="form-control" name="full_name" placeholder="Full Name">
</div>
<div class="form-group">
<label for="codeforces_id" class="control-label">codeforces_id</label>
<input type="text" class="form-control" name="codeforces_id" placeholder="codeforces_id">
</div>
<div class="form-group">
<label for="Uva_Id" class="control-label">Uva_Id</label>
<input type="text" class="form-control" name="Uva_Id" placeholder="uva_id">
</div>
<div class="form-group">
<label for="department" class="control-label">department</label>
<input type="text" class="form-control" name="department" placeholder="department">
</div>
<button type="submit" style="margin-top:20px">
<span>Register</span>
</button>
<p style="color: red">{{ msg }}</p>
<a style="float: right" href="/login">Already have an account</a>
</form>
{% endblock %}
</div>
</div>
</body>
Updated:
url.py
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^login/$',views.Login,name= 'Login'),
url(r'^signup/$',views.signup,name='signup'),
url(r'^logout/$',views.Logout,name='logout'),
You havent included the url that the form should hit on POST
[...]
<form action="{% url 'name-of-the-url-that-leads-to-your-view' %}" method="post" style
[...]
I suppose that the problem of this error is hidden in template. Here is my form:
<form class="form-horizontal loginFrm" action="/login/" method="post">
{% csrf_token %}
<div class="control-group">
<input type="text" id="inputEmail" placeholder="Email" name = "username">
</div>
<div class="control-group">
<input type="password" id="inputPassword" placeholder="Password" name = "password">
</div>
<div class="control-group">
<label class="checkbox">
<input type="checkbox"> Remember me
</label>
</div>
<input type="submit" class="btn btn-success" value="Sign in">
</form>
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
And my login view:
def login(request):
args = {}
args.update(csrf(request))
if request.POST:
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
args['username'] = username
return HttpResponseRedirect('/', args, context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/', args, context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/',args,context_instance=RequestContext(request))
In my last project, it worked correctly. But here is this error.
View the html source on your page with the rendered login form and confirm that you have a hidden field with the csrf token.
Something like this:
<input type='hidden' name='csrfmiddlewaretoken' value='NzYXoXbN9beogdB6gf22rNXkTNQd6Jri' />
It's possible that the view you have is not passing the context_instance. It depends which method you are using to render the view in the first place.
You could use:
return render_to_response('my_template.html',
context_instance=RequestContext(request))
Or the easier render() which will automatically use RequestContext
return render(request, 'my_template.html')
as a case you can use ensure_csrf_cookie view decorator.