Я пытаюсь осуществить регистрацию в Django и столкнулся с ошибкой:
models.py ", строка 20, в user_registrated_dispatcher send_activation_notification (kwargs ['instance']) KeyError: 'instance'
Я отправил регистрационную форму, затем получил это сообщение об ошибке.
Как я могу устранить ошибку?
Не могли бы вы порекомендовать хороший учебник по регистрации по электронной почте в Django?
Полный код приложения находится здесь (ветка Login-version-2-site): https://github.com/mascai/reg_app/tree/Login-version-2-site
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.dispatch import Signal
from .utilities import send_activation_notification
class AdvUser(AbstractUser):
is_activated = models.BooleanField(default=True, db_index=True,
verbose_name='Пpoшeл активацию?')
send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?')
class Meta(AbstractUser.Meta):
pass
user_registrated = Signal(providing_args=['instance'])
def user_registrated_dispatcher(sender, **kwargs):
send_activation_notification(kwargs['instance'])
user_registrated.connect(user_registrated_dispatcher)
forms.py
class RegisterUserForm(forms.ModelForm):
email = forms.EmailField(required=True, label="Email address")
password1 = forms.CharField(label="Password", widget=PasswordInput,
help_text=password_validation.password_validators_help_text_html())
password2 = forms.CharField(label="Password", widget=PasswordInput,
help_text=password_validation.password_validators_help_text_html())
def clean_password1(self):
password1 = self.cleaned_data['password1']
if password1:
password_validation.validate_password(password1)
return password1
def clean(self):
super().clean()
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
errors = {'password2': ValidationError('Введённые пароли не совпадают', code='password_mismatch')}
raise ValidationError(errors)
else:
return self.cleaned_data
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data['password1'])
user.is_active = False
user.is_activated = False
if commit:
user.save()
user_registrated.send(RegisterUserForm, isinstance=user)
return user
class Meta:
model = AdvUser
fields = ('username', 'email', 'password', 'password2',
'first_name', 'last_name', 'send_messages')
urls.py
from .views import BBLoginView, BBLogoutView, profile, RegisterUserView, RegisterDoneView, user_activate
urlpatterns = [
path('', views.post_list, name='post_list'),
path('accounts/login/', BBLoginView.as_view(), name='login'),
path('accounts/profile/', profile, name='profile'),
path('accounts/logout/', BBLogoutView.as_view(), name='logout'),
path('accounts/register/done', RegisterDoneView.as_view(), name='register_done'),
path('accounts/register/', RegisterUserView.as_view(), name='register'),
path('accounts/register/activate/<str:sign>/', user_activate, name='register_activate'),
]
views.py
def post_list(request):
return render(request, 'blog/post_list.html', {})
class BBLoginView(LoginView):
template_name = 'blog/login.html'
class BBLogoutView(LoginRequiredMixin, LogoutView):
template_name = 'blog/logout.html'
@login_required
def profile(request):
return render(request, 'blog/profile.html')
class RegisterUserView(CreateView):
model = AdvUser
template_name = 'blog/register_user.html'
form_class = RegisterUserForm
success_url = '/register_done'
class RegisterDoneView(TemplateView):
template_name = "blog/register_done.html"
def user_activate(request, sign):
try:
username = signer.unsign(sign)
except:
return render(request, 'blog/bad_signature.html')
user = get_object_or_404(AdvUser, username=username)
if user.is_activated:
template = 'blog/user_is_activated.html'
else:
template = 'blog/activation_done.html'
user.is_active = True
user.is_activated = True
user.save()
return render(request, template)