Create account edit page in Django
In the previous tutorial we created a sign up / register page. We now need to create a page to edit the information for the user.
Create the form
In the 'users' app folder, open 'forms.py'. This should currently have the 'UserRegistrationForm'. Now copy the entire class, and rename it 'UserViewForm'. Also remove the references to 'password1' and 'password2'. Also note the change from 'UserCreationForm' to 'forms.ModelForm':
class UserViewForm (forms.ModelForm):
email = forms.EmailField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
class Meta:
model=User
fields = [
'username',
'first_name',
'last_name',
'email',
]
Declare a view
Now in the 'views.py' within the 'users' app folder, add the 'UserViewForm' to the import:
from .forms import UserRegistrationForm, UserViewForm
Now copy the entire 'register' def, now change the def to 'update'. Change 'UserRegistrationForm' to 'UserViewForm'. Change the messages to reflect an update instead of create. Final change the 'register.html' to 'update.html':
def update(request):
if request.method=='POST':
form = UserViewForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
form.save()
messages.success(request, 'Your account has been updated!')
return redirect('login')
else:
form = UserViewForm(request.POST)
messages.success(request, 'Your account has not been updated! form invalid!')
return render(request, 'users/update.html', {'form':form})
else:
form = UserViewForm(request.POST)
return render(request, 'users/update.html', {'form':form})
Create the template
In the 'templates' folder of the 'users' app, copy the 'register.html' and duplicate it and rename it to 'update.html':
Change the references for 'Register' to 'Update'.
Define URL
Now open the 'urls.py' from the project folder (mine is called 'MyProject'). Add this path to the 'urlpatterns':