Update Profile
Goal for this part
Turn the profile page into an editable form. You will use two forms—one for User fields and one for Profile—save both on valid POST, and show the current image.
After this snapshot, a logged-in author can update their account details without visiting the admin.
What you should already know
Registration forms and login_required from earlier parts are the main prerequisites. You should already have a Profile model with an image field.
File uploads need enctype="multipart/form-data" on the HTML form and request.FILES passed into the profile form.
Concepts: ModelForm instances and multipart posts
Pass instance=request.user (and instance=request.user.profile) so the forms edit existing rows instead of creating new ones. On POST, bind both forms; only save if both are valid.
Image fields read uploaded files from request.FILES. Forgetting that argument leaves the old image in place even when the user chose a file.
@login_required
def profile(request):
if request.method == "POST":
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(
request.POST, request.FILES, instance=request.user.profile
)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, "Your account has been updated.")
return redirect("profile")
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {"u_form": u_form, "p_form": p_form}
return render(request, "users/profile.html", context)
How to run it and what you should see
Run 08-Update-Profile, log in, open the profile page, change your email and image, and save. You should see a success message and the new image on the feed.
git clone https://github.com/michaeldunga1/fcc-django-blog.git
cd fcc-django-blog/08-Update-Profile
python3 -m venv .venv
source .venv/bin/activate
pip install -r ../requirements.txt
python manage.py migrate
python manage.py runserver
Common mistakes and troubleshooting
If uploads silently fail, check enctype and request.FILES. If only one form saves, you may be saving before both pass is_valid().
Permission errors writing under MEDIA_ROOT mean the process cannot create files in that folder—fix permissions on your machine.
Try this
Update username, log out, and log back in with the new username. Then upload a large image and, if the snapshot resizes images, confirm the saved file is smaller on disk.
- Two forms, one page, one atomic success path
- multipart/form-data is required for file fields
- Redirect after POST to avoid duplicate saves
Next: Posts CRUD
Comments
One comment per signed-in account. Comments are saved with this page’s URL.