在开发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},\n {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.
答案 0 :(得分:0)
根据您的urls.py
文件,您的激活链接应如下所示:
http://0.0.0.0:8000/activate/NTY/4ze-3028a8e050e89eed45a1
但是您在激活消息中获得的网址是:
http://0.0.0.0:8000/uid%3DNTY/token%3D4ze-3028a8e050e89eed45a1
您可以通过更改格式化activation_link
的方式来解决此问题
signUp视图,可以通过以下方式完成:
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},\n {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})