本文整理汇总了Python中models.Vote.save方法的典型用法代码示例。如果您正苦于以下问题:Python Vote.save方法的具体用法?Python Vote.save怎么用?Python Vote.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Vote
的用法示例。
在下文中一共展示了Vote.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: vote
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def vote(request, new_vote):
response = ""
error = ""
status = 201
if not request.user.is_authenticated():
error = "Must be logged in"
status = 403
elif request.method == "POST":
data = request.POST
r = Review.objects.get(pk=data["review_pk"])
try:
prev_vote_obj = Vote.objects.get(review=r.pk, user=request.user)
prev_vote = prev_vote_obj.vote
if new_vote != prev_vote:
prev_vote_obj.delete()
r.up_down_rank += new_vote
except ObjectDoesNotExist:
r.up_down_rank += new_vote
v = Vote(user=request.user, review=r, vote=new_vote)
v.save()
r.save()
response = serialize([r])
else:
error += "No POST data in request.\n"
status = 415
return HttpResponse(package_error(response, error), status=status)
示例2: vote
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def vote(request):
comment_id = request.POST['comment_id']
value = request.POST['value']
comment = Comment.objects.get(pk=comment_id)
try:
vote = Vote.objects.get(comment=comment, author=request.user)
vote.value = value
except Vote.DoesNotExist:
vote = Vote(comment=comment, value=value, author=request.user)
vote.save()
# Reload the comment to make sure vote counts are up to date
comment = Comment.objects.get(pk=comment_id)
try:
task = Task.objects.get(chunk=comment.chunk,
reviewer=request.user)
if task.status == 'N' or task.status == 'O':
task.mark_as('S')
except Task.DoesNotExist:
pass
response_json = json.dumps({
'comment_id': comment_id,
'upvote_count': comment.upvote_count,
'downvote_count': comment.downvote_count,
})
return HttpResponse(response_json, mimetype='application/javascript')
示例3: post
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def post():
values = {}
vote_value = request.form['vote']
vote = Vote()
for item in request.form.getlist('value[]'):
if vote.get_vote_title(item) is not None:
values[item] = vote.get_vote_title(item)
elif int(item) == Vote.CUSTOM_VOTE_ID and vote_value:
values[item] = vote_value
if values:
# add vote
vote.ip = request.remote_addr
vote.votes = values
try:
vote_current = Vote.objects(ip=request.remote_addr,
created_at__gte=(datetime.datetime.now() - datetime.timedelta(minutes=15)))
if vote_current:
raise ValueError("You've already voted!")
vote.save()
suffix = VoteView.ordinal(len(Vote.objects))
return jsonify({'status': 'ok',
'message': 'Thank your for voting! You are the %s fan of python' % suffix})
except ValueError as e:
return jsonify({'status': 'error', 'message': e.message})
except Exception:
return jsonify({'status': 'error', 'message': 'Error while saving vote. Sorry :('})
else:
return jsonify({'status': 'error', 'message': 'Choose any option to vote'})
示例4: post
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def post(self):
data = self.get_arguments()
try:
type = int(self.get_argument('type'))
flag = self.get_argument('flag')
slug = self.get_argument('slug')
spec = {'type': type, 'slug': slug}
cid = Content.one(spec)['_id']
uid = self.current_user['_id']
if int(flag) in [x for x,_y in MY_FLAGS]:
has_vote = Vote.one({'uid': uid ,'cid': cid})
if not has_vote:
Content.collection.update(
spec, {'$inc': { "votes." + flag: 1}}
)
vote = Vote()
vote['uid'], vote['cid'], vote['vote'] = uid, cid, int(flag)
vote.save()
return self.json_response("You have voted has been noted", "OK")
else:
Content.collection.update(
spec, {'$inc': { "votes." + flag: -1}}
)
Vote.remove({'uid': uid, 'cid': cid})
return self.json_response("Your vote has been removed", "OK")
raise Exception("Invalid vote")
except Exception, e:
raise
return self.json_response(e.__str__(), "ERROR", data)
示例5: vote_post
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def vote_post(request, post_id, mode='plain'):
post_id = int(post_id)
post = get_object_or_404(Post, id=post_id)
kwargs = dict(post=post)
if not mode in ['plain', 'ajax'] or '_pv_%d' % post_id in request.session:
return HttpResponseRedirect(post.get_absolute_url())
if request.user.is_authenticated():
kwargs['user'] = request.user
else:
kwargs['ip'] = request.META['REMOTE_ADDR']
try:
Vote.objects.get(**kwargs)
output_ajax = 0
except Vote.DoesNotExist:
new_vote = Vote(**kwargs)
new_vote.save()
post.nb_votes += 1
post.save()
request.session['_pv_%d' % post_id] = True
request.session.set_expiry(timedelta(days=365))
output_ajax = 1
if mode == 'ajax':
return HttpResponse(output_ajax)
else:
return HttpResponseRedirect(post.get_absolute_url())
示例6: create_vote
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def create_vote(voter, nodes):
v = Vote()
v.user = voter
v.save()
for node in nodes:
v.nodes.add(node)
v.save()
return v
示例7: create_vote
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def create_vote(voter, nodes):
v = Vote()
v.user = voter
v.save()
for node in nodes:
v.nodes.add(node)
v.save()
for node in nodes:
node.update_favorite_for_all_parents()
return v
示例8: vote
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def vote(request, id_num):
vf = VoteForm(request.POST or None)
post = get_object_or_404(Post, pk=id_num)
if vf.is_valid() and request.user.is_authenticated():
user = request.user
prev_vote = Vote.objects.filter(user=user, parent_post=post.parent,)
if prev_vote.exists():
prev_vote.delete()
messages.warning(request, 'Changing your vote because you already voted on some child of the parent post')
vote = Vote(post=post, parent_post=post.parent, user=user)
vote.save()
return HttpResponseRedirect(request.META["HTTP_REFERER"])
示例9: handle_call_request
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def handle_call_request(request):
if request.method != 'POST':
msg = "Only POST Request Allowed"
else:
# dont accept requests from any other system
if request.META['REMOTE_ADDR'] not in settings.ALLOWED_IPS:
msg = "IP not allowed"
else:
to_no = get_post_param(request, 'To')
from_no = get_post_param(request, 'From')
if from_no == "":
msg = "No Number Recieved"
else:
direction = get_post_param(request, 'Direction')
if not (to_no == settings.DID and direction == 'inbound'):
msg = "Invalid Direction"
else:
# get current speaker
try:
speaker = get_object_or_404(Speaker, currently_speaking=True)
except Http404:
speaker = None
if speaker is None:
msg = "No Current Speaker"
else:
# check if this vote is already considered
try:
vote = get_object_or_404(Vote, speaker=speaker,
phone_no=from_no)
except Http404:
vote = None
if vote is not None:
msg = "Duplicate Vote"
else:
speaker.total_votes = speaker.total_votes + 1
speaker.save()
vote_dict={
"speaker": speaker,
"phone_no": from_no,
}
vote_obj= Vote(**vote_dict)
vote_obj.save()
tweet_text = '''Got a vote for "%s" speaking on "%s" from the number "+%s" #cluecon''' % (speaker.name,
speaker.talk_name,
mask_phone(from_no))
if not post_tweet(tweet_text):
pass # do some logging here
# return success
response = create_success_restxml()
return HttpResponse(response, mimetype='text/xml')
return HttpResponse(create_fail_restxml(msg), mimetype='text/xml')
示例10: vote
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def vote(request, id_num):
vf = VoteForm(request.POST or None)
post = get_object_or_404(Post, pk=id_num)
if request.method == "POST" and vf.is_valid():
if request.user.is_authenticated():
user = request.user
else:
user = User.objects.get(username="anon")
vote = Vote(post=post, user=user, ip=request.META["REMOTE_ADDR"])
vote.save()
return HttpResponseRedirect(request.META["HTTP_REFERER"])
return render_to_response("vote.html",
{"form": vf},
context_instance=RequestContext(request))
示例11: update_votes
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def update_votes():
'''
Updates the Vote table with the json retrieved from Kimono.
If a vote is not in the table it creates one.
Returns the number of new votes and new orphan players added to the db
'''
logger.info('Updating votes...')
url = settings.KIMONO['votes_url']
votes = _get_results_collection1(url)
# Keeping a list of players with votes but not present in the Player table
# so that they could be added later
logger.info(' - Updating database...')
no_new_votes = 0
no_new_orphans = 0
for vote in votes:
p_id = _id_from_url(vote['name']['href'])
v_day = _day_from_url(vote['url'])
# Checking if the vote already exists. If not, creates a new one, if it
# exists it will get the current vote and update it
try:
v = Vote.objects.get(player__pk=p_id, day=v_day)
except Vote.DoesNotExist:
v = Vote()
no_new_votes += 1
# Creating a orphan player if there is not a player for this vote
try:
p = Player.objects.get(pk=p_id)
except Player.DoesNotExist:
p = Player(pk=p_id)
p.role = _fix_role(vote['role'])
p.save()
no_new_orphans += 1
v.player = p
v.vote = _fix_zero(vote['vote'])
v.gol = _fix_zero(vote['gol'])
v.assist = _fix_zero(vote['assists'])
v.penalties_scored_saved = _fix_zero(vote['penalties_scored_saved'])
v.penalties_missed = _fix_zero(vote['penalties_missed'])
v.own_gol = _fix_zero(vote['own_gol'])
v.yellow_cards = _fix_zero(vote['yellow_cards'])
v.red_cards = _fix_zero(vote['red_cards'])
v.magicvote = _fix_zero(vote['own_gol'])
v.day = v_day
v.sub_in = _sub_in(vote['in']['class'])
v.sub_out = _sub_out(vote['out']['class'])
# Storing on the db
v.save()
return no_new_votes, no_new_orphans
示例12: add_vote
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def add_vote(request, uuid, polluuid, choice):
if request.method == 'GET':
try:
vote = Vote.objects.get(voter=uuid, poll=polluuid)
return HttpResponse(json.dumps('fail: vote exists'),
mimetype='application/json')
except Vote.DoesNotExist:
vote = Vote()
_poll = Poll.objects.get(uuid=polluuid)
vote.voter = User.objects.get(uuid=uuid)
vote.poll = _poll
vote.vote = choice
vote.save()
_poll.votes = _poll.votes + 1
_poll.save()
return HttpResponse(json.dumps('ok'),
mimetype='application/json')
else:
raise Http404
示例13: dvote
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def dvote():
for i in xrange(5):
email = str(i) + '@gmail.com'
password = str(i)
try:
u = User.objects.get(username=email)
except:
u = User.objects.create_user(email, email, password)
questions = Question.objects.all()
for q in questions:
choice = random.sample(q.choice_set.all(),1)[0]
v = Vote()
v.user = u
v.question = q
v.choice = choice
v.save()
choice.votes += 1
choice.save()
示例14: create_models
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def create_models(request):
json_file = json.load(request.FILES['file'])
type = request.POST['options']
for obj in json_file:
new_model = {'election_type': type}
votes = []
for k, v in obj.iteritems():
if 'Pkt' in k:
try:
new_model['notes'].append({k: v})
except:
new_model['notes'] = [{k: v}]
continue
k_coded = coder[k.encode('utf-8')]
if 'kw' in k_coded or 'prez' in k_coded:
vote = Vote(political_party=k, amount=v)
vote.save()
votes.append(vote)
else:
if 'Gmina' == k:
new_model['district'] = v
else:
new_model[coder[k.encode('utf-8')]] = v
try:
new_model['notes'] = json.dumps(new_model['notes'])
except:
pass
if type != 'candidate':
election_model = Election(**new_model)
election_model.save()
elif type == 'candidate':
election_model = Candidate(**new_model)
election_model.save()
continue
for v in votes:
v.election = election_model
v.save()
示例15: index
# 需要导入模块: from models import Vote [as 别名]
# 或者: from models.Vote import save [as 别名]
def index(request):
sujets = Sujet.objects
#sujets = sujets.filter(vote__date__lt=datetime.now())
sujets = sujets.order_by('nom')
sujets = sujets.all()
poids = Poids.objects
poids = poids.order_by('ordre')
poids = poids.all()
render_params = {}
render_params['sujets'] = sujets
render_params['l_poids'] = poids
if request.method == "POST":
votes_in = (entry for entry in request.POST.items() if entry[0].isdigit())
for poids_id, sujet_id in votes_in:
sujet = Sujet.objects.get(id=sujet_id)
poids = Poids.objects.get(id=poids_id)
vote = Vote(nom="Jacques", sujet=sujet, poids=poids)
vote.save()
return render(request, 'vote/index.html', render_params)