这是我的forms.py文件。我得到了一个";NameError:名称"username"未定义"在这一行:
def clean_username(self):
试图提交这份表格,但是,AFAIK,没有任何问题。
from .models import Blog
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.core.exception import ValidationError
class PostForm(forms.ModelForm):
class Meta:
model = Blog
fields = ('title', 'description',)
class SignUpForm(UserCreationForm):
username = forms.CharField(max_length=30)
first_name = forms.CharField(max_length=150) #, help_text='First Name')
last_name = forms.CharField(max_length=150) #, help_text='Last Name')
email = forms.EmailField(max_length=200, help_text='Required. Enter a valid email address')
def clean_username(self):
nom_de_guerre=self.cleaned_data['username']
if User.objects.filter(username=nom_de_guerre).exists():
raise forms.ValidationError('User with this name is already exists!')
return nom_de_guerre
def clean_email(self):
addresse_de_mail=self.cleaned_data['email']
if User.object.filter(email=addresse_de_mail).exists():
raise forms.ValidationError('User with this email is already exists!')
return addresse_de_mail
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name',)
以下是我使用此表格的看法:
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
subject = '''Activate your Bard's Lair Account'''
message = render_to_string('blog/activation_request.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
user.email_user(subject, message)
return redirect('activation_sent_view')
else:
form = SignUpForm()
return render(request, 'blog/signup.html', {'form': form}
这是我的全部回溯:
Request Method: POST
Request URL: http://www.bards-lair.com/signup/
Django Version: 4.0
Python Version: 3.8.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'portfolio',
'markdownx']
Installed 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']
Traceback (most recent call last):
File "/home/mougrim/simple_django3_blog/django3blogenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/mougrim/simple_django3_blog/django3blogenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/mougrim/simple_django3_blog/blog/views.py", line 56, in user_signup
if form.is_valid():
File "/home/mougrim/simple_django3_blog/django3blogenv/lib/python3.8/site-packages/django/forms/forms.py", line 190, in is_valid
return self.is_bound and not self.errors
File "/home/mougrim/simple_django3_blog/django3blogenv/lib/python3.8/site-packages/django/forms/forms.py", line 185, in errors
self.full_clean()
File "/home/mougrim/simple_django3_blog/django3blogenv/lib/python3.8/site-packages/django/forms/forms.py", line 404, in full_clean
self._clean_fields()
File "/home/mougrim/simple_django3_blog/django3blogenv/lib/python3.8/site-packages/django/forms/forms.py", line 419, in _clean_fields
value = getattr(self, 'clean_%s' % name)()
File "/home/mougrim/simple_django3_blog/blog/forms.py", line 19, in clean_username
def clean_username(self):
Exception Type: NameError at /signup/
Exception Value: name 'username' is not defined
如果(已清理(值有效,则需要返回该值,因此:
class SignUpForm(UserCreationForm):
username = forms.CharField(max_length=30)
first_name = forms.CharField(max_length=150) #, help_text='First Name')
last_name = forms.CharField(max_length=150) #, help_text='Last Name')
email = forms.EmailField(max_length=200, help_text='Required. Enter a valid email address')
def clean_username(self):
nom_de_guerre = self.cleaned_data['username']
if User.objects.filter(username=nom_de_guerre).exists():
raise forms.ValidationError('User with this name is already exists!')
return nom_de_guerre
def clean_email(self):
addresse_de_mail = self.cleaned_data['email']
if User.object.filter(email=addresse_de_mail).exists():
raise forms.ValidationError('User with this email is already exists!')
return addresse_de_mail
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name')