This article is based on the previous article Django in allauth Installation with basic use
In this part , Two functions will be developed , One is that the user logs in and jumps to profile The interface of (accounts/profile), The other is to allow login users to modify their personal information (accounts/profile/update).
The first step is to create UserProfile application , It is used to store additional information of users .
python manage.py startapp UserProfile
After registering the application, you should remember to do a few things , One is in settings.py
Of INSTALLED_APPS Register the application , Second, in the project urls.py
Register in url.
# settings.py
INSTALLED_APPS = [
......
'UserProfile',
......
]
# urls.py
urlpatterns = [
path('admin/', admin.site.urls),
# register allauth
path('accounts/', include('allauth.urls')),
# Register extended user model
path('accounts/',include('UserProfile.urls'))
]
Because we want users to log in successfully and jump to profile Interface , So we are setting.py
Add this sentence to .
# accounts
LOGIN_REDIRECT_URL = '/accounts/profile/'
The second step , Let's define the extended information table .
because Django Self contained User Model field mailbox , So we need to extend it , The most convenient way is to create UserProfile Model of , Add the fields we need .
Definition UserProfile/models.py
from django.db import models
# Import django The self-contained user table is used as the foreign key
from django.contrib.auth.models import User
# Create your models here.
CAMPUS_TYPE = (
(' jiangwan ', ' jiangwan '),
(' Xianxi ', ' Xianxi '),
(' Riverside ', ' Riverside '),
)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
name = models.CharField(max_length=50, null=True, blank=True, verbose_name=' full name ')
classes = models.CharField(max_length=50, blank=True, verbose_name=' In class ')
bank_card = models.CharField(max_length=50,blank=True,verbose_name=' BOC Card No ')
identity_card = models.CharField(smax_length=18, blank=True, unique=True, verbose_name=' Id card number ')
telephone = models.CharField(max_length=50, blank=True, verbose_name=' Contact information ')
campus = models.CharField(choices=CAMPUS_TYPE, max_length=50,blank=True, verbose_name=' Campus ')
modified_date = models.DateTimeField(auto_now=True, verbose_name=' Last modified ')
class Meta:
verbose_name = 'User Profile'
def __str__(self):
return "{}".format(self.user.__str__())
Write two url Corresponds to two views , First write UserProfile Internal urls.py
from django.urls import re_path,path
from UserProfile import views
app_name = "UserProfile"
urlpatterns = [
re_path(r'^profile/$', views.profile, name='profile'),
re_path(r'^profile/update/$', views.profile_update, name='profile_update'),
]
Two corresponding view functions
from django.shortcuts import render, get_object_or_404
from .models import UserProfile
from .forms import ProfileForm
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
@login_required
def profile(request):
user = request.user
return render(request, 'account/profile.html', {'user': user})
@login_required
def profile_update(request):
user = request.user
user_profile = get_object_or_404(UserProfile, user=user)
if request.method == "POST":
form = ProfileForm(request.POST)
if form.is_valid():
# Use django Bring their own User in first_name Field storage name
user.first_name = form.cleaned_data['name']
user.save()
user_profile.name = form.cleaned_data['name']
user_profile.classes = form.cleaned_data['classes']
user_profile.bank_card = form.cleaned_data['bank_card']
user_profile.identity_card = form.cleaned_data['identity_card']
user_profile.telephone = form.cleaned_data['telephone']
user_profile.campus = form.cleaned_data['campus']
user_profile.save()
return HttpResponseRedirect(reverse('UserProfile:profile'))
else:
default_data = {'name': user_profile.name,
'classes': user_profile.classes,
'bank_card': user_profile.bank_card,
'identity_card': user_profile.identity_card,
'telephone': user_profile.telephone,
'campus': user_profile.campus,
}
form = ProfileForm(default_data)
return render(request, 'account/profile_update.html', {'form': form, 'user': user})
Users need to use forms to update information , So we put the form separately forms.py
, The code is as follows . We created two forms : One is to use when updating user data , One is to rewrite the user login form .
from django import forms
from .models import UserProfile
from UserProfile.models import CAMPUS_TYPE
class ProfileForm(forms.Form):
name = forms.CharField(label=' full name ', max_length=50, required=False)
classes = forms.CharField(label=' class ',max_length=50,required=False)
bank_card = forms.CharField(label=' BOC Card No ',max_length=50,required=False)
identity_card = forms.CharField(label=' ID number ',max_length=18,required=False)
telephone = forms.CharField(label=' Contact information ',max_length=11,required=False)
campus = forms.ChoiceField(label=' Campus ',choices=CAMPUS_TYPE,required=False)
# Rewrite the registration form , Create an associated object during registration
class SignupForm(forms.Form):
def signup(self, request, user):
user_profile = UserProfile()
user_profile.user = user
user.save()
user_profile.save()
Rewrite profile Page template
from github above django-allauth Pull it down templates
Folder , In the UserProfile
In the folder .
Later on UserProfile/templates/accounts/
Create under directory profile.html
and profile_update
file . It is strictly required to create files according to the above directory structure , because allauth The default will be templates/account/
Find the template file under the folder .
profile.html
{% block content %}
{% if user.is_authenticated %}
<a href="{% url 'UserProfile:profile_update' %}">Update Profile</a> | <a href="{% url 'account_email' %}">Manage Email</a> | <a href="{% url 'account_change_password' %}">Change Password</a> |
<a href="{% url 'account_logout' %}">Logout</a>
{% endif %}
<p>Welcome, {{ user.username }}.</p>
<h2>My Profile</h2>
<ul>
<li>Name: {{ user.profile.name }} </li>
<li>classes: {{ user.profile.classes }} </li>
<li>bank_card: {{ user.profile.bank_card }} </li>
<li>telephone: {{ user.profile.telephone }} </li>
</ul>
{% endblock %}
profile_update.html
{% block content %}
{% if user.is_authenticated %}
<a href="{% url 'UserProfile:profile_update' %}">Update Profile</a> | <a href="{% url 'account_email' %}">Manage Email</a> | <a href="{% url 'account_change_password' %}">Change Password</a> |
<a href="{% url 'account_logout' %}">Logout</a>
{% endif %}
<h2>Update My Profile</h2>
<div class="form-wrapper">
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<div class="button-wrapper submit">
<input type="submit" value="Update" />
</div>
</form>
</div>
{% endblock %}
Then you can use the three board axe to see the effect
python manage.py makemigrations
python manage.yy migrate
python manage.py runserver
A new user named Xiao Ming has been registered , Registration can automatically jump to profile page .
thus , This basically completes the requirements for expanding the user model .