Edit functionality for profile

This commit is contained in:
Maxime Bloch 2020-07-22 16:06:04 +02:00
parent a5d3510bdb
commit 4a80c56e85
3 changed files with 36 additions and 7 deletions

View file

@ -1,4 +1,5 @@
from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.forms import ModelForm
from .models import CustomUser from .models import CustomUser
@ -13,3 +14,9 @@ class CustomUserChangeForm(UserChangeForm):
class Meta: class Meta:
model = CustomUser model = CustomUser
fields = ('username', 'student_number', 'real_name',) fields = ('username', 'student_number', 'real_name',)
class UserMetaForm(ModelForm):
class Meta:
model = CustomUser
fields = ['student_number', 'real_name']

View file

@ -5,12 +5,13 @@
{% block content %} {% block content %}
<h1>Profile</h1> <h1>Profile</h1>
{% if user.is_authenticated %} {% if user.is_authenticated %}
<p>Username: {{ username }}</p> <p>Username: {{ user.username }}</p>
<label>Student number</label>
<input type="text" placeholder="1234567" value="{{ user.student_number }}"/> <form action="/user/profile" method="post">
<label>Real name</label> {% csrf_token %}
<input type="text" value="{{ user.real_name }}"> {{ form }}
<input type="submit" value="Save"/> <input type="submit" value="Submit">
</form>
{% else %} {% else %}
<p>Not logged in</p> <p>Not logged in</p>
{% endif %} {% endif %}

View file

@ -1,10 +1,31 @@
from pprint import pprint
from django.contrib.auth import logout from django.contrib.auth import logout
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect from django.shortcuts import render, redirect
from users.forms import UserMetaForm
from users.models import CustomUser
def profile(request): def profile(request):
return render(request, "profile.html", {"username": request.user.username}) # if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = UserMetaForm(request.POST, instance=request.user)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
form.save()
# redirect to a new URL:
return HttpResponseRedirect('/user/profile')
# if a GET (or any other method) we'll create a blank form
else:
form = UserMetaForm(instance=request.user)
return render(request, 'profile.html', {'form': form})
def logout_view(request): def logout_view(request):
logout(request) logout(request)