Coverage for website/views/ProfileUpdateView.py: 76%
55 statements
« prev ^ index » next coverage.py v7.5.0, created at 2025-09-13 15:29 -0300
« prev ^ index » next coverage.py v7.5.0, created at 2025-09-13 15:29 -0300
1from django.contrib import messages
2from django.contrib.auth.decorators import login_required
3from django.shortcuts import redirect, render
5from website.forms.ProfileUpdateForm import ProfileUpdateForm
6from website.models import Author, Reader
7from website.views.SignUpView import treat_accentuation
10@login_required
11def update_profile(request):
12 user = request.user
13 current_profile_type = None
15 # Determine current profile state
16 if hasattr(user, "author"):
17 current_profile_type = "author"
18 elif hasattr(user, "reader"):
19 current_profile_type = "reader"
21 if request.method == "POST":
22 form = ProfileUpdateForm(user=user, data=request.POST, files=request.FILES)
23 if form.is_valid():
24 new_profile_type = form.cleaned_data["profile_type"]
25 name = form.cleaned_data["name"]
26 image = form.cleaned_data.get("image")
28 # Handle profile type change
29 if current_profile_type and current_profile_type != new_profile_type:
30 # Delete old profile
31 if current_profile_type == "author":
32 user.author.delete()
33 user.is_staff = False
34 else:
35 user.reader.delete()
37 current_profile_type = None
39 # Create or update profile
40 if new_profile_type == "author":
41 if current_profile_type == "author":
42 # Update existing author
43 author = user.author
44 author.author_name = name
45 if image:
46 if author.image:
47 author.image.delete(save=False)
48 author.image = image
49 author.save()
50 else:
51 # Create new author
52 user.is_staff = True
53 user.save()
55 # Generate slug
56 author_name_replaced = treat_accentuation(name)
57 slug = "-".join(author_name_replaced.split()).lower()
59 author = Author.objects.create(
60 user=user,
61 author_name=name,
62 author_url_slug=slug,
63 access_level=1,
64 image=image,
65 )
66 messages.success(request, "Perfil de Autor atualizado com sucesso!")
67 else: # reader
68 if current_profile_type == "reader":
69 # Update existing reader
70 reader = user.reader
71 reader.reader_name = name
72 if image:
73 if reader.image:
74 reader.image.delete(save=False)
75 reader.image = image
76 reader.save()
77 else:
78 # Create new reader
79 reader = Reader.objects.create(
80 user=user, reader_name=name, access_level=2, image=image
81 )
82 messages.success(request, "Perfil de Leitor atualizado com sucesso!")
84 return redirect("/")
85 else:
86 form = ProfileUpdateForm(user=user)
88 context = {
89 "form": form,
90 "has_profile": current_profile_type is not None,
91 "profile_type": current_profile_type,
92 "is_creating": current_profile_type is None,
93 }
94 return render(request, "profile-update/update-profile.html", context)