我试图呈现登录和注册视图在一个单一的模板中使用变量赋值和如果。我很抱歉,如果这是一个新手的错误,我很新的这一点。
github存储库-https://github.com/varundhand/DevSearch
我的urls.py:-
urlpatterns = [
path('login/',views.loginUser,name='login'),
path('logout/',views.logoutUser,name='logout'),
path('register/',views.registerUser,name='register'),
path('',views.profiles,name='profiles'),
path('profile/<str:pk>/',views.userProfile,name='user-profile'),
]
我的views.py:-
def loginUser(request):
page = "login"
if request.user.is_authenticated:
return redirect('profiles')
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
try:
user = User.objects.get(username=username)
except:
messages.error(request,'Username doesnt exist')
user = authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect ('profiles')
else:
messages.error(request,'Username/Password incorrect')
context = {page:'page'}
return render(request, 'users/login_register.html', context)
def logoutUser(request):
logout(request)
messages.error(request,'User was logged out!')
return redirect('login')
def registerUser(request):
page = "register"
context= {page:'page'}
return render(request,'users/login_register.html', context)
我的html模板文件:-
{% extends 'main.html' %}
{% block content %}
{% if page == "register" %}
<h1>Register User</h1>
<p>Already have an account? <a href="{% url 'login' %}">Login</a> </p>
{% else %}
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<input type="text" name="username" placeholder="Username">
<input type="pass`your text`word" name="password" placeholder="Enter Password">
<input type="submit" value="Login">
<p>Dont have an account? <a href="{% url 'register' %}">Sign Up</a></p>
</form>
{% endif %}
{% endblock content %}
我的方法我分别在loginUser和registerUser视图中给变量赋值page ='login'和page ='register',然后在我的公共模板中给了一个if-else,但由于某种原因,即使我转到注册URL,也只有loginUser视图工作。
1条答案
按热度按时间6ju8rftf1#
忽略我愚蠢的问题,我传递了错误的上下文字典,即它应该是context ={'page':page}