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 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 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 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 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 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(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_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 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_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, 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 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, 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_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 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 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 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 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 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 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 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 if request.method == "POST": if request.POST["action"] == "remove": Friendship.objects.remove(request.user, other_user) request.user.message_set.create(message=_("You have removed %(from_user)s from friends") % {'from_user': other_user}) is_friend = False invite_form = InviteFriendForm(request.user, { 'to_user': username, 'message': ugettext("Let's be friends!"), }) 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!"), }) invitation_id = request.POST.get("invitation", "") if request.POST["action"] == "accept": # @@@ perhaps the form should just post to friends and be redirected here 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 elif request.POST["action"] == "decline": try: invitation = FriendshipInvitation.objects.get(id=invitation_id) if invitation.to_user == request.user: invitation.decline() request.user.message_set.create(message=_("You have declined the friendship request from %(from_user)s") % {'from_user': invitation.from_user}) 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!"), }) if request.user.is_authenticated(): previous_invitations_to = FriendshipInvitation.objects.filter(to_user=other_user, from_user=request.user).exclude(status=8).exclude(status=6) previous_invitations_from = FriendshipInvitation.objects.filter(to_user=request.user, from_user=other_user).exclude(status=8).exclude(status=6) 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 total_duration = timedelta() total_distance = 0 total_avg_speed = 0 total_avg_hr = 0 nr_trips = 0 nr_hr_trips = 0 longest_trip = 0 avg_length = 0 avg_duration = 0 bmidataseries = '' bmiline = '' pulsedataseries = "" tripdataseries = "" avgspeeddataseries = "" avghrdataseries = "" ftpdataseries = '' height = other_user.get_profile().height if height: height = float(other_user.get_profile().height)/100 weightqs = other_user.get_profile().userprofiledetail_set.filter(weight__isnull=False).order_by('time') for wtuple in weightqs.values_list('time', 'weight'): bmidataseries += '[%s, %s],' % (datetime2jstimestamp(wtuple[0]), wtuple[1]/(height*height)) bmiline += '[%s, 25],' %datetime2jstimestamp(wtuple[0]) pulseqs = other_user.get_profile().userprofiledetail_set.filter(resting_hr__isnull=False).order_by('time') for hrtuple in pulseqs.values_list('time', 'resting_hr'): pulsedataseries += '[%s, %s],' % (datetime2jstimestamp(hrtuple[0]), hrtuple[1]) ftpqs = other_user.get_profile().userprofiledetail_set.filter(ftp__isnull=False).order_by('time') for ftuple in ftpqs.values_list('time', 'ftp'): ftpdataseries += '[%s, %s],' % (datetime2jstimestamp(ftuple[0]), ftuple[1]) exerciseqs = other_user.exercise_set.select_related('route','exercise_type').order_by('date') exerciseqs_dataseries = other_user.exercise_set.select_related('route','exercise_type').order_by('date')[:7] i = 0 for trip in reversed(exerciseqs): if trip.avg_speed and trip.exercise_type.name=="Cycling": # only increase counter if trip has speed avgspeeddataseries += '[%s, %s],' % (datetime2jstimestamp(trip.date), trip.avg_speed) i += 1 if i > 7: break i = 0 for trip in reversed(exerciseqs): if trip.avg_hr: avghrdataseries += '[%s, %s],' % (datetime2jstimestamp(trip.date), trip.avg_hr) i += 1 if i > 7: break for trip in exerciseqs: if trip.route: tripdataseries += '[%s, %s],' % ( nr_trips, trip.route.distance) if trip.route.distance > longest_trip: longest_trip = round(trip.route.distance) total_distance += trip.route.distance if trip.duration: total_duration += trip.duration if trip.avg_speed: # only increase counter if trip has speed total_avg_speed += trip.avg_speed nr_trips += 1 if total_avg_speed: total_avg_speed = total_avg_speed/nr_trips for event in exerciseqs: if event.avg_hr: total_avg_hr += event.avg_hr nr_hr_trips += 1 if total_avg_hr: total_avg_hr = total_avg_hr/nr_hr_trips total_kcals = max(0, other_user.exercise_set.aggregate(Sum('kcal'))['kcal__sum']) # TODO fix total_duration for hike and otherexercise # Todo filter ? for cycletrip in exerciseqs: if exerciseqs[0].date: days_since_start = (datetime.now() - datetime(exerciseqs[0].date.year, exerciseqs[0].date.month, exerciseqs[0].date.day, 0, 0, 0)).days # TODO check in exercise and hike for first if days_since_start == 0: # if they only have one trip and it was today days_since_start = 1 km_per_day = total_distance / days_since_start kcal_per_day = total_kcals / days_since_start time_per_day = total_duration / days_since_start latest_exercises = other_user.exercise_set.select_related('route','exercise_type', 'user').order_by('-date')[:20] return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def register(request): registered = False # Messy to include profile stuff here if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = ProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user unique_slugify(profile, user.username) profile.save() # Give user permission to view and edit own profile assign_perm('profiles.view_profile', user, profile) assign_perm('profiles.change_profile', user, profile) registered = True # Invitation stuff if 'invitation' in request.session: # Retrieve invitation object invitation = Invitation.objects.get( id=request.session['invitation']) # Create membership of profile with group m = Membership(profile=profile, giftgroup=invitation.gift_group) m.save() # Delete the used invitation from the (database and) session # invitation.delete() del request.session['invitation'] else: # If user was not invited profile.save() # Check if all invited people have registered invites = Invitation.objects.all() all_users = [u.username for u in User.objects.all()] for invite in invites: if invite.to_name in all_users: pass else: break # User no longer has admin property # # Check if user is an admin # if user.profile.admin: # permission_invites = Permission.objects.get( # codename='send_invites') # permission_assign = Permission.objects.get( # codename='assign_pairs') # user.user_permissions.add( # permission_invites, # permission_assign # ) # Log user in after registration user = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, user) else: print(user_form.errors, profile_form.errors) else: # TODO repetition checking for invite if 'invitation' in request.session: # Retrieve invitation object invitation = Invitation.objects.get( id=request.session['invitation']) user_form = UserForm(initial={ 'username': invitation.to_name, 'email': invitation.to_email }) user_form.fields['username'].widget.attrs['readonly'] = True user_form.fields['email'].widget.attrs['readonly'] = True else: user_form = UserForm() profile_form = ProfileForm() return render( request, 'registration/register.html', { 'user_form': user_form, 'profile_form': profile_form, 'registered': registered })
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 profile(request, username, template_name="profiles/profile.html"): 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 request.user.is_authenticated() and request.method == "POST" and not is_me: # @@@ some of this should go in zwitschern itself if request.POST["action"] == "follow": Following.objects.follow(request.user, other_user) is_following = True request.user.message_set.create(message=_("You are now following %(other_user)s") % {'other_user': other_user}) if notification: notification.send([other_user], "tweet_follow", {"user": request.user}) elif request.POST["action"] == "unfollow": Following.objects.unfollow(request.user, other_user) is_following = False request.user.message_set.create(message=_("You have stopped following %(other_user)s") % {'other_user': other_user}) 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"] == "delete": file_form = UploadFileForm() fname = request.POST['file'] delete_uploaded_file(fname, request.user) invite_form = InviteFriendForm(request.user, { 'to_user': username, 'message': ugettext("Let's be friends!"), }) request.user.message_set.create(message=_("You have deleted %(file)s") % {'file': fname}) elif request.POST["action"] == "upload": invite_form = InviteFriendForm(request.user, { 'to_user': username, 'message': ugettext("Let's be friends!"), }) file_form = UploadFileForm(request.POST, request.FILES) if file_form.is_valid(): uFile = handle_uploaded_file(request.FILES['file'], request.user) myAccount = Account.objects.get(user = request.user) myAccount.files.add(uFile) myAccount.save() request.user.message_set.create(message="uploaded %(file)s"%{'file':request.FILES['file'].name}) elif request.POST["action"] == "invite": file_form = UploadFileForm() invite_form = InviteFriendForm(request.user, request.POST) if invite_form.is_valid(): invite_form.save() else: file_form = UploadFileForm() 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: file_form = UploadFileForm() 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: file_form = UploadFileForm() myAccount = Account.objects.get(user = request.user) file_list = myAccount.files.all() 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: file_form = None file_list = None profile_form = None 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, "other_friends": other_friends, "invite_form": invite_form, "previous_invitations_to": previous_invitations_to, "previous_invitations_from": previous_invitations_from, "file_list":file_list, "file_form":file_form }, context_instance=RequestContext(request))
def profile(request, username, to_follow = None, template_name="profiles/profile.html"): other_user = get_object_or_404(User, username=username) publications = [] is_follow = False calc_age(other_user.get_profile()) if request.user == other_user: is_me = True else: is_me = False if not is_me and to_follow == '1': button_follow(request, other_user) elif not is_me and to_follow == '0': button_unfollow(request, other_user) #Finding publications if request.user.is_authenticated(): calc_age(request.user.get_profile()) publications = getPublications(request, other_user, is_me) else: publications = getPublicPublications(request, other_user) #Finding followings followinUsers = getFollowings(request,other_user) #Finding followers followerUsers = getFollowers(request,other_user) posts = getPosts(request, other_user) # Post.objects.filter(status=2).select_related(depth=1).order_by("-publish") #posts = blogs.filter(author=other_user) is_edit = 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() profile.user = other_user profile.save() request.user.message_set.create(message=_(u"Perfil atualizado com sucesso")) template_name="profiles/profile_edit.html" is_edit = True else: template_name="profiles/profile_edit.html" is_edit = True elif request.POST["action"] == "edit": template_name="profiles/profile_edit.html" profile_form = ProfileForm(instance=other_user.get_profile()) is_edit = True else: profile_form = ProfileForm(instance=other_user.get_profile()) else: profile_form = ProfileForm(instance=other_user.get_profile()) else: profile_form = None if request.user.is_authenticated(): try: follow = FollowAuthor.objects.get( UserFrom=request.user, UserTo=other_user ) if follow: is_follow = True else: is_follow = False except FollowAuthor.DoesNotExist: pass nr_publications = len(publications) nr_posts = len(posts) nr_followings = len(followinUsers) nr_followers = len(followerUsers) publications = publications[:6] posts = posts[:8] followinUsers = followinUsers[:21] followerUsers = followerUsers[:21] return render_to_response(template_name, { "form": profile_form, "is_me": is_me, "is_follow": is_follow, "other_user": other_user, "publications": publications, "followings": followinUsers, "followers": followerUsers, "is_profile": True, "is_edit": is_edit, "posts": posts, "nr_publications": nr_publications, "nr_posts": nr_posts, "nr_followings": nr_followings, "nr_followers": nr_followers, }, 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))
def create_profile(request): """ Create a formset to allow for multiple profile photos to be uploaded Assistance from https://stackoverflow.com/questions/34006994/how-to-upload-multiple-images-to-a-blog-post-in-django """ ImageFormSet = modelformset_factory(ProfileImage, form=ProfileImageForm, extra=6, max_num=6, help_texts=None) # If user has submitted profile form if request.method == "POST": profile_form = ProfileForm(request.POST, instance=request.user.profile) image_form = ProfileImageForm(request.POST, request.FILES) formset = ImageFormSet(request.POST, request.FILES, queryset=ProfileImage.objects.filter( user_id=request.user.id).all()) # Update profile and change profile to 'to be approved' if profile_form.is_valid() and formset.is_valid(): instance = profile_form.save(commit=False) instance.user_id = request.user.id instance.is_verified = 'TO BE APPROVED' instance.save() # Get images requested to be deleted and delete them deleted_images = request.POST.getlist('delete') for image in deleted_images: if not image == "None": ProfileImage.objects.get(pk=image).delete() # Save submitted images for form in formset: if form.is_valid() and form.has_changed(): instance_image = form.save(commit=False) instance_image.user = request.user instance_image.is_verified = False instance_image.save() return redirect(reverse('verification_message')) else: profile_form = ProfileForm(instance=request.user.profile) image_form = ProfileImageForm(instance=request.user.profile) initial_images = [{ 'image_url': i.image } for i in ProfileImage.objects.filter(user_id=request.user.id).all() if i.image] formset = ImageFormSet(queryset=ProfileImage.objects.filter( user_id=request.user.id).all(), initial=initial_images) context = { 'page_ref': 'create_profile', 'profile_form': profile_form, 'image_form': image_form, 'formset': formset } return render(request, 'create-profile.html', context)