I'm working on Django blog, and I'm working on register form. I got error Page not found at /register/
like you can see on image. But it say that error was raised by post_detail - Raised by: my_blog.views.post_detail
This is register.html
{% extends "base.html" %}
{% load static %}
{% block content %}
{% load crispy_forms_tags %}
<!--Register-->
<div class="container py-5">
<h1>Register</h1>
<form method="POST">
{% csrf_token %}
{{ register_form|crispy }}
<button class="btn btn-primary" type="submit">Register</button>
</form>
<p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p>
</div>
{% endblock %}
Views.py
def register_request(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
messages.success(request, "Registration successful." )
return redirect("main:homepage")
messages.error(request, "Unsuccessful registration. Invalid information.")
form = NewUserForm()
return render (request=request, template_name="register.html", context={"register_form":form})
def post_detail(request, slug):
latest_posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9]
post = get_object_or_404(Post, slug=slug)
context = {'post': post, 'latest_posts': latest_posts}
return render(request, 'post_detail.html', context)
blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
path('', views.home, name='home'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
path('category/<slug:slug>/', views.category_detail, name='category_detail'),
path('register/', views.register_request, name='register'),
]
forms.py
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
I got this error and I don't understand why I get this error. Any ideas?
Thanks in advance!
"register" is a valid slug so the post_detail url is matching the incoming path as it's before your register url in urlpatterns.
The first option is to change post_detail to include a prefix so that it doesn't match your other urls
urlpatterns = [
path('', views.home, name='home'),
path('post/<slug:slug>/', views.post_detail, name='post_detail'),
path('category/<slug:slug>/', views.category_detail, name='category_detail'),
path('register/', views.register_request, name='register'),
]
Or you could put post_detail last so that other urls are matched first
urlpatterns = [
path('', views.home, name='home'),
path('category/<slug:slug>/', views.category_detail, name='category_detail'),
path('register/', views.register_request, name='register'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
]