我想使用用户输入在Django中为我的应用创建/添加新用户。我使用的是django提供的默认登录名。我正在尝试将用户添加到默认登录。 https://docs.djangoproject.com/en/dev/topics/auth/中的示例:
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'john password')
传递用户名和密码。但我希望这可以通过用户输入来实现。我该怎么做?
需要一些指导......
我试过了,但它似乎不起作用:
def lexusadduser(request):
"""
add user
"""
if request.method == "POST":
user.save()
auth_user = authenticate(username=user.username,password=user.password)
if auth_user is not None:
lexusmain(request)
else:
return render('adduser.html')
答案 0 :(得分:26)
您需要做的第一件事是创建ModelForm:
<强> forms.py 强>
from django.contrib.auth.models import User
class UserForm(ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'password')
ModelForm会自动根据您提供的模型构建表单。它根据字段处理验证。
<强> views.py 强>
from forms import UserForm
from django.contrib.auth import login
from django.http import HttpResponseRedirect
def lexusadduser(request):
if request.method == "POST":
form = UserForm(request.POST)
if form.is_valid():
new_user = User.objects.create_user(**form.cleaned_data)
login(new_user)
# redirect, or however you want to get to the main view
return HttpResponseRedirect('main.html')
else:
form = UserForm()
return render(request, 'adduser.html', {'form': form})
如果是POST请求,我们会根据POST值创建一个UserForm。然后我们检查它是否是有效的表格。如果是,我们创建用户,否则我们返回带有错误的表单。如果它不是POST请求,我们发送一个干净的表单
<强>模板强>
<form method="post" action="">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create new user account" />
</form>
答案 1 :(得分:0)
使用表格。空编码在这里:
class SignupForm(forms.Form):
username = forms.CharField()
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)