def post(self, request, *args, **kwargs): # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and PublicForm. form_args = { 'data': request.POST, } user_form = UserForm(data=request.POST, instance=request.user) instance = UserProfile.objects.get(user=request.user) kwargs.setdefault('curruser', instance) profile_form = UserProfileForm(data=request.POST, instance=instance) # If the two forms are valid... if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Now sort out the Public instance. # Since we need to set the user attribute ourselves, we set commit=False. # This delays saving the model until we're ready to avoid integrity problems. profile = profile_form.save(commit=False) profile.user = user # Did the user provide a profile picture? # If so, we need to get it from the input form and put it in the Public model. if 'picture' in request.FILES: profile.picture = request.FILES['picture'] # Now we save the Public model instance. profile.save() # Invalid form or forms - mistakes or something else? # Print problems to the terminal. # They'll also be shown to the user. else: print user_form.errors, profile_form.errors kwargs.setdefault("user_form", self.user_form_class(instance=instance.user)) kwargs.setdefault("profile_form", self.profile_form_class(instance=instance)) return super(Profile, self).get(request, *args, **kwargs)
def settings(request): user_details = get_object_or_404(UserDetails, user=request.user) following = request.user.following.all() followers = request.user.followers.all() if request.POST: form = UserForm(request.POST) if form.is_valid(): request.user.email = form.cleaned_data['email'] request.user.save() user_details.about_me = form.cleaned_data['about_me'] user_details.save() return redirect('settings') form = UserForm(initial={ 'email': request.user.email, 'about_me': user_details.about_me }) context = { "username": request.user.username, "about_me": user_details.about_me, "gravatar": user_details.gravatar(), "following": following, "followers": followers, "following_count": len(following), "follower_count": len(followers), "form": form, } return render(request, 'accounts/settings.html', context)
def user_profile(request): profile = request.user.get_profile() if request.method == "POST": # Read params form = ProfileForm(request.POST, instance=profile) subscriptionform = SubscriptionForm(request.POST, instance=profile) userform = UserForm(request.POST, instance=request.user) if appsettings.DEMO_SERVER and request.user.username == "demo": messages.warning(request, _("You can not change demo profile on the demo server.")) return redirect("profile") if form.is_valid() and userform.is_valid() and subscriptionform.is_valid(): # Save changes form.save() subscriptionform.save() userform.save() # Change language set_lang(request.user, request=request, user=request.user) # Redirect after saving (and possibly changing language) response = redirect("profile") # Set language cookie and activate new language (for message below) lang_code = profile.language response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) translation.activate(lang_code) messages.info(request, _("Your profile has been updated.")) return response else: form = ProfileForm(instance=profile) subscriptionform = SubscriptionForm(instance=profile) userform = UserForm(instance=request.user) social = request.user.social_auth.all() social_names = [assoc.provider for assoc in social] new_backends = [x for x in load_backends(BACKENDS).keys() if x == "email" or x not in social_names] response = render_to_response( "accounts/profile.html", RequestContext( request, { "form": form, "userform": userform, "subscriptionform": subscriptionform, "profile": profile, "title": _("User profile"), "licenses": Project.objects.exclude(license=""), "associated": social, "new_backends": new_backends, }, ), ) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, profile.language) return response
def profile(request, success_url='/accounts/profile/', form_class=ProfileForm, template_name='accounts/profile_form.html'): usp = UserProfile.objects.get_or_create(user=request.user)[0] if request.method == 'POST': form = form_class(request.POST, request.FILES, instance=usp) user_form = UserForm(request.POST, instance=request.user) forms = (form, user_form) if not False in [i.is_valid() for i in forms]: for i in forms: i.save() return HttpResponseRedirect(success_url) else: form = form_class(instance=usp) user_form = UserForm(instance=request.user) return render_to_response(template_name, { 'form': form, 'user_form': user_form, 'profile': usp, 'left_links': None }, context_instance=RequestContext(request))
def signup(request): context = {} context['title'] = _('Register') user = User() if request.user.is_authenticated(): return redirect('accounts_accounts') userProfile = UserProfile() if request.method == 'POST': userForm = UserForm(request.POST, instance=user) userProfileForm = UserProfileForm(request.POST, instance=userProfile) if userForm.is_valid() and userProfileForm.is_valid(): userData = userForm.cleaned_data user.username = userData['username'] user.first_name = userData['first_name'] user.last_name = userData['last_name'] user.email = userData['email'] user.set_password(userData['password']) user.save() userProfile = user.get_profile() userProfileData = userProfileForm.cleaned_data userProfile.gender = userProfileData['gender'] userProfile.birthday = userProfileData['birthday'] userProfile.save() user = authenticate(username=userData['username'], password=userData['password']) login(request, user) return redirect('accounts_accounts') else: userForm = UserForm(instance=user) userProfileForm = UserProfileForm(instance=userProfile) context['userForm'] = userForm context['userProfileForm'] = userProfileForm return render_to_response('accounts/register.html', context, context_instance=RequestContext(request))
def add_employee(request): check_user_login(request) u = User.objects.all() countries = get_country() user_form = UserForm(request.POST or None) employee_form = EmployeeForm(request.POST or None) emp = Employee.objects.get(user = User.objects.get(username = request.session['username']).id) if request.method == 'POST': if employee_form.is_valid(): if user_form.is_valid(): user = user_form.save(commit = False) password = user_form.cleaned_data['password'] user.set_password(password) user.save() employee = employee_form.save(commit = False) employee.user = user if 'profile_pic' in request.FILES: employee.profile_pic = request.FILES['profile_pic'] employee.save() messages.success(request, 'You hav success added new employee!') return HttpResponseRedirect(reverse('accounts:employees')) else: messages.warning(request, 'Some information missing!') return render(request, "accounts/register.html", {'user_form': user_form, 'employee_form': employee_form, "countries": countries,"employee":emp,}) return render(request, "accounts/register.html", {'user_form': user_form, 'employee_form': employee_form, "countries": countries,"employee":emp,})
def userinfo(request): if not request.session.get('is_login'): return HttpResponseRedirect(reverse('accounts:login')) user_id = request.session.get('user_id') user = User.objects.get(id=user_id) likes = user.likerecord_set.all() pars = user.parrecord_set.all() if user.groups_set.filter(user_id=user_id): group = user.groups_set.get(user_id=user_id) isgroup = group.permitted group_name = group.group_name else: isgroup = False if request.method != 'POST': form = UserForm(instance=user) else: form = UserForm(instance=user, data=request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] if (user.username != username) and (User.objects.filter( username=username)): message = 'username already exists' return render(request, 'accounts/userinfo.html', locals()) else: if (User.objects.filter( email=email)) and (user.email != email): message = 'email address already exists' return render(request, 'accounts/userinfo.html', locals()) user.username = username user.email = email user.save() request.session['user_name'] = username notice = 'you have successfully edit your information' return render(request, 'accounts/userinfo.html', locals())
def register(request): registered = False profile = UserProfile.objects.get(user=request.user) if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() registered = True else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() return render(request, 'accounts/reg.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered, 'profile': profile,} )
def test_profile_forms(self): user_form_data = {'username': '******', 'first_name': 'dave', 'last_name': 'Bright', 'email':'*****@*****.**', 'password':'******', 'password_confirm':'pwd123', } user_form = UserForm(data=user_form_data) if not user_form.is_valid(): print user_form.errors else: self.assertTrue(user_form.is_valid()) user = user_form.save(commit=False) user.set_password(user.password) user.save() profile_form_data = { 'birth_year':1983, 'captcha_0':'dummy-value', 'captcha_1':'PASSED' } profile_form = UserProfileForm(data=profile_form_data) if not profile_form.is_valid(): print profile_form.errors else: profile = profile_form.save(commit=False) profile.user = user profile.save()
def contrainer(request, urlloc): if request.method == "POST": form = UserForm(request.POST, request.FILES) if form.is_valid(): compte = form.save() cheekin_v = Checkin() doc = urlloc.split("a") locx = doc[0].replace("p", ".") locy = doc[1].replace("p", ".") cheekin_v.username = User.objects.get(username=compte.username) cheekin_v.x = Decimal(locx) cheekin_v.y = Decimal(locy) cheekin_v.cheek_date = timezone.now() cheekin_v.save() request.session['username'] = newuser.id # compte = User.objects.all()[User.objects.count()-1] compte = User.objects.get(id=request.session['username']) cheekin_compte = Checkin.objects.get(username=compte) cheekin_view = Checkin.objects.all().order_by('-cheek_date') vx = float(cheekin_compte.x) vy = float(cheekin_compte.y) aux = [] # user in space of 2km of your current compte for d in cheekin_view: m = float(d.x) n = float(d.y) if vx - 0.2 < m < vx + 0.2 and vy - 0.2 < n < vy + 0.2: f = User.objects.filter(username=d.username) aux.append(f) return render(request, 'space/index.html', { 'vuser': aux, 'last': compte, 'cheekin': cheekin_view, 'x': urlloc })
def register(request): context = RequestContext(request) registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() registered = True else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() #Render the template depending on the context return render_to_response('register.html', {'user_form':user_form,'profile_form':profile_form, 'registered':registered}, context )
def edit_profile(request): """ Create a view that allows us to edit your profile """ user = request.user profile = user.profile if request.method == 'POST': # create a form instance and populate it with data from the request: userForm = UserForm(request.POST) profileForm = ProfileForm(request.POST, request.FILES, instance=profile) # check whether it's valid: if userForm.is_valid() and profileForm.is_valid(): # Save User model fields user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.email = request.POST['email'] user.save() profile = profileForm.save(commit=False) profile.save() # if a GET (or any other method): create a blank form else: userForm = UserForm(instance=user) profileForm = ProfileForm(instance=profile) return render(request, 'profile.html', { 'userForm': userForm, 'profileForm': profileForm })
def profile(request): form = UserForm(instance=request.user) pwd_form = PasswordChangeForm(request.user) associations = {'twitter': False, 'google_oauth2': False, 'github': False} for association in request.user.social_auth.all(): associations[association.provider.replace('-', '_')] = True if request.method == 'POST': if request.POST.get('do_password'): pwd_form = PasswordChangeForm(request.user, request.POST) if pwd_form.is_valid(): pwd_form.save() messages.success(request, "Password successfully changed.") else: messages.error(request, "Could not update password. See errors below.") elif request.POST.get('do_profile'): form = UserForm(request.POST, instance=request.user) if form.is_valid(): form.save() messages.success(request, 'Profile successfully updated.') else: messages.error(request, 'You have an error in your profile. See below errors.') else: messages.error(request, "Er, something weird happened. Contact the site admin.") return render(request, 'accounts/profile.html', locals())
def edit_my_profile(request): u = request.user try: profile = u.get_profile() except UserProfile.DoesNotExist: profile = None if request.method == 'POST': POST = request.POST.copy() POST['user'] = u.id profile_form = UserProfileForm(POST, request.FILES, instance=profile) user_form = UserForm(request.POST, request.FILES, instance=u) if user_form.is_valid() and profile_form.is_valid(): u = user_form.save() profile = profile_form.save() profile.user = u request.user.message_set.create(message="Your Profile was updated") return HttpResponseRedirect(profile.get_absolute_url()) else: user_form = UserForm(instance=u) if profile: profile_form = UserProfileForm(instance=profile) else: profile_form = UserProfileForm(initial={'user':request.user}) return render(request, 'edit_profile.html', {'profile_form':profile_form, 'user_form':user_form})
def edit_user(request): profile = User_Profile.objects.get(User_associated=request.user) user = User.objects.get(id=request.user.id) # img = None if request.method == "POST": profileForm = ProfileForm(request.POST, instance=profile, prefix="profile_form") userForm = UserForm(request.POST, instance=user, prefix="user_form") # passwordForm = PasswordChangeForm(data=request.POST, user=request.user, prefix="password_form") if profileForm.is_valid() and userForm.is_valid(): profileForm.save() userForm.save() # passwordForm.save() else: profileForm = ProfileForm(prefix="profile_form", instance=profile, initial={"Degree": profile.Degree, "Year_first_enrolled": profile.Year_first_enrolled,}) userForm = UserForm(prefix="user_form", instance=user, initial={'username': user.username, 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name}) return render_to_response("accounts/settings.html", {"profile_form": profileForm, "user_form": userForm}, context_instance=RequestContext(request))
def add_teammate(request, slug): user = request.user friends = AccountDetails.get_my_friends(user) if len(friends) == 0: return render(request, 'friends/no_friends.html') event = Event.objects.get(slug=slug) form = UserForm(request.POST or None) context = {'form': form} filtered_users = [] if request.method == 'POST': if form.is_valid(): username = request.POST.get('username') users = User.objects.all().filter(username__icontains=username) for user in users: if AccountDetails.is_my_friend(request.user, user): if AccountDetails.objects.filter(user=user): details = AccountDetails.objects.get(user=user) user.details = details user.my_friend = AccountDetails.is_my_friend( request.user, user) filtered_users.append(user) context = {'users': filtered_users, 'form': form, 'event': event} return render(request, 'events/add_teammate.html', context)
def user_profile(request): """ Form to update User profile """ user_ = get_user_in_token(request) if request.method == 'POST': nic = request.POST.get('nicname') profileForm = UserProfileForm(request.POST, request.FILES, instance=user_.get_profile()) userForm = UserForm(request.POST, instance=user_) # if profileForm.is_valid() and userForm.is_valid(): if profileForm.is_valid(): profileForm.save() userForm.save() return output_format_json_response(201, message='프로필이 변경 되었습니다.', statusCode='0000') else: profile = request.user.get_profile() profile_data = { 'nickname': profile.nickname, 'picture_url': profile.get_image_url(), 'phone_number': profile.phone_number } return output_format_response(200, statusCode='0000', data=profile_data) return output_format_json_response(message='요청이 잘못되었습니다.', statusCode='5555')
def signup_user(request): if request.method == 'GET': context = { 'user_form': UserForm(), 'profile_form': UserProfileForm(), } return render(request, 'accounts/signup.html', context) else: user_form = UserForm(request.POST) profile_form = UserProfileForm(request.POST, request.FILES) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() profile = profile_form.save(commit=False) profile.user = user group = Group.objects.get(name='customer') user.groups.add(group) profile.save() login(request, user) return redirect('user profile') context = { 'user_form': user_form, 'profile_form': profile_form, } return render(request, 'accounts/signup.html', context)
def post(self, *args, **kwargs): data = self.request.POST # Load User and Profile forms form = UserForm(data) profileform = UserProfileForm(data) # Calls the validation method of the two model forms if form.is_valid() and profileform.is_valid(): # create and save user object user = form.save() # create and save profile object # assign `user` as a fk of the user field in the profile object profile = profileform.save(commit=False) profile.user = user profile.save() # authenticate user self.login_user_no_password(user) # Redirect to dashboard return HttpResponseRedirect(reverse('dashboard')) else: self.context['form'] = form self.context['profileform'] = profileform return render(self.request, self.template_name, self.context)
def test_password_no_match(self): user_form_data = {'username': '******', 'first_name': 'martin', 'last_name': 'Bright', 'email':'*****@*****.**', 'password':'******', 'password_confirm':'pwd123x', } user_form = UserForm(data=user_form_data) if not user_form.is_valid(): pass # print user_form.errors else: self.assertTrue(user_form.is_valid()) user = user_form.save(commit=False) user.set_password(user.password) profile_form_data = { 'birth_year':1983, 'captcha_0':'dummy-value', 'captcha_1':'PASSED' } profile_form = UserProfileForm(data=profile_form_data) self.assertFalse(profile_form.is_valid(), "test_password_no_match not success")
def register(request): if request.user.is_authenticated: return redirect("/") if request.method == "POST": errors = {} gender = request.POST.get('gender') name = request.POST.get('name') email = request.POST.get('email') password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') age = request.POST.get('age') if password != confirm_password: errors["password"] = "******" return render(request, 'accounts/register.html', errors) else: form = UserForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get("password1") user.set_password(password) user.save() return redirect('/') else: print(form.errors) return render(request, 'accounts/register.html') return render(request, 'accounts/register.html')
def test_userform_data_is_valid(self): form = UserForm(data={ 'username': '******', 'email': '*****@*****.**', 'password': '******' }) self.assertEqual(form.is_valid(), True)
def donation_request(request): donation_form = DonationForm(data=request.POST or None) user_form = UserForm(data=request.POST or None) if donation_form.is_valid(): donation = donation_form.save(commit=False) user = None send_mail_new_user = False if request.user.is_authenticated(): user = request.user elif user_form.is_valid(): user = user_form.save() send_mail_new_user = True if user: donation.user = user donation.save() send_mail_compatible_donors.delay(donation.id) if send_mail_new_user: send_signup_mail.delay(user.name, user.email) messages.add_message( request, messages.SUCCESS, _(u'Sua solicitação foi gravada com sucesso! Vamos procurar doadores compatíveis com o tipo sanguíneo informado. Você pode ajudar compartilhando este link com amigos através das redes sociais.' )) return redirect('donation_details', donation_id=donation.id) return render_to_response('donations/donation_request.html', { 'donation_form': donation_form, 'user_form': user_form }, context_instance=RequestContext(request))
def test_success_user_form(self): """正常な入力を行いエラーにならないことを検証""" print('Test Case 4-1') print() user = User() form = UserForm(data={'username': '******', 'password': '******'}, instance=user) self.assertTrue(form.is_valid())
def registration(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() registered = True else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() return render(request, 'accounts/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
def test_failure_user_form(self): """正常ではない入力を行いエラーになることを検証""" print('Test Case 4-2') print() user = User() form = UserForm(data={'username': '', 'password': '******'}, instance=user) self.assertTrue(not(form.is_valid()))
def add_operator(request): is_login = True user = request.user form = UserForm() if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): new_user = User.objects.create_user( username = form.cleaned_data['username'], first_name = form.cleaned_data['first_name'], last_name = form.cleaned_data['last_name'], email = form.cleaned_data['email'], password = form.cleaned_data['password'], ) request.session['user_created'] = json.dumps(True) request.session['user_created_id'] = json.dumps(new_user.id) return redirect("/accounts/operatorslist/") context = { "header": { "title": "Добавить оператора" }, "is_login": is_login, "user": user, "form": form } template = loader.get_template('accounts/addaccount.html') return HttpResponse(template.render(context, request))
def register(request): if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() context = {'user_form' : user_form, 'profile_form' : profile_form} return render_to_response('accounts/register.html', context, context_instance=RequestContext(request))
def register(request): # Like before, get the request's context. context = RequestContext(request) # A boolean value for telling the template whether the registration was successful. # Set to False initially. Code changes value to True when registration succeeds. registered = False # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. # Note that we make use of both UserForm and UserProfileForm. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # If the two forms are valid... if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Now we hash the password with the set_password method. # Once hashed, we can update the user object. user.set_password(user.password) user.save() # Now sort out the UserProfile instance. # Since we need to set the user attribute ourselves, we set commit=False. # This delays saving the model until we're ready to avoid integrity problems. profile = profile_form.save(commit=False) profile.user = user # Did the user provide a profile picture? # If so, we need to get it from the input form and put it in the UserProfile model. if 'picture' in request.FILES: profile.picture = request.FILES['picture'] # Now we save the UserProfile model instance. profile.save() # Update our variable to tell the template registration was successful. registered = True # Invalid form or forms - mistakes or something else? # Print problems to the terminal. # They'll also be shown to the user. else: print user_form.errors, profile_form.errors # Not a HTTP POST, so we render our form using two ModelForm instances. # These forms will be blank, ready for user input. else: user_form = UserForm() profile_form = UserProfileForm() # Render the template depending on the context. return render_to_response( 'register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, context)
def test_UserForm_blank_invalid(self): form = UserForm(data={ 'username': "", 'first_name': "", 'email': "", 'password': "" }) self.assertFalse(form.is_valid())
def post(self, request): profile_form = UserForm(request.POST, request.FILES, instance=request.user) if profile_form.is_valid(): profile_form.save() return redirect('accounts_profile') else: return self._render(request, profile_form=profile_form)
def register_view(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return HttpResponse('<h2>Thank you! You are now registered!</h2>') return render(request, 'accounts/registration_form.html', {'form': form})
def post(self, request): form = UserForm(request.POST, instance=request.user) if form.is_valid(): request.user.save() messages.add_message(request, messages.SUCCESS, "You profiles was updated successfully!") else: for error in form.errors: messages.add_message(request, messages.ERROR, error) return redirect('profile')
def register(request): if request.method == 'POST': uf = UserForm(request.POST) if uf.is_valid(): user = uf.save() return HttpResponseRedirect('main') else: uf = UserForm() return render_to_response('register.html', {'form': uf}, RequestContext(request))
def client_create(request): form = UserForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return redirect('accounts:clients') return render(request, "clients/client_create.html", context={"form": form})
def edit_profile(request): if request.method == 'POST': form = UserForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('account') else: form = UserForm(instance=request.user) return render(request, 'registration/edit_profile.html', {'form':form})
def test_UserForm_valid(self): form = UserForm( data={ 'username': "******", 'first_name': "krzz", 'last_name': self.user.last_name, 'email': self.user.email, 'password': self.user.password }) self.assertTrue(form.is_valid())
def signup(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): del(form.cleaned_data["password2"]) User.objects.create_user(**form.cleaned_data) return redirect("board:board_list") else: form = UserForm() return render(request, "accounts/signup.html", {"form": form})
def test_UserForm_blank_email(self): form = UserForm( data={ 'username': "******", 'first_name': "tmp", 'last_name': self.user.last_name, 'email': "", 'password': self.user.password }) self.assertTrue(form.is_valid())
def test_UserForm_blank_username(self): form = UserForm( data={ 'username': "", 'first_name': self.user.first_name, 'last_name': self.user.last_name, 'email': self.user.email, 'password': self.user.password }) self.assertFalse(form.is_valid())
def test_UserForm_blank_passwoard(self): form = UserForm( data={ 'username': "******", 'first_name': "tmp", 'last_name': self.user.last_name, 'email': self.user.email, 'password': "" }) self.assertFalse(form.is_valid())
def registration_page(request): if request.method == 'GET': UserCreationForm = UserForm return render(request, 'registration.html', {'form': UserCreationForm}) if request.method == 'POST': UserCreationForm = UserForm(request.POST) if UserCreationForm.is_valid(): context = {} full_name = UserCreationForm.cleaned_data['full_name'] email = UserCreationForm.cleaned_data['email'] address = UserCreationForm.cleaned_data['address'] password1 = UserCreationForm.cleaned_data['password1'] password2 = UserCreationForm.cleaned_data['password2'] Captcha_response = request.POST['g-recaptcha-response'] secret_key = '6Lco6RwaAAAAAPplcNfJsiKRBXvHXQzFRyPzXesO' sending_request = requests.post( 'https://www.google.com/recaptcha/api/siteverify', data={ 'response': Captcha_response, 'secret': secret_key }) status = json.loads(sending_request.text)['success'] if password1 != password2: context['passerror'] = 'password did not match' context['form'] = UserForm return render(request, 'registration.html', context) elif status == False: context['form'] = UserForm context['captcha_error'] = 'captcha validation failed' return render(request, 'registration.html', context) else: try: User.objects.get(email=email) return render(request, 'registration.html', { 'form': UserForm, 'userexist': 'user aready exists' }) except User.DoesNotExist: create_user = User.objects.create_user(password=password1, full_name=full_name, email=email, address=address) return render( request, 'registration.html', { 'form': UserForm, 'success': 'account created successfully.You can login now' })
def register(request): context = RequestContext(request) registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.is_active = False username = user.username email = user.email salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(salt + email).hexdigest() key_expires = datetime.datetime.today() + datetime.timedelta(2) user.save() profile = profile_form.save(commit=False) profile.user = user profile.activation_key = activation_key profile.key_expires = key_expires profile.save() registered = True # Send email with activation key email_subject = 'Account confirmation' email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \ 48hours http://127.0.0.1:8000/accounts/confirm/%s" % (username, activation_key) send_mail(email_subject, email_body, '*****@*****.**', [email], fail_silently=False) else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() # Render the template depending on the context. return render_to_response( 'accounts/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, context)
def test_userForm_valid_form(self): context = { 'first_name': 'ggg', 'last_name': 'mmm', 'username': '******', 'password': '******', 'email': '*****@*****.**' } form = UserForm(context) self.assertTrue(form.is_valid())
def user_add(): """ 创建用户 """ form = UserForm() if form.validate_on_submit(): user_obj = form.save() if user_obj is None: flash('服务器忙,稍后重试', 'danger') else: flash('{},创建成功'.format(user_obj.username), 'success') return redirect(url_for('index')) return render_template('add.html', form=form)
def test_userForm_invalid_form(self): a = self.create_user() context = { 'first_name': a.first_name, 'last_name': '', 'username': a.username, 'password': a.password, 'email': a.email } form = UserForm(context) self.assertFalse(form.is_valid())
def post(self, request, *args, **kwargs): self.user_form = UserForm(request.POST, instance=request.user) if self.user_form.is_valid(): self.user_form.save() messages.add_message(request, messages.SUCCESS, "Ваш профиль был успешно обновлён !") return redirect('main') else: messages.add_message(request, messages.ERROR, "Please correct the error below.") return super(ProfilePageView, self).get(request, *args, **kwargs)
def user_create(request): ''' create a new user ''' if not request.user.is_superuserish: return redirect('dashboard') form = UserForm(request.POST or None) if request.method == 'POST' and form.is_valid(): user = form.save() return redirect('user-single', user.pk) ctx = { 'form': form } return render(request, 'user_create.html', ctx)
def test_username_duplicate(self): form_data = {'username': '******', 'first_name': 'dave', 'last_name': 'Bright', 'email':'*****@*****.**', 'password':'******', 'password_confirm':'pwd123', 'captcha_0':'dummy-value', 'captcha_1':'PASSED'} user_form = UserForm(data=form_data) self.assertFalse(user_form.is_valid(), "test_username_duplicate not success")
def add_user(request): if request.user.is_authenticated and request.user.is_superuser: form = UserForm() if request.method == 'POST': form = UserForm(data=request.POST) username = request.POST['username'] email = request.POST['email'] if form.is_valid(): user = form.save(commit=False) return {'form':form} return render_to_response("home.html",{'404':'404'}, context_instance=RequestContext(request))
def user_edit(user_id): user = ManagerUser.query.filter_by(id=user_id).first_or_404() form = UserForm(obj=user) if request.method == 'POST': if form.validate_on_submit(): user_obj = form.edit(user) if user_obj: flash('修改成功', 'success') return redirect(url_for('accounts.user_list')) else: flash('修改失败', 'danger') print(form.errors) return render_template('edit.html', user=user, form=form)
def user_profile(request): profile = request.user.get_profile() if request.method == "POST": # Read params form = ProfileForm(request.POST, instance=profile) subscriptionform = SubscriptionForm(request.POST, instance=profile) userform = UserForm(request.POST, instance=request.user) if form.is_valid() and userform.is_valid() and subscriptionform.is_valid(): # Save changes form.save() subscriptionform.save() userform.save() # Change language set_lang(request.user, request=request, user=request.user) # Redirect after saving (and possibly changing language) response = HttpResponseRedirect(reverse("profile")) # Set language cookie and activate new language (for message below) lang_code = profile.language response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) translation.activate(lang_code) messages.info(request, _("Your profile has been updated.")) return response else: form = ProfileForm(instance=profile) subscriptionform = SubscriptionForm(instance=profile) userform = UserForm(instance=request.user) response = render_to_response( "profile.html", RequestContext( request, { "form": form, "userform": userform, "subscriptionform": subscriptionform, "profile": profile, "title": _("User profile"), "licenses": Project.objects.exclude(license=""), }, ), ) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, profile.language) return response
def signup_teacher(request): teacher_form = TeacherForm(request.POST or None) user_form = UserForm(request.POST or None) if request.method == "POST": if teacher_form.is_valid() and user_form.is_valid(): user = user_form.save() teacher = teacher_form.save(commit=False) teacher.user = user teacher.save() return redirect("index") return render(request, "signup_teacher.html", {"form": user_form, "teacher_form": teacher_form})
def registration(request): registered = False # If it's a HTTP POST, we're interested in processing form data. if request.method == 'POST': # Attempt to grab information from the raw form information. user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # If the two forms are valid... if user_form.is_valid() and profile_form.is_valid(): # Save the user's form data to the database. user = user_form.save() # Now sort out the UserProfile instance. # Since we need to set the user attribute ourselves, we set commit=False. # This delays saving the model until we're ready to avoid integrity problems. profile = profile_form.save(commit=False) profile.user = user # Did the user provide a profile picture? # If so, we need to get it from the input form and put it in the UserProfile model. if 'picture' in request.FILES: profile.picture = request.FILES['picture'] # Now we save the UserProfile model instance. profile.save() # Update our variable to tell the template registration was successful. registered = True # Invalid form or forms - mistakes or something else? # Print problems to the terminal. # They'll also be shown to the user. else: print user_form.errors, profile_form.errors # Not a HTTP POST, so we render our form using two ModelForm instances. # These forms will be blank, ready for user input. else: user_form = UserForm() profile_form = UserProfileForm() # Render the template depending on the context. return render(request, 'accounts/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
def register(request): if request.POST: form = UserForm(request.POST) if form.is_valid(): username = request.POST['username'] # screenname = request.POST['screenname'] password = request.POST['password'] new_user = User.objects._create_user(username=username, password=password, is_superuser=False) new_user.is_active = True new_user.save() return render(request, 'accounts/login.html') else: form = UserForm() return render(request, 'accounts/register.html', {'form': form})
def register(request): # Like before,get the request's context. context = RequestContext(request) registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) # two forms are valid if user_form.is_valid() and profile_form.is_valid(): # save the user's form data to the database user = user_form.save() # hash the password user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user # Did the user provide a profile picture? if 'picture' in request.FILES: profile.picture = request.FILES['picture'] # save UserProfile model instance profile.save() registered = True # invalid forms, else: print user_form.errors, profile_form.errors # not a http post else: user_form = UserForm() profile_form = UserProfileForm() # Render the template depending on the context return render_to_response( 'account/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, context )
def signup_student(request): student_form = StudentForm(request.POST or None) user_form = UserForm(request.POST or None) if request.method == "POST": if student_form.is_valid() and user_form.is_valid(): user = user_form.save() student = student_form.save(commit=False) student.user = user student.save() return redirect("index") return render( request, "signup_student.html", {"form": user_form, "student_form": student_form, "grades": GRADE_CHOICES} )
def register(request): registered = False if request.method == 'POST': form = UserForm(data=request.POST) if form.is_valid(): user = form.save() user.set_password(user.password) user.save() registered = True messages.success(request, "Thank you for registering.") return redirect('login') else: form.errors else: form = UserForm() return render(request, 'accounts/register.html', {'form': form})
def register(request): user = None if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): #https://github.com/realpython/book3-exercises/blob/7dce6dbf77c62124cb0ef6d909cdd1a1afdc88de/django_ecommerce/payments/views.py cd = form.cleaned_data try: with transaction.atomic(): user = User.create(cd['name'], cd['email'], cd['password']) user.save() except IntegrityError: form.addError(cd['email'] + ' is already a member') else: request.session['user'] = user.pk return HttpResponseRedirect('/') #user = User( #name=form.cleaned_data['name'], # email=form.cleaned_data['email'], #) #ensure encrpyted password #user.set_password(form.cleaned_data['password']) #try: # user.save() #except IntegrityError: # form.addError(user.email + ' is already a member') #else: # request.session['user'] = user.pk # return HttpResponseRedirect('/') else: form = UserForm() return render_to_response( 'accounts/register.html', { 'form': form, 'user': user, }, context_instance=RequestContext(request) )
def add(request): user_form = UserForm( data=request.POST or None ) if user_form.is_valid(): user_form.save(auth.get_user(request)) messages.success(request, u"Usuário salvo com sucesso.") return redirect('user_list') template_context = { 'user_form': user_form, } return render( request=request, template_name='add.html', dictionary=template_context )