shellfly / django-vote Goto Github PK
View Code? Open in Web Editor NEWSimple vote for django
Home Page: http://django-vote.readthedocs.io
License: Apache License 2.0
Simple vote for django
Home Page: http://django-vote.readthedocs.io
License: Apache License 2.0
This is the entire traceback provided by Django:
Environment:
Request Method: GET
Request URL: http://192.168.2.155:8000/quotes/
Django Version: 4.0.8
Python Version: 3.10.8
Installed Applications:
['django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.flatpages',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.humanize',
'django.contrib.postgres',
'django.forms',
'crispy_forms',
'bootstrapform',
'pinax.messages',
'pinax.notifications',
'notifications',
'haystack',
'ircdriven',
'django_filters',
'martor',
'formtools',
'debug_toolbar',
'django_gravatar',
'django_extensions',
'django_countries',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.github',
'allauth.socialaccount.providers.google',
'rest_framework',
'rest_framework.authtoken',
'drf_spectacular',
'friendship',
'captcha',
'mptt',
'widget_tweaks',
'machina',
'machina.apps.forum',
'machina.apps.forum_conversation',
'machina.apps.forum_conversation.forum_attachments',
'machina.apps.forum_conversation.forum_polls',
'machina.apps.forum_feeds',
'machina.apps.forum_moderation',
'machina.apps.forum_search',
'machina.apps.forum_tracking',
'machina.apps.forum_member',
'machina.apps.forum_permission',
'django_nyt.apps.DjangoNytConfig',
'sekizai',
'sorl.thumbnail',
'wiki.apps.WikiConfig',
'wiki.plugins.attachments.apps.AttachmentsConfig',
'wiki.plugins.editsection.apps.EditSectionConfig',
'wiki.plugins.globalhistory.apps.GlobalHistoryConfig',
'wiki.plugins.help.apps.HelpConfig',
'wiki.plugins.images.apps.ImagesConfig',
'wiki.plugins.links.apps.LinksConfig',
'wiki.plugins.macros.apps.MacrosConfig',
'wiki.plugins.notifications.apps.NotificationsConfig',
'vote']
Installed Middleware:
['debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.sites.middleware.CurrentSiteMiddleware',
'machina.apps.forum_permission.middleware.ForumPermissionMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'ircdriven.middleware.TimezoneMiddleware']
Template error:
In template /home/daniel/Repos/website/templates/ircdriven/quotes/main.html, error at line 50
operator does not exist: character varying = numeric
LINE 1: ...content_type_id" = 93 AND "vote_vote"."object_id" = 15663665...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
40 : <div class="card">
41 : <div class="card-body elegant-color p-0">
42 : <pre style="white-space: pre-wrap;" class="p-2 mb-0 white-text">
43 : {{ quote.quote }}</pre>
44 : </div>
45 : <div class="card-footer m-0 p-1 px-2">
46 : <div class="small text-muted d-inline">Submitted by <a class="black-text" href="{% url 'user_profile' quote.submitter.username %}">{{ quote.submitter.username }}</a></div>
47 : <div class="float-right d-inline">
48 : <div class="badge badge-pill badge-dark d-inline">{{ quote.vote_score }}</div>
49 : {% if request.user.is_authenticated %}
50 : {% vote_exists quote request.user 0 as vote_up %}
51 : {% vote_exists quote request.user 1 as vote_down %}
52 : <div class="form-inline d-inline">
53 : <form class="d-inline" action="{% url 'quotes_home' %}" method="post">
54 : {% csrf_token %}
55 : <input type="hidden" name="id" value="{{ quote.id }}" />
56 : <input type="hidden" name="vote" value="up" />
57 : <button class="btn btn-link p-0 m-0" {% if vote_up %}disabled="disabled"{% endif %} type="submit"><i class="fa-sharp fa-solid fa-arrow-alt-up fa-lg green-text"></i></button>
58 : </form>
59 : <form class="d-inline" action="{% url 'quotes_home' %}" method="post">
60 : {% csrf_token %}
Traceback (most recent call last):
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
The above exception (operator does not exist: character varying = numeric
LINE 1: ...content_type_id" = 93 AND "vote_vote"."object_id" = 15663665...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
) was the direct cause of the following exception:
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/daniel/Repos/website/ircdriven/views/quote.py", line 51, in quotes_page
return render(request, 'ircdriven/quotes/main.html', context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/shortcuts.py", line 24, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/backends/django.py", line 62, in render
return self.template.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 175, in render
return self._render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/test/utils.py", line 111, in instrumented_test_render
return self.nodelist.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 958, in render_annotated
return self.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/loader_tags.py", line 157, in render
return compiled_parent._render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/test/utils.py", line 111, in instrumented_test_render
return self.nodelist.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 958, in render_annotated
return self.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/classytags/core.py", line 151, in render
return str(self.render_tag(context, **kwargs))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/sekizai/templatetags/sekizai_tags.py", line 87, in render_tag
rendered_contents = nodelist.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 958, in render_annotated
return self.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/defaulttags.py", line 322, in render
return nodelist.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 958, in render_annotated
return self.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/loader_tags.py", line 63, in render
result = block.nodelist.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 958, in render_annotated
return self.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/defaulttags.py", line 238, in render
nodelist.append(node.render_annotated(context))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 958, in render_annotated
return self.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/defaulttags.py", line 322, in render
return nodelist.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/base.py", line 958, in render_annotated
return self.render(context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/template/library.py", line 239, in render
output = self.func(*resolved_args, **resolved_kwargs)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/vote/templatetags/vote.py", line 15, in vote_exists
return model.votes.exists(user.pk, action=action)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/vote/utils.py", line 12, in inner
return func(self, *args, **kwargs)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/vote/managers.py", line 145, in exists
).exists()
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/models/query.py", line 892, in exists
return self.query.has_results(using=self.db)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/models/sql/query.py", line 589, in has_results
return compiler.has_results()
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1329, in has_results
return bool(self.execute_sql(SINGLE))
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1361, in execute_sql
cursor.execute(sql, params)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/backends/utils.py", line 103, in execute
return super().execute(sql, params)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute
with self.db.wrap_database_errors:
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/daniel/.pyenv/versions/website/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /quotes/
Exception Value: operator does not exist: character varying = numeric
LINE 1: ...content_type_id" = 93 AND "vote_vote"."object_id" = 15663665...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
The main piece throwing this is:
50 : {% vote_exists quote request.user 0 as vote_up %}
51 : {% vote_exists quote request.user 1 as vote_down %}
To me it didn't seem very obvious to me, that it only counts the UP votes if no parameter is given.
The Code snippet I'm talking about is the following:
def count(self, action=UP):
return self.through.votes_for(self.model,
self.instance, action).count()
My suggestion would be, to introduce 2 new functions:
count_up(self)
and
count_down(self)
I would still keep the count function, but modify it in a way, that leads to it counting the up and down votes, by just calling the two other functions and returning them as a dict to the caller
Dear Author,
We are thinking to use user ID as a UUID.
Example:
from django.contrib.auth.models import AbstractUser
class MyUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
While in the Vote model we have the bigint field.
Do you think it's accetable to change
user_id = models.BigIntegerField()
to
user = models.ForeignKey(settings.AUTH_USER_MODEL,
as suggested here.
Thanks so much,
D
I solve this error by using the pk of the user instead of the user instance.
But doesn't that seem counterintuitive?
Any feedback is appreciated.
So, I'm trying to have the comment automatically upvoted by the request's user, (ala reddit).
class PostCommentsView(viewsets.ModelViewSet, VoteMixin):
permission_classes = [IsOwnerOrReadOnly]
serializer_class = CommentSerializer
queryset = PostComment.objects.all()
def perform_create(self, serializer):
# create comment
comment = serializer.save()
# upvote that comment automatically!
self.vote(request=self.request, pk=comment.pk)
what happens here works! sort of...
Here is the response after posting a comment:
{
"id": 114,
"post": 7,
"content": "This is an example comment",
"owner": 1,
"username": "admin",
"vote_score": 0, <==
"is_voted_up": false, <==
"is_voted_down": false
}
See the problem? querying the comment again shows the 'vote_score'
and 'is_upvoted'
field with correct values, but ideally, the response should be annotated correctly.
I tried many different things, such as trying to return a custom response by querying and annotating the object that was just created, to no avail. If this issue has an easy solution, please reach out to me. If not, lets work on adding some sort of feature that automatically upvotes on creation.
Is it possible to make downvote decrement 1, instead of just removing the upvote?
So negative numbers is possible. And down voting without upvoting is possible.
Dear Author,
How can I extend the VotableManager? I would need to add model.votes.my_function
, but like this
class CustomVotableManager(VotableManager):
def my_function(self, *args, **kwargs):
doesn't work.
Thanks,
D
I have implemented django-vote in one of my projects and I found an odd behaviour where a user could perform a 'downvote' to the same object over and over, and obj.votes.exists(user_id)
would return false because the 'downvote' is not committed to the vote object but nevertheless is counted in num_vote_down
.
If 5 users decided to 'downvote' an object, we will have num_vote_down
equals 5, but the user_ids would still return an empty queryset and the exists method would return false for each users.
This happens only regarding the down
method.
Am I missing something?
Thank you for your help!
Hi! Is it possible to get the info if the user voted up or down?
Even if there isn't a method, is it possible to get all user.ids who voted up? So I can find it in here?
I know how to get user_ids, but I've checked models.py and the manager, and I can't find how to get the 'action' the user pressed.
Cause basically I need a reddit/stackoverflow like upvote/downvote, and jQuery to add an 'active' class to the voting button the user already used.
Tnx for the app.
Assuming a votable object has an "author" field, is there an easy query to get the sum votes for a given "author" across all instances of a votable object?
The aim is similar to finding a user's "karma" on reddit; a query for the sum of all upvotes on all objects for which the user is author ... is there an efficient way to do this?
We can only add one vote by the add function, but some user should have more power, need an option to specify the vote affects
When I run "python manage.py makemigrations vote", python raise an exception.
WARNINGS:
?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_CONTEXT_PROCESSORS.
Migrations for 'vote':
Traceback (most recent call last):
File "manage.py", line 10, in
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\management_init_.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Python34\lib\site-packages\django\core\management_init_.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 345, in execute
output = self.handle(*args, **options)
File "C:\Python34\lib\site-packages\django\core\management\commands\makemigrations.py", line 189, in handle
self.write_migration_files(changes)
File "C:\Python34\lib\site-packages\django\core\management\commands\makemigrations.py", line 207, in write_migration_files
migration_string = os.path.relpath(writer.path)
File "C:\Python34\lib\ntpath.py", line 579, in relpath
raise ValueError(error)
ValueError: path is on mount 'C:', start on mount 'D:'
I am using django vote on a model that is tracked by django-reversion.
I am trying to debug django reversion - because deleted votes are not being tracked - and to do this I need some low-level knowledge of django-vote :)
How does django-vote manage the deletion of Votes when the model that has the VotableManager
property? Say I have:
class MyModel(models.Model):
...
votes = VotableManager()
...
and I do
my_instance = MyModel()
and then do
my_instance.votes.add(...)
and then a bit of
my_instance.delete()
How is the deletion of my_instances
's votes handled?
I looked at the source code but either I missed the important but, or the important bit is implicit?
Hii, I think this plugin needs a detailed and easy to use doc.
In current doc their is no detail about how to use it in templates.
Or how to create a custom template tags.
I want to work on this issue.Thanks
I'm not sure if this is an "issue", but how are we supposed to see what the user voted? Also, there's very little documentation on template tags we can use. How do we figure that out?
If you up vote something, then remove the vote by down voting you can down down vote again. This is also broken is the other direction. If you down vote then up vote(canceling you votes out), you cant up vote again.
Heyho,
user.is_anonymous became an attribute in django 2.0. Thus the vote_exists does no longer work.
I fixed it. Pull request incoming...
ib/python2.7/site-packages/vote/managers.py:7: RemovedInDjango19Warning: django.contrib.contenttypes.generic is deprecated and will be removed in Django 1.9. Its contents have been moved to the fields, forms, and admin submodules of django.contrib.contenttypes.
from django.contrib.contenttypes.generic import GenericRelation
Would you be so kind to explain how the annotate function works for the votes Manager, i would like to be able to get the num of votes in a query to related model and if it would be posible to also include if user have voted.
Dear All
Using it (1.1.0) with Python 3 + Django 1.9 error I got this error in models.py line 44
AttributeError: 'dict' object has no attribute 'has_key'
def votes_for(cls, model, instance=None):
*
return cls.objects.filter(**kwargs) <----
Thanks!
D
hi, we've been using this app since 1.1.2 in a project.
now we're in the process of upgrading Django and the dependencies, and it turns out all of a sudden the user FK has changed to a user_id
BigIntegerField. It would've been nice to document this somewhere, as this is a massive breaking change.
Related to that, it would be nice to distribute the migrations for the models, and this would also have caught the breaking change.
Hi,
Love your app. I was wondering if you could extend it to allow the use of custom user model as the user model in the app possibly through settings.AUTH_USER_MODEL if it exists.
Hi. I would like to display the total number of votes in the administrator, how could do this?
Thanks,
Hi,
I am a newbie in Django, and I have struggled with two problems.
The first issue seems to be related to the user_id section. Every time I try to run python manage.py runserver, I face an error message as follows: "ValueError at /feedback/display/up/
invalid literal for int() with base 10: '12345a1dd12345555a0a55" <--- this is a random string to deidentify the id info, but basically you can see it is a mixture of numbers and alphabets, which are not int() at all. How should I change the user_id section to include not only ints but also strings?
The second issue popped up after I put random numbers instead of the strings in the user_id section. An error message I've got is as follows :ProgrammingError at /feedback/display/up/
(1146, "Table 'mydb.vote_vote' doesn't exist"). Should there be a db table called vote_vote in my database? Should I create one or it should've been there once I install django-vote?
Thanks!
This is my view.py
def feedback_display (request) :
if request.GET.get("vote-up"):
thumbsup_1 = PeerFeedback.objects.get(reviewee_user_id=given_user_id, reviewer_user_id=reviewer_user_id_1)
thumbsup_1.votes.up(request.session['lti_launch_params']['user_id'])
return redirect("polls/feedback_display.html", {'thumbsup_1': thumbsup_1})
Hi,
There is a name error in models.py. A 'a' is missing.
class VoteMan**a**ger(models.Manager):
Dear All,
It's not the correct place to ask these questions, sorry for this. I spent quite a lot of time looking for the answer without having success.
Let's take the Django example for prefetch_related
, hence having:
class VoteCountMixin(object):
@property
def vote_count(self):
return self.votes.count()
class Topping(VoteCountMixin, models.Model):
pass
class Pizza(VoteCountMixin, models.Model):
pass
class Restaurant(VoteCountMixin, models.Model):
pass
How is it possible to implement Restaurant.objects.prefetch_related('vote')?
Thanks,
Hi django-vote Team,
my App is using a legacy MySQL-Database. I created the models via manage.py inspectdb.. I have installed your plugin django-vote and migrated as suggested.
The new table (vote_vote) could be created, but the fields to the existing table could not be added (because MySQL..). So I added the neccessary fields: vote_score, num_vote_up and num_vote_down to my model manually (via SQL-queries). Now I get the following error:
Internal Server Error: /upvote/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/maximilianendter/code/LEGAL_MINING/legal_mining/document_manager/views.py", line 16, in upvote
document.votes.up(user)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/vote/utils.py", line 12, in inner
return func(self, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/vote/managers.py", line 95, in up
return self.vote(user_id, action=UP)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/vote/managers.py", line 85, in vote
getattr(self.instance, statistics_field) + 1)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
[14/Apr/2017 14:45:30] "POST /upvote/ HTTP/1.1" 500 14702
By calling following lines in my view.py:
def upvote(request):
user = request.user.id
doc_hash = request.POST.get('hash', None)
document = get_object_or_404(Documentstorage, hash=doc_hash)
document.votes.up(user)
Do I need to add more fields to the database? I appreciate your help in this case!
Thank you very much,
Max
The doc doesn't have explanation of how to use this package in templates!
I will be very grateful if you give me example.... Thanks
After upgrading django to 2.0, I get this error:
File "/home/x/y/.venvs/z/lib/python3.6/site-packages/vote/models.py", line 31, in Vote
content_type = models.ForeignKey(ContentType)
TypeError: __init__() missing 1 required positional argument: 'on_delete'
I'm pretty new to Django and struggling to implement django-vote to my app.
For voting up a review in my Car page, I tried this in my template:
<form action="{% url 'reviews:review-vote-up' review.id %}" method="GET">
<input type="submit" value="Up" name="vote-up" />
</form>
My URL:
url(r'^(?P<review_id>\d+)/up/$', views.review_vote_up, name="review-vote-up"),
My view function:
def review_vote_up(request, review_id):
if request.GET.get("vote-up"):
review = Review.objects.get(id=review_id)
review.votes.up(request.user)
context = {"make": review.car.make,
"model": review.car.model,
"platform": review.car.platform,
"body": review.car.body,
"version": review.car.version,
"years": review.car.years}
return redirect("reviews:car", context)
But this doesn't register the vote, and it doesn't redirect me back to the Car page.
Could you give me a simple template implementation and view function example of voting up, or clarify my errors?
Any suggestion or feedback will be welcomed and greatly appreciated.
Thank you.
Hi,
I am trying to add django-vote into my project but have come across a problem :(
I am getting the following error message.
UNIQUE constraint failed: vote_vote.user_id, vote_vote.content_type_id, vote_vote.object_id
Here are the following files:
views.py
def vote_up(request, id):
entry = Entries.objects.get(id=1)
entry.votes.up(request.user)
return HttpResponseRedirect(reverse('playlists.views.index'))
models.py
from vote.managers import VotableManager
class Entries(models.Model):
votes = VotableManager()
title = models.CharField(max_length=255)
url = models.CharField(max_length=255)
datetime = models.DateTimeField(auto_now_add=True)
posted_by = models.ForeignKey(User, unique=True)
def str(self):
return (self.title)
It would be awesome if anyone could point me in the right direction :)
VotableManager
实现的功能并不是一个 Model Manager
,叫这个名字是否会误导使用者?
I tried reseting all the votes count in my inherited model by updating the num_vote_up
, num_vote_down
and vote_score
.
I can iterate over all the instances via vote manager and remove the votes. But I want to avoid that.
Is there a simpler way I can clear all existing votes from the vote table as well or that is the only way and I need to do that asynchronously?
ViewSets that dynamically determines the queryset it should operate on, would override get_queryset() method omitting the queryset class attribute. In such viewsets, VoteMixin would cause an exception during runtime.
Solution is to replace all self.queryset
with self.get_queryset()
.
Hi,
If a user changes his/her vote, it's create time does not change. Is it more sense to use update_at instead of create_at?
I have a use case where I'd need to attach a comment when a used voted down an instance. How could I extend the VoteModel
model to add this field and related checks?
Thanks!
I have a user who has up-voted 4 items in total. When I then use object1.votes.down(user_id), it does decrement the vote as it should but then, If I make the query Objects.votes.all(user_id), that query only returns 3 items. I'm using the django shell and this is the exact code that I am executing.
>>> toppings = Toppings.votes.all(1)
>>> toppings
<QuerySet [<Toppings: sprinkles>, <Toppings: hot fudge>, <Toppings: whipped cream>, <Toppings: cherries>] >
>>> t1 = toppings[0]
>>> t1
<QuerySet [<Toppings: sprinkles>]>
>>> t1.votes.down(1)
True
>>> Toppings.votes.all(1)
<QuerySet [<Toppings: hot fudge>, <Toppings: whipped cream>, <Toppings: cherries>] >
Can someone let me know if I am using this incorrectly please?
I also want to know how to check whether the user has up or downvoted.
I want to get the voters of an instance. That way I will check in the frontend if has already voted and displayed a UI according to that status.
But getting the review.votes.user_ids() results in additional database hit.
How to get this value without some additional database hits?
I tweaked my app, for now, to use prefetch_related('votes'). But this will still result in a 1-time additional database hit.
I want to avoid that altogether if possible.
Hi!
Whats the diff. between upvoting and then downvoting,
and just upvoting and deleting the vote?
Makes no sense to me to have a downvoting feature when it's the same as delete (doesn't go into negative)
Hi,
I've been using this app happily on models with regular PKs, however I've tried changing my model PKs over to short strings instead of integers. This seems to play well with other components of my app (such as Django Rest Framework) but unfortunately the Vote and VoteManager models both expect a positive integer.
Any plans to allow use of string PKs in the future?
Cheers
Dear,
I need to declare six votes field to the model, for example:
class Exercise(models.Model):
difficulty_1 = VotableManager()
difficulty_2 = VotableManager()
difficulty_3 = VotableManager()
difficulty_4 = VotableManager()
difficulty_5 = VotableManager()
Does your vote app work?
Really thanks
Want to show in template amount of votes for object, added to installed apps 'vote', though {% load vote %}
doesn't work for me, raises an error that there is no such library.
I followed the step by step instructions, it's stating vote.manager cannot be found. I'm using Django 1.7, Python 2.7 and working within a virtualenv.
It'd be great to have the latest commits in a new release.
Thanks!
Hi,
I'm a newbie, please bear with me :)
It's possible to implement up-down button on the template based on IP? So anomymous user can vote on review.
Thank you in advance for any helps you can provide :)
Regards,
i would like to check if current logged in user have voted or not.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.