I've been trying to create a user registration page and have gotten the form itself and the render for the form set up. I have also gotten the form to save user input as POST, but haven't been able to send that info to a view function I have created to save that info to a database.
Here is my html/css template form:(userinfo.html)
<div>
{% block content %}
<form action="register" method="post" name="Userinfo" id="Userinfo">
<label for="fname">First Name</label>
{% csrf_token %}
<input type="text" id="fname" name="firstname" placeholder="Your first name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
<label for="DOB">Date Of Birth</label>
<input type="text" id="DOB" name="DOB" placeholder="The Date you were born">
<label for="Email">Email Address</label>
<input type="text" id="Email" name="Email" placeholder="Your email address">
<input type="submit" value="Submit">
</form>
{% endblock %}
</div>
The name of my view function is register and here it is:(views.py)
def register(request):
if request.method == 'POST':
first_name = request.POST['first_name'],
last_name = request.POST['last_name'],
date_of_birth = request.POST['DOB'],
email = request.POST['email']
newuser= User.objects.create_user(first_name=first_name,last_name=last_name, email=email)
newuser.save()
print('user created')
return redirect('/home')
else:
return render(request,'register.html')
This is supposed to save the user input into django's user database table.
How would I go about linking the form to the view I have set up?
CodePudding user response:
Notice, that firstname from form is not the same as first_name you seek in views. You have to fetch exactly the same data, as you place in html. You can always
print(request.POST)
to see what the POST dictionary has :)
With that fixed it should work for now.
CodePudding user response:
Assuming the name of your register view is also register, i.e.,
# urls.py
urlpatterns = [
...
path('register', views.register, name='register'),
...
]
then you can just change the form tag as follows:
<form action="{% url 'register' %}" method="post" name="Userinfo" id="Userinfo">
<label for="fname">First Name</label>
{% csrf_token %}
<input type="text" id="fname" name="first_name" placeholder="Your first name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="last_name" placeholder="Your last name..">
...
</form>
Note the change in the name for the inputs to first_name and last_name so the match your request.POST['first_name'] and request.POST['last_name']
The {% url 'register' %} tells Django to look for a url path that has a view with the name register.
