我不是Django的高级用户。我在网上看过很多不同的方法,但它们都是针对修改过的模型,或者太复杂,我无法理解。
我正在重复UserCreationForm
MyRegistrationForm
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
我很难理解或找到一种方法来检查用户输入的用户名是否已被占用。 所以我只是用它来重定向到html,它说错误的用户名或密码不匹配:
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
return render_to_response('invalid_reg.html')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
print args
return render_to_response('register.html', args)
这是我的注册模板(如果需要):
{% extends "base.html" %}
{% block content %}
<section>
<h2 style="text-align: center">Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>
<input type="submit" value="Register" onclick="validateForm()"/>
</form>
</section>
{% endblock %}
但是我需要在用户重定向之前提出某种异常或类似的问题。也许当用户按下注册时,他/她会收到错误/警告说用户名已被占用?这可能吗?
答案 0 :(得分:17)
您可以使用exists:
from django.contrib.auth.models import User
if User.objects.filter(username=self.cleaned_data['username']).exists():
# Username exists
...
答案 1 :(得分:3)
您可以使用username
方法检查clean_username
是否存在,并引发 ValidationError :
def clean_username(self, username):
user_model = get_user_model() # your way of getting the User
try:
user_model.objects.get(username__iexact=username)
except user_model.DoesNotExist:
return username
raise forms.ValidationError(_("This username has already existed."))
如果是这种情况,您可以在注册表单中显示错误,而无需重定向到其他页面。
根据@Spacedman指出关于在形式逻辑上针对数据库级别检查用户名唯一性的竞争条件的有效点,虽然你很有可能获得这个,如果你在这里做的是相关的SO答案可能值得读:
How to avoid race condition with unique checks in Django
根据OP的评论,这里可以对视图进行另一项更改:
def register_user(request):
# be DRY, the form can be reused for both POST and GET
form = MyRegistrationForm(request.POST or None)
# check both request is a POST and the form is valid
# as you don't need to redirect for form errors, remove else block
# otherwise it's going to redirect even form validation fails
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
# I use render so need not update the RequestContext, Django does it for you
html = render(request, 'register.html', {'form': form})
return HttpResponse(html)
希望这有帮助。
答案 2 :(得分:0)
如果您使用的是django内置的Usercreationform,则只需键入模板:
{{form.errors}}
这将检查几乎所有内容,例如: 1.是否创建用户 2.密码是否匹配
答案 3 :(得分:0)
我解决了这个问题。
forms.py
package main
import (
"bufio"
"golang.org/x/text/encoding/charmap"
"os"
)
func main() {
f, err := os.Open("LDA-PHASE90.ANS")
if err != nil {
panic(err)
}
defer f.Close()
s := bufio.NewScanner(charmap.CodePage437.NewDecoder().Reader(f))
s.Split(ansi)
for s.Scan() {
println(s.Text())
}
}
答案 4 :(得分:0)
views.py
def register(request):
form = RegisterForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
newUser = User(username=username,email=email)
newUser.set_password(password)
newUser.save()
messages.success(request,"You're registered successfully")
return redirect("user:login")
return render(request,"signup.html",{"form":form})