skip to Main Content

i’m trying to make a registration page for my Django project. When i compile the registration form it gives me the error in the image because it tries to go to this path (he doubles users/register): localhost/users/register/users/register/. How can i fix it? this is my code:

Error image:

users/view.py:

def register_view(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('homepage')
    else:
        form = UserCreationForm()
    return render(request, "users/register.html", {"form": form})


users/urls.py:

urlpatterns = [
    path('register/', views.register_view, name="register"),
]



main/views.py:
def homepage(request):
    return render(request, 'homepage.html')


main/urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.homepage, name="homepage"),
    path('music/', include('music.urls')),
    path('users/', include('users.urls')),
]


html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Registration</title>
</head>
<body>
    <h1>REGISTER A NEW USER</h1>
    <form class="form-with-validation" action="users/register/" method="post">
        {% csrf_token %}
        {{ form }}
        <button class="form-submit">Submit</button>
    </form>
</body>
</html>

2

Answers


  1. It seems like you are already on the register page and then you are hitting the URL users/register/ with POST request while already being on register page. So it doubles the URL.
    To resolve this you need to put a slash before, like /users/register/. this is because then through this slash you will be going from home (let’s say localhost:8000) to users/register. So try adding a slash before and see what happens.

    Login or Signup to reply.
  2. the problem is with how you have specified the action attribute in your form’s html by using relative path users/register/ the browser appends this to the current url leading to incorrect path like: localhost/users/register/users/register/
    to fix this you should use url template tag to dynamically generate the correct url based on the name of the url pattern this way django will correctly resolve the path for you.
    so your html form should looks like this:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Registration</title>
    </head>
    <body>
        <h1>REGISTER A NEW USER</h1>
        <form class="form-with-validation" action="{% url 'register' %}" method="post">
            {% csrf_token %}
            {{ form }}
            <button class="form-submit">Submit</button>
        </form>
    </body>
    </html>
    

    I hope this helps you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search