更新时间:2023-01-24 14:25:01
首先需要做的是创建一个 ModelForm :
forms.py
从django.contrib.auth.models import User
class UserForm(ModelForm):
class Meta:
model = User
fields =('username','email','password')
一个ModelForm会自动根据您提供的模型构建您的表单。它根据字段处理验证。
views.py
如果是POST请求,我们从POST值创建一个UserForm。那么我们检查一下它的有效表单。如果是,我们创建用户,否则我们返回带有错误的表单。如果它不是POST请求,我们发送一个干净的表单
模板
< form method =postaction =>
{%csrf_token%}
{{form}}
< input type =submitvalue =创建新用户帐户/>
< / form>
I would like to create/add new users to my app in Django using the user input. I am using the default login provided by django. I am trying to add users to the default login. The example in 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')
passes the username and password. But i would like this to happen with user input. How do i do this?
Need some guidance...
I tried this but it doesn't seem to work:
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')
First thing you need to do is create a ModelForm:
forms.py
from django.contrib.auth.models import User
class UserForm(ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'password')
A ModelForm automatically builds your form off a model you provide. It handles the validations based on the fields.
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})
If its a POST request, we create a UserForm from the POST values. Then we check if its a valid form. If it is, we create the user, otherwise we return the form with the errors. If its not a POST request, we send a clean form
template
<form method="post" action="">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create new user account" />
</form>