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 editProfile(request): user = request.user if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): try: userprofile = user.userprofile except UserProfile.DoesNotExist: userprofile = form.instance userprofile.user = user userprofile.is_verified = True userprofile.act_key = "1111" userprofile.exp_key = datetime.datetime.now() userprofile.gender = form.cleaned_data['gender'] userprofile.birth_date = form.cleaned_data['birth_date'] user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.save() userprofile.save() messages.success(request, _('Changes are done.')) return redirect(reverse('profile')) else: messages.error(request, _('Edit is failed.')) return redirect(reverse('register')) else: form = UserProfileForm() return render(request, 'accounts/profile.html', {'form': form})
def test_valid_bio_passes_validation(self): # A valid bio must have at least 10 characters form = UserProfileForm( data={'date_of_birth': self.valid_date, 'bio': self.valid_bio} ) self.assertTrue(form.is_valid())
def test_failure_user_profile_form(self): """正常ではない入力を行いエラーになることを検証""" print('Test Case 3-2') print() profile = UserProfile() form = UserProfileForm(data={'work_place': '', 'work_status': self.work_state01.id, 'division': self.division01.id}, instance=profile) self.assertTrue(not(form.is_valid()))
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 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 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 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 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 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 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.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 change_user_profile(request): """ View for display and processing of a user profile form. """ try: # Try to get a existing user profile user_profile = request.user.get_profile() except UserProfile.DoesNotExist: user_profile = None if request.method == 'POST': # Form processing form = UserProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) if user_profile: profile.id = user_profile.id profile.user = request.user profile.save() else: # Render the form form = UserProfileForm(instance=user_profile) return render_to_response('accounts/profile_form.html', { 'formset': form,}, context_instance=RequestContext(request))
def get_context_data(self, **kwargs): context = {} try: context['emp_info'] = Employment_detail.objects.none() except : context['emp_info'] = UserProfileForm() try: context['profile_form'] = UserProfileForm(instance = self.get_object()) except : context['profile_form'] = UserProfileForm() try: context['edu_detailform'] = Education_levelForm(instance=Education_level.objects.filter(user=self.request.user).first()) except : context['edu_detailform'] = Education_levelForm() try: context['emp_detailform'] = Employement_DetailForm(instance=Employment_detail.objects.all().filter(user=self.request.user).first()) except : context['emp_detailform'] = Employement_DetailForm() try: context['pref_form'] = Preference_Form(instance=Preference.objects.filter(user=self.request.user).first()) except : context['pref_form'] = Preference_Form() try: context['file_uploadform'] = File_UploadForm(instance=File_uploaded.objects.filter(user=self.request.user).first()) except : context['file_uploadform'] = File_UploadForm() return context
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 register(request): if request.method == "POST": uform = CreateUserForm(request.POST) pform = UserProfileForm(request.POST) if uform.is_valid() and pform.is_valid(): # create the user and redirect to profile user = uform.save() profile = pform.save(commit=False) profile.user = user profile.save() # this would be usefull when the profile is # allready created when post_save is triggered # profile = user.get_profile() # profile.address = pform.cleaned_data['address'] # profile.save() # login the user automatically after registering user = authenticate(username=user.username, password=uform.cleaned_data['password']) login(request, user) return HttpResponseRedirect(reverse('fi_home')) else: uform = CreateUserForm() pform = UserProfileForm() ctx = { 'user_form':uform, 'profile_form':pform, } return render(request, 'accounts/register.html', ctx)
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 change_avatar(request): if request.user.is_authenticated: if request.method == "POST": profileform = UserProfileForm(request.POST, request.FILES) if profileform.is_valid(): pf = profileform.save(commit=False) pf.user = request.user pf.link = request.FILES['avatar'].name if pf.link[-3:] not in ['png', 'jpg', 'gif']: pass else: with open(AVATAR_DIR + pf.user.username, "wb+") as f: print AVATAR_DIR + pf.user.username for chunk in request.FILES['avatar'].chunks(): f.write(chunk) return HttpResponseRedirect('/') else: return render(request, 'update_avatar.html', { 'form': profileform, 'merrors': True }) else: pform = UserProfileForm() return render(request, 'update_avatar.html', {'form': pform}) else: return HttpResponseRedirect("/")
def profile(request): # fetch user from db user = User.objects.get(pk=request.user.id) # save the forms if request.method == "POST": # create the form to edit the user uform = EditUserForm(data=request.POST, instance=user) # also edit the profile of this user pform = UserProfileForm(data=request.POST, instance=request.user.get_profile()) if uform.is_valid() and pform.is_valid(): uform.save() pform.save() messages.success(request, 'User udated.') else: messages.success(request, 'There was an error.') else: # create the form to edit the user uform = EditUserForm(instance=user) # also edit the profile of this user pform = UserProfileForm(instance=request.user.get_profile()) ctx = { 'user_form':uform, 'profile_form':pform, } return render(request, 'accounts/profile.html', ctx)
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 test_success_user_profile_form(self): """正常な入力を行いエラーにならないことを検証""" print('Test Case 3-1') print() profile = UserProfile() form = UserProfileForm(data={'work_place': self.work_place01.id, 'work_status': self.work_state01.id, 'division': self.division01.id}, instance=profile) self.assertTrue(form.is_valid())
def post(self, request, *args, **kwargs): form = self.get_form() self.profile_form = UserProfileForm(request.POST, request.FILES) if form.is_valid() and self.profile_form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form)
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_form_renders_inputs(self): form = UserProfileForm() expected_inputs = self.required_form_fields + self.optional_form_fields rendered_form = form.as_p() for field in expected_inputs: self.assertIn(f'id_{field}', rendered_form)
def get(self, request, *args, **kwargs): if request.user.account_type == 'school': self.user_form = SchoolUserForm(instance=request.user) self.profile_form = SchoolProfileForm(instance=request.user.school_profile) elif request.user.account_type == 'teacher' or request.user.account_type == 'student': self.user_form = UserProfileForm(instance=request.user) return self.render_to_response({'form': self.user_form, 'profile_form': self.profile_form})
def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) user_profile_form = UserProfileForm(self.request.POST, instance=self.object.get_profile()) if form.is_valid() and user_profile_form.is_valid(): return self.form_valid(form, user_profile_form) else: return self.form_invalid(form, user_profile_form)
def checkout(request): if request.method == "POST": billing_form = BillingForm(request.POST) payment_form = MakePaymentForm(request.POST) shipping_form = UserProfileForm(request.POST) if payment_form.is_valid() and billing_form.is_valid( ) and shipping_form.is_valid(): order = billing_form.save(commit=False) order.user = request.user order.date = timezone.now() order.save() cart = request.session.get('cart', {}) total = 0 for id, quantity in cart.items(): product = get_object_or_404(Product, pk=id) total += quantity * product.price order_line_item = OrderLineItem(order=order, product=product, quantity=quantity) order_line_item.save() try: customer = stripe.Charge.create( amount=int(total * 100), currency="EUR", description=request.user.email, card=payment_form.cleaned_data['stripe_id']) except stripe.error.CardError: messages.error(request, "Your card was declined!") if customer.paid: messages.error(request, "You have successfully paid") request.session['cart'] = {} return redirect(reverse('products')) else: messages.error(request, "Unable to take payment") else: print(payment_form.errors) messages.error(request, "We were unable to take a payment with that card!") else: profile = get_object_or_404(UserProfile, user=request.user) payment_form = MakePaymentForm() billing_form = BillingForm() shipping_form = UserProfileForm(instance=profile) return render( request, "checkout.html", { "billing_form": billing_form, "shipping_form": shipping_form, "payment_form": payment_form, "publishable": settings.STRIPE_PUBLISHABLE })
def test_form_fails_validation_if_required_items_missing(self): no_dob_form = UserProfileForm( data={'date_of_birth': None, 'bio': self.valid_bio} ) no_bio_form = UserProfileForm( data={'date_of_birth': self.valid_date, 'bio': ''} ) for form in [no_dob_form, no_bio_form]: self.assertFalse(form.is_valid())
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_update_profile(self): self.set_up() author = Author.objects.get(email='*****@*****.**') form = UserProfileForm({'displayName':'new', 'bio':'http://new.com', 'github':'http://new.com'}) self.assertTrue(form.is_valid()) author.displayName = form.cleaned_data['displayName'] author.bio = form.cleaned_data['bio'] author.github = form.cleaned_data['github'] self.assertEqual(author.displayName,'new') self.assertEqual(author.github,'http://new.com') self.assertEqual(author.bio,'http://new.com')
def profile_edit(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. updated = 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 = UpdateProfile(data=request.POST, instance=request.user) profile_form = UserProfileForm(data=request.POST, instance=request.user.userprofile) # 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() 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 'mobitel' in request.POST: profile.mobitel = request.POST['mobitel'] if 'zupanija' in request.POST: profile.zupanija = request.POST['zupanija'] # Now we save the UserProfile model instance. profile.save() # Update our variable to tell the template registration was successful. updated = 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 = UpdateProfile(instance=request.user) profile_form = UserProfileForm(instance=request.user.userprofile) # Render the template depending on the context. return render(request, 'accounts/profile_edit_form.html', {'user_form': user_form, 'profile_form': profile_form, 'updated': updated} )
def post(self, request): form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): user_profile = form.save(commit=False) user_profile.user = request.user user_profile.save() return HttpResponseRedirect(reverse_lazy('xplrmain:feed-page')) else: print("Image Upload: {}".format(request.POST['profile_pic'])) return render(request, 'registration/welcome.html', {'form': form})
def order_info(request, template_name="registration/order_info.html"): if request.method == 'POST': postdata = request.POST.copy() form = UserProfileForm(postdata) if form.is_valid(): profile.set(request) url = reverse('my_account') return HttpResponseRedirect(url) else: user_profile = profile.retrieve(request) form = UserProfileForm(instance=user_profile) page_title = 'Edit Order Information' return render(request, template_name, locals(), RequestContext(request))
def order_info(request, template_name="registration/order_info.html"): if request.method == 'POST': postdata = request.POST.copy() form = UserProfileForm(postdata) if form.is_valid(): profile.fill(request) url = reverse('accounts:my_account') return HttpResponseRedirect(url) else: user_profile = profile.retrieve(request) form = UserProfileForm(instance=user_profile) page_title = 'Edit Order Information' return render(request, template_name, locals())
def edit(request): try: profile = UserProfile.objects.get(pk=1) except UserProfile.DoesNotExist: raise Http404 if 'POST' == request.method: form = UserProfileForm(request.POST, instance=profile) if request.is_ajax(): if form.is_valid(): form.save() success = True errors = [] else: success = False errors = [(k, unicode(v[0])) for k, v in form.errors.items()] json = simplejson.dumps(({'success': success, 'errors': errors, })) return HttpResponse(json, mimetype='application/javascript') else: if form.is_valid(): form.save() return HttpResponseRedirect('/edit/saved/') else: form = UserProfileForm(instance=profile) return render_to_response('accounts/edit.html', {'form': form}, context_instance=RequestContext(request))
def order_info(request, template_name="accounts/order_info.html"): if request.method == 'POST': postdata = request.POST.copy() form = UserProfileForm(postdata) if form.is_valid(): profile.set(request) url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url) else: user_profile = profile.retrieve(request) form = UserProfileForm(instance=user_profile) page_title = 'Edit Order Information' return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def test_user_profile_form_valid(self): """ Testing user_profile form is valid """ form = UserProfileForm( data={ 'default_phone_number': 'test_phone_number', 'default_town_or_city': 'test_town_or_city', 'default_street_address1': 'test_street1', 'default_street_address2': 'test_street2', 'default_county': 'test_county', 'default_country': 'GB', }) self.assertTrue(form.is_valid())
class ProfileView(TemplateResponseMixin, LoginRequiredMixin, View): template_name = 'aonebrains_main/students/profile_form.html' user_form = None def get(self, request, *args, **kwargs): self.user_form = UserProfileForm(instance=request.user) return self.render_to_response({'form': self.user_form}) def post(self, request, *args, **kwargs): self.user_form = UserProfileForm(instance=request.user, data=request.POST, files=request.FILES) if self.user_form.is_valid(): self.user_form.save() return redirect('aonebrains_main:Home') return self.render_to_response({'form': self.user_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 profile_edit(request): profile, is_created = UserProfile.objects.get_or_create(user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, 'Profile 정보가 업데이트되었습니다.') next_url = request.GET.get('next', 'accounts.views.profile_detail') return redirect(next_url) else: form = UserProfileForm(instance=profile) return render(request, 'form.html', { 'form': form, })
def order_info(request, template_name="registration/order_info.html"): """ page containing a form that allows a customer to edit their billing and shipping information that will be displayed in the order form next time they are logged in and go to check out """ if request.method == 'POST': postdata = request.POST.copy() form = UserProfileForm(postdata) if form.is_valid(): profile.set(request) url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url) else: user_profile = profile.retrieve(request) form = UserProfileForm(instance=user_profile) page_title = 'Edit Order Information' return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def test_user_profile_form_invalid(self): """ Testing user_profile form is invalid """ form = UserProfileForm( data={ 'default_phone_number': 'test_phone_number', 'default_town_or_city': 'test_town_or_city', 'default_street_address1': 'test_street1', 'default_street_address2': 'test_street2', 'default_county': 'test_county', 'default_country': 'test_country', }) self.assertFalse(form.is_valid()) self.assertEquals(len(form.errors), 1)
def edit_profile(request): if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Your profile has been updated') return HttpResponseRedirect('/profile') else: # form = ContactView() # messages.add_message(request, messages.ERROR, 'Your message not sent. Not enough data') return render(request, 'loggedin.html', {'form': form}) else: form = UserProfileForm() return render(request, 'loggedin.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 post(self, request, *args, **kwargs): if request.user.account_type == 'school' or request.user.is_school: self.user_form = SchoolUserForm(instance=request.user, data=request.POST, files=request.FILES) self.profile_form = SchoolProfileForm(instance=request.user.school_profile, data=request.POST) if self.user_form.is_valid() and self.profile_form.is_valid(): self.user_form.save() self.profile_form.save() return redirect('schools:profile') elif request.user.account_type == 'teacher' or request.user.account_type == 'student': self.user_form = UserProfileForm(instance=request.user, data=request.POST, files=request.FILES) print(request.POST) if self.user_form.is_valid(): self.user_form.save() return redirect('schools:teachers:profile') return self.render_to_response({'form': self.user_form, 'profile_form': self.profile_form})
def details(request): ctx = {} form = AccountForm(instance=request.user) pform = UserProfileForm(instance=request.user.get_profile()) if request.method == 'POST': form = AccountForm(request.POST, instance=request.user) pform = UserProfileForm(request.POST, instance=request.user.get_profile()) if form.is_valid() and pform.is_valid(): form.save() pform.save() messages.info(request, _('Account updated.')) ctx['form'] = form ctx['pform'] = pform return render_to_response('accounts/details.html', ctx, context_instance=RequestContext(request))
def addStudent(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): userr = form.save() userrr = User.objects.get(username=userr) userid = userrr.id phone = request.POST.get("phone") user = UserProfile.objects.get(user=request.user) org = user.Organisation profile = "S" UserProfile.objects.create(user_id=userid, phone=phone, profile=profile, Organisation=org) return redirect(reverse('teacher:addStudent')) else: return HttpResponse("form invalid") elif request.user.userprofile.profile == "T": form1 = RegistrationForm() form2 = UserProfileForm() usr = UserProfile.objects.get(user=request.user) org = usr.Organisation usrp = UserProfile.objects.filter(Organisation=org) args = {'form1': form1, 'form2': form2, 'usrp': usrp} return render(request, 'panel1.html', args) else: return HttpResponse( "<h1>You are not authorised to view this page</h1>")
def get(self, request, *args, **kwargs): user_form = UserForm() profile_form = UserProfileForm() return render_to_response( 'accounts/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': False}, RequestContext(request))
def user_profile(request): if request.method == "POST": form = UserProfileForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): # my_form = form.save(commit=False) form.save() # messages.add_message(request, messages.SUCCESS, 'Your message has been sent. Thank you.') return HttpResponseRedirect("/profile") else: # form = ContactView() # messages.add_message(request, messages.ERROR, 'Your message not sent. Not enough data') return render(request, "contact.html", {"form": form}) else: form = UserProfileForm() return render(request, "contact.html", {"form": form})
def profile_update(request): profile, created = UserProfile.objects.get_or_create(user=request.user) if request.method == 'POST': form = UserProfileForm(request.POST, instance=profile) if form.is_valid(): profile = form.save() messages.add_message(request, SUCCESS, 'Your profile has been updated successfully.') else: messages.add_message(request, ERROR, 'Something went wrong.') else: form = UserProfileForm(instance=profile) return render(request, 'profile_update.html', { 'userprofile': form, })
def profile(request): try: info = UserProfile.objects.get(user=request.user) except: info = UserProfile(user=request.user) if request.method == 'POST': info_form = UserProfileForm(request.POST, request.FILES, instance=info) if info_form.is_valid(): info_form = info_form.save() else: logger.debug("验证错误!") return HttpResponseRedirect("/accounts/profile") else: info_form = UserProfileForm(instance=info) return render_to_response("accounts/profile.html", { 'form':info_form },context_instance=RequestContext(request))
def register(request): if request.method == "POST": form = UserProfileForm(request.POST) if form.is_valid(): user = User.objects.create_user(request.POST['username'],request.POST['email'],request.POST['password1']) user.save() userp = UserProfile(user=user) userp.save() messages.info(request, "Thanks for registering. You are now logged in.") new_user = authenticate(username=request.POST['username'], password=request.POST['password2']) login_after_registration(request, new_user) return HttpResponseRedirect("/events/") else: form = UserProfileForm() return render_to_response("accounts/register.html", {'form':form },context_instance=RequestContext(request))
def update_profile(request): """User can update its profile via Profile.html and related form""" if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = UserProfileForm(request.POST, instance=request.user.userprofile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, ('Your profile was successfully updated!'), extra_tags="Profile Updated") return redirect(reverse('index')) else: messages.error(request, ('Please correct the error below.')) return render( request, 'edit_profile.html', { "user_form": user_form, "profile_form": profile_form, "background_image": background["default"] }) else: user_form = UserForm(instance=request.user) profile_form = UserProfileForm(instance=request.user.userprofile) return render( request, 'profile.html', { 'user_form': user_form, 'profile_form': profile_form, "background_image": background["default"] })
def edit_profile(request): if request.method == "POST": form = UserProfileForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): print "FORM IS VALID" user = request.user if request.POST.get('first_name', False): user.first_name = request.POST.get('first_name', False) if request.POST.get('last_name', False): user.last_name = request.POST.get('last_name', False) if request.POST.get('company', False): user.company = request.POST.get('company', False) if request.POST.get('phone_number', False): user.phone_number = request.POST.get('phone_number', False) if request.POST.get('location', False): user.location = request.POST.get('location', False) user.save() form.save() return redirect(profile) else: form = UserProfileForm(instance=request.user) return render(request, 'edit-profile.html', {'form': form})
def dashboard(request): user = request.user try: user_profile = UserProfile.objects.get(user=user) except Exception: _profile(user) user_profile = UserProfile.objects.get(user=user) orders = Order.objects.order_by('-created_at').filter(user_id=request.user.id, is_ordered=True) orders_count = orders.count() if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = UserProfileForm(request.POST, request.FILES, instance=user_profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'Ваши данные успешно обновлены!') return redirect('dashboard') else: user_form = UserForm(instance=request.user) profile_form = UserProfileForm(instance=user_profile) context = { 'orders': orders, 'orders_count': orders_count, 'user_form': user_form, 'profile_form': profile_form, 'user_profile': user_profile, } return render(request, 'accounts/dashboard.html', context)
def profile(request): # fetch user from db user = User.objects.get(pk=request.user.id) # save the forms if request.method == "POST": # create the form to edit the user uform = EditUserForm(data=request.POST, instance=user) # also edit the profile of this user pform = UserProfileForm(data=request.POST, instance=request.user.get_profile()) if uform.is_valid() and pform.is_valid(): uform.save() pform.save() messages.success(request, 'User udated.') else: messages.success(request, 'There was an error.') else: # create the form to edit the user uform = EditUserForm(instance=user) # also edit the profile of this user pform = UserProfileForm(instance=request.user.get_profile()) ctx = { 'user_form': uform, 'profile_form': pform, } return render(request, 'accounts/profile.html', ctx)
def user_profile_edit(request, pk): page = "edit-profile-page" user_obj = User.objects.get(pk=pk) current_user = request.user if user_obj != current_user: context = { 'current_user': current_user, 'page': page, } return render(request, 'access-denied.html', context) if request.method == 'GET': form = UserProfileForm(instance=user_obj.userprofile) context = { 'form': form, 'current_user': user_obj, 'user': user_obj, 'page': page, } return render(request, 'profile-edit.html', context) # old_img = user_obj.userprofile.profile_picture form = UserProfileForm(request.POST, request.FILES, instance=user_obj.userprofile) if form.is_valid(): # if old_img: # clean_up_files(old_img.path) form.save() return redirect('user profile', user_obj.pk) context = { 'form': form, 'user': user_obj, 'current_user': user_obj, 'page': page, } return render(request, 'profile.html', context)
def checkout(request): user_form = UserForm(request.POST or None, instance=request.user) user_profile_form = UserProfileForm(request.POST or None, request.FILES or None, instance=request.user.userprofile) return render(request, 'carts/checkout.html', { 'user_form': user_form, 'user_profile_form': user_profile_form, })
def post(self, request): user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): self.process_valid_forms(profile_form, user_form) else: print user_form.errors, profile_form.errors return render_to_response( 'accounts/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': False}, RequestContext(request)) return render_to_response( 'accounts/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': True}, RequestContext(request))
def order_info(request, template_name="registration/order_info.html"): """ page containing a form that allows a customer to edit their billing and shipping information that will be displayed in the order form next time they are logged in and go to check out """ if request.method == 'POST': post_data = request.POST.copy() form = UserProfileForm(post_data) if form.is_valid(): profile.set(request) url = urlresolvers.reverse('accounts:my_account') return HttpResponseRedirect(url) else: user_profile = profile.retrieve(request) form = UserProfileForm(instance=user_profile) page_title = 'Edit Order Information' return render(request, template_name, locals())