Why HTML Registration Form Data is not Received in django

Hi All

I am New to Django. I am trying to Register a New User using an HTML Form which will send Data to Django where it will be Save in Sqlite Database & return a Successful Message. But when I entered data in HTML Registration form & press the Submit button from Registration Page, it shows Error
“Your file couldn’t be accessed”. Also, Data is Not received at Django neither Saved in Database.

Below is the Code

1- NewUser.html -----Registration Form - HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Traffic Violation - New User Registration</title>
    <link rel="stylesheet" href="stylesNU.css">
</head>

<body>
	<div class="main">
			<center><h2>New User Registration</h2></center>
	</div>
		
	<div class="forms">
			
	<form id="NewUser" action="{% url 'register' %}" method="POST">
			{% csrf_token %}
				<label for="name">Name:</label><br>
				<input type="text" id="name" name="name"><br>
				
				<label for="email">Email:</label><br>
				<input type="email" id="email" name="email"><br>
				
		<label for="password">Password:</label><br>
		<input type="password" id="password" name="password"><br>
				
				<script>
				// Generate current datetime for Hidden fields
				var current_datetime = new Date().toISOString();
				document.getElementById('current_datetime').value = current_datetime;
				</script>

				<!-- Hidden fields for created_at and updated_at -->
				<input type="hidden" name="created_at" value="{{ current_datetime }}">
				<input type="hidden" name="updated_at" value="{{ current_datetime }}">		
				
				<input type="submit" value="Register">
		</form>
		
	</div>

</body>
</html>

2- Django Structure

DjangoTestProject/
├── demo/
│   ├── __init__.py
|    ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
├── user/
 |   ├── migrations
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── models.py
│   ├── tests.py
|    ├── urls.py
│   └── views.py
├── db.sqlite3

2.1 demo - settings.py

Added following under INSTALLED_APPS

    'rest_framework',
    'user',

2.2 demo - urls.py

from django.contrib import admin
from django.urls import path
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include([
        path('user/', include('user.urls')),
    ])),
]

2.3 user - admin

from django.contrib import admin
from .models import UserProfile

admin.site.register(UserProfile)

2.4 user - models.py

from django.db import models

#Create your models here.

class UserProfile(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()
    password = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

def __str__(self):
    return self.name

2.5 user - urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.register, name='register'),
    path('cart.json', views.cart_data_view, name='cart_json'),
]

2.6 user - views.py

from django.shortcuts import render
from django.http import HttpResponse

#Create your views here.

def register(request):
    if request.method == 'POST':
        name = request.POST["name"]
        email = request.POST["email"]
        password = request.POST["password"]
        created_at = request.POST["created_at"]
        updated_at = request.POST["updated_at"]

        #Check Data received at Django
        print(name, email, password, created_at, updated_at)


        # Save data to database
        user_profile = models.UserProfile.objects.create(name=name, email=email, password=password, created_at=created_at, updated_at=updated_at)
        user_profile.save()

    # Return OK message to the registration page
    return HttpResponse('OK')

    # Redirect to registration success page
    # return render(request, "Registration_Success.html")

    # Render the registration form
    return render(request, 'Index.html')

Thanks in Advance
Regards

Side Note: When posting code here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. (I’ve taken the liberty of modifying your original post for you. Please remember to do this in the future.)

If you’re requesting assistance with a specific error message being received, please post the complete error with the full traceback as shown on your server’s console. (Fence the text between lines of ``` as mentioned above.)

Also, a lot of what you’re doing here would be easier if you used a ModelForm for the entry and submission of this data.

1 Like

Much Appreciated @KenWhitesell for your efforts

I want to know where I am doing Wrong & how to Fix it
Also, want to know the ModelForm way as you have suggested.

Kind Regards

Start with:

Start with reading the docs at Creating forms from models | Django documentation | Django, and feel free to come back and ask questions if there is something you don’t understand.

HI

Here is the Error of New User Registration HTML Form

Here is DjangoTestProject Error which I got after running Server i.e.,
C:\Users\PC\PycharmProjects\DjangoTestProject\demo\manage.py runserver

Problems Sections of PyCharm

views.py


Code is as follow for above Error

```# Save data to database
```user_profile = userprofile.objects.create(name=name, email=email, password=password, created_at=created_at, updated_at=updated_at)
```user_profile.save()


```Error2: PEP 8: E501 line too long (138 > 120 characters)
Which means the # Save data to database code line is > 120 Chars as shown above


```Error3: This code is unreachable

Code for above Error is as follow
```return render(request, 'Index.html')

Above 3 Errors I got when I run Django Server in views.py & HTML Error as attached above

Regards
  1. You’re trying to go a file rather than accessing the url from runserver.

Have you worked your way through either the Official Django Tutorial or the Django Girls Tutorial? If you haven’t, you should do them first.

  1. The “line too long” message is a warning, the length of the line does not affect the behavior of the code.

  2. You have two return statements in your view, the second one will never be executed. This may simply be a case of the first return statement not being properly indented. However, when you’re working with standard Django, Django is expecting to return a complete page, not just a message that you can add to the existing page.

  1. Thanks for pointing it out. Need to know how to access URL from runserver.
    As I am submitting data from HTML. I have also added URL in django as mentioned below

2.5 user - urls.py

from django.urls import path
from . import views

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

Acknowledged & Thanks for the Official Django Tutorial or the Django Girls Tutorial as this is my First Time using Django & HTML. I will go through them for better Understanding

  1. Noted. As there was warning about that so I had added it as well

  2. Two Return Statements.Yes I wanted to see which one is working either HTTPResponse OK or return index.html. Then I will use it. But after your Explanation, I understood, it would be second return where I am returning web page not first one where I am returning a message.

Hi
I have below configurations of demo\urls.py, user\urls.py, views.py & HTML Form.

Still when I press the submit button of HTML Form it says File Not Found. Taking help from ChatGPT which provided two Solutions as mentioned in attached file, even then I am getting Error. What to do

demo\urls.py

	urlpatterns = [
    		path('admin/', admin.site.urls),
    		path('user', views.register),
	]

user\urls.py

	urlpatterns = [
        	path('register', views.register),
	]



views.py

def register(request):
    if request.method == 'POST':
        name = request.POST.get("name")
        email = request.POST.get("email")
        password = request.POST.get("password")
        created_at = request.POST.get("created_at")
        updated_at = request.POST.get("updated_at")

I have following congifuration in HTML Form

	<form id="NewUser" method="POST" action="{% url 'register' %}">
			{% csrf_token %}<br>
				<label for="name">Name:</label><br>
				<input name="name" type="text" id="name" name="name"><br>
				
				<label for="email">Email:</label><br>
				<input name="email" type="email" id="email" name="email"><br>
				
				<label for="password">Password:</label><br>
				<input name="password" type="password" id="password" name="password"><br>
				
				<script>
				// Generate current datetime for Hidden fields
				var current_datetime = new Date().toISOString();
				document.getElementById('current_datetime').value = current_datetime;
				</script>

				<!-- Hidden fields for created_at and updated_at -->
				<input type="hidden" name="created_at" value="{{ current_datetime }}">
				<input type="hidden" name="updated_at" value="{{ current_datetime }}">

				<button type="submit">Register</button>
				
		</form>
		
	</div>

</body>
</html>

When I press the submit button of HTML Form it syas File Not Found. What is the Error & how to fix it

ChatGPT

The issue you’re encountering is likely due to the way you’ve configured your URL patterns in Django. Let’s go through the configuration and identify the problem:

  1. URL Configuration:

    You have two different URL configurations:

    • In demo/urls.py:

      urlpatterns = [
          path('admin/', admin.site.urls),
          path('user', views.register),
      ]
      
    • In user/urls.py:

      urlpatterns = [
          path('register', views.register),
      ]
      

    The problem here is that the URL pattern in demo/urls.py for the register view is catching the URL /user, and there’s no pattern for the base URL (/). So when you submit the form, the action points to {% url 'register' %}, which resolves to /user, but the form is being submitted to /user/register.

  2. Form Action:

    In your HTML form, the action attribute is set to {% url 'register' %}, which will resolve to the URL /user because of the configuration in demo/urls.py. However, your actual URL pattern for the register view is /user/register, as defined in user/urls.py.

  3. Solution:

    You have a couple of options to resolve this issue:

    • Update your form action in the HTML template to point directly to /user/register:

      <form id="NewUser" method="POST" action="/user/register">
      
    • Alternatively, you can modify your URL configurations to align with your application structure:

      In demo/urls.py:

      from django.urls import include
      
      urlpatterns = [
          path('admin/', admin.site.urls),
          path('user/', include('user.urls')), # Include user URLs
      ]
      

      In user/urls.py:

      urlpatterns = [
          path('register/', views.register), # Add a trailing slash
      ]
      

      With this setup, your form action in the HTML template can remain as {% url 'register' %}, and it will correctly resolve to /user/register.

Choose the approach that best fits your application structure and preferences. Either way, ensure that the form action matches the URL pattern where the register view is defined.

I have tried both suggestion, even then I am getting following Error

Not Found: /
[04/Apr/2024 00:42:20] “GET / HTTP/1.1” 404 2162
Not Found: /cart.json
[04/Apr/2024 00:42:20] “GET /cart.json HTTP/1.1” 404 2207
Not Found: /
[04/Apr/2024 00:42:21] “GET / HTTP/1.1” 404 2162
Not Found: /cart.json
[04/Apr/2024 00:42:21] “GET /cart.json HTTP/1.1” 404 2207
[04/Apr/2024 00:42:25] “GET /admin/user/userprofile/ HTTP/1.1” 200 4977
[04/Apr/2024 00:42:25] “GET /admin/jsi18n/ HTTP/1.1” 200 3195
Not Found: /cart.json
[04/Apr/2024 00:42:26] “GET /cart.json HTTP/1.1” 404 2207

Regards

First, please don’t quote ChatGPT here. As far as I’m concerned, its value for Django ranges from “worthless” to “dangerous”.

So addressing these one-by-one:

You don’t have any path defined for the empty url - ""

You don’t have any path defined for cart.json.

See the docs for the url tag. That first parameter is supposed to be a pattern name, not a url.

Finally, you are still not posting the complete error (with traceback) that you are receiving. None of these issues are a “File Not Found”.