- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试创建一个带有电子邮件验证的注册页面。我是 Python Dajngo 网络开发的新手。目前我使用 Python 3.6、Django 2.2.4、Postgresql 11 和 Ubuntu OS。但是我遇到了问题,无法弄清楚。各位大侠能帮我解决一下问题吗?提前致谢!
我提供了以下所有代码:
这是我得到的错误:
AttributeError at /register/
'str' object has no attribute 'decode'
Request Method: POST
Request URL: http://127.0.0.1:8000/register/
Django Version: 2.2.4
Exception Type: AttributeError
Exception Value:
'str' object has no attribute 'decode'
Exception Location: /media/coduser/KAPTRANS/ProgrammingProj-2/test/ChhichhiProject_comment_done/ChhichhiProject/chhichhi_project/users/views.py in register, line 36
Python Executable: /media/coduser/KAPTRANS/ProgrammingProj-2/test/ChhichhiProject_comment_done/ChhichhiProject/env/chhichhi/bin/python
Python Version: 3.6.8
Python Path:
['/media/coduser/KAPTRANS/ProgrammingProj-2/test/ChhichhiProject_comment_done/ChhichhiProject/chhichhi_project',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/media/coduser/KAPTRANS/ProgrammingProj-2/test/ChhichhiProject_comment_done/ChhichhiProject/env/chhichhi/lib/python3.6/site-packages']
Server time: Wed, 28 Aug 2019 09:37:05 +0000
"""
Django settings for chhichhi_project project.
Generated by 'django-admin startproject' using Django 2.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "2ba!+2akp+w%d_dfhj)u_@+rg&t8)r$&uyfwza+cza4jv55cyr"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'users.apps.UsersConfig', # new
'comments.apps.CommentsConfig', # new
'blog.apps.BlogConfig', # new
'crispy_forms', # 3rd party form styler
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'chhichhi_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'chhichhi_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'cicidb1',
'USER': 'postgres',
'PASSWORD': '1324pass',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'blog/static/')
]
STATIC_ROOT= os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_REDIRECT_URL = 'blog_home'
LOGIN_URL = 'login'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# my custom local host mail server
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'youremail@gmail.com'
EMAIL_HOST_PASSWORD = 'yourpassword'
# my custom local host mail server
# EMAIL_HOST = 'smtp.gmail.com'
# EMAIL_PORT = 465
# EMAIL_HOST_USER = 'youremail@gmail.com'
# EMAIL_HOST_PASSWORD = 'yourpassword'
# EMAIL_USE_TLS = False
# EMAIL_USE_SSL = True
# END custom mail server
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
# Email verification
from django.http import HttpResponse
# from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
# from .forms import UserSignUpForm
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode,
urlsafe_base64_decode
from django.template.loader import render_to_string
from .token_generator import account_activation_token
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
# Email verificatin end
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
email_subject = 'Activate Your Account'
message = render_to_string('activate_account.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token': account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(email_subject, message, to=[to_email])
email.send()
return HttpResponse('We have sent you an email, please confirm your email address to complete registration')
# username = form.cleaned_data.get('username')
# messages.success(request, f'Your account has been created! You are now able to log in.')
# return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html',{'form': form})
def activate_account(request, uidb64, token):
try:
uid = force_bytes(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.save()
login(request, user)
return HttpResponse('Your account has been activate successfully')
else:
return HttpResponse('Activation link is invalid!')
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.register, name='register_user'),
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.activate_account, name='activate'),
]
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active)
)
account_activation_token = TokenGenerator()
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from users import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
# path('register/', user_views.register, name='register'),
path('register/', include('users.urls')), # new url
path('profile/', user_views.profile, name='profile'),
path('login/', auth_views.LoginView.as_view(template_name = 'users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name = 'users/logout.html'), name='logout'),
path('password-reset/',
auth_views.PasswordResetView.as_view(template_name = 'users/password_reset.html'),
name='password_reset'),
path('password-reset/done/',
auth_views.PasswordResetDoneView.as_view(template_name = 'users/password_reset_done.html'),
name='password_reset_done'),
path('password-reset-confirm/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(template_name = 'users/password_reset_confirm.html'),
name='password_reset_confirm'),
path('password-reset-complete/',
auth_views.PasswordResetCompleteView.as_view(template_name = 'users/password_reset_complete.html'),
name='password_reset_complete'),
path('', include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block title %}Registration{% endblock title %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
最佳答案
你应该学会阅读你的错误跟踪,通常它们会准确地告诉你发生了什么。
在这种情况下,错误位置( Exception Location
)是行
'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode()
str
类型没有属性
decode
, 意思是
urlsafe_base64_encode(force_bytes(user.pk))
str
, 不是字节字符串,因此您不能应用该方法
decode
到它。下一步是检查
documentation for urlsafe_base64_encode你会在 Django 2.2 中读到,这将返回
str
.
bytestring
, 只需传递您从
urlsafe_base64_encode
获得的字符串直接发送到您的邮件模板。
关于django - 为什么我收到这个错误?属性错误 : 'str' object has no attribute 'decode' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57689928/
你信吗?我有一个这样的循环(请原谅任何错误,我不得不大量编辑大量信息和变量名称,相信我它有效)。 ...旧示例已删除,请参见下面的代码... 如果我将那些中间的 str = "Blah\(odat.c
我正在做一个本地测试来比较 C# 中 String 和 StringBuilder 的 Replace 操作性能,但是对于 String 我使用了以下代码: String str = "String
我想知道为什么str += "A"和 str = str + "A"有不同的表现。 在实践中, string str = "cool" for(int i = 0; i approximately
我有一个类型列表 [("['106.52.116.101']", 1), ("['45.136.108.85']", 1)] 并想将其转换为 [('106.52.116.101', 1), ('45.
我有一个类型列表 [("['106.52.116.101']", 1), ("['45.136.108.85']", 1)] 并想将其转换为 [('106.52.116.101', 1), ('45.
我正在遍历 HashMap并通过一些本地变量中的模式匹配将值放入其中。 委托(delegate)者 fn lyrics_no_bottles(song_template:&mut String){
如果字符串(短语)中只有元音,它(对我而言)说True;否则说 False。我不明白为什么它总是返回 False,因为 (x >= x) 总是返回 True。我感谢任何人检查此查询的解决方案。 (st
我有代码以某种方式转换字符串引用,例如取第一个字母 trait Tr { fn trim_indent(self) -> Self; } impl Tr for &'a str { f
我正在学习指针,这是我的代码。我定义了一个指向 char(实际上是字符串)的指针 *str 和一个指向 int *a 的指针,它们的定义方式相同。我认为 str 和 a 都应该是一个地址,但是当我试图
为什么我会收到错误消息?我已经正确添加了类型,对吗? Invalid index type "str" for "Union[str, Dict[str, str]]"; expected type
你知道下面两个函数是否等价吗? function validate(str) { return ( ['null','','undefined'].indexOf(str) [v, valida
我正在解决这里的 Dataquest 问题:https://app.dataquest.io/m/293/data-cleaning-basics/5/removing-non-digit-chara
我有一个字符串列表,如下所示: ["A TB", "A-R TB", "B TB", "B-R TB", "C TB", "C-R TB"...] 但字符串的顺序是随机的。我如何编写一个将元素配对的函
我正在尝试将此函数从使用 split 改为使用 str.extract (正则表达式)。 def bull_lev(x): spl = x.rsplit(None, 2)[-2].strip(
给定这样的数据结构: [{'a':1, 'b': 2}, {'c':3 }, {'a':4, 'c':9}, {'d':0}, {'d': 0, 'b':6}] 目标是解析数据以产生: {'a': 2
给定这样的数据结构: [{'a':1, 'b': 2}, {'c':3 }, {'a':4, 'c':9}, {'d':0}, {'d': 0, 'b':6}] 目标是解析数据以产生: {'a': 2
s = 'someString' s = QTreeWidgetItem(s) print(s.text(0)) # 0 being 'column' 输出: 's' 如果我对另一
黑白有什么区别: function(char* str ) function(char* str[] ) function(char str[] ) 它们是如何被调用的(通过什么类型的string/c
我试过谷歌搜索但找不到准确的答案,所以请允许我尝试在这里提问。如果问题看起来不合适,请告诉我,我会删除它。 在 JS 中,您可以通过三种不同的方式编写特定的内置功能: 字符串长度 str.toStri
我有这段代码(我的 strlen 函数) size_t slen(const char *str) { size_t len = 0; while (*str) {
我是一名优秀的程序员,十分优秀!