def register(request): if request.method == "POST": form = RegisterForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): form_data = form.cleaned_data profile_form_data = profile_form.cleaned_data user = User.objects.create_user(username=form_data['username'], email=form_data['email'], password=form_data['password1'], first_name=form_data['first_name'], last_name=form_data['last_name']) Profile.objects.filter(user=user).update( dob=profile_form_data['dob'], divorced=profile_form_data['divorced'], divorced_number=profile_form_data['divorced_number'], children=profile_form_data['children'], children_number=profile_form_data['children_number'], description=profile_form_data['description']) return HttpResponseRedirect('/admin/') else: form = RegisterForm() profile_form = ProfileForm() context = { "form": form, "profile_form": profile_form, } return render(request, "core/register.html", context)
def profile_edit(request, template_name="profiles/profile_edit.html"): helper = FormHelper() submit = Submit('edit','Edit') helper.add_input(submit) reset = Reset('reset','Reset') helper.add_input(reset) profile = get_object_or_404(Profile, user=request.user) form = ProfileForm(request.POST or None, instance=profile) if form.is_valid(): form.save() msg = 'Profile edited' messages.add_message(request, messages.INFO, msg) return HttpResponseRedirect(reverse("profile_detail", kwargs={"username":profile.user.username })) return render_to_response(template_name, { "profile": profile, "form": form, "helper":helper, }, context_instance=RequestContext(request) )
def edit_user(request): user = request.user rater = user.rater profile = user.profile if request.method == "POST": if "user_edit" in request.POST: user_form = UserForm(request.POST) if user_form.is_valid(): user_form.save(commit=False) password = user_form.password user.set_password(password) user.save() messages.add_message(request, messages.SUCCESS, "You have updated your account") elif "rater_edit" in request.POST: rater_form = RaterForm(request.POST) if rater_form.is_valid(): rater_form.save() messages.add_message(request, messages.SUCCESS, "You have updated your demographic info") elif "profile_edit" in request.POST: profile_form = ProfileForm(request.POST) if profile_form.is_valid(): profile_form.save() messages.add_message(request, messages.SUCCESS, "You have updated your profile") user_form = UserForm(request.POST or None, instance=request.user) rater_form = RaterForm(request.POST or None, instance=request.user.rater) profile_form = ProfileForm(request.POST or None, instance=request.user.profile) return render(request, "user_edit.html", {'user_form': user_form, 'rater_form': rater_form, 'profile_form':profile_form})
def add(request): """ add profile, on GET returns common profile-add-page on POST | validates sended data, on success: redirect to show page, on fail returns to add page on ajax POST | on success: returns updated profile, on fail returns errors :param request: :return: """ context = {} if request.method == "GET": context['form'] = ProfileForm() return render(request, "profiles/add.html", context) elif request.method == "POST": form = ProfileForm(request.POST) context['form'] = ProfileForm() if form.is_valid(): profile = form.save() if request.is_ajax(): return HttpResponse(serialize('json', [profile, ]).strip("[]")) else: if profile.slug: return redirect(reverse("profiles.views.profile.show_by_slug", args=[profile.slug])) else: return redirect(reverse("profiles.views.profile.show", args=[profile.pk])) else: if request.is_ajax(): return HttpResponse(serialize('json', form.errors)) else: return render(request, "profiles/add.html", context) return HttpResponseBadRequest()
def setProfile(request, **kwargs): """用户profile设置""" template = kwargs.pop("template", settings.TEMPLATE_SETTINGS) if request.method == "POST": form = ProfileForm(request.POST, user=request.user) if form.is_valid(): profile = form.save(request) if profile: utils.addMsg(request, messages.SUCCESS, ugettext(u"更新设置成功.")) return HttpResponseRedirect(reverse("profiles_setting")) else: soup = BeautifulSoup(str(form.errors)) utils.addMsg(request, messages.ERROR, soup.ul.li.ul.li.contents[0]) # utils.addMsg(request, messages.ERROR, form.errors) else : draftProfile = request.session.get("draftProfile", None) form = ProfileForm(user=request.user, draftProfile=draftProfile) if draftProfile: request.session["draftProfile"] = None return render_to_response(template, RequestContext(request, {"form": form}))
def signup(request): if request.method == 'POST': user_form = UserCreationForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.save() name = profile_form.cleaned_data['name'] email_id = profile_form.cleaned_data['email_id'] profile = Profile.objects.create(user=user, name=name, email_id=email_id) profile.save() username = user_form.cleaned_data['username'] password = user_form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect(reverse('home')) context = {'user_form': user_form, 'profile_form': profile_form} return render(request, 'accounts/signup.html', context) else: user_form = UserCreationForm() profile_form = ProfileForm() context = {'user_form': user_form, 'profile_form': profile_form} return render(request, 'accounts/signup.html', context)
def update_profile(request): submitted = False try: inst = Researcher.objects.get(user=request.user) except ObjectDoesNotExist: inst = Academic.objects.get(user=request.user) if request.method == 'POST': profile_form = ProfileForm(data=request.POST, instance=inst) if profile_form.is_valid(): profile = profile_form.save(commit=False) profile.user= request.user if 'pic' in request.FILES: profile.pic= request.FILES['pic'] profile.save() submitted=True else: print profile_form.errors else: profile_form = ProfileForm(instance=inst) return render(request, 'update_profile.html', {'profile_form': profile_form, 'submitted': submitted})
def _profile_change(request, name, website, location): if request.method == 'POST': profile_form = ProfileForm(request.POST, instance=request.user.get_profile()) if profile_form.is_valid(): profile = profile_form.save() return profile return False
def profile_edit(request, template_name="profiles/profile_edit.html"): helper = FormHelper() submit = Submit('edit', 'Edit') helper.add_input(submit) reset = Reset('reset', 'Reset') helper.add_input(reset) profile = get_object_or_404(Profile, user=request.user) form = ProfileForm(request.POST or None, instance=profile) if form.is_valid(): form.save() msg = 'Profile edited' messages.add_message(request, messages.INFO, msg) return HttpResponseRedirect( reverse("profile_detail", kwargs={"username": profile.user.username})) return render_to_response(template_name, { "profile": profile, "form": form, "helper": helper, }, context_instance=RequestContext(request))
def edit_profile(req): if req.user.profile.car: form = ProfileForm( initial={ 'hometown': req.user.profile.hometown, 'major': req.user.profile.major, 'phone_number': req.user.profile.phone_number, 'affiliation': req.user.profile.affiliation, 'org_email': req.user.profile.org_email, 'car_make': req.user.profile.car.make, 'car_model': req.user.profile.car.model, 'plate': req.user.profile.car.plate, 'venmo': req.user.profile.venmo, 'bio': req.user.profile.bio }) else: form = ProfileForm( initial={ 'hometown': req.user.profile.hometown, 'major': req.user.profile.major, 'phone_number': req.user.profile.phone_number, 'affiliation': req.user.profile.affiliation, 'org_email': req.user.profile.org_email, 'venmo': req.user.profile.venmo, 'bio': req.user.profile.bio }) context = { 'title': 'CarTrek -- Edit Profile', 'organizations': Organization.objects.all(), 'form': form, } return render(req, 'edit.html', context=context)
def profile_edit(request, user_id): user = get_object_or_404(User, id=user_id) profile_instance = user.get_profile() profile_form = ProfileForm(instance = profile_instance) default_icon = Icon.objects.get(name='home') if profile_instance.location_id is not None: point = MaapPoint.objects.get(id=profile_instance.location_id) point_form = InlinePointForm(instance=point) else: point_form = InlinePointForm point = None if request.method == 'POST': profile_form = ProfileForm(request.POST, instance=profile_instance) if point: point_form = InlinePointForm(request.POST, instance=point) else: point_form = point_form(request.POST) if profile_form.is_valid(): profile = profile_form.save(commit=False) if point_form.is_valid(): point = point_form.save(commit=False) point.name = profile.name point.creator = request.user point.editor = request.user point.icon = default_icon try : point.save() success = True except: success = False if success: profile.user = user profile.location = point profile.location_id = point.id try: profile.save() success = success and True except: success = False if success: return redirect('profile_detail', username = user.username) return simple.direct_to_template( request, 'profiles/profile_form.html', extra_context={ 'form':profile_form, 'inline_form':point_form, 'user':user } )
def change_profile_photos(request, pk): if request.method == 'POST': user = User.objects.get(pk=pk) owner = {"owner": user} form = ProfileForm(request.FILES, owner) if form.is_valid(): form.save() return redirect('posts:homepage')
def profile(request): template = 'profile.html' if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = ProfileForm return render(request, template, {'form': form})
def test_change_user_profile_information(self): """ Submit valid data through the ProfileForm, and ensure that it was validated by the form. """ form_data = { "profile_image": self.new_profile_img, "description": "Hi! I'm Meepy!", } profile_form = ProfileForm(instance=self.user, data=form_data) self.assertTrue(profile_form.is_valid())
def test_bad_url(self): form = ProfileForm(instance=self.profile_one) # include a bad url to force an error data = { "name": "John Smith", "about": "John likes wine", "location": "France maybe!", "website": "httpasd://python.org" } form = ProfileForm(data) self.assertEquals(False, form.is_valid())
def edit(request): profile = UserProfile.objects.get(user=request.user) # Is this a POST method? If so, validate and save if request.method == 'POST': form = ProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, 'Your profile was updated successfully.') else: form = ProfileForm(instance=profile) return { 'form': form }
def test_create_profile_form_with_mandatory_fields_filled(self): form = ProfileForm({ 'first_name': 'test', 'last_name': 'test', 'email_address': '*****@*****.**', 'phone_number': '123 456 789', 'street_address1': '5 test street', 'town_or_city': 'test city', 'country': 'test country' }) self.assertTrue(form.is_valid())
def checkout_success(request, order_number): """ Handle successful checkouts """ order = get_object_or_404(Order, order_number=order_number) template = render_to_string('checkout/confirmation_emails/order_email.txt', {'order': order}) email = EmailMessage( 'Your order has been received', template, settings.EMAIL_HOST_USER, [order.email], ) email.fail_silently = False email.send() save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = Profile.objects.get(user=request.user) # Bind user profile object to the order order.profile = profile order.save() if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, 'default_postcode': order.postcode, 'default_country': order.country, } profile_form = ProfileForm(profile_data, instance=profile) if profile_form.is_valid(): profile_form.save() messages.success( request, f'Order successfully processed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.email}.') if 'cart' in request.session: del request.session['cart'] context = { 'order': order, } return render(request, 'checkout/checkout_success.html', context)
def post_profile(request, cipher_text): try: profile = Profile.objects.get(cipher_text=cipher_text) except Profile.DoesNotExist: profile = Profile(cipher_text=cipher_text) profile_form = ProfileForm(request.POST, instance=profile) if profile_form.is_valid(): # TODO reverse geocoding of address by geo location # TODO update oDesk profile profile_form.save() return {'status': 'ok'} else: logging.error(profile_form.errors) return HttpResponseBadRequest()
def usersignup(request): form = UserSignup() profile_form = ProfileForm() if request.method == 'POST': form = UserSignup(request.POST) profile_form = ProfileForm(request.POST, request.FILES) if form.is_valid() and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.owner = user profile.save() profile_form.save_m2m() user.set_password(user.password) user.save() login(request, user) messages.success(request, "Successfully signed up!") return redirect("profile", pk=profile.pk) messages.error(request, form.errors) messages.error(request, profile_form.errors) return redirect("signup") context = { "form": form, 'profile_form': profile_form, } return render(request, 'signup.html', context)
def checkout_success(request, order_number): """ Render successful order view with the order summary displayed and a message that thge order was successfully proccessed. """ # Display a success message order = get_object_or_404(Order, order_number=order_number) save_details = request.session.get('save_details') if request.user.is_authenticated: # If user has logged in, attach their profile to the order profile = Profile.objects.get(user=request.user) order.user_profile = profile order.save() # If the user has ticked 'save_details', save them in the profile if save_details: user_details = { 'user_phone_number': order.phone_number, 'user_address_line_1': order.address_line_1, 'user_address_line_2': order.address_line_2, 'user_city': order.city, 'user_region': order.region, 'user_country': order.country, 'user_postcode': order.postcode, } profile_form = ProfileForm(user_details, instance=profile) if profile_form.is_valid(): profile_form.save() # Calculate discount applied if any discount = round((order.subtotal - (order.total - order.delivery_cost)) / order.subtotal * 100, 0) # delete cart contents if 'cart' in request.session: del request.session['cart'] if 'delivery' in request.session: del request.session['delivery'] template = 'checkout/checkout_success.html' context = { 'order': order, 'discount': discount, } return render(request, template, context)
def _test_bad_country(self): form = ProfileForm(instance=self.profile_one) # include a bad country to force an error data = { "name": "John Smith", "about": "John likes wine", "location": "Paris", "website": "http://python.org", "street_address": "80, bd Auguste-Blanqui", "street_address_two": "Cedex 13", "city": "Paris", "postal_code": "75707", "country": "FA", # wrong: France is "FR", there is no "FA" } form = ProfileForm(data) self.assertEquals(False, form.is_valid())
def profile_edit(request, template_name="profiles/profile_edit.html"): profile = request.user.get_profile() form = ProfileForm(request.POST or None, instance=profile) if form.is_valid(): form.save() # msg = 'Profile edited' # messages.add_message(request, messages.INFO, msg) return HttpResponseRedirect(reverse("profile_detail", kwargs={"username":profile.username })) return render(request, template_name, { "profile": profile, "form": form, })
def profile_edit(request): title = "Update Profile" profile, created = Profile.objects.get_or_create(user=request.user) form = ProfileForm(request.POST or None, request.FILES or None, instance=profile) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect("profile_user") context = { "form": form, "title": title, } return render(request, "forms.html", context)
def post(self, request, *args, **kwargs): user = self.request.user profile_form = ProfileForm(request.POST, request.FILES, instance=user.profile) if not (profile_form.is_valid()): messages.error(request, "There was a problem with the form. " "Please check the details.") profile_form = ProfileForm(instance=user.profile) return super(EditProfile, self).get(request, profile_form=profile_form) profile = profile_form.save(commit=False) profile.user = user profile.save() messages.success(request, "Profile details saved!") return redirect("smriti:home")
def edit(request): """ Edits profile data. """ profile = Profile.objects.get(user=request.user) if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form.save(profile) logger.info("%s - profile-edit: user '%s', form %s" % (request.META.get('REMOTE_ADDR'), request.user, form.cleaned_data)) request.user.message_set.create(message=_('Profile updated.')) return HttpResponseRedirect(reverse('profile-show')) form = ProfileForm(profile.get_init_data()) dict_data['form'] = form return render_to_response('profiles/edit_form.html', dict_data, context_instance=RequestContext(request))
def profile_edit(request, template_name="profiles/profile_edit.html"): profile = request.user.get_profile() form = ProfileForm(request.POST or None, instance=profile) if form.is_valid(): form.save() # msg = 'Profile edited' # messages.add_message(request, messages.INFO, msg) return HttpResponseRedirect( reverse("profile_detail", kwargs={"username": profile.username})) return render(request, template_name, { "profile": profile, "form": form, })
def test_valid_profile(self): form = ProfileForm(instance=self.profile_one) # include a bad country to force an error data = { "name": "John Smith", "about": "John likes wine", "location": "Paris", "website": "http://python.org", "street_address": "80, bd Auguste-Blanqui", "street_address_two": "Cedex 13", "city": "Paris", "postal_code": "75707", "country": "FR", "date_of_birth": "1986-05-05", } form = ProfileForm(data) self.assertEquals(True, form.is_valid(), 'Form errors: %s' % form.errors)
def update_profile_form(request,username) : """ Get a prefilled basic form for the profile """ other_user = get_object_or_404(User,username=username) p = other_user.get_profile() if not has_access(request.user,p,'Profile.Viewer') : raise PlusPermissionsNoAccessException(Profile,p.pk,'update_profile_form') else : profile_form = ProfileForm(request.POST, p)
def register(request): ''' TO DO: Authenticate email ''' if request.method == 'POST': formUser = UserForm(data=request.POST) formProfile=ProfileForm(data=request.POST) if formUser.is_valid() and formProfile.is_valid(): password1=formUser.cleaned_data['password'] password2=request.POST.get('password2') first_name=formUser.cleaned_data['first_name'] last_name=formUser.cleaned_data['last_name'] email=formUser.cleaned_data['email'] if(password1!=password2): return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile,'passwordError':'passwordError'}) if User.objects.filter(username = email).exists(): return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile, 'error_message':'error_message'}) user = formUser.save() user.set_password(user.password) user.is_active = False user.first_name=first_name user.last_name=last_name user.email=email user.username=email body=formProfile.cleaned_data['body'] birthDate=formProfile.cleaned_data['birthDate'] gender=formProfile.cleaned_data['gender'] city=formProfile.cleaned_data['city'] country=formProfile.cleaned_data['country'] address=formProfile.cleaned_data['address'] postalCode=formProfile.cleaned_data['postalCode'] phoneNumber=formProfile.cleaned_data['phoneNumber'] try: image = request.FILES['image'] except: image="" user.save() newProfile=Profile(user=user,body=body,birthDate=birthDate,gender=gender,city=city,address=address,postalCode=postalCode,phoneNumber=phoneNumber,country=country,image=image) newProfile.save() return HttpResponseRedirect('/profiles/login') else: formUser = UserForm() formProfile=ProfileForm() return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile})
def checkout_success(request, order_number): """ handle successful checkouts """ # for use with profiles save_info = request.session.get('save_info') # the "=order_number" comes from view prams order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) # attatch order to profile order.user_profile = profile order.save() # update info if box ticked if save_info: profile_data = { # keys match user profile model 'default_name': order.full_name, 'default_email': order.email, 'default_contact_number': order.phone_number, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_town': order.town_or_city, 'default_postcode': order.postcode, # spelling consistant with model 'default_counrty': order.country, } user_profile_form = ProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success( request, f'Your order has been processed. \ Your order number is: {order_number}. A confirmation email is\ on its way to {order.email}') if 'basket' in request.session: del request.session['basket'] template = 'checkout/checkout_success.html' context = {'order': order} return render(request, template, context)
def profile(request): profile = get_object_or_404(Profile, owner=request.user) if request.method == 'POST': form = ProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, ('Your details have been saved')) else: messages.error(request, ('An error occured, please check your form.')) return redirect(reverse('profile')) else: form = ProfileForm(instance=profile) recent_orders = profile.orders.all().order_by('-date')[:3] context = { 'form': form, 'orders': recent_orders, } return render(request, 'profile.html', context)
def newProfile(request): user = request.user.username user_profile = Profile.objects.filter(username=user, completed=True) # Check if logged in user already has a completed profile if user_profile.count() > 0: return HttpResponseRedirect('/swt/') profile = Profile.objects.get(username=user) if request.POST: form = ProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() # Create hash name for profile image signer = Signer() img_hash = signer.sign('p-img-' + user) data = form.cleaned_data if data['profile_pic'] == '': folder = '/home/phoenix470/swt/media/static/assets/uploaded_files' imgurl = 'http://terryshoemaker.files.wordpress.com/2013/03/placeholder1.jpg' urllib.urlretrieve(imgurl, folder + '/' + img_hash + '.jpg') else: folder = '/home/phoenix470/swt/media/static/assets/uploaded_files' imgurl = data['profile_pic'] urllib.urlretrieve(imgurl, folder + '/' + img_hash + '.jpg') profile.completed = True profile.save() return HttpResponseRedirect('/swt/') else: form = ProfileForm() args = {} args.update(csrf(request)) args['form'] = form return render_to_response('profile-new.html', args)
def get(self, request, pk): order = Order.objects.filter(id=pk, cart__user=request.user, accepted=False).aggregate( Sum('cart__cartitem__price_sum')) form = ProfileForm(instance=Profile.objects.get(user=request.user)) return render(request, 'shop/checkout.html', { "order": order, "form": form })
def checkout_success(request, order_number): """ A view to confirm a successful checkout """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: currentprofile = Profile.objects.get(user=request.user) # Attach the user's profile to the order order.user_profile = currentprofile order.save() # Save the user's info if save_info: profile_data = { 'default_full_name': order.full_name, 'default_email': order.email, 'default_phone_number': order.phone_number, 'default_street_address': order.street_address, 'default_address2': order.address2, 'default_country': order.country, 'default_town_or_city': order.town_or_city, 'default_postcode': order.postcode, } user_profile_form = ProfileForm(profile_data, instance=currentprofile) if user_profile_form.is_valid(): user_profile_form.save() messages.success( request, f'Success! Your orser is now processed! \ Your order number is {order_number}.') if 'bag' in request.session: del request.session['bag'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ Show user the checkout success page if an order is successfully placed and gives them feedback. This view will also link orders to the user profile who submit it if they are logged in. """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = Profile.objects.get(user=request.user) # Link the order to user profile order.user_profile = profile order.save() # Saves user info as defualt (can be viewed on Profile Page) if save_info: profile_data = { 'default_phone_number': order.phone_number, 'default_country': order.country, 'default_postcode': order.postcode, 'default_town_or_city': order.town_or_city, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_county': order.county, } profile_form = ProfileForm(profile_data, instance=profile) if profile_form.is_valid(): profile_form.save() save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) messages.success(request, 'Order successful') if 'bag' in request.session: del request.session['bag'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def profile_edit(request,username=None): profile = request.user.get_profile() form = ProfileForm(instance=profile) form.initial['username'] = profile.user.username if request.method=="POST": form = ProfileForm(request.POST,request.FILES,instance=profile) form.initial['username'] = profile.user.username form.initial = request.POST if form.is_valid(): form.save() return HttpResponseRedirect(form.instance.get_absolute_url()) return render_to_response("profiles/profile_create.html",{"form":form},context_instance=RequestContext(request))
def user_register(request): if request.method == "GET": user_form = UserForm() profile_form = ProfileForm() elif request.method == "POST": user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) # setting password done in forms.py user.alias = user.username user.save() # extra password thing # password = user.password # The form doesn't know to call this special method on user. # user.set_password(password) # user.save() # You must call authenticate before login. :( # end extra password thing profile = profile_form.save(commit=False) if Location.objects.count() > 0: profile.location = Location.objects.all()[0] profile.user = user profile.save() user = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, user) messages.add_message( request, messages.SUCCESS, "Congratulations, {}, on creating your new account! You are now logged in.".format( user.username)) send_mail("Welcome to Share Lockers","""\ {}, Your account on sharelockers.come has been created! \ We look forward to seeing what you have to share. \ You might start by stocking some items to sell, or by adding items you have \ at home which you would be willing to sell. -ShareLockers Team""".format(user.username), settings.EMAIL_HOST_USER, [user.email], fail_silently=settings.EMAIL_SILENT) return redirect('view_index') return render(request, "profiles/register.html", {'user_form': user_form, 'profile_form': profile_form, })
def checkout_success(request, order_number): """ Handle successful checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) if request.user.is_authenticated: profile = Profile.objects.get(user=request.user) # Attach the user's profile to the order order.profile = profile order.save() # Save the user's info if save_info: profile_data = { 'profile_full_name': order.full_name, 'profile_phone_number': order.phone_number, 'profile_country': order.country, 'profile_postcode': order.postcode, 'profile_town_or_city': order.town_or_city, 'profile_address_line1': order.address_line1, 'profile_address_line2': order.address_line2, 'profile_county': order.county, } user_profile_form = ProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success( request, f'Order successfully processed! A confirmation \ email will be sent to {order.email}.') if 'cart' in request.session: del request.session['cart'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context)
def checkout_success(request, order_number): """ Handle Successful checkouts """ save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) user = request.user if user.is_authenticated: profile = UserProfile.objects.get(user=user) # Attach the user's profile to the order order.user_profile = profile order.save() # Save user info if seleceted if save_info: profile_data = { 'default_full_name': order.full_name, 'default_phone_number': order.phone_number, 'default_street_address1': order.street_address1, 'default_street_address2': order.street_address2, 'default_town_city': order.town_city, 'default_postcode': order.postcode, 'default_county': order.county, 'default_country': order.country, } user_profile_form = ProfileForm(profile_data, instance=profile) if user_profile_form.is_valid(): user_profile_form.save() messages.success( request, f'Order successfully processed \ Your order number is {order_number}. A confirmation emial \ will be sent to {order.email}.') if 'basket' in request.session: del request.session['basket'] context = { 'order': order, } return render(request, 'checkout/checkout_success.html', context)
def my_profile_view(request): profile = Profile.objects.get(user=request.user) print(request.POST) print(request.FILES) form = ProfileForm(request.POST or None, request.FILES or None, instance=profile) confirm = False if request.method == "POST": if form.is_valid: form.save() confirm = True context = { 'profile': profile, 'form': form, 'confirm': confirm, } return render(request, 'profiles/main.html', context)
def profile_edit(request, template_name="profiles/profile_edit.html"): profile = request.user.get_profile() form = ProfileForm(request.POST or None, instance=profile) if form.is_valid(): form.save() msg = 'Profile edited' messages.add_message(request, messages.INFO, msg) return HttpResponseRedirect(reverse("profile_detail", kwargs={"github_account":profile.github_account })) # TODO - move this to a template github_account = """ <div id="div_id_github_account" class="ctrlHolder"><label for="id_github_account" >Github account</label><strong>{0}</strong></div> """.format(profile.github_account) helper = FormHelper() helper.form_class = "profile-edit-form" helper.layout = Layout( Fieldset( '', HTML(github_account), 'bitbucket_url', 'google_code_url', 'email', ), ButtonHolder( Submit('edit', 'Edit', css_class="awesome forestgreen"), ) ) return render_to_response(template_name, { "profile": profile, "form": form, "helper":helper, }, context_instance=RequestContext(request) )
def profile(request, template_name="profiles/edit_profile.html"): user = request.user profile = user.profile def update_profile(): profile_form = ProfileForm(data=request.POST, instance=request.user.get_profile()) if profile_form.is_valid(): profile_form.save() messages.success(request, 'Profile updated.') def update_skills(): #f**k capitals tag_list = request.POST.get('skills_text').lower().split(',') for tag in tag_list: if tag and tag != '': #f*****g excess whitespace man tag = tag_clean(tag) skill, created = Skill.objects.get_or_create(name=tag) profile.skills.add(skill) psf = ProfileSkillsForm(request.POST) if psf.is_valid(): skills_list = Skill.objects.filter( id__in=psf.cleaned_data.get('skills')) for skill in skills_list: profile.skills.add(skill) profile.save() messages.success(request, 'Skills updated.') if request.method == "POST": origin = request.POST.get('origin') if origin == "profile": update_profile() else: #origin == "skill": update_skills() profile_form = ProfileForm(instance=request.user.get_profile()) skill_form = ProfileSkillsForm() skills = profile.skills.all() events = Event.objects.filter(creator=user) start = datetime.now() end = start + timedelta(days=30) office_hours = reduce(lambda x, y: x + y, [e.get_occurrences(start, end) for e in events]) if events else [] return direct_to_template( request, template_name, { 'skill_form': skill_form, 'profile_form': profile_form, 'profile': profile, 'skills': skills, 'editable': True, 'office_hours': office_hours })
def edit(request, username): user = get_object_or_404(User, username=username) if request.user != user: return http.HttpResponseForbidden() try: profile = user.get_profile() except Profile.DoesNotExist: raise http.Http404 form = ProfileForm(instance=profile) if request.method == 'POST': form = ProfileForm(instance=profile, data=request.POST, files=request.FILES) if form.is_valid(): form.save() return http.HttpResponseRedirect(reverse('profiles_show', kwargs={ 'username': profile.user.username })) return render_to_response('profiles/edit.html', { 'form': form, 'profile': profile, }, context_instance=RequestContext(request))
def create_profile(req): if req.user.groups.filter(name='adults').exists(): return redirect('browse') context = { 'title': 'CarTrek -- Create Profile', 'organizations': Organization.objects.all(), 'form': ProfileForm(initial={ 'phone_number': '', 'org_email': 'none', }), } return render(req, 'create.html', context=context)
def create_profile(request): """ Create a profile for the current User, if one doesn't already exist. If the User already has a profile, as determined by `request.user.profile`, a redirect will be issued to the `profiles.views.edit_profile` view. If no profile model has been specified in the `AUTH_PROFILE_MODULE` setting, `django.contrib.auth.models.SiteProfileNotAvailable` will be raised. """ try: profile_obj = request.user.profile return redirect("profiles_edit_profile") except ObjectDoesNotExist: pass form = ProfileForm(request.POST or None, request.FILES or None, request=request) if form.is_valid(): profile_obj = form.save(commit=False) profile_obj.user = request.user profile_obj.save() if hasattr(form, "save_m2m"): form.save_m2m() return redirect("profiles_my") return {"form": form}
def model_profile_upload(request): if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('profile') else: form = ProfileForm() return render(request, 'model_profile_upload.html', { 'form': form })
def update(request, id): """ updates profile by id, on GET returns common profile-update-page on POST | validates sended data, on success: redirect to show page, on fail returns to update page on ajax POST | on success: returns updated profile, on fail returns errors :param request: :param id: :return: """ profile = get_object_or_404(Profile, pk=id) context = { 'profile': profile } # # if user is admin, check has he access for that profile # if hasattr(request.user, 'is_admin') and request.user.is_admin: # if request.user.is_superuser or request.user.profile.profiles.filter(pk=profile.id).count(): # return render_show_view(profile) if request.method == "GET": context['form'] = ProfileForm(instance=profile) return render(request, "profiles/update.html", context) elif request.method == "POST": form = ProfileForm(request.POST, instance=profile) if form.is_valid(): profile = form.save() if request.is_ajax(): return HttpResponse(serialize('json', [profile, ]).strip("[]")) else: if profile.slug: return redirect(reverse("profiles.views.profile.show_by_slug", args=[profile.slug])) else: return redirect(reverse("profiles.views.profile.show", args=[profile.pk])) else: if request.is_ajax(): return render(request, "profiles/update.html", context) else: return HttpResponse(serialize('json', form.errors)) return HttpResponse()
def test_form_instructor_labels(self): ''' Test labels are tailored to instructor if user is instructor ''' profile = UserProfile.objects.get(user__username='******') login_successful = self.client.login(username=profile.user.username, password='******') self.assertTrue(login_successful) form = ProfileForm(instance=profile) self.assertEqual(form.fields['profile_description'].label, ('Instructor Studio Info'))
def profile_edit(request, template_name="profiles/profile_edit.html"): profile = request.user.get_profile() form = ProfileForm(request.POST or None, instance=profile) if form.is_valid(): print form.instance.__dict__ form.save() msg = 'Profile edited' messages.add_message(request, messages.INFO, msg) return HttpResponseRedirect(reverse("profile_detail", kwargs={"github_account": profile.github_account})) # TODO - move this to a template github_account = """ <div id="div_id_github_account" class="ctrlHolder"><label for="id_github_account" >Github account</label><strong>{0}</strong></div> """.format(profile.github_account) helper = FormHelper() helper.form_class = "profile-edit-form" helper.layout = Layout( Fieldset( '', HTML(github_account), 'bitbucket_url', 'google_code_url', ), ButtonHolder( Submit('edit', 'Edit', css_class="awesome forestgreen"), ) ) return render(request, template_name, { "profile": profile, "form": form, "helper": helper, })
def edit_profile(request, username): """ Displays a form to edit the current user's profile. This page should only be assessible to the profile's owner. If the form is valid, the profile is updated and the view redirects to the profile consultation view. :param request: request object :param username: login name of the user whom profile is to be edited """ user = get_object_or_404(User, username=username) # The following line should reject any illegitimate accesses : if request.user != user: raise PermissionDenied user_profile = get_object_or_404(Profile, user=user.id) profile_edition_form = ProfileForm( request.POST or None, request.FILES or None, instance=user_profile) if profile_edition_form.is_valid(): profile_edition_form.save() messages.success(request, u'Votre profil a bien été mis à jour.') elif request.POST: messages.error(request, u'Erreur lors de la modification du profil.') return render_to_response( "profile_edition.html", { 'request': request, 'profile_edition_form': profile_edition_form, }, context_instance=RequestContext(request))
def profile(request, username, template_name="profiles/profile.html"): other_user = get_object_or_404(User, username=username) profile = other_user.get_profile() try: cal = Calendar.objects.get(pk=1) except Calendar.DoesNotExist: cal = Calendar(name="Community Calendar") cal.save() if request.user.is_authenticated(): if request.user == other_user: is_me = True else: is_me = False else: is_me = False if is_me: if request.method == "POST": if request.POST["action"] == "update": profile_form = ProfileForm(request.POST, instance=other_user.get_profile()) if profile_form.is_valid(): profile = profile_form.save(commit=False) profile.user = other_user profile.save() else: profile_form = ProfileForm(instance=other_user.get_profile()) else: profile_form = ProfileForm(instance=other_user.get_profile()) else: profile_form = None return render_to_response(template_name, { "profile_form": profile_form, "is_me": is_me, "other_user": other_user, "profile": profile, "calendar": cal, }, context_instance=RequestContext(request))
def profile_edit(request): page_title = "Edit Profile" profile, created = Profile.objects.get_or_create(user=request.user) form = ProfileForm(request.POST or None, request.FILES or None, instance=profile) projects = Project.objects.filter(user=request.user) projects_count = projects.count() form.fields["featured_project"].queryset = projects if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect ("profile_user") context = { 'profile': profile, 'form': form, 'page_title': page_title, 'projects_count': projects_count, } return render(request, 'profile_settings.html', context)
def view_register(request): if request.method == "GET": user_form = UserForm() profile_form = ProfileForm() rater_form = RaterForm() elif request.method == "POST": user_form = UserForm(request.POST) rater_form = RaterForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and rater_form.is_valid(): user = user_form.save() rater = rater_form.save(commit=False) rater.user = user profile = profile_form.save(commit=False) profile.user = user profile.age = rater.age profile.gender = rater.gender profile.save() rater.save() password = user.password # The form doesn't know to call this special method on user. user.set_password(password) user.save() # You must call authenticate before login. :( user = authenticate(username=user.username, password=password) login(request, user) messages.add_message( request, messages.SUCCESS, "Congratulations, {}, on creating your new account! You are now logged in.".format( user.username)) return redirect('/') return render(request, "profiles/register.html", {'user_form': user_form, 'rater_form': rater_form})
def create(request): try: request.user.get_profile() return http.HttpResponseRedirect(reverse('profiles_show', kwargs={ 'username': request.user.username })) except Profile.DoesNotExist: pass form = ProfileForm() if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user hashed_email = hashlib.md5( request.user.email.lower().strip()).hexdigest() profile.hashed_email = hashed_email profile.save() return http.HttpResponseRedirect(reverse('profiles_show', kwargs={ 'username': profile.user.username, })) return render_to_response('profiles/create.html', { 'form': form, }, context_instance=RequestContext(request))
def editProfile(request): user = request.user.username profile = Profile.objects.get(username=user) if request.POST: form = ProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save() # create hash name for profile image signer = Signer() img_hash = signer.sign('p-img-' + user) data = form.cleaned_data if data['profile_pic'] == '': folder = '/home/phoenix470/swt/media/static/assets/uploaded_files' imgurl = 'http://terryshoemaker.files.wordpress.com/2013/03/placeholder1.jpg' urllib.urlretrieve(imgurl, folder + '/' + img_hash + '.jpg') else: folder = '/home/phoenix470/swt/media/static/assets/uploaded_files' imgurl = data['profile_pic'] urllib.urlretrieve(imgurl, folder + '/' + img_hash + '.jpg') return HttpResponseRedirect('/swt/profiles/') else: form = ProfileForm(instance=profile) args = {} args.update(csrf(request)) args['form'] = form return render_to_response('profile-edit.html', args)
def settings(request): if request.method == "POST": p = Profile.objects.get(user=request.user) if p is None: p = Profile(user=request.user) form = ProfileForm(request.POST, request.FILES, instance=p) if form.is_valid(): form.save() return redirect(reverse("settings")) else: return render(request, "profiles/settings.html", {"f": form}) else: p = Profile.objects.get(user=request.user) if p is None: form = ProfileForm() else: form = ProfileForm(instance=p) return render(request, "profiles/settings.html", {"f": form})
def profile(request, username, template_name="profiles/profile.html"): other_user = get_object_or_404(User, username=username) other_user.save() p = other_user.get_profile() p.save() if request.user.is_authenticated(): is_friend = Friendship.objects.are_friends(request.user, other_user) is_following = Following.objects.is_following(request.user, other_user) other_friends = Friendship.objects.friends_for_user(other_user) if request.user == other_user: is_me = True else: is_me = False else: other_friends = [] is_friend = False is_me = False is_following = False if is_friend: invite_form = None previous_invitations_to = None previous_invitations_from = None else: if request.user.is_authenticated() and request.method == "POST": if request.POST["action"] == "invite": invite_form = InviteFriendForm(request.user, request.POST) if invite_form.is_valid(): invite_form.save() else: invite_form = InviteFriendForm(request.user, { 'to_user': username, 'message': ugettext("Let's be friends!"), }) if request.POST["action"] == "accept": # @@@ perhaps the form should just post to friends and be redirected here invitation_id = request.POST["invitation"] try: invitation = FriendshipInvitation.objects.get(id=invitation_id) if invitation.to_user == request.user: invitation.accept() request.user.message_set.create(message=_("You have accepted the friendship request from %(from_user)s") % {'from_user': invitation.from_user}) is_friend = True other_friends = Friendship.objects.friends_for_user(other_user) except FriendshipInvitation.DoesNotExist: pass else: invite_form = InviteFriendForm(request.user, { 'to_user': username, 'message': ugettext("Let's be friends!"), }) previous_invitations_to = FriendshipInvitation.objects.filter(to_user=other_user, from_user=request.user) previous_invitations_from = FriendshipInvitation.objects.filter(to_user=request.user, from_user=other_user) if is_me: if request.method == "POST": if request.POST["action"] == "update": profile_form = ProfileForm(request.POST, instance=other_user.get_profile()) if profile_form.is_valid(): profile = profile_form.save(commit=False) profile.user = other_user profile.save() else: profile_form = ProfileForm(instance=other_user.get_profile()) else: profile_form = ProfileForm(instance=other_user.get_profile()) else: profile_form = None interests = get_tags(tagged=other_user.get_profile(), tagged_for=other_user, tag_type='interest') skills = get_tags(tagged = other_user.get_profile(), tagged_for=other_user, tag_type='skill') needs = get_tags(tagged = other_user.get_profile(), tagged_for=other_user, tag_type='need') profile = other_user.get_profile() user = request.user if not user.is_authenticated(): user = get_anon_user() user_type = ContentType.objects.get_for_model(other_user) other_user_tweets = Tweet.objects.filter(sender_type=user_type, sender_id=other_user.id).order_by("-sent") # other_user if other_user_tweets : latest_status = other_user_tweets[0] dummy_status = DisplayStatus( defaultfilters.safe( defaultfilters.urlize(latest_status.html())), defaultfilters.timesince(latest_status.sent) ) else : dummy_status = DisplayStatus('No status', '') profile = secure_wrap(profile, user) try: profile.get_all_sliders perms_bool = True except PlusPermissionsNoAccessException: perms_bool = False profile = TemplateSecureWrapper(profile) search_type = 'profile_list' search_types = narrow_search_types() search_types_len = len(search_types) search_type_label = search_types[0][1][2] return render_to_response(template_name, { "profile_form": profile_form, "is_me": is_me, "is_friend": is_friend, "is_following": is_following, "other_user": other_user, "profile":profile, "other_friends": other_friends, "invite_form": invite_form, "previous_invitations_to": previous_invitations_to, "previous_invitations_from": previous_invitations_from, "head_title" : "%s" % other_user.get_profile().get_display_name(), "head_title_status" : dummy_status, "host_info" : other_user.get_profile().get_host_info(), "skills" : skills, "needs" : needs, "interests" : interests, "other_user_tweets" : other_user_tweets, "permissions":perms_bool, "search_type":search_type, "search_type_label":search_type_label, "search_types_len":search_types_len }, context_instance=RequestContext(request))