Web Development 701 ~ Profile (editing)
Last blog covered extending the user model of Django to add additional fields and then implementing a profile page. In this blog we are going to cover editing and updating the profile information. The first thing to do is to add the following to the urlpatterns
variable in the urls.py
file.
path('edit_profile', views.edit_profile, name='edit_profile')
Next to create the edit_profile
view in the views.py
file. The code will look as follows.
from .forms import ProfileForm, EditProfileForm
def edit_profile(request):
if request.method == 'POST':
profile_form = EditProfileForm(request.POST, instance=request.user.profile)
if profile_form.is_valid():
profile = profile_form.save(commit=False)
profile.save()
return redirect('view_profile')
else:
profile_form = EditProfileForm(instance=request.user.profile)
context = {'profile_form': profile_form}
return render(request, 'authentication/edit_profile.html', context)
Now we have to create the EditProfileForm
form in forms.py
file.
class EditProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = (
'email',
'address',
'phone'
)
We also want to create a new file called signals.py
in authentication
which will contain the following code.
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
Next we have to add the following code to the apps.py
file.
from django.apps import AppConfig
class AuthenticationConfig(AppConfig):
name = 'authentication'
def ready(self):
import authentication.signals
Finally to create the edit_profile.html
template.
{% extends "skeleton.html" %}
{% block title %}Edit Profile{% endblock %}
{% block body %}
<form method="POST" action="{% url 'edit_profile' %}">
{% csrf_token %}
{% if form.errors %}
<p>Errors in the form</p>
{% endif %}
{{ profile_form.as_p }}
<p><input type="submit" value="confirm"></p>
</form>
{% endblock %}
The last thing to do is add the edit_profile
route to the view_profile.html
template via the following.
<h5><a href="/edit_profile">Edit Profile</a></h5>
With that we can now edit and update user profile information.