Я новичок в django, я пытаюсь создать систему регистрации пользователей и входа в систему.Я могу зарегистрировать пользователей, но каким-то образом они не входят в систему. Система выхода также работает нормально.Я не знаю, что мне не хватает
вот мой код
def register(request):
if request.method == 'POST':
data={}
firstname = request.POST['firstname']
surname = request.POST['surname']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
confirm = request.POST['confirm']
if password == confirm:
# check username, so that we do not repeat usernames
if User.objects.filter(username=username).exists():
data['error'] = "This username is taken"
print(data)
else:
if User.objects.filter(email=email).exists():
data['error'] = "This email is already assigned to another user"
print(data)
else:
user = User.objects.create_user(username=username, email=email, first_name=firstname, last_name=surname)
if password:
user.set_password(password)
else:
user.set_unusable_password()
user.save()
user = authenticate(request, username=username, password=password)
login(request, user)
data['success'] = "You are successfully registered"
print(data)
else:
data['error'] = "passwords do not match"
print(data)
return HttpResponse(simplejson.dumps(data), content_type = "application/json")
def my_login(request):
if request.method == 'POST':
data = {}
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
print("it all checks out so far")
if user is None:
print('no user')
if user is not None:
if user.is_active:
print("user exists")
login(request, user)
print("you are logged in")
else:
data['error'] = "username or password incorrect"
print(data)
return HttpResponse(simplejson.dumps(data), content_type = "application/json")
def logout(request):
if request.method == 'POST':
auth.logout(request)
return redirect('index')
вот HTML
<section id="logging">
<div class="user-container">
<!-- to make the logout and login dynamic-->
{% if user.is_authenticated %}
<div class=" log">
<a href="{ url 'accounts/dashboard'}" class="register">Welcome {{user.username}}</a>
</div>
<div></div> <!--this is to make a div for row grid-->
<!--create the logout and its form-->
<div class="log">
<a href="javascript:{document.getElementById('logout').submit()}"> logout
</a>
<form action="{% url 'logout' %}" method="POST" id="logout">
{% csrf_token %}
<input type="hidden">
</form>
</div>
{% else %}
<div></div>
<!-- link for registration-->
<div class=" log">
<i class="fas fa-user"></i> <a href="#" class="register">register</a>
</div>
<!--modal for register-->
<div class="modal" id="modal">
<div class="modal-content">
<!--closing button-->
<a href="#" class="close-window"><i class="fas fa-times"></i></a>
<!--top bar-->
<div class="top-form">
<i class="fas fa-user"></i> <a href="#">register</a>
</div>
<!--form-->
<div class="form-container">
<form id="register-form">
{% csrf_token %} <!--this isto secure my form for forgery -->
<!-- div for error messages-->
<div class="messages"></div>
<!--form content-->
<div class="form">
<label for="firstname">name</label> <br>
<input type="text" name="firstname" class="name" required>
</div>
<div class="form">
<label for="surname">surname</label><br>
<input type="text" name="surname" class="surname" required>
</div>
<div class="form">
<label for="email">email</label><br>
<input type="text" name="email" class="email" required>
</div>
<div class="form">
<label for="">username</label><br>
<input type="text" name="username" class="user" required>
</div>
<div class="form">
<label for="password">password</label><br>
<input type="text" name="password" class="password" required>
</div>
<div class="form">
<label for="confirm">confirm password</label><br>
<input type="text" name="confirm" class="confirm" required>
</div>
<div class="form">
<input type="submit" value="submit" class="form-submit register-submit">
</div>
</form>
</div>
</div>
</div>
<!--login link-->
<div class="login log">
<i class="fas fa-sign-in-alt" class="login"></i> <a href="#">login</a>
</div>
<!--modal for rlogin-->
<div class="modal" id="modal-login">
<div class="modal-content2">
<!--closing button-->
<a href="#" class="close-window2"><i class="fas fa-times"></i></a>
<!--top bar-->
<div class="top-form">
<i class="fas fa-sign-in-alt"></i> <a href="#">login</a>
</div>
<!--form-->
<div class="form-container formo">
<form id="login-form">
{% csrf_token %} <!--this is to secure my form for forgery -->
<!-- div for error messages-->
<div class="messages"></div>
<div class="form">
<label for="">username</label><br>
<input type="text" name="username" class="user" placeholder="username/email" required>
</div>
<div class="form">
<label for="password">password</label><br>
<input type="text" name="password" class="password" required>
</div>
<div class="forgot">
<div class="userr"><a href="#">forgot username</a></div>
<div class="passw"><a href="#">forgot password</a></div>
</div>
<div class="form">
<input type="submit" value="submit" class="form-submit log-submit">
</div>
</form>
</div>
<!--form for forgot password or username-->
<div class="form-container2">
<div class="form">
<label for="">email</label><br>
<input type="text" name="email" class="email" placeholder="email" required>
</div>
<div class="form">
<input type="submit" value="submit" class="form-submit">
</div>
</div>
</div>
</div>
{% endif %}
</div>
здесьurls.py
urlpatterns = [
path('register',views.register,name='register'),
path('login',views.my_login,name='login'),
path('logout',views.logout,name='logout'),
path('dashboard',views.dashboard,name='dashboard')
]
вот мой аякс
$(document).on('submit', '#register-form', function(e){
// to prevent the page to reload
e.preventDefault();
$.ajax({
type: 'POST',
url:'/accounts/register',
data:{
firstname:$('.name').val(),
surname:$('.surname').val(),
email:$('.email').val(),
username:$('.user').val(),
password:$('.password').val(),
confirm:$('.confirm').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
// I will get messages in the backend
},
success:function(data){
if(data.success){
setTimeout(function() {
$('#modal').fadeOut('fast');
location.reload();
}, 2000);
$('.messages').append(data.success);
} else {
$('.messages').show();
$('.messages').empty();
$('.messages').append(data.error);
}
//console.log(data)
//('#modal').hide(); // hide the modal after 2s
}
});
});
// aJAX for the login page
$(document).on('submit', '#login-form', function(e){
// to prevent the page to reload
e.preventDefault();
$.ajax({
type: 'POST',
url:'/accounts/login',
data:{
username:$('.user').val(),
password:$('.password').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
// I will get messages in the backend
},
success:function(data){
if(data.error){
$('.messages').hide();
$('.messages').empty();
$('.messages').append(data.error);
$('.messages').show();
}else {
setTimeout(function() {
$('#modal-login').fadeOut('fast');
location.reload();
}, 1000);
$('.messages').hide();
}
}
});
})
Буду очень признателен за вашу помощь.Я изучаю это, используя HTML-форму, так как я понимаю, как заставить его работать с ajax