当前位置: 首页>>代码示例>>Python>>正文


Python models.Activity类代码示例

本文整理汇总了Python中home.models.Activity的典型用法代码示例。如果您正苦于以下问题:Python Activity类的具体用法?Python Activity怎么用?Python Activity使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Activity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: setup_PetReunion

def setup_PetReunion(sender, instance, created, **kwargs):
	if created == True:
		userprofile = instance.petreport.proposed_by
		instance.petreport.closed = True
		instance.petreport.save()

		if instance.matched_petreport:
			instance.matched_petreport.closed = True
			instance.matched_petreport.save()

		Activity.log_activity("ACTIVITY_PETREUNION_CREATED", userprofile, source=instance)
		userprofile.update_reputation("ACTIVITY_PETREUNION_CREATED")
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:12,代码来源:models.py

示例2: unfollow

def unfollow(request):
    if request.method == "POST":
        userprofile = request.user.userprofile
        target_userprofile_id = request.POST["target_userprofile_id"]
        target_userprofile = get_object_or_404(UserProfile, pk=target_userprofile_id)

        if userprofile.id != target_userprofile.id:
            if target_userprofile in userprofile.following.all():
                userprofile.following.remove(target_userprofile)
                target_userprofile.update_reputation("ACTIVITY_SOCIAL_UNFOLLOW")
                messages.success(request, "You are no longer following " + str(target_userprofile.user.username) + ".")
                Activity.log_activity("ACTIVITY_SOCIAL_UNFOLLOW", userprofile, source=target_userprofile)
                return redirect(URL_USERPROFILE + str(target_userprofile.id))
    raise Http404
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:14,代码来源:views.py

示例3: create_random_following_list

def create_random_following_list (userprofile, num_following=None):
	allusers = UserProfile.objects.exclude(pk = userprofile.user.id)
	#Remember to initialize this list first before adding.
	userprofile.following = []

	if num_following == None:
		num_following = random.randint(0, len(allusers)/2)

	following_list = random.sample(allusers, num_following)

	for followed in following_list:
		userprofile.following.add(followed)
		Activity.log_activity("ACTIVITY_SOCIAL_FOLLOW", userprofile, followed)

	print_success_msg("following list created for %s" % userprofile)
	return userprofile
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:16,代码来源:fixture.py

示例4: message

def message(request):
    if request.method == "POST":
        message = request.POST ["message"]
        target_userprofile_id = request.POST ["target_userprofile_id"]
        target_userprofile = get_object_or_404(UserProfile, pk=target_userprofile_id)
        from_userprofile = request.user.userprofile

        if len(message) > USERPROFILE_MESSAGE_LENGTH:
            messages.error(request, "Message size is too big. Please try again.")
            return redirect(URL_USERPROFILE + str(target_userprofile_id))

        if from_userprofile.id == target_userprofile.id:
            messages.error (request, "You cannot send a message to yourself.")
            return redirect(URL_USERPROFILE + str(from_userprofile.id))

        print_info_msg ("Sending an email message from %s to %s" % (from_userprofile.user.username, target_userprofile.user.username))
        completed = from_userprofile.send_email_message_to_UserProfile(target_userprofile, message, test_email=False)
        Activity.log_activity("ACTIVITY_SOCIAL_SEND_MESSAGE_TO_USER", from_userprofile, source=target_userprofile)
        messages.success(request, "You have successfully sent your message to %s" % target_userprofile.user.username + ".")
        return redirect(URL_USERPROFILE + str(target_userprofile_id))
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:20,代码来源:views.py

示例5: bookmark

def bookmark(request):
    if request.method == "POST" and request.is_ajax() == True:
        profile = request.user.userprofile
        petreport = get_object_or_404(PetReport, pk=request.POST['petreport_id'])
        action = request.POST['action']

        if ((petreport.UserProfile_has_bookmarked(profile) == True) and (action == "Remove Bookmark")) :
            petreport.bookmarked_by.remove(profile)
            petreport.save()
            message = "You have successfully removed the bookmark for this pet."
            text = "Bookmark this Pet"
            Activity.log_activity("ACTIVITY_PETREPORT_REMOVE_BOOKMARK", profile, source=petreport)

        elif ((petreport.UserProfile_has_bookmarked(profile) == False) and (action == "Bookmark this Pet")):
            petreport.bookmarked_by.add(profile)
            petreport.save()
            message = "You have successfully bookmarked this pet!"
            text = "Remove Bookmark"
            Activity.log_activity("ACTIVITY_PETREPORT_ADD_BOOKMARK", profile, source=petreport)
        else:
            raise Http404
        return JsonResponse({"message":message, "text":text}, safe=False)
    else:
        raise Http404
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:24,代码来源:views.py

示例6: post

    def post(self, crowd_request, data, form, **kwargs):
        if kwargs.get('pipe_data'):
            petmatch_id = kwargs['pipe_data']['petmatch_id']
            action = kwargs['pipe_data']["action"] #Specifies the endpoint that we're using.
        else:
            petmatch_id = data["petmatch_id"]
            action = URL_VOTE_PETMATCH

        if form.get('up') != None:
            vote = "upvote"
        else:
            vote = "downvote"

        request = crowd_request.request_strategy.request
        userprofile = request.user.userprofile
        pm = get_object_or_404(PetMatch, pk=petmatch_id)

        if vote == "upvote":
            if pm.UserProfile_has_voted(userprofile) is False: # If the user is voting for the 1st time, add reputation points
                userprofile.update_reputation("ACTIVITY_PETMATCH_UPVOTE")

            pm.up_votes.add(userprofile)
            pm.down_votes.remove(userprofile)
            Activity.log_activity("ACTIVITY_PETMATCH_UPVOTE", userprofile, source=pm)
            message = "You have upvoted this PetMatch!"

        elif vote == "downvote":
            if pm.UserProfile_has_voted(userprofile) is False: # If the user is voting for the 1st time, add reputation points
                userprofile.update_reputation("ACTIVITY_PETMATCH_DOWNVOTE")

            pm.down_votes.add(userprofile)
            pm.up_votes.remove(userprofile)
            Activity.log_activity("ACTIVITY_PETMATCH_DOWNVOTE", userprofile, source=pm)
            message = "You have downvoted this PetMatch!"

        #Was the petmatch triggered for verification? Check here.
        threshold_reached = pm.has_reached_threshold()

        #If the votes reach the threshold, prepare for pet checking!
        if threshold_reached == True:
            new_check = PetMatchCheck.objects.create(petmatch=pm)
            Activity.log_activity("ACTIVITY_PETMATCHCHECK_VERIFY", userprofile, source=new_check)
            message = new_check.send_messages_to_contacts()

        num_upvotes = len(pm.up_votes.all())
        num_downvotes = len(pm.down_votes.all())

        return {
            "status":"ok",
            "vote":vote,
            "path": URL_HOME,
            "message": message,
            "threshold_reached": threshold_reached,
            "num_downvotes": num_downvotes,
            "num_upvotes": num_upvotes
        }
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:56,代码来源:crowdwork.py

示例7: vote

def vote(request, petmatch_id):
    if request.method == "POST":
        userprofile = request.user.userprofile
        import ipdb; ipdb.set_trace()
        if request.POST.get("up") != None:
            vote = "upvote"
        else:
            vote = "downvote"
        pm = get_object_or_404(PetMatch, pk=petmatch_id)

        if vote == "upvote":
            if pm.UserProfile_has_voted(userprofile) is False: # If the user is voting for the 1st time, add reputation points
                userprofile.update_reputation("ACTIVITY_PETMATCH_UPVOTE")

            pm.up_votes.add(userprofile)
            pm.down_votes.remove(userprofile)
            Activity.log_activity("ACTIVITY_PETMATCH_UPVOTE", userprofile, source=pm)
            message = "You have upvoted this PetMatch!"

        elif vote == "downvote":
            if pm.UserProfile_has_voted(userprofile) is False: # If the user is voting for the 1st time, add reputation points
                userprofile.update_reputation("ACTIVITY_PETMATCH_DOWNVOTE")

            pm.down_votes.add(userprofile)
            pm.up_votes.remove(userprofile)
            Activity.log_activity("ACTIVITY_PETMATCH_DOWNVOTE", userprofile, source=pm)
            message = "You have downvoted this PetMatch!"

        #Was the petmatch triggered for verification? Check here.
        threshold_reached = pm.has_reached_threshold()

        #If the votes reach the threshold, prepare for pet checking!
        if threshold_reached == True:
            new_check = PetMatchCheck.objects.create(petmatch=pm)
            Activity.log_activity("ACTIVITY_PETMATCHCHECK_VERIFY", userprofile, source=new_check)
            message = new_check.send_messages_to_contacts()

        num_upvotes = len(pm.up_votes.all())
        num_downvotes = len(pm.down_votes.all())
        messages.success(request, message)
        return redirect(URL_HOME)
    else:
        raise Http404
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:43,代码来源:views.py

示例8: submit

def submit(request):
    form = PetReportForm(request.POST, request.FILES)
    if not request.POST["g-recaptcha-response"]:
        messages.error (request, "Please fill in the RECAPTCHA.")
        return redirect(URL_PETREPORT_FORM)

    if not recaptcha_ok(request.POST["g-recaptcha-response"]):
        messages.error(request, "CAPTCHA was not correct. Please try again.")
        return redirect(URL_PETREPORT_FORM)

    #Let's make some adjustments to non-textual form fields before converting to a PetReportForm.
    geo_lat = request.POST ["geo_location_lat"] or ""
    geo_long = request.POST ["geo_location_long"] or ""

    if (geo_lat == "" or geo_lat == "None") or (geo_long == "" or geo_long == "None"):
        request.POST ['geo_location_lat'] = 0.00
        request.POST ['geo_location_long'] = 0.00
    else:
        request.POST ["geo_location_lat"] = float("%.5f" % float(geo_lat))
        request.POST ["geo_location_long"] = float("%.5f" % float(geo_long))

    if form.is_valid() == True:
        #Create (but do not save) the Pet Report Object associated with this form data.
        pr = form.save(commit=False)
        pr.proposed_by = request.user.userprofile

        #Deal with Contact Information.
        if pr.contact_name.strip() == "":
            pr.contact_name = None
        if pr.contact_email.strip() == "":
            pr.contact_email = None
        if pr.contact_number.strip() == "":
            pr.contact_number = None
        if pr.contact_link.strip() == "":
            pr.contact_link = None

        pr.breed = pr.breed.strip()
        print_info_msg ("Pet Report Image Path: %s" % pr.img_path)

        #Make and save images from img_path and thumb_path AND save the PetReport.
        pr.set_images(pr.img_path, save=True, rotation=request.POST.get("img_rotation"))

        #Add reputation points for submitting a pet report
        request.user.userprofile.update_reputation("ACTIVITY_PETREPORT_SUBMITTED")
        message = "Thank you for your submission. %s %s (%s) is front row on the gallery! " % (pr.status, pr.pet_type, pr.pet_name)
        if pr.status == 'Lost':
            messages.success (request, message + "Your contribution will go a long way towards helping volunteers find your lost pet.")
        else:
            messages.success (request, message + "Your contribution will go a long way towards helping volunteers match your found pet.")

        #Log the PetReport submission for this UserProfile
        Activity.log_activity("ACTIVITY_PETREPORT_SUBMITTED", request.user.userprofile, source=pr)
        print_success_msg("Pet Report submitted successfully")

        #Check to see if there are any matching petreports that have the same microchip ID.
        matching_pet = pr.find_by_microchip_id()
        if matching_pet != None: #Send an email about the match!
            contact1 = generate_pet_contacts(pr)[0]
            contact2 = generate_pet_contacts(matching_pet)[0]
            email_body = render_to_string(EMAIL_BODY_MATCH_BY_MICROCHIP_ID, {
                "pet": pr,
                "other_pet": matching_pet,
                "site": Site.objects.get_current()
            })
            send_email(EMAIL_SUBJECT_MATCH_BY_MICROCHIP_ID, email_body, None, [contact1["email"]])
        return redirect(URL_HOME)
    else:
        messages.error(request, "Something went wrong. Please check the fields and try again.")
        print_error_msg ("Pet Report not submitted successfully")
        print_error_msg (form.errors)
        print_error_msg (form.non_field_errors())
        return render_to_response(HTML_PETREPORT_FORM, {
            "form": form,
            "PETREPORT_TAG_INFO_LENGTH":PETREPORT_TAG_INFO_LENGTH,
            "PETREPORT_DESCRIPTION_LENGTH":PETREPORT_DESCRIPTION_LENGTH,
            "PETREPORT_CONTACT_NAME_LENGTH": PETREPORT_CONTACT_NAME_LENGTH,
            "PETREPORT_CONTACT_NUMBER_LENGTH": PETREPORT_CONTACT_NUMBER_LENGTH,
            "PETREPORT_CONTACT_EMAIL_LENGTH": PETREPORT_CONTACT_EMAIL_LENGTH,
            "PETREPORT_CONTACT_LINK_LENGTH": PETREPORT_CONTACT_LINK_LENGTH
        }, RequestContext(request))
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:80,代码来源:views.py

示例9: close_PetMatch

	def close_PetMatch(self):
		petmatch = self.petmatch
		petmatch_owner = petmatch.proposed_by
		lost_pet = petmatch.lost_pet
		lost_pet_contact = lost_pet.proposed_by
		found_pet = petmatch.found_pet
		found_pet_contact = found_pet.proposed_by
		self.closed_date = datetime.now()

		if self.verification_successful() == True:
			successful = True
			self.is_successful = True
			lost_pet.closed = True
			found_pet.closed = True
			self.save()
			lost_pet.save()
			found_pet.save()

			Activity.log_activity("ACTIVITY_PETMATCHCHECK_VERIFY_SUCCESS", lost_pet_contact, source=self)
			lost_pet_contact.update_reputation("ACTIVITY_PETMATCHCHECK_VERIFY_SUCCESS")
			Activity.log_activity("ACTIVITY_PETMATCHCHECK_VERIFY_SUCCESS", found_pet_contact, source=self)
			found_pet_contact.update_reputation("ACTIVITY_PETMATCHCHECK_VERIFY_SUCCESS")

			#Check if the petmatch owner is somebody different - if so, log and award him/her points too.
			if petmatch_owner.id not in [lost_pet_contact.id, found_pet_contact.id]:
				Activity.log_activity("ACTIVITY_PETMATCHCHECK_VERIFY_SUCCESS", petmatch_owner, source=self)
				petmatch_owner.update_reputation("ACTIVITY_PETMATCHCHECK_VERIFY_SUCCESS")
			print_info_msg ("PetMatch %s is now closed" % (self))

		#If not successful, delete the PetMatchCheck object, award pet points, and notify.
		else:
			successful = False
			petmatch.has_failed = True
			Activity.log_activity("ACTIVITY_PETMATCHCHECK_VERIFY_FAIL", lost_pet_contact, source=self)
			Activity.log_activity("ACTIVITY_PETMATCHCHECK_VERIFY_FAIL", found_pet_contact, source=self)
			found_pet_contact.update_reputation("ACTIVITY_PETMATCHCHECK_VERIFY_FAIL")
			lost_pet_contact.update_reputation("ACTIVITY_PETMATCHCHECK_VERIFY_FAIL")

			#Check if the petmatch owner is somebody different - if so, log and award him/her points too.
			if petmatch_owner.id not in [lost_pet_contact.id, found_pet_contact.id]:
				Activity.log_activity("ACTIVITY_PETMATCHCHECK_VERIFY_FAIL", petmatch_owner, source=self)
				petmatch_owner.update_reputation("ACTIVITY_PETMATCHCHECK_VERIFY_FAIL")

			print_info_msg ("PetMatch %s did not pass verification!" % (self))
			del self

		petmatch.save()
		return successful
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:48,代码来源:models.py

示例10: mixed1

def mixed1(request, petmatch_id):
    if request.method == "POST":
        userprofile = request.user.userprofile
        if request.POST.get("up") != None:
            vote = "upvote"
        else:
            vote = "downvote"
        pm = get_object_or_404(PetMatch, pk=petmatch_id)

        if vote == "upvote":
            if pm.UserProfile_has_voted(userprofile) is False: # If the user is voting for the 1st time, add reputation points
                userprofile.update_reputation("ACTIVITY_PETMATCH_UPVOTE")

            pm.up_votes.add(userprofile)
            pm.down_votes.remove(userprofile)
            Activity.log_activity("ACTIVITY_PETMATCH_UPVOTE", userprofile, source=pm)
            message = "You have upvoted this PetMatch!"

        elif vote == "downvote":
            if pm.UserProfile_has_voted(userprofile) is False: # If the user is voting for the 1st time, add reputation points
                userprofile.update_reputation("ACTIVITY_PETMATCH_DOWNVOTE")

            pm.down_votes.add(userprofile)
            pm.up_votes.remove(userprofile)
            Activity.log_activity("ACTIVITY_PETMATCH_DOWNVOTE", userprofile, source=pm)
            message = "You have downvoted this PetMatch!"

        #Was the petmatch triggered for verification? Check here.
        threshold_reached = pm.has_reached_threshold()

        #If the votes reach the threshold, prepare for pet checking!
        if threshold_reached == True:
            new_check = PetMatchCheck.objects.create(petmatch=pm)
            Activity.log_activity("ACTIVITY_PETMATCHCHECK_VERIFY", userprofile, source=new_check)
            message = new_check.send_messages_to_contacts()

        num_upvotes = len(pm.up_votes.all())
        num_downvotes = len(pm.down_votes.all())
        petreport_id = PetReport.objects.filter(closed=False).order_by("?").first().id
        return redirect("/reporting/mixed2/%s" % petreport_id)

    else:
        pm = get_object_or_404(PetMatch, pk=petmatch_id)
        voters = list(pm.up_votes.all()) + list(pm.down_votes.all())

        #Need to check if the user is authenticated (non-anonymous) to find out if he/she has voted on this PetMatch.
        if request.user.is_authenticated() == True:
            user_has_voted = pm.UserProfile_has_voted(request.user.userprofile)
        else:
            user_has_voted = False

        num_upvotes = len(pm.up_votes.all())
        num_downvotes = len(pm.down_votes.all())

        ctx = {
            "petmatch": pm,
            "action": "/reporting/mixed1/" + str(pm.id) + "/",
            "site_domain":Site.objects.get_current().domain,
            "petreport_fields": pm.get_display_fields(),
            "num_voters": len(voters),
            "user_has_voted": user_has_voted,
            "num_upvotes":num_upvotes,
            "num_downvotes":num_downvotes
        }

        if pm.lost_pet.closed:
            ctx["petreunion"] = pm.lost_pet.get_PetReunion()
        elif pm.found_pet.closed:
            ctx["petreunion"] = pm.found_pet.get_PetReunion()
        return render_to_response(HTML_PMDP, ctx, RequestContext(request))
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:70,代码来源:views.py

示例11: mixed3

def mixed3(request, target_id, candidate_id):
    target = get_object_or_404(PetReport, pk=target_id)
    candidate = get_object_or_404(PetReport, pk=candidate_id)

    if request.method == "POST" and request.POST.get("g-recaptcha-response"):
        if not recaptcha_ok(request.POST["g-recaptcha-response"]):
            messages.error(request, "CAPTCHA was not correct. Please try again.")
            return redirect(request.path)
        proposed_by = request.user.userprofile

        if target.status == "Lost":
            pm = PetMatch(lost_pet=target, found_pet=candidate, proposed_by=proposed_by)
        else:
            pm = PetMatch(lost_pet=candidate, found_pet=target, proposed_by=proposed_by)

        #Try saving the PetMatch object.
        # We will expect the following output:
        # None --> PetMatch was not inserted properly OR DUPLICATE PETMATCH
        # PetMatch Object --> Existing PetMatch (UPDATE) OR Brand new PetMatch.
        # "Existing" means the PetMatch to be saved is the same PetMatch found, "Duplicate" means
        # another PetMatch with the same Lost+Found Pets were found.
        (result, outcome) = pm.save()

        if result != None:
            if outcome == PETMATCH_OUTCOME_UPDATE:
                #Has the user voted for this PetMatch before?
                user_has_voted = result.UserProfile_has_voted(proposed_by)

                if user_has_voted == UPVOTE or user_has_voted == DOWNVOTE:
                    messages.error(request, "This Pet Match has already been proposed, and you have voted for it already!")
                    return redirect("/reporting/mixed2/%s/" % (target.id))

                # add voting reputation points if the user didn't vote before for this duplicate petmatch
                # if (proposed_by not in result.up_votes.all()) and (proposed_by not in result.down_votes.all()):
                if pm.UserProfile_has_voted(userprofile) is False:
                    proposed_by.update_reputation("ACTIVITY_PETMATCH_UPVOTE")

                result.up_votes.add(proposed_by)
                result.save()
                messages.success(request, "Because there was an existing match between the two pet reports that you tried to match, You have successfully up-voted the existing pet match. Help spread the word about this match!")
                Activity.log_activity("ACTIVITY_PETMATCH_UPVOTE", proposed_by, source=result)

            elif outcome == PETMATCH_OUTCOME_NEW_PETMATCH:
                messages.success(request, "Congratulations, the pet match was successful! You can view your pet match in the home page and in your profile. Help spread the word about your match!")
                Activity.log_activity("ACTIVITY_PETMATCH_PROPOSED", proposed_by, source=result)
                # add reputation points for proposing a new petmatch
                proposed_by.update_reputation("ACTIVITY_PETMATCH_PROPOSED")

        else:
            if outcome == PETMATCH_OUTCOME_DUPLICATE_PETMATCH:
                result = PetMatch.get_PetMatch(target, candidate)
                #Has the user voted for this PetMatch before?
                user_has_voted = result.UserProfile_has_voted(proposed_by)

                if user_has_voted == UPVOTE or user_has_voted == DOWNVOTE:
                    messages.error(request, "This Pet Match has already been proposed, and you have voted for it already!")
                    return redirect("/reporting/mixed2/%s/" % (target.id))

                # add voting reputation points if the user didn't vote before for this duplicate petmatch
                if user_has_voted == False:
                    proposed_by.update_reputation("ACTIVITY_PETMATCH_UPVOTE")

                result.up_votes.add(proposed_by)
                result.save()
                messages.success(request, "Because there was an existing match between the two pet reports that you tried to match, You have successfully up-voted the existing pet match. Help spread the word about this match!")
                Activity.log_activity("ACTIVITY_PETMATCH_UPVOTE", proposed_by, source=result)
            else:
                messages.error(request, "A Problem was found when trying to propose the PetMatch. We have been notified of the issue and will fix it as soon as possible.")

        #Finally, return the redirect.
        return redirect("/reporting/mixed4/%s/" % pm.id)

    else:
        if request.method == "POST" and not request.POST["g-recaptcha-response"]:
            messages.error(request, "Please Fill in the RECAPTCHA.")

        if (target.pet_type != candidate.pet_type) or (target.status == candidate.status):
            messages.error(request, "This proposal is invalid! Please try another one.")
            return redirect("/reporting/mixed2/%s/" % (target.id))

        return render_to_response(HTML_PROPOSE_MATCH, {
            'RECAPTCHA_CLIENT_SECRET': settings.RECAPTCHA_CLIENT_SECRET,
            'action': '/reporting/mixed3/%s/%s/' % (target_id, candidate_id),
            'target': target,
            'candidate': candidate,
            'petreport_fields': [{'attr':a['attr'], 'label':a['label'], 'lost_pet_value':a['value'], 'found_pet_value':b['value']} for a,b in zip(target.get_display_fields(), candidate.get_display_fields())]
        }, RequestContext(request))
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:87,代码来源:views.py

示例12: update_info

def update_info(request):
    if request.method == "POST":
        user = request.user
        profile = user.userprofile
        user_changed = email_changed = False
        #Hack to circumvent UserProfileForm validation.
        request.POST["password1"] = request.POST["password2"] = "TEST"
        request.POST["dob"] = profile.dob
        form = UserProfileForm(request.POST, request.FILES)

        if form.is_valid() == False:
            return render_to_response(HTML_EDITUSERPROFILE_FORM, {
                "form": form,
                "pic_url": profile.img_path,
                "password_form": PasswordChangeForm(user)
            }, RequestContext(request))

        if request.FILES.get("img_path"): #Change the photo
            user_changed = True
            profile.set_images(request.FILES.get("img_path"), save=True, rotation=request.POST.get("img_rotation"))
            messages.success(request, "Looking good!")
            Activity.log_activity("ACTIVITY_USER_SET_PHOTO", profile)
            profile.update_reputation("ACTIVITY_USER_SET_PHOTO")

        if request.POST ["username"] != user.username: #Check if username has changed
            if UserProfile.get_UserProfile(username=request.POST["username"]) != None:
                messages.error(request, "Sorry, that username is already being used. Try another one.")
                return redirect(URL_EDITUSERPROFILE + str(profile.id))
            else:
                user.username = request.POST["username"]
                Activity.log_activity("ACTIVITY_USER_CHANGED_USERNAME", profile)
                user_changed = True

        if request.POST["email"] != user.email: #Check if email has changed.
            if UserProfile.get_UserProfile(email=request.POST["email"]) != None:
                messages.error(request, "Sorry, that email is already being used. Try another one.")
                return redirect(URL_EDITUSERPROFILE + str(profile.id))
            else:
                activation_key = create_sha1_hash(user.username)
                print_info_msg ('user: %s \tactivation-key: %s' % (user, activation_key))

                try: #Create a new EditUserProfile object for activating a new email address.
                    edit_userprofile = EditUserProfile.objects.get(user=user)
                except:
                    edit_userprofile = EditUserProfile()
                    edit_userprofile.user = user

                edit_userprofile.activation_key = activation_key
                edit_userprofile.new_email = request.POST["email"]
                edit_userprofile.date_of_change = datetime.now()
                edit_userprofile.save()
                #Prepare the email for verification.
                subject = render_to_string(TEXTFILE_EMAIL_CHANGE_SUBJECT, {})
                ctx = {
                    "site": Site.objects.get_current(),
                    "activation_key":activation_key,
                    "expiration_days":settings.ACCOUNT_ACTIVATION_DAYS
                }

                body = render_to_string(TEXTFILE_EMAIL_CHANGE_BODY, ctx)
                send_email(subject, body, None, [edit_userprofile.new_email])
                print_info_msg ("Sent email verification for %s" % user)
                user_changed = True
                email_changed = True

        if request.POST ["first_name"] != user.first_name: #First name check.
            user.first_name = request.POST["first_name"]
            user_changed = True
        if request.POST ["last_name"] != user.last_name: #Last name check.
            user.last_name = request.POST["last_name"]
            user_changed = True
        if request.POST ["description"] != profile.description: #Description check.
            profile.description = request.POST ["description"]
            user_changed = True
        if user_changed == True:
            user.save()
            profile.save()
            if email_changed == True:
                messages.success(request, "Your changes have been saved. Please check your email to find an email from us asking to verify your new email address.")
            else:
                messages.success(request, "Your changes have been saved.")
        else:
            messages.info(request, "Nothing was changed!")
        return redirect(URL_USERPROFILE + str(profile.id))
    else:
        raise Http404
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:86,代码来源:views.py

示例13: create_random_PetMatch

def create_random_PetMatch(lost_pet=None, found_pet=None, user=None, pet_type=None, threshold_bias=False, success_bias=False):
	#If the lost or found pet (or both) wasn't supplied, then search for potential PetMatch PetReport pairs
	if lost_pet == None or found_pet == None:

		#Get some potential matches
		potential_matches = get_potential_PetMatch_PetReport_pairs(pet_type=pet_type)
		if len(potential_matches) == 0:
			print_error_msg ("Can't create random PetMatch: There isn't at least one lost and found %s." % pet_type)
			return None

		#Get a random match.
		potential_match = random.choice(potential_matches)

		if(lost_pet == None):
			lost_pet = potential_match[0]
		if(found_pet == None):
			found_pet = potential_match[1]

	#If no user supplied, then get a random one.
	if(user == None):
		user = random.choice(User.objects.all())

	#Make your PetMatch.
	pm = PetMatch(lost_pet = lost_pet, found_pet = found_pet, proposed_by = user.userprofile)
	(petmatch, outcome) = pm.save()

	#If the PetMatch save was successful...
	if (petmatch != None):
		if outcome == "NEW PETMATCH":
			#petmatch.is_open = random.choice ([True, False])
			user_count = len(UserProfile.objects.all())

			#if threshold_bias is True, the petmatch has a chance of reaching the threshold.
			if threshold_bias == True and random.randint(1,2) == 1:
				up_votes = create_random_Userlist(num_users=random.randint(5, VERIFICATION_DEFAULT_THRESHOLD))
				down_votes = create_random_Userlist(num_users=random.randint(5, VERIFICATION_DEFAULT_THRESHOLD))
				petmatch.down_votes = set(down_votes) - set(up_votes)
				petmatch.up_votes = set(up_votes)

			else:
				up_votes = create_random_Userlist(num_users=random.randint(0, VERIFICATION_DEFAULT_THRESHOLD/4))
				down_votes = create_random_Userlist(num_users=random.randint(0, VERIFICATION_DEFAULT_THRESHOLD/4))
				petmatch.down_votes = set(down_votes) - set(up_votes)
				petmatch.up_votes = set(up_votes) - set(down_votes)

			Activity.log_activity("ACTIVITY_PETMATCH_PROPOSED", user.userprofile, petmatch)

		elif outcome == "SQL UPDATE":
			petmatch.up_votes.add(user.userprofile)
			Activity.log_activity("ACTIVITY_PETMATCH_UPVOTE", user.userprofile, petmatch)

	else:
		if outcome =="DUPLICATE PETMATCH":
			existing_petmatch = PetMatch.get_PetMatch(lost_pet, found_pet)

			if random.random() >= 0.5:
				existing_petmatch.up_votes.add(user.userprofile)
				existing_petmatch.down_votes.remove(user.userprofile)
				Activity.log_activity("ACTIVITY_PETMATCH_UPVOTE", user.userprofile, existing_petmatch)
			else:
				existing_petmatch.down_votes.add(user.userprofile)
				existing_petmatch.up_votes.remove(user.userprofile)
				Activity.log_activity("ACTIVITY_PETMATCH_DOWNVOTE", user.userprofile, existing_petmatch)

	print "\n"
	#Return the (possibly None) PetMatch
	return petmatch
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:67,代码来源:fixture.py

示例14: create_random_PetReport

def create_random_PetReport(save=True, user=None, status=None, pet_type=None):
	#Bias the distribution towards (in order): [Dog, Cat, Bird, Horse, Rabbit, Snake, Turtle]
	if pet_type == None:
		random_var = random.random()
		if random_var < 0.60:
			pet_type = PETREPORT_PET_TYPE_DOG
		elif random_var >= 0.60 and random_var < 0.93:
			pet_type = PETREPORT_PET_TYPE_CAT
		elif random_var >= 0.93 and random_var < 0.95:
			pet_type = PETREPORT_PET_TYPE_BIRD
		elif random_var >= 0.95 and random_var < 0.97:
			pet_type = PETREPORT_PET_TYPE_HORSE
		elif random_var >= 0.97 and random_var < 0.98:
			pet_type = PETREPORT_PET_TYPE_RABBIT
		elif random_var >= 0.98 and random_var < 0.99:
			pet_type = PETREPORT_PET_TYPE_SNAKE
		elif random_var >= 0.99 and random_var < 0.995:
			pet_type = PETREPORT_PET_TYPE_TURTLE
		else:
			pet_type = PETREPORT_PET_TYPE_OTHER

	if status == None:
		status = random.choice(STATUS_CHOICES)[0]
	if user == None:
		user = random.choice(User.objects.all())

	#Populate the PetReport with the required fields.
	pr = PetReport (pet_type = pet_type, status = status, proposed_by = user.userprofile)
	pr.date_lost_or_found = generate_random_date(DATE_LOWER_BOUND, DATE_UPPER_BOUND, "%Y-%m-%d", random.random())
	pr.sex = random.choice(SEX_CHOICES)[0]
	pr.size = random.choice(SIZE_CHOICES)[0]
	pr.location = generate_string(PETREPORT_LOCATION_LENGTH)
	pr.color = generate_string(PETREPORT_COLOR_LENGTH)
	pr.event_tag = random.choice(["Valley Fires", "Butte Fires", "Charleston Floods (SC)", "Washington Wildfires"])
	pr.age = random.choice(AGE_CHOICES)[0]

	if random.random() > 0.65: #Some of the time, pets are microchipped.
		pr.microchip_id = generate_string(PETREPORT_MICROCHIP_ID_LENGTH)

	#Majority of PetReports are cross-posted, so let's add contact information in.
	random_var = random.random()
	if random_var < 0.60:
		pr.contact_name = random.choice(USER_NAMES)
		pr.contact_email = generate_string(6) + '(at)' + 'test.com'
		pr.contact_number = generate_string(10, phone=True)
		pr.contact_link = generate_string(100, url=True)

	#Randomly generate attributes, or not.
	if status == "Found":
		if random.random() > 0.5:
			pr.pet_name = random.choice(PETREPORT_NAMES)
		if random.random() > 0.3:
			pr.description = generate_lipsum_paragraph(PETREPORT_DESCRIPTION_LENGTH)
			pr.tag_info = generate_string(PETREPORT_TAG_INFO_LENGTH)
		if random.random() > 0.3:
			pr.breed = random.choice(BREEDS[pr.pet_type])
		if random.random() > 0.25:
			pr.geo_location_long = random.randrange(-180.0, 180.0)
			pr.geo_location_lat = random.randrange(-90.0, 90.0)

	#The Pet Owner knows his/her own pet.
	else:
		pr.pet_name = random.choice(PETREPORT_NAMES)
		pr.description = generate_lipsum_paragraph(PETREPORT_DESCRIPTION_LENGTH)
		pr.breed = random.sample(BREEDS[pr.pet_type], 1)[0]
		pr.tag_info = generate_string(PETREPORT_TAG_INFO_LENGTH)

	#Need to handle the cases where the contact might/might not have a photo for this PetReport!
	if random.random() <= 0.95:
		load_PetReport_sample_images()

		if pr.pet_type == PETREPORT_PET_TYPE_DOG:
			pr.img_path = pr.thumb_path = random.choice(PETREPORT_SAMPLE_DOG_IMAGES)
		elif pr.pet_type == PETREPORT_PET_TYPE_CAT:
			pr.img_path = pr.thumb_path = random.choice(PETREPORT_SAMPLE_CAT_IMAGES)
		elif pr.pet_type == PETREPORT_PET_TYPE_BIRD:
			pr.img_path = pr.thumb_path = random.choice(PETREPORT_SAMPLE_BIRD_IMAGES)
		elif pr.pet_type == PETREPORT_PET_TYPE_HORSE:
			pr.img_path = pr.thumb_path = random.choice(PETREPORT_SAMPLE_HORSE_IMAGES)
		elif pr.pet_type == PETREPORT_PET_TYPE_RABBIT:
			pr.img_path = pr.thumb_path = random.choice(PETREPORT_SAMPLE_RABBIT_IMAGES)
		elif pr.pet_type == PETREPORT_PET_TYPE_SNAKE:
			pr.img_path = pr.thumb_path = random.choice(PETREPORT_SAMPLE_SNAKE_IMAGES)
		elif pr.pet_type == PETREPORT_PET_TYPE_TURTLE:
			pr.img_path = pr.thumb_path = random.choice(PETREPORT_SAMPLE_TURTLE_IMAGES)
		else:
			pr.img_path = pr.thumb_path = PETREPORT_UPLOADS_DEFAULT_OTHER_IMAGE

	else:
		pr.set_images (None, save=False) #Set the img and thumb paths.

	#Need to save (most of the time).
	if save == False:
		return pr
	else:
		pr.save()
		pr.workers = create_random_Userlist()
		Activity.log_activity("ACTIVITY_PETREPORT_SUBMITTED", user.userprofile, pr)
		return pr
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:99,代码来源:fixture.py

示例15: setup_UserProfile

def setup_UserProfile(sender, instance, created, **kwargs):
    if created == True:
        userprofile = UserProfile.objects.create(user=instance)
        Activity.log_activity("ACTIVITY_ACCOUNT_CREATED", userprofile)
        userprofile.update_reputation("ACTIVITY_ACCOUNT_CREATED")
开发者ID:Project-EPIC,项目名称:emergencypetmatcher,代码行数:5,代码来源:models.py


注:本文中的home.models.Activity类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。