django - 如何通过从注册表单中获取用户名来创建@username
问题描述
我已经在前端设置了表单我想要的是任何用户如果给出他的用户名,例如用户名-> helloworld,那么它被解释为@helloworld,然后这个更改了@username的表单应该保存在数据库中,这样我就可以之后使用它.....我是 django 框架中的菜鸟。自过去 2 天以来,我一直在尝试在这里找到答案并使用谷歌,但无法找到有用的答案
这是我的->forms.py
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name','last_name','username', 'email', 'password1', 'password2']
这是我的 -> views.py 文件
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate
from django.contrib import messages
from django.contrib.auth.models import User
from .forms import SignUpForm
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
UserModel = get_user_model()
#index and signin def have been removed because it is out of context of question
def signup(request):
if request.user.is_authenticated:
return redirect('index')
else:
form = SignUpForm()
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
User.username = "@{}".format(User.username)
user.is_active = False
user = form.save
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your account.'
message = render_to_string('activation_mail.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': default_token_generator.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse('Please confirm your email address to complete the registration')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
解决方案
只需覆盖表单的save
方法即可在保存之前更改数据。
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name','last_name','username', 'email', 'password1', 'password2']
def save(self, *args, **kwargs):
self.instance.username = f"@{self.instance.username}"
return super().save(*args, **kwargs)
推荐阅读
- javascript - 如何从 Firebase 登录错误中获取冲突的电子邮件地址
- java - jsonPath Criteria 中不推荐使用的方法 andOperator() 替换为什么?
- user-interface - NVDA 读取空白,这不是预期的
- php - 在 Laravel 8 上发送自动电子邮件
- python - 带有 Nginx 和 uwsgi 的 restapi 没有传递标头信息
- python - Python - 如何在 Boto3 中处理 Cognito 客户端异常?
- asp.net - CheckBoxList ListItem 正在保存错误的值
- php - 验证输入文件
- string - 如何修复我的 VS 代码 C++ 设置,以便我可以像通常在 Xcode 或任何其他 IDE 中一样初始化我的向量?
- php - 当值为空时如何在所有行中分配“无数据”