I
I
Iskandar Dvurogov2015-12-15 12:23:48
Django
Iskandar Dvurogov, 2015-12-15 12:23:48

What is the correct way to store an activation key in Django?

The User model had an activation key field, I removed it into a separate model and now I can’t figure out how to save it correctly so that I can activate the user after registration.
I don't know how to put it more precisely. I don't study Django for long. I attach the code https://dpaste.de/jGVk

#модели
class User(AbstractUser):
    class Meta:
        verbose_name = 'пользователь'
        verbose_name_plural = 'пользователи'
 
    phone = models.CharField('номер телефона', max_length=127, blank=True)
    # activation_key = models.CharField(max_length=40, blank=True)
    # key_expires = models.DateTimeField(default=datetime.date.today())
 
    @models.permalink
    def get_absolute_url(self):
        return 'user-detail', (self.pk,)
 
    def __str__(self):
        name = self.get_full_name()
        if not name:
            name = self.username
        return name
 
class UserActivationKey(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    activation_key = models.CharField(max_length=40, blank=True)
 
    def __str__(self):
        return self.user.username
 
#вью
def registration_view(request):
    form = UserRegistrationForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        create_hash_for_register_email(request, user)
        user.save()
        send_registration_email(request, user)
        return redirect('register-success')
    return render(request, 'adverts/registration.html', {'form': form})
 
def register_confirmation(request, activation_key):
    if request.user.is_authenticated():
        return redirect('home')
    user_check_token = get_object_or_404(UserActivationKey, activation_key=activation_key)
    # if user_profile.key_expires < datetime.datetime.now():
    #     return render_to_response('adverts/registration_link_expired.html')
    user = user_check_token
    user.is_active = True
    user.save()
    return render_to_response('adverts/registration_email_confirmed.html')
 
#утилиты
def create_hash_for_register_email(request, user):
    email = request.POST.get('email')
    email_utf = email.encode('utf-8')
    str_salt_utf = str(random.random()).encode('utf-8')
    salt = hashlib.sha1(str_salt_utf).hexdigest()[:5]
    salt_utf = salt.encode('utf-8')
    user.activation_key = hashlib.sha1(email_utf + salt_utf).hexdigest()
 
 
def send_registration_email(request, user):
    username = request.POST.get('username')
    email = request.POST.get('email')
    subject = 'Подтверждение регистрации'
    message = "Привет %s, спасибо за регистрацию. Для того чтобы активировать аккаунт," \
                      " перейдите по этой ссылке: http://127.0.0.1:8010/confirm/%s" % (username, user.activation_key)
    send_mail(subject, message, 'ххх@yandex.ru', [email], fail_silently= False)

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gasoid, 2015-12-15
@1nussebedernipes

def registration_view(request):
    form = UserRegistrationForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        key = create_hash_for_register_email(request, user)
        user.save()
        send_registration_email(user, key)
        return redirect('register-success')
    return render(request, 'adverts/registration.html', {'form': form})

def create_hash_for_register_email(request, user):
    email = request.POST.get('email')
    email_utf = email.encode('utf-8')
    str_salt_utf = str(random.random()).encode('utf-8')
    salt = hashlib.sha1(str_salt_utf).hexdigest()[:5]
    salt_utf = salt.encode('utf-8')
    key = hashlib.sha1(email_utf + salt_utf).hexdigest()
    UserActivationKey.objects.create(user=user, activation_key=key)
    return key


def send_registration_email(user, key):
    subject = 'Подтверждение регистрации'
    message = "Привет %s, спасибо за регистрацию. Для того чтобы активировать аккаунт," \
                      " перейдите по этой ссылке: http://127.0.0.1:8010/confirm/%s" % (user.username, key)
    send_mail(subject, message, 'ххх@yandex.ru', [user.email], fail_silently= False)

the rest you have i see

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question