Сделал вроде всё по этому гайду:
https://habrahabr.ru/post/313764/#OneToOneField
Однако в итоге получаем исключение:
spoilerRelatedObjectDoesNotExist at /profiles/
User has no profile.
Request Method: GET
Request URL: http://localhost:8000/profiles/
Django Version: 2.0.1
Exception Type: RelatedObjectDoesNotExist
Exception Value:
User has no profile.
Exception Location: C:\Phyton\lib\site-packages\django\db\models\fields\related_descriptors.py in __get__, line 389
Python Executable: C:\Phyton\python.exe
Python Version: 3.6.4
Python Path:
['E:\\work\\life',
'C:\\Phyton\\python36.zip',
'C:\\Phyton\\DLLs',
'C:\\Phyton\\lib',
'C:\\Phyton',
'C:\\Phyton\\lib\\site-packages']
Server time: Вт, 10 Апр 2018 16:13:01 +0000
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django import forms
from .forms import UserForm
from .forms import ProfileForm
from .models import Profile
from django.contrib.auth.models import User
@login_required
@transaction.atomic
def update_profile(request):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST, instance=request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, _('Your profile was successfully updated!'))
return redirect('settings:profile')
else:
messages.error(request, _('Please correct the error below.'))
else:
user_form = UserForm(instance=request.user)
profile_form = ProfileForm(instance=request.user.profile)
return render(request, 'profiles/profile.html', {
'user_form': user_form,
'profile_form': profile_form
})
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)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birthday = models.DateField(null=True, blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
forms.py
from django.db import models
from django.contrib.auth.models import User
from .models import *
from django import forms
from django import views
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('bio', 'location', 'birthday')