Доброго времени суток. Делаю по примеру как на хабрахабре
Использование связи один-к-одному с пользовательской моделью (user profiles)
models.py
from django.db import models
from django.contrib.auth.models import User
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)
birth_date = models.DateField(null=True, blank=True)
Теперь добавим немножко магии: определим сигналы, чтобы наша модель Profile автоматически обновлялась при создании/изменении данных модели User.
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)
birth_date = 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()
Мы «зацепили» create_user_profile() и save_user_profile() к событию сохранения модели User. Такой сигнал называется post_save.
А теперь пример шаблона Django с использованием данных Profile:
<h2>{{ user.get_full_name }}</h2>
<ul>
<li>Username: {{ user.username }}</li>
<li>Location: {{ user.profile.location }}</li>
<li>Birth Date: {{ user.profile.birth_date }}</li>
</ul>
Ошибка когда нажимаю сохранить форму
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8001/profile/
Django Version: 1.9.8
Python Version: 3.6.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python36\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Python36\lib\contextlib.py" in inner
53. return func(*args, **kwds)
File "C:/skript/untitled2\blog\views.py" in update_profile
20. messages.success(request, _('Your profile was successfully updated!'))
Exception Type: NameError at /profile/
Exception Value: name '_' is not defined
если убираю нижние подчёркивания возникает другая ошибка
Traceback:
File "C:\Python36\lib\site-packages\django\core\urlresolvers.py" in reverse
586. extra, resolver = resolver.namespace_dict[ns]
During handling of the above exception ('settings'), another exception occurred:
File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python36\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Python36\lib\contextlib.py" in inner
53. return func(*args, **kwds)
File "C:/skript/untitled2\blog\views.py" in update_profile
21. return redirect('settings:profile')
File "C:\Python36\lib\site-packages\django\shortcuts.py" in redirect
116. return redirect_class(resolve_url(to, *args, **kwargs))
File "C:\Python36\lib\site-packages\django\shortcuts.py" in resolve_url
204. return urlresolvers.reverse(to, args=args, kwargs=kwargs)
File "C:\Python36\lib\site-packages\django\core\urlresolvers.py" in reverse
596. key)
Exception Type: NoReverseMatch at /profile/
Exception Value: 'settings' is not a registered namespace