我在Profile Model中使用OneToOne
关系扩展Django默认用户模型
我希望用户能够访问某些个人资料信息,并允许他更新这些信息。
我是Django的初学者,所以如果你能告诉我最简单的方法,那就太棒了。
我的代码:
views.py
from mysite.core.forms import SignUpForm, ProfileForm, DocumentForm
from mysite.core.models import Profile
from mysite.core.tokens import account_activation_token
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
# Create your views here.
def index(request):
return render(request, 'index.html')
@login_required
def home(request):
return render(request, 'home.html')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
subject = 'Activate Your MySite Account'
message = render_to_string('account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
user.email_user(subject, message)
return redirect('account_activation_sent')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
def account_activation_sent(request):
return render(request, 'account_activation_sent.html')
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user,
token):
user.is_active = True
user.profile.email_confirmed = True
user.save()
login(request, user)
return render(request, 'email_confirmation_done.html')
else:
return render(request, 'account_activation_invalid.html')
def email_confirmation_done(request):
return render(request, 'email_confirmation_done.html' )
def complete_profile(request):
if request.user.is_authenticated():
if request.method == 'POST':
form = ProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
profile = form.save(commit=False)
profile.profile_completed = True
profile.save()
return redirect('upload_files')
else:
form = ProfileForm()
return render(request, 'complete_profile.html', {'form': form})
else:
return redirect('login')
def upload_files(request):
if request.user.is_authenticated():
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES,
instance=request.user.profile)
if form.is_valid():
form.save()
return redirect('home')
else:
form = DocumentForm()
return render(request, 'upload_files.html', {'form': form})
else:
return redirect('login')
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(('Date de Naissance'), null=True,
blank=True)
birth_place = models.CharField(('Lieu de Naissance'), max_length=80 )
email_confirmed = models.BooleanField(('Email confirmé'), default=False)
adress = models.CharField(('Adresse'), max_length=80)
adress_complement = models.CharField(('Complément d\'adresse'),
max_length=80)
city = models.CharField(('Ville'), max_length=80)
zip_code = models.IntegerField(('Code postal'), null=True, blank=True)
drive_licence_num = models.CharField(('N° du Permis de conduire'),
max_length=80)
social_secu_num = models.IntegerField(('N° de sécurité sociale'),
null=True, blank=True)
phone_number = models.IntegerField(('N° de Téléphone'), null=True,
blank=True)
profile_completed = models.BooleanField(('Profile completé'),
default=False)
#DOCUMENTS TO UPLOAD
id_card = models.FileField(('Carte Nationale d\'Identité'),
upload_to='documents/CNI')
drive_licence = models.FileField(('Permis de conduire'),
upload_to='documents/PERMIS_CONDUIRE')
police_record = models.FileField(('Casier judiciaire'),
upload_to='documents/CASIER_JUDICIAIRE')
carte_vitale = models.FileField(('Carte vitale'),
upload_to='documents/CARTE_VITALE')
medical_visit = models.FileField(('Visite médicale'),
upload_to='documents/MEDICAL_VISIT')
rib = models.FileField(('Relevé d\'Identité Bancaire (RIB)'),
upload_to='documents/RIB')
uploaded_at = models.DateTimeField(('Ajouté le'), auto_now_add=True)
docs_are_checked = models.BooleanField(('documents verifés'),
default=False)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
应用/ urls.py
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from . import views as core_views
urlpatterns = [
url(r'^accounts/login/$', auth_views.login, {'template_name':
'login.html'}, name='login'),
url(r'^accounts/logout/$', auth_views.logout, {'next_page': 'login'},
name='logout'),
url(r'^accounts/signup/$', core_views.signup, name='signup'),
url(r'^account_activation_sent/$', core_views.account_activation_sent,
name='account_activation_sent'),
url(r'^accounts/activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-
z]{1,13}-[0-9A-Za-z]{1,20})/$', core_views.activate,
name='activate'),
url(r'^accounts/email_confirmation_done/$',
core_views.email_confirmation_done, name='email_confirmation_done'),
url(r'^accounts/complete_profile/$', core_views.complete_profile,
name='complete_profile'),
url(r'^accounts/upload_files/$', core_views.upload_files,
name='upload_files'),
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from mysite.core.models import Profile
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Required. Inform a
valid email address.')
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1',
'password2',)
def clean_email(self):
email = self.cleaned_data.get("email")
qs = User.objects.filter(email__iexact=email)
if qs.exists():
raise forms.ValidationError("Cannot use this email. It's already
registered")
return email
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('birth_date','birth_place', 'adress', 'adress_complement',
'city', 'zip_code', 'drive_licence_num',
'social_secu_num', 'phone_number')
help_texts = {
'birth_date': 'Format AAAA/MM/JJ',
'birth_place': 'Indiquer Pays si né à l\'étranger',
'adress': 'N°,Rue,Boulevard,Nom, (Ex: 01 Rue de Craiova)',
'adress_complement': 'Res, Bât, Apprt, BP, Chez...',
}
class DocumentForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('id_card', 'drive_licence', 'police_record',
'carte_vitale', 'medical_visit', 'rib',)
help_texts = {
'id_card': '*Required Recto / Verso',
}
答案 0 :(得分:1)
您可以设置一个类似的简单视图,
def profile_view(request):
if request.method == "POST":
form = ProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
else:
form = ProfileForm(instance=request.user.profile)
return render(request, "your_template.html", { "form" : form })