我想實現一個登記表,但我得到了以下錯誤:Django的1.6.5 - 「無效的字面INT()與基地10」 regirstration形式
invalid literal for int() with base 10:'alex'
我之前實現它,它運作良好!但現在不行!我的表單包含'ImageField',我遵循this和this文檔和教程。我刪除了Imagefield
,但錯誤仍然存在!我在SO上看過類似的問題,但他們沒有解決問題。
該錯誤發生在username
字段中。
感謝您的任何意見。
我form.py
是:
class RegisterationForm(ModelForm):
# user name
user_name = forms.CharField(max_length=32, label="Username account")
# password
password = forms.CharField(label='Password', widget=forms.PasswordInput(render_value=False))
re_password = forms.CharField(label='Repeat Password', widget=forms.PasswordInput(render_value=False))
# email
email = forms.EmailField(label='Email Address')
class Meta:
model = WebsiteUser
exclude = ('user',)
def clean_user_name(self):
user_name = self.cleaned_data['user_name']
try:
User.objects.get(username=user_name)
except User.DoesNotExist:
return user_name
raise forms.ValidationError(u'UserName Error')
def clean(self):
password = self.cleaned_data['password']
password1 = self.cleaned_data['re_password']
if password != password1:
raise forms.ValidationError(u'Passwords are not equal')
return self.cleaned_data
和我view.py
負責我register.html
:
def register_view(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = RegisterationForm(request.POST, request.FILES)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['user_name'],
password=form.cleaned_data['password'],
email=form.cleaned_data['email'])
user.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
else:
form = RegisterationForm()
context = {'form': form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
最後我register.html
:
{% extends 'bases/home_base.html' %}
{% block content %}
<form method="POST" action="">
{% csrf_token %}
{% if form.errors %}
<p>
Fix the errors!
</p>
{% endif %}
<div id="register_div">
{% comment %} User Name {% endcomment %}
{% if form.user_name.errors %}<p>{{ form.user_name.error_messages }}</p>{% endif %}
<p><label for="user_name">User Name:</label></p>
<p>{{ form.user_name }}</p>
{% comment %} password {% endcomment %}
{% if form.password.errors %}<p>{{ form.password.error_messages }}</p>{% endif %}
<p><label for="password">password:</label></p>
<p>{{ form.password }}</p>
{% comment %} re_password {% endcomment %}
{% if form.re_password.errors %}<p>{{ form.re_password.error_messages }}</p>{% endif %}
<p><label for="re_password">re_password:</label></p>
<p>{{ form.re_password }}</p>
{% comment %} email {% endcomment %}
{% if form.email.errors %}<p>{{ form.email.error_messages }}</p>{% endif %}
<p><label for="email">email:</label></p>
<p>{{ form.email }}</p>
</div>
<input type="submit"/>
</form>
{% endblock %}
UPDATE
我model.py
:
class WebsiteUser(models.Model):
# username
user_name = models.OneToOneField(User, max_length=32)
# birth day
birth_day = models.DateField()
# email address
email = models.EmailField(max_length=50)
# watched movies
watched_movies = models.ManyToManyField(Movie, related_name='watched', blank=True, null=True)
# rated movies
rated_movies = models.ManyToManyField(Movie, related_name='rated', blank=True, null=True)
# recent movies
recent_movies = []
def __unicode__(self):
return " ".join([self.first_name, self.last_name])
回溯:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/register/
Django Version: 1.6.5
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'movie_app',
'person_app',
'home_app',
'social_auth',
'website_user')
Installed Middleware:
('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:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Programming\Django\DBMI_Final\website_user\views.py" in register_view
15. if form.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
129. return self.is_bound and not bool(self.errors)
File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
121. self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
275. self._post_clean()
File "C:\Python27\lib\site-packages\django\forms\models.py" in _post_clean
413. validate_unique=False)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in full_clean
928. self.clean_fields(exclude=exclude)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in clean_fields
970. setattr(self, f.attname, f.clean(raw_value, self))
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in clean
255. self.validate(value, model_instance)
File "C:\Python27\lib\site-packages\django\db\models\fields\related.py" in validate
1203. **{self.rel.field_name: value}
File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
593. return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
611. clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
1204. clause = self._add_q(where_part, used_aliases)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
1240. current_negated=current_negated)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
1131. clause.add(constraint, AND)
File "C:\Python27\lib\site-packages\django\utils\tree.py" in add
104. data = self._prepare_data(data)
File "C:\Python27\lib\site-packages\django\db\models\sql\where.py" in _prepare_data
79. value = obj.prepare(lookup_type, value)
File "C:\Python27\lib\site-packages\django\db\models\sql\where.py" in prepare
352. return self.field.get_prep_lookup(lookup_type, value)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_lookup
369. return self.get_prep_value(value)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
613. return int(value)
Exception Type: ValueError at /register/
Exception Value: invalid literal for int() with base 10: 'alex'
建議張貼引起錯誤和堆棧跟蹤的行。 – arocks
您至少應該指定錯誤的位置。 – Rohan
我們是否也可以看到用戶對象的模型? –