What I am trying to do:
I want to click a link on my page and then be redirected to another of my pages.
login.html:
{% block body %}
<h1>Login</h1>
{% if message %}
<div>
{{ message }}
</div>
{% endif %}
<form action="{% url 'login' %}" method="post">
{% csrf_token %}
<input name="username" type="text" />
<input name="password" type="password" />
<input type="submit" value="Login" />
</form>
<a class="btn btn-primary" href="{% url 'new_user' %}">New user</a>
{% endblock %}
new_user.html:
{% block body %}
<h1>New user</h1>
{% if message %}
<div>
{{ message }}
</div>
{% endif %}
<form action="{% url 'new_user' %}" method="post">
{% csrf_token %}
<input name="username" type="text" />
<input name="password" type="password" />
<input name="email" type="email" />
<input type="submit" value="Login" />
</form>
{% endblock %}
urls.py in main app:
urlpatterns = [
path("", include("orders.urls")),
path("new_user/", include("users.urls")),
path("login/", include("users.urls")),
path("admin/", admin.site.urls),
]
urls.py in users:
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("new_user", views.new_user_view, name="new_user")
]
views.py:
def index(request):
if not request.user.is_authenticated:
return render(request, "users/login.html", {"message": None})
context = {
"user": request.user
}
return render(request, "users/user.html", context)
def login_view(request):
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "users/login.html", {"message": "Invalid credentials."})
def new_user_view(request):
username = request.POST["username"]
password = request.POST["password"]
user = User.objects.create_user(username=username, password=password)
if user is not None:
user.save()
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "users/new_user.html", {"message": "Invalid credentials."})
Behavior:
What happens is I go to localhost:8000/login press the link for a new user, my browser redirects me to localhost:8000/new_user but is still rendering login.html and not new_user.html
What am I missing?
Change this
urlpatterns = [
path("", include("orders.urls")),
path("new_user/", include("users.urls")),
path("login/", include("users.urls")),
path("admin/", admin.site.urls),
]
to this
urlpatterns = [
path("", include("orders.urls")),
path("", include("users.urls")),
path("admin/", admin.site.urls),
]
All URLs from users will be included.
path("new_user/", include("users.urls")) would result in additional prefix new_user for all the urls from users. In this case localhost:8000/new_user matches index page from users app. You can try accessing localhost:8000/new_user/new_user with current configuration - it will render the page you're expecting.
Related
So I've got three users, a teacher, student, and admin. Both teacher and student users work fine but when I try to login using the admin form, it redirects to the student login form. I think it's because there's something wrong with the urls.py and the way the next parameter is configured but I'm not quite sure where to proceed.
Any help is much appreciated. Let me know if you need more information
Here are my admin views.py
#login_required
#admin_required
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/profile.html', context)
main urls.py
urlpatterns = [
path('', classroom.home, name='home'),
path('students/', include(([
path('', students.QuizListView.as_view(), name='quiz_list'),
path('interests/', students.StudentInterestsView.as_view(), name='student_interests'),
path('taken/', students.TakenQuizListView.as_view(), name='taken_quiz_list'),
path('quiz/<int:pk>/', students.take_quiz, name='take_quiz'),
], 'classroom'), namespace='students')),
path('teachers/', include(([
path('', teachers.QuizListView.as_view(), name='quiz_change_list'),
path('quiz/add/', teachers.QuizCreateView.as_view(), name='quiz_add'),
path('quiz/<int:pk>/', teachers.QuizUpdateView.as_view(), name='quiz_change'),
path('quiz/<int:pk>/delete/', teachers.QuizDeleteView.as_view(), name='quiz_delete'),
path('quiz/<int:pk>/results/', teachers.QuizResultsView.as_view(), name='quiz_results'),
path('quiz/<int:pk>/question/add/', teachers.question_add, name='question_add'),
path('quiz/<int:quiz_pk>/question/<int:question_pk>/', teachers.question_change, name='question_change'),
path('quiz/<int:quiz_pk>/question/<int:question_pk>/delete/', teachers.QuestionDeleteView.as_view(), name='question_delete'),
], 'classroom'), namespace='teachers')),
path('admins/', include(([
path('', admins.profile, name='profile'),
], 'classroom'), namespace='admins')),
]
login urls.py
urlpatterns = [
path('', include('classroom.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('accounts/signup/', classroom.SignUpView.as_view(), name='signup'),
path('accounts/signup/student/', students.StudentSignUpView.as_view(), name='student_signup'),
path('accounts/signup/teacher/', teachers.TeacherSignUpView.as_view(), name='teacher_signup'),
path('accounts/signup/admin/', admins.register, name='register'),
]
signup form template
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="row">
<div class="col-md-8 col-sm-10 col-12">
<h2>Sign up as a {{ user_type }}</h2>
<form method="post" novalidate>
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}">
{{ form|crispy }}
<button type="submit" class="btn btn-success">Sign up</button>
</form>
</div>
</div>
{% endblock %}
admin form template
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<input type="hidden" name="next" value="{{ next }}">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
Try just removing #login_required from your profile view.
Since Django decorators work top-down, #login_required will kick in before #admin_required. But from https://pypi.org/project/django-simple-rest/:
admin_required simply makes sure that the user is logged in and is
also a super user before they will be granted access to the decorated
view method.
So, I think that #admin_required will already check if the user is logged in.
I builded a login form in Django. Now I have a problem with the routing.
When I select the login button, the form doesn`t send the correct awnser.
I think the form in the frontend cannot gets the correct awnser from the
view.py file. So it will send no awnser and the login process canot work and
the form is a simple static html form.
I hope you can help me.
HTML:
<form class="windowlogscreen-content" method="POST">
{% csrf_token %}
<input type="text" placeholder="account" name="username">
<br>
<input type="password" placeholder="password" name="password">
<br>
<button style="margin: 20px;" type="submit">join</button>
</div>
</div>
</form>
views.py
def loginuser(request):
if request.method == "POST":
username = request.POST['accountName']
password = request.POST['accountPassword']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return views.homepage
else:
return redirect('start')
else:
return render(request, 'start', {})
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', start),
path('homepage/', include('homepage.urls'))
]
homepage urls.py
urlpatterns = [
path('login/', views.login, name="login"),
path('register/', views.register, name="register"),
path('', views.homepage, name="homepage"),
path('account/', views.account, name="account")
]
def login(request):
if request.method = 'POST':
username = request.POST['username']
password = request.method = POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect(#User to the dashboard!)
else:
message.info(request, "invalid credentials")
return redirect('login')
else:
return render(request, 'login.html')
Login.html:
<form method="POST" action="{% url 'login' %}">
{% csrf_token %}
<div class="form-group">
<label class="text-primary text-dark font-weight-bold">Enter Username</label>
<input type="text" class="form-control" name="username" placeholder="Enter Username">
</div>
<br>
<div class="form-group">
<label class="text-primary text-dark font-weight-bold">Enter Password</label>
<input type="password" class="form-control" name="password" placeholder="Enter Password">
</div>
<br>
<button type="submit" class="btn btn-primary btn-lg">Log in</button>
</form>
Docs
I've tried to add login form to my tasks web-app, but something goes wrong and I can't login to my created admin user. After click on the login button page just clearing up and my url changes to that. I have no idea how to fix it, help me please.
urls.py
urlpatterns = [
path('', TaskList.as_view(), name='tasks'),
path('login/', CustomLoginView.as_view(), name='login'),
path('logout/', LogoutView.as_view(next_page='login'), name='logout'),
path('task/<int:pk>', TaskDetail.as_view(), name='task'),
path('task-create/', TaskCreate.as_view(), name='task-create'),
path('task-edit/<int:pk>', TaskUpdate.as_view(), name='task-edit'),
path('task-delete/<int:pk>', TaskDelete.as_view(), name='task-delete'),
]
views.py
class CustomLoginView(LoginView):
template_name = 'base/login.html'
fields = '__all__'
redirect_authenticated_user = True
def get_success_url(self):
return reverse_lazy('tasks')
login.html
<h1>Login</h1>
<form metrhod="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Login">
</form>
Could it possibly be a spelling error? metrhod="POST"
Try this:
<h1>Login</h1>
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Login">
</form>
I have a login function, however when I try to login with a user that is not admin Django's authenticate function returns None even though the user exists in the database and the function receives the right username and password.
def login_user(request):
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
print(username, password)
user = authenticate(username=username, password=password)
print(user)
if user is not None:
login(request, user)
return redirect("/")
else:
return render(request, "orders/login.html",
{"message":"Username and password did not match."})
else:
return render(request, "orders/login.html")
login template:
{% extends "orders/layout.html" %}
{% block title %}
Login
{% endblock %}
{% block body %}
<div class="forms">
<form action="{% url 'login' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label>Username</label>
<input class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="password">
{% if message %}
<small id="emailHelp" class="form-text text-muted">{{ message }}</small>
{% endif %}
</div>
<button type="submit" class="btn button" id="button1" >Log In</button>
<a class="btn button" href="{% url 'register' %}" role="button" id="button2">Register</a>
</form>
</div>
{% endblock %}
url.py :
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("menu/<product>/", views.menu, name="menu"),
path("register", views.register, name="register"),
path("add_to_cart", views.addToCart, name="add_to_cart"),
path("cart", views.cart, name="cart"),
path("confirm", views.confirm, name="confirm"),
path("login", views.login_user, name="login"),
path("logout", views.logout_user, name="logout")
]
Try this :
def login_user(request):
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
print(username, password)
if username and password:
user = authenticate(username=username, password=password)
if user is not None:
If user.is_active:
login(request, user)
return redirect("/")
else:
return render(request, "orders/login.html",
{"message":"User does not exist."})
else:
return render(request, "orders/login.html",
{"message":"Username and password did not match."})
else:
return render(request, "orders/login.html")
I'm deploying a django app, and I have two forms: One for rating and another for contact in the home page. Both of them redirect to the home page after save a model. The contact form works fine, but the rating form keeps the post url and doesn't save the model, and after doing it again, it save it.
For example, I'm in www.site.com, then I send a post request from the rating form, the form redirect me to www.site.com/rating/ without saving the data. Then, if I'm send from www.site.com/rating/ the same form, the data is saved and redirect to www.site.com/rating/rating/ (404). The contact form works fine with the same process, and I think both are similar. The contact form redirects me to www.site.com like I want. I don't know why is this happening.
urls.py
urlpatterns = i18n_patterns(
url(r'^admin/', admin.site.urls),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^', include('myapp.urls')),
prefix_default_language=False
)
myapp/urls.py
urlpatterns = [
url(r'^contact/', views.contact, name='contact'),
url(r'^rating/', views.raiting, name='rating'),
url(r'^', views.index, name='home'),
]
myapp/views.py
def contact(request):
if request.method != 'POST':
raise Http404('acceding from GET')
msg = ContactForm(request.POST)
if not msg.is_valid():
context = {
'contact_errors': msg.errors
}
return render(request, 'home.html', context)
msg.save()
return redirect('home')
def rating(request):
if request.method != 'POST':
raise Http404('acceding from GET')
msg_form = OpinionForm(request.POST)
if not msg_form.is_valid():
context = {
'rating_errors': msg_form.errors
}
return render(request, 'home.html', context)
msg = msg_form.save(commit=False)
if 'picture' in request.FILES:
msg.picture = request.FILES['picture']
msg.save()
return redirect('home')
the forms in home.html
<form action="{% url 'rating' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input name="name" type="text" class="form-control" placeholder="Your name" required>
<textarea name="text" id="" cols="30" rows="5" class="form-control" placeholder="Your comment" required></textarea>
<input name="picture" type="file" id="upload-photo">
<input type="submit" class="button" value="Send">
</form>
<form action="{% url 'contact' %}" method="post">
{% csrf_token %}
<input name="email" type="text" class="form-control" placeholder="Email" required>
<textarea name="message" id="" cols="30" rows="5" class="form-control" required placeholder="Your message"></textarea>
<input type="submit" class="button" value="Send">
</form>
I guess that this is a typo, but check your urls.py:
url(r'^rating/', views.raiting, name='rating'),
should be rating instead o raiting, right?