Cześć
No, może jest to trochę skomplikowanie, ale napewno nie trudne.
Na początku zauważ że w templatkach twój profil użytkownika odwołuje się do dwóch różnych modeli, więc będziemy potrzebować dwóch różnych formularzy. I to pewnie tu jest twój problem. Teraz kod:
Zaczynamy od stworzenia pliku forms.py
from django import forms
from .models import UserProfile
from django.contrib.auth.models import User
class EditUserForm(forms.ModelForm):
class Meta:
model = User
fields = [
"username",
"first_name",
"last_name",
"email"
]
class EditUserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = [
"website",
"city",
"signature"
]
Więcej szczegółów w dokumentacji
W pliku views.py tworzymy widok (nie zapomnij zaimportować formularzy z poprzedniego pliku)
def edit_user_profile(request, pk):
user = get_object_or_404(User, pk=pk)
user_profile = user.userprofile
user_form = EditUserForm(request.POST or None, instance=user)
profile_form = EditUserProfileForm(request.POST or None, instance=user_profile)
if request.method == "POST" and user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
return redirect(f"/accounts/{pk}")
return render(request, "accounts/edit.html", {
"user_form": user_form,
"profile_form": profile_form
})
Teraz czas na templatke (templates/accounts/edit.html)
<form method="post" action=".">
{{ user_form }}
{{ profile_form }}
{% csrf_token %}
<input type="submit" value="Submit">
</form>
Nie zapominamy o urls.py, gdzie dodajemy np. coś takiego:
path("edit/<int:pk>/", views.edit_user_profile)
Pozdrawiam, jak chcesz aby coś wyjaśnić pisz komentarz.