Python django.contrib.auth.forms 模块,UserCreationForm() 实例源码
我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用django.contrib.auth.forms.UserCreationForm()。
def signup(request):
if request.user.is_authenticated:
return HttpResponseRedirect('/post/')
if request.method == 'GET':
form = UserCreationForm()
return render(request, 'tilweb/signup.html', {'form': form})
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
# https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#the-save-method
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect('/post/')
else:
# If there were errors,we render the form with these
# errors
return render(request, {'form': form})
def register(request):
'''
?????
'''
if request.method != 'POST':
form = UserCreationForm()
else:
form = UserCreationForm(data=request.POST)
if form.is_valid():
new_user = form.save()
authenticated_user = authenticate(username=new_user.username,
password=request.POST['password1'])
login(request, authenticated_user)
return HttpResponseRedirect(reverse('logs:index'))
context = {'form': form}
return render(request, 'users/register.html', context)
def register(request):
username = auth.get_user(request).username
if not (username):
args={}
args.update(csrf(request))
args['form']=UserCreationForm()
if request.POST:
newuser_form=UserCreationForm(request.POST)
if newuser_form.is_valid():
newuser_form.save()
newuser = auth.authenticate(username=newuser_form.cleaned_data['username'],password=newuser_form.cleaned_data['password2'])
auth.login(request, newuser)
return redirect('/')
else:
args['errors'] = format_html('<div class="main-error alert alert-error">?????? ??? ???????????</div>')
args['form'] = newuser_form
return render_to_response('register.html',args)
else:
return redirect('/')
def create_user(request, agent_id):
if not request.user.is_staff:
return render_to_response('valueaccounting/no_permission.html')
agent = get_object_or_404(EconomicAgent, id=agent_id)
if request.method == "POST":
user_form = UserCreationForm(data=request.POST)
#import pdb; pdb.set_trace()
if user_form.is_valid():
user = user_form.save(commit=False)
user.email = agent.email
is_staff = request.POST.get("is_staff")
if is_staff == 'on':
user.is_staff = True
#user.last_login = datetime.datetime.Now()
user.save()
au = AgentUser(
agent = agent,
user = user)
au.save()
if use_faircoins:
agent.request_faircoin_address()
return HttpResponseRedirect('/%s/%s/'
% ('accounting/agent', agent.id))
def signup_view(request):
if request.user.is_authenticated():
return redirect(reverse('home_projects'))
if request.method == 'POST':
post = request.POST
form = UserCreationForm(post)
if form.is_valid():
form.save()
new_post = QueryDict(mutable=True)
new_post.update(post)
new_post['password'] = post['password1']
request.POST = new_post
return login_view(request)
else:
log.warn(form.is_valid())
log.warn(form.errors)
else:
form = UserCreationForm()
token = {}
token.update(csrf(request))
token['form'] = form
return render(request, 'signup.html', token)
def update_profile(request):
if request.method == 'POST':
user_form = UserCreationForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST, instance=request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, 'Your profile was successfully updated!')
return redirect('settings:profile')
else:
messages.error(request, 'Please correct the error below.')
else:
user_form = UserCreationForm(instance=request.user)
profile_form = ProfileForm(instance=request.user.profile)
return render(request, 'profiles/profile.html', {
'user_form': user_form,
'profile_form': profile_form
})
def create_profile(request):
if request.method == 'POST':
user_form = UserCreationForm(data=request.POST)
profile_form = ProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save(commit=False)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
messages.success(request, 'Your profile was successfully created!')
return redirect('/dashboard/')
else:
messages.error(request, 'Please correct the error below.')
else:
# GET request.. return the form
user_form = UserCreationForm()
profile_form = ProfileForm()
return render(request, 'people/create_profile.html', {'user_form': user_form, 'profile_form': profile_form})
def register_view(request):
if request.user.is_authenticated:
return close_response(request)
if request.method == 'POST':
form = UserCreationForm(data=request.POST)
if form.is_valid():
user = form.save()
login(request, user)
redeem_token_after_login(request)
return close_response(request)
else:
form = UserCreationForm()
form.fields['username'].max_length = 20
for field in form.fields.values():
field.help_text = None
return render(request, 'site/account_form.html', {
'title': _('Create new account'),
'back_url': reverse('site.login'),
'form': form
})
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
# Add honeypots
self.honeypot_fieldnames = "address", "phone"
self.honeypot_class = ''.join(
random.choice(string.ascii_uppercase + string.digits)
for __ in range(10))
self.honeypot_jsfunction = 'f' + ''.join(
random.choice(string.ascii_uppercase + string.digits)
for __ in range(10))
for fieldname in self.honeypot_fieldnames:
self.fields[fieldname] = forms.CharField(
widget=forms.TextInput(attrs={'class': self.honeypot_class}),
required=False,
)
def sign_up(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(data=request.POST)
if form.is_valid():
form.save()
return redirect(reverse('example:log_in'))
else:
print(form.errors)
return render(request, 'example/sign_up.html', {'form': form})
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
user.groups.add(Group.objects.get_or_create(name='basic_user')[0])
user.save()
return user
def create_user_and_agent(request):
#import pdb; pdb.set_trace()
if not request.user.is_superuser:
return render_to_response('valueaccounting/no_permission.html')
agent_selection_form = AgentSelectionForm(data=request.POST or None)
agent_form = CreateAgentForm(data=request.POST or None)
user_form = UserCreationForm(data=request.POST or None)
if request.method == "POST":
#import pdb; pdb.set_trace()
selected_agent = None
if agent_selection_form.is_valid():
selected_agent = agent_selection_form.cleaned_data['selected_agent']
agent_form = CreateAgentForm(
data=request.POST or None,
instance=selected_agent
)
if agent_form.is_valid() and user_form.is_valid():
agent = agent_form.save(created_by=request.user)
user = user_form.save(commit=False)
user.first_name = request.POST.get("first_name")
user.last_name = request.POST.get("last_name")
user.email = request.POST.get("email")
user.save()
au = AgentUser(
agent = agent,
user = user)
au.save()
return HttpResponseRedirect('/%s/%s/'
% ('accounting/agent', agent.id))
return render_to_response("valueaccounting/create_user_and_agent.html", {
"user_form": user_form,
"agent_form": agent_form,
"agent_selection_form": agent_selection_form,
}, context_instance=RequestContext(request))
def is_valid(self, bundle, request=None):
data = bundle.data or {}
if request.method == "PUT":
errors = {}
try:
user = get_object_or_404(User, pk=data['id'])
except KeyError:
errors['id'] = ['id attribute is mandatory']
else:
change_pw_fields = ['new_password1', 'new_password2']
if any((True for k in change_pw_fields if data[k] is not None)):
from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm
# Non-superusers always require old_password
# Superusers require old_password when editing themselves
if not request.user.is_superuser or request.user.id == user.id:
form = PasswordChangeForm(user, data)
else:
form = SetPasswordForm(user, data)
if not form.is_valid():
errors.update(form.errors)
return errors
form = ChromaUserChangeForm(data, instance=user)
if not form.is_valid():
errors.update(form.errors)
return errors
elif request.method == "POST":
form = UserCreationForm(data)
if form.is_valid():
return {}
else:
return form.errors
else:
raise NotImplementedError
def register_page(request):
form = UserCreationForm(data=request.POST)
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect('login')
return render(request, 'registration/register.html', {'form': UserCreationForm()})
def test_registration_uses_register_form(self):
response = self.client.get(reverse('register'))
registration_form = response.context['form']
self.assertisinstance(registration_form, UserCreationForm)
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
user = authenticate(
username=form.cleaned_data.get('username'),
password=form.cleaned_data.get('password1')
)
login(request, user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'registration/signup.html', {'form': form})
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
user = authenticate(
username=form.cleaned_data.get('username'), {'form': form})
def sign_up(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(data=request.POST)
if form.is_valid():
form.save()
return redirect(reverse('example:log_in'))
else:
print(form.errors)
return render(request, {'form': form})
def register_view(request):
redirect_path = request.GET['r'] if request.GET.get('r', '').startswith('/editor/') else reverse('editor.index')
if request.user.is_authenticated:
return redirect(redirect_path)
if request.method == 'POST':
form = UserCreationForm(data=request.POST)
if form.is_valid():
user = form.save()
login(request, user)
if request.changeset.pk is not None:
request.changeset.author = user
request.changeset.save()
return redirect(redirect_path)
else:
form = UserCreationForm()
form.fields['username'].max_length = 20
for field in form.fields.values():
field.help_text = None
return render(request, 'editor/account_form.html',
'form': form
})
def clean(self):
cd = super(UserCreationForm, self).clean()
for fieldname in self.honeypot_fieldnames:
if cd[fieldname]:
raise forms.ValidationError(
"Thank you,non-human visitor. Please keep trying to fill in the form.")
return cd
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
return HttpResponseRedirect('/accounts/login/')
else:
form = UserCreationForm()
return render_to_response('register.html', RequestContext(request,locals()))
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return render_to_response('registration/registration_complete.html')
else:
form = UserCreationForm()
token = {}
token.update(csrf(request))
token['form'] = form
return render_to_response('registration/registration_form.html', token)
def save(self, self).save(commit=False)
LOG.debug("user_type from form:" + self.cleaned_data['user_type'])
if commit:
user.save() # First save the created user,
user.basicinfo.user_type = self.cleaned_data['user_type']
user.save() # save the basic info
return user
def register(request):
s = "%12x" % uuid.getnode()
mac = ":".join(x+y for x, y in zip(s[::2], s[1::2]))
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
Usertable.objects.create(name=user,address=mac)
return HttpResponseRedirect('/accounts/login/')
else:
form = UserCreationForm()
return render_to_response('register.html',RequestContext(request,locals()))
def save(self, self).save(commit=False)
user.email = self.cleaned_data["email"]
user.username = self.cleaned_data["username"]
if commit:
user.save()
return user
def save(self, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, {'form': form})
def register(request):
'''?????????????'''
if request.method != 'POST':
form = UserCreationForm()
else:
# ???????
form =UserCreationForm(data=request.POST)
if form.is_valid():
new_user = form.save()
#???????????????
authenticated_user = authenticate(username=new_user.username, password=request.POST['password1'])
login(request, authenticated_user)
return HttpResponseRedirect(reverse('learning_logs:index'))
context = {'form': form}
return render (request, 'user/register.html', context)
def inscription(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, user)
return redirect('/')
else:
form = UserCreationForm()
return render(request, 'inscription.html', {'form': form})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。