0
我想在填充表單後自動增加user_id。
它確實出現在cleared_data中,但我仍然無法註冊一個帳戶。
Django如何在表單有效後設置自定義主鍵
forms.py
class RegForm(forms.ModelForm):
password=forms.CharField(widget=forms.PasswordInput())
password_confirm = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = models.UserProfile
fields = ['user_name','password','email','birthday','address']
def clean(self):
user_id = models.UserProfile.user_id
cleaned_data = super(RegForm, self).clean()
password = cleaned_data["password"]
password_confirm = cleaned_data["password_confirm"]
if user_id == None:
self.cleaned_data['user_id'] = 1
else:
self.cleaned_data['user_id'] = models.UserProfile.objects.count() + 1
if password != password_confirm:
raise forms.ValidationError("wrong password")
return self.cleaned_data
def clean_asset_code(self):
user_name = self.cleaned_data['user_name']
if models.UserProfile.objects.filter(user_name=user_name).exists():
raise forms.ValidationError("This user_name already exist.")
return user_name
views.py
def regist(request):
if request.method == 'POST':
register_form = forms.RegForm(request.POST)
if register_form.is_valid():
register_form.save()
return HttpResponseRedirect('/')
else:
register_form = forms.RegForm()
messages.get_messages(request)
template = get_template('regist.html')
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)
謝謝!它確實有效。但是當我創建一個帳戶後,它提出**當我嘗試登錄時,'UUID'類型的對象不是JSON可序列化的**! – max
在上面添加serialize = True並檢查user_id = models.UUIDField(primary_key = True,default = uuid.uuid4,editable = False,serialize = True) –
你是什麼意思「add serialize = True in above」,結果相同在我添加** serialize = True ** – max