Django 3 : Create an HTML form
In this post, we will show you how to add a profile without using Django forms. This example will show the time that can be saved by using Django.
Step 1 : Add the following URL to your urls.py file:
path('create-profile', views.create_profile, name="create_profile"),
Step 2 : We will create a template before the view. Indeed, we are going to fill the view with the template that contains the form. We do not put all the fields in the model because the code is too long. The following is our template in template/create_profile.html
{% extends "base.html" %}
{% block title %}
Create Profile
{% endblock %}
{% block h1 %}
Create Profile
{% endblock %}
{% block content %}
<form method="post" action="{% url "create_profile" %}">
{% csrf_token %}
<table>
<tr>
<td>Name</td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td>Login</td>
<td>
<input type="text" name="login" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="text" name="password" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Valid" />
</td>
</tr>
</table>
</form>
{% endblock %}
Step 3 : The view that will process this form will be as follows. Save the view in the file views.py:
from django.shortcuts import render
from myproject.models import UserProfile
from django.http import HttpResponse
def create_profile(request):
error = False
if request.POST:
if 'name' in request.POST:
name = request.POST.get('name', '')
else:
error=True
if 'login' in request.POST:
login = request.POST.get('login', '')
else:
error=True
if 'password' in request.POST:
password = request.POST.get('password', '')
else:
error=True
if not error:
new_profile = UserProfile(name=name, login=login, password=password)
new_profile.save()
return HttpResponse("UserProfile added")
else:
return HttpResponse("An error has occured")
else:
return render(request, 'create_profile.html')
Step 4 : Now start the development server with the python manage.py runserver command and open http://127.0.0.1:8000/create-profile in your browser.
Step 5 : If you want to verify whether your code works properly, do not forget to check the data in the administration module.