Web Development 701 ~ Profile
In the previous blog we implemented the registration functionality. Now to add additional fields when registering and a profile page for users. In this blog we are going to explore extending the user model. The first thing we need to do is to create a new class in the models.py
file in our authentication
app. To this file we are going to add the following code.
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.EmailField()
address = models.CharField(max_length=30)
phone = models.CharField(max_length=20)
Next to register the model in our admin.py
file via the following.
from django.contrib import admin
from .models import Profile
admin.site.register(Profile)
Now to create a file called forms.py
and create a form via the following code.
from django import forms
from .models import Profile
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = (
'email',
'address',
'phone'
)
Then to change the views.py
file with the following.
from .forms import ProfileForm
def register(request):
if request.method == 'POST':
user_form = UserCreationForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
username = user_form.cleaned_data['username']
password = user_form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('index')
else:
user_form = UserCreationForm()
profile_form = ProfileForm()
context = {'user_form': user_form, 'profile_form': profile_form}
return render(request, 'registration/register.html', context)
Finally to edit the register.html
template to include the following under {{ user_form.as_p }}
{{ profile_form.as_p }}
With the additional fields added we can now add a profile page. The first thing to do is to add the following to the urlpatterns
variable in urls.py
.
path('view_profile', views.view_profile, name='view_profile')
Now to add the following in the views.py
file.
def view_profile(request):
return render(request, 'authentication/view_profile.html')
Finally to create the view_profile.html
template, which is as follows.
{% extends "skeleton.html" %}
{% block title %}Profile{% endblock %}
{% block body %}
<h1>Profile</h1>
<br>
{% if user.is_authenticated %}
<h4>Username: {{ user.username }}</h2>
<br>
<h4>Email: {{ user.profile.email }}</h4>
<br>
<h4>Address: {{ user.profile.address }}</h4>
<br>
<h4>Phone number: {{ user.profile.phone }}</h4>
{% else %}
<h2>Not authenticated</h2>
{% endif %}
{% endblock %}
One last thing to do is add the view_profile
route to the skeleton.html
template.
<li><a href="{% url 'view_profile' %}">Profile</a></li>