首页 > 解决方案 > 如何通过从注册表单中获取用户名来创建@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})

标签: djangodjango-modelsdjango-formsdjango-viewsdjango-3.0

解决方案


只需覆盖表单的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)

推荐阅读