激活用户Django 2.1
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了激活用户Django 2.1相关的知识,希望对你有一定的参考价值。
我在开发Django应用程序时遇到了一个问题。我需要注册用户并发送链接以激活用户帐户,但是当我点击链接时它不会激活帐户,它只会返回到我的主页。如何激活用户帐户?
我的urls.py
代码:
from django.contrib import admin
from django.urls import path
from contas.views import home, nova_transacao, update, delete, notSuper, signUp, activation_sent, activate
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='url_home'),
path('update/<int:pk>/', update, name='url_update'),
path('delete/<int:pk>/', delete, name='url_delete'),
path('403/', notSuper, name='url_notSuper'),
path('form/', nova_transacao, name='url_novaTransacao'),
path('signup/', signUp, name='url_signUp'),
path('signup/activation_sent/', activation_sent, name='url_activationSent'),
path('activate/<slug:uidb64>/<slug:token>', activate, name='activate'),
]
我的views.py
代码:
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, redirect
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from contas.tokens import account_activation_token
from .models import Transacao
from .form import TransacaoForm, SignUpForm
from django.core.mail import send_mail
from django.conf import settings
import datetime, time
# Create your views here.
def home(request):
data = {}
data["transacoes"] = Transacao.objects.all()
data["now"] = datetime.datetime.now()
return render(request, "contas/home.html", data)
def nova_transacao(request):
form = TransacaoForm(request.POST or None)
if form.is_valid():
if request.user.is_authenticated:
if request.user.is_superuser:
form.save()
return redirect('url_home')
else:
return redirect('url_notSuper')
else:
return redirect('url_login')
return render(request, "contas/form.html", {"form": form})
def update(request, pk):
transacao = Transacao.objects.get(pk=pk)
form = TransacaoForm(request.POST or None, instance=transacao)
if form.is_valid():
if request.user.is_authenticated:
if request.user.is_staff:
form.save()
return redirect('url_home')
else:
return redirect('url_notSuper')
else:
return redirect('url_login')
return render(request, "contas/form.html", {"form": form, "transacao": transacao})
def delete(request, pk):
transacao = Transacao.objects.get(pk=pk)
if request.user.is_authenticated:
if request.user.is_staff:
transacao.delete()
return redirect('url_home')
else:
return redirect('url_notSuper')
else:
return redirect('url_login')
def signUp(request):
if request.method == 'POST':
form = SignUpForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
subject = 'Ative sua conta Controller-Gastos'
uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()
token = account_activation_token.make_token(user)
activation_link = "{0}/uid={1}/token={2}".format(current_site, uid, token)
email_from = settings.EMAIL_HOST_USER
to_email = [form.cleaned_data.get('email')]
message = "Hello {0},
{1}".format(user.username, activation_link)
# send_mail(subject, message, email_from, to_email)
return HttpResponse('Please confirm your email address to complete the registration using the link below<br>' + message)
else:
form = SignUpForm()
return render(request, 'contas/signUp.html', {'form': form})
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 HttpResponse('Account activated successfully')
# time.sleep(5)
# return redirect('url_home')
else:
return render(request, 'contas/account_activation_invalid.html')
def notSuper(request):
return render(request, 'contas/notSuper.html')
def activation_sent(request):
return render(request, 'contas/activation_sent.html')
我的contas/activate.html
代码:
{% autoescape off %}
Hi {{ user.username }},
Please click on the link below to confirm your registration:
http://{{ domain }}{% url 'activate' uidb64 token %}
{% endautoescape %}
我的models.py
代码:
from django.db import models
from django.utils.timezone import now
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)
email_confirmed = models.BooleanField(default=False)
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
目前,当我注册一个新用户时,我获得了带有激活链接的HttpResponse,但它什么也没做。
Page not found (404)
Request Method: GET
Request URL: http://0.0.0.0:8000/uid%3DNTY/token%3D4ze-3028a8e050e89eed45a1
Using the URLconf defined in controle_gastos.urls, Django tried these URL patterns, in this order:
admin/
[name='url_home']
update/<int:pk>/ [name='url_update']
delete/<int:pk>/ [name='url_delete']
403/ [name='url_notSuper']
form/ [name='url_novaTransacao']
signup/ [name='url_signUp']
signup/activation_sent/ [name='url_activationSent']
activate/<slug:uidb64>/<slug:token> [name='activate']
The current path, uid=NTY/token=4ze-3028a8e050e89eed45a1, didn't match any of these.
答案
根据您的urls.py
文件,您的激活链接应如下所示:
http://0.0.0.0:8000/activate/NTY/4ze-3028a8e050e89eed45a1
但是您在激活消息中获得的URL是:
http://0.0.0.0:8000/uid%3DNTY/token%3D4ze-3028a8e050e89eed45a1
您可以通过更改在signUp视图中格式化activation_link
的方式来解决此问题,这可以通过以下方式完成:
def signUp(request):
if request.method == 'POST':
form = SignUpForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
subject = 'Ative sua conta Controller-Gastos'
uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()
token = account_activation_token.make_token(user)
# activation_link = "{0}/uid={1}/token={2}".format(current_site, uid, token)
activation_link = "{0}/activate/{1}/{2}".format(current_site, uid, token)
email_from = settings.EMAIL_HOST_USER
to_email = [form.cleaned_data.get('email')]
message = "Hello {0},
{1}".format(user.username, activation_link)
# send_mail(subject, message, email_from, to_email)
return HttpResponse('Please confirm your email address to complete the registration using the link below<br>' + message)
else:
form = SignUpForm()
return render(request, 'contas/signUp.html', {'form': form})
以上是关于激活用户Django 2.1的主要内容,如果未能解决你的问题,请参考以下文章