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 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 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 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 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 _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 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 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 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 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 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 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 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_edit(request, template_name='profiles/profile_form.html'): """Edit profile.""" if request.POST: profile = Profile.objects.get(user=request.user) user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, request.FILES, instance=profile) service_formset = ServiceFormSet(request.POST, instance=profile) link_formset = LinkFormSet(request.POST, instance=profile) if profile_form.is_valid() and user_form.is_valid( ) and service_formset.is_valid() and link_formset.is_valid(): profile_form.save() user_form.save() link_formset.save() service_formset.save() # return HttpResponseRedirect(reverse('profile_detail', kwargs={'username': request.user.username})) return HttpResponseRedirect(reverse('profiles-profile-edit')) else: from lib.util.form_errors import merge_form_errors form_errors = merge_form_errors([ user_form, profile_form, service_formset, link_formset, ]) context = { 'object': profile, 'action_form': ActionForm(), 'profile_form': profile_form, 'user_form': user_form, 'service_formset': service_formset, 'link_formset': link_formset, 'form_errors': form_errors, } else: profile = Profile.objects.get(user=request.user) link_formset = LinkFormSet(instance=profile) service_formset = ServiceFormSet(instance=profile) context = { 'object': profile, 'action_form': ActionForm(), 'profile_form': ProfileForm(instance=profile), 'user_form': UserForm(instance=request.user), 'service_formset': service_formset, 'link_formset': link_formset } return render_to_response(template_name, context, context_instance=RequestContext(request))
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 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 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 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 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 model_profile_upload(request): try: profile = request.user.profile except Profile.DoesNotExist: profile = Profile(user=request.user) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save() return redirect('profile') else: form = ProfileForm(instance=profile) return render(request, 'model_profile_upload.html', {'form': form})
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 my_profile(request): if request.method == 'POST': try: profile_form = ProfileForm(request.POST, instance=request.user) if profile_form.is_valid(): profile_form.save() if profile_form.changed_data: idp_interface.update_user(request.user) # crm_interface.update_contact(request.user) messages.success(request, _('Profile has been successfully changed')) else: messages.error( request, _('Changes could not be made. Please check form for errors.' )) except Exception as e: logger.exception(e) return HttpResponseServerError() else: profile_form = ProfileForm(instance=request.user) support_details = {} try: support_details = utils.get_support_details(request) except (KeyError, TypeError) as e: log_crm( 'Unexpected support plan value: {}, {}'.format(support_details, e), 'ERROR') pass return render( request, 'profiles/edit_profile.html', { 'profile_form': profile_form, 'page_type': 'my-profile', 'support_details': support_details })
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 edit_profile(request): user = request.user if not request.user.is_authenticated: return render(request, 'profile_form.html') profile = Profile(user=user) if request.method == "POST": form = ProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save() profile.save() return HttpResponseRedirect( reverse("profile-detail", args=(user.id, ))) else: form = ProfileForm() return render(request, 'profile_form.html', context={'form': form})
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_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 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 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 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 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 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 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 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 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 """ # 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 update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, ('Ваш профиль был успешно обновлен!')) return redirect('profile') else: messages.error(request, ('Пожалуйста, исправьте ошибки.')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'profile.html', { 'user_form': user_form, 'profile_form': profile_form })
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 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, 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_edit(request): user = request.user if request.method == 'POST': user_form = EditUserForm(request.POST, instance=user) profile_form = ProfileForm(request.POST, instance=Profile.objects.get(user=user)) if profile_form.is_valid() and user_form.is_valid(): with transaction.atomic(): profile_form.save() user_form.save() return redirect('profile-detail', user.username) else: profile_form = ProfileForm(instance=Profile.objects.get(user=user)) user_form = EditUserForm(instance=user) return render(request, 'profile_edit.html', { 'profile_form': profile_form, 'user': user, 'user_form': user_form, })
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 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 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 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 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 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 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 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_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 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 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 profile(request, username, template_name="profiles/profile.html", extra_context=None): if extra_context is None: extra_context = {} other_user = get_object_or_404(User, username=username) 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).exclude(status=8) previous_invitations_from = FriendshipInvitation.objects.filter(to_user=request.user, from_user=other_user).exclude(status=8) 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, dict({ "profile_form": profile_form, "is_me": is_me, "is_friend": is_friend, "is_following": is_following, "other_user": other_user, "other_friends": other_friends, "invite_form": invite_form, "previous_invitations_to": previous_invitations_to, "previous_invitations_from": previous_invitations_from, }, **extra_context), context_instance=RequestContext(request))
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))