├── .DS_Store
├── .editorconfig
├── .gitignore
├── .idea
├── .name
├── django-rest-vote.iml
├── encodings.xml
├── misc.xml
├── modules.xml
├── scopes
│ └── scope_settings.xml
├── vcs.xml
└── workspace.xml
├── .travis.yml
├── AUTHORS.rst
├── CONTRIBUTING.rst
├── HISTORY.rst
├── LICENSE
├── MANIFEST.in
├── Makefile
├── README.rst
├── docs
├── Makefile
├── authors.rst
├── conf.py
├── contributing.rst
├── history.rst
├── index.rst
├── installation.rst
├── make.bat
├── readme.rst
└── usage.rst
├── migrations
├── 0001_initial.py
├── 0002_vote_vote.py
├── __init__.py
└── __pycache__
│ ├── 0001_initial.cpython-35.pyc
│ ├── 0002_vote_vote.cpython-35.pyc
│ └── __init__.cpython-35.pyc
├── requirements-test.txt
├── requirements.txt
├── requirements_dev.txt
├── runtests.py
├── setup.cfg
├── setup.py
├── tests
├── __init__.py
└── test_models.py
├── tox.ini
└── votes
├── __init__.py
├── admin.py
├── api.py
├── compat.py
├── managers.py
├── migrations
├── 0001_initial.py
├── 0002_vote_vote.py
└── __init__.py
├── models.py
├── serializers.py
├── static
├── css
│ └── votes.css
├── img
│ └── .gitignore
└── js
│ └── votes.js
├── templates
└── votes
│ └── base.html
├── tests
├── __init__.py
├── test_api.py
└── test_models.py
├── urls.py
├── utils.py
└── views.py
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thecodinghouse/votes/24aac2487f41cd07bfb54d4b854dcb32322ce955/.DS_Store
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # http://editorconfig.org
2 |
3 | root = true
4 |
5 | [*]
6 | charset = utf-8
7 | end_of_line = lf
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.{py,rst,ini}]
12 | indent_style = space
13 | indent_size = 4
14 |
15 | [*.{html,css,scss,json,yml}]
16 | indent_style = space
17 | indent_size = 2
18 |
19 | [*.md]
20 | trim_trailing_whitespace = false
21 |
22 | [Makefile]
23 | indent_style = tab
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.py[cod]
2 | __pycache__
3 |
4 | # C extensions
5 | *.so
6 |
7 | # Packages
8 | *.egg
9 | *.egg-info
10 | dist
11 | build
12 | eggs
13 | parts
14 | bin
15 | var
16 | sdist
17 | develop-eggs
18 | .installed.cfg
19 | lib
20 | lib64
21 |
22 | # Installer logs
23 | pip-log.txt
24 |
25 | # Unit test / coverage reports
26 | .coverage
27 | .tox
28 | nosetests.xml
29 | htmlcov
30 |
31 | # Translations
32 | *.mo
33 |
34 | # Mr Developer
35 | .mr.developer.cfg
36 | .project
37 | .pydevproject
38 |
39 | # Pycharm/Intellij
40 | .idea
41 |
42 | # Complexity
43 | output/*.html
44 | output/*/index.html
45 |
46 | # Sphinx
47 | docs/_build
48 |
--------------------------------------------------------------------------------
/.idea/.name:
--------------------------------------------------------------------------------
1 | django-rest-vote
--------------------------------------------------------------------------------
/.idea/django-rest-vote.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/scopes/scope_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
120 |
121 |
122 | true
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 | 1459865094821
201 |
202 | 1459865094821
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 |
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 |
312 |
313 |
314 |
315 |
316 |
317 |
318 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | # Config file for automatic testing at travis-ci.org
2 |
3 | language: python
4 |
5 | python:
6 | - "3.5"
7 | - "3.4"
8 | - "3.3"
9 | - "2.7"
10 |
11 | before_install:
12 | - pip install codecov
13 |
14 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors
15 | install: pip install -r requirements-test.txt
16 |
17 | # command to run tests using coverage, e.g. python setup.py test
18 | script: coverage run --source votes runtests.py
19 |
20 | after_success:
21 | - codecov
22 |
--------------------------------------------------------------------------------
/AUTHORS.rst:
--------------------------------------------------------------------------------
1 | =======
2 | Credits
3 | =======
4 |
5 | Development Lead
6 | ----------------
7 |
8 | * ayush jain
9 |
10 | Contributors
11 | ------------
12 |
13 | None yet. Why not be the first?
14 |
--------------------------------------------------------------------------------
/CONTRIBUTING.rst:
--------------------------------------------------------------------------------
1 | ============
2 | Contributing
3 | ============
4 |
5 | Contributions are welcome, and they are greatly appreciated! Every
6 | little bit helps, and credit will always be given.
7 |
8 | You can contribute in many ways:
9 |
10 | Types of Contributions
11 | ----------------------
12 |
13 | Report Bugs
14 | ~~~~~~~~~~~
15 |
16 | Report bugs at https://github.com/ayushj31/votes/issues.
17 |
18 | If you are reporting a bug, please include:
19 |
20 | * Your operating system name and version.
21 | * Any details about your local setup that might be helpful in troubleshooting.
22 | * Detailed steps to reproduce the bug.
23 |
24 | Fix Bugs
25 | ~~~~~~~~
26 |
27 | Look through the GitHub issues for bugs. Anything tagged with "bug"
28 | is open to whoever wants to implement it.
29 |
30 | Implement Features
31 | ~~~~~~~~~~~~~~~~~~
32 |
33 | Look through the GitHub issues for features. Anything tagged with "feature"
34 | is open to whoever wants to implement it.
35 |
36 | Write Documentation
37 | ~~~~~~~~~~~~~~~~~~~
38 |
39 | votes could always use more documentation, whether as part of the
40 | official votes docs, in docstrings, or even on the web in blog posts,
41 | articles, and such.
42 |
43 | Submit Feedback
44 | ~~~~~~~~~~~~~~~
45 |
46 | The best way to send feedback is to file an issue at https://github.com/ayushj31/votes/issues.
47 |
48 | If you are proposing a feature:
49 |
50 | * Explain in detail how it would work.
51 | * Keep the scope as narrow as possible, to make it easier to implement.
52 | * Remember that this is a volunteer-driven project, and that contributions
53 | are welcome :)
54 |
55 | Get Started!
56 | ------------
57 |
58 | Ready to contribute? Here's how to set up `votes` for local development.
59 |
60 | 1. Fork the `votes` repo on GitHub.
61 | 2. Clone your fork locally::
62 |
63 | $ git clone git@github.com:your_name_here/votes.git
64 |
65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development::
66 |
67 | $ mkvirtualenv votes
68 | $ cd votes/
69 | $ python setup.py develop
70 |
71 | 4. Create a branch for local development::
72 |
73 | $ git checkout -b name-of-your-bugfix-or-feature
74 |
75 | Now you can make your changes locally.
76 |
77 | 5. When you're done making changes, check that your changes pass flake8 and the
78 | tests, including testing other Python versions with tox::
79 |
80 | $ flake8 votes tests
81 | $ python setup.py test
82 | $ tox
83 |
84 | To get flake8 and tox, just pip install them into your virtualenv.
85 |
86 | 6. Commit your changes and push your branch to GitHub::
87 |
88 | $ git add .
89 | $ git commit -m "Your detailed description of your changes."
90 | $ git push origin name-of-your-bugfix-or-feature
91 |
92 | 7. Submit a pull request through the GitHub website.
93 |
94 | Pull Request Guidelines
95 | -----------------------
96 |
97 | Before you submit a pull request, check that it meets these guidelines:
98 |
99 | 1. The pull request should include tests.
100 | 2. If the pull request adds functionality, the docs should be updated. Put
101 | your new functionality into a function with a docstring, and add the
102 | feature to the list in README.rst.
103 | 3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check
104 | https://travis-ci.org/tixdo/votes/pull_requests
105 | and make sure that the tests pass for all supported Python versions.
106 |
107 | Tips
108 | ----
109 |
110 | To run a subset of tests::
111 |
112 | $ python -m unittest tests.test_votes
113 |
--------------------------------------------------------------------------------
/HISTORY.rst:
--------------------------------------------------------------------------------
1 | .. :changelog:
2 |
3 | History
4 | -------
5 |
6 | 0.1.0 (2016-02-01)
7 | ++++++++++++++++++
8 |
9 | * First release on PyPI.
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) You can read more about it on my blog., ayush jain
2 | All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5 |
6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7 |
8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9 |
10 | * Neither the name of votes nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11 |
12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include AUTHORS.rst
2 | include CONTRIBUTING.rst
3 | include HISTORY.rst
4 | include LICENSE
5 | include README.rst
6 | recursive-include votes *.html *.png *.gif *js *.css *jpg *jpeg *svg *py
7 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: clean-pyc clean-build docs
2 |
3 | help:
4 | @echo "clean-build - remove build artifacts"
5 | @echo "clean-pyc - remove Python file artifacts"
6 | @echo "lint - check style with flake8"
7 | @echo "test - run tests quickly with the default Python"
8 | @echo "test-all - run tests on every Python version with tox"
9 | @echo "coverage - check code coverage quickly with the default Python"
10 | @echo "docs - generate Sphinx HTML documentation, including API docs"
11 | @echo "release - package and upload a release"
12 | @echo "sdist - package"
13 |
14 | clean: clean-build clean-pyc
15 |
16 | clean-build:
17 | rm -fr build/
18 | rm -fr dist/
19 | rm -fr *.egg-info
20 |
21 | clean-pyc:
22 | find . -name '*.pyc' -exec rm -f {} +
23 | find . -name '*.pyo' -exec rm -f {} +
24 | find . -name '*~' -exec rm -f {} +
25 |
26 | lint:
27 | flake8 votes tests
28 |
29 | test:
30 | python runtests.py tests
31 |
32 | test-all:
33 | tox
34 |
35 | coverage:
36 | coverage run --source votes runtests.py tests
37 | coverage report -m
38 | coverage html
39 | open htmlcov/index.html
40 |
41 | docs:
42 | rm -f docs/votes.rst
43 | rm -f docs/modules.rst
44 | sphinx-apidoc -o docs/ votes
45 | $(MAKE) -C docs clean
46 | $(MAKE) -C docs html
47 | open docs/_build/html/index.html
48 |
49 | release: clean
50 | python setup.py sdist upload
51 | python setup.py bdist_wheel upload
52 |
53 | sdist: clean
54 | python setup.py sdist
55 | ls -l dist
56 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | =============================
2 | DRF Votes
3 | =============================
4 |
5 | .. image:: https://badge.fury.io/py/votes.png
6 | :target: https://badge.fury.io/py/votes
7 |
8 |
9 | DRF Vote is a simple Django Rest Framework app to add ability to like/dislike a model.
10 |
11 | Blog
12 | -------------
13 |
14 | You can read more about it on my blog_
15 |
16 | .. _blog: https://medium.com/tixdo-labs/vote-your-model-with-no-pain-9d7670b65bfd#.5q8jkl7xt.
17 |
18 | Quickstart
19 | ----------
20 |
21 |
22 | Note
23 | ----------
24 | User must be logged-in to user user-specific apis.
25 |
26 | 1. Install votes::
27 |
28 | pip install votes
29 |
30 |
31 |
32 |
33 | 2. Add ``'votes'`` to your ``INSTALLED_APPS`` setting like this::
34 |
35 | INSTALLED_APPS = (
36 | ...
37 | 'votes',
38 | )
39 |
40 | 3. Run ``python manage.py syncdb`` to create the vote models.
41 |
42 |
43 | 4. Declare vote field to the model you want to vote::
44 |
45 | from votes.managers import VotableManager
46 |
47 | class ArticleReview(models.Model):
48 | ...
49 | votes = VotableManager()
50 |
51 | 5. Include votes url to your urls.py file::
52 |
53 | from django.conf.urls import include
54 | from django.conf.urls import url
55 |
56 | from votes import urls
57 |
58 | urlpatterns += [
59 | url(r'^', include(urls)),
60 | ]
61 |
62 | =====
63 | DRF Vote
64 | =====
65 |
66 | This is extended version of repo django-vote_
67 |
68 | .. _django-vote: https://github.com/Beeblio/django-vote
69 |
70 | DRF Vote is a simple Django Rest Framework app to add ability to like/dislike a model.
71 |
72 | You can read more about it on my blog post_
73 |
74 | .. _post: https://medium.com/@3117Jain/vote-your-model-with-no-pain-9d7670b65bfd#.3zttxekr2
75 |
76 | =====
77 | How is it different ?
78 | =====
79 |
80 | - Modified to work with django rest framework.
81 | - A new feature of disliking an object is added in this version.
82 |
83 |
84 | APIs
85 | -----------
86 |
87 | /votes/up/
88 | ==========
89 | Adds a new like or dislike vote to the object
90 |
91 | * param: model, id, vote i.e. model=movies&id=359&vote=true
92 | * vote=option[true for up-vote, false for down-vote, None for no-vote]
93 |
94 | This api is used for both liking and disliking the object.
95 | Send
96 | vote=true for like
97 | vote=false for dislike
98 |
99 | /votes/down/
100 | ==========
101 | Removes vote to the object
102 |
103 | * param: model, id i.e. model=movies&id=359
104 |
105 | /votes/exists/
106 | ============
107 | Check if the user already voted the object
108 |
109 | * param: model, id i.e. model=movies&id=359
110 |
111 | /votes/all/
112 | =========
113 | return all instances voted by user
114 |
115 | * param: model, id i.e. model=movies&id=359
116 |
117 | /votes/count/
118 | =======
119 | Returns the number of votes for the object
120 |
121 | * param: model, id i.e. model=movies&id=359
122 |
123 | /votes/users/
124 | =======
125 | Returns a list of users who voted and their voting date
126 |
127 | * param: model, id i.e. model=movies&id=359
128 |
129 | /votes/likes/
130 | =======
131 | Returns the number of likes and dislikes for the object.
132 |
133 | * param: model, id i.e. model=movies&id=359
134 |
135 |
136 |
137 | Running Tests
138 | --------------
139 |
140 | Does the code actually work?
141 |
142 | ::
143 |
144 | source /bin/activate
145 | (myenv) $ pip install -r requirements-test.txt
146 | (myenv) $ python runtests.py
147 |
148 | Credits
149 | ---------
150 |
151 | Tools used in rendering this package:
152 |
153 | * Cookiecutter_
154 | * `cookiecutter-pypackage`_
155 |
156 | .. _Cookiecutter: https://github.com/audreyr/cookiecutter
157 | .. _`cookiecutter-djangopackage`: https://github.com/pydanny/cookiecutter-djangopackage
158 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = _build
9 |
10 | # User-friendly check for sphinx-build
11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
13 | endif
14 |
15 | # Internal variables.
16 | PAPEROPT_a4 = -D latex_paper_size=a4
17 | PAPEROPT_letter = -D latex_paper_size=letter
18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
19 | # the i18n builder cannot share the environment and doctrees with the others
20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
21 |
22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
23 |
24 | help:
25 | @echo "Please use \`make ' where is one of"
26 | @echo " html to make standalone HTML files"
27 | @echo " dirhtml to make HTML files named index.html in directories"
28 | @echo " singlehtml to make a single large HTML file"
29 | @echo " pickle to make pickle files"
30 | @echo " json to make JSON files"
31 | @echo " htmlhelp to make HTML files and a HTML help project"
32 | @echo " qthelp to make HTML files and a qthelp project"
33 | @echo " devhelp to make HTML files and a Devhelp project"
34 | @echo " epub to make an epub"
35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
36 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
38 | @echo " text to make text files"
39 | @echo " man to make manual pages"
40 | @echo " texinfo to make Texinfo files"
41 | @echo " info to make Texinfo files and run them through makeinfo"
42 | @echo " gettext to make PO message catalogs"
43 | @echo " changes to make an overview of all changed/added/deprecated items"
44 | @echo " xml to make Docutils-native XML files"
45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes"
46 | @echo " linkcheck to check all external links for integrity"
47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
48 |
49 | clean:
50 | rm -rf $(BUILDDIR)/*
51 |
52 | html:
53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
54 | @echo
55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
56 |
57 | dirhtml:
58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
59 | @echo
60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
61 |
62 | singlehtml:
63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
64 | @echo
65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
66 |
67 | pickle:
68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
69 | @echo
70 | @echo "Build finished; now you can process the pickle files."
71 |
72 | json:
73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
74 | @echo
75 | @echo "Build finished; now you can process the JSON files."
76 |
77 | htmlhelp:
78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
79 | @echo
80 | @echo "Build finished; now you can run HTML Help Workshop with the" \
81 | ".hhp project file in $(BUILDDIR)/htmlhelp."
82 |
83 | qthelp:
84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
85 | @echo
86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp"
89 | @echo "To view the help file:"
90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc"
91 |
92 | devhelp:
93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
94 | @echo
95 | @echo "Build finished."
96 | @echo "To view the help file:"
97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity"
98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity"
99 | @echo "# devhelp"
100 |
101 | epub:
102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
103 | @echo
104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
105 |
106 | latex:
107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
108 | @echo
109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
111 | "(use \`make latexpdf' here to do that automatically)."
112 |
113 | latexpdf:
114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
115 | @echo "Running LaTeX files through pdflatex..."
116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
118 |
119 | latexpdfja:
120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
121 | @echo "Running LaTeX files through platex and dvipdfmx..."
122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
124 |
125 | text:
126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
127 | @echo
128 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
129 |
130 | man:
131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
132 | @echo
133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
134 |
135 | texinfo:
136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
137 | @echo
138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
139 | @echo "Run \`make' in that directory to run these through makeinfo" \
140 | "(use \`make info' here to do that automatically)."
141 |
142 | info:
143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
144 | @echo "Running Texinfo files through makeinfo..."
145 | make -C $(BUILDDIR)/texinfo info
146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
147 |
148 | gettext:
149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
150 | @echo
151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
152 |
153 | changes:
154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
155 | @echo
156 | @echo "The overview file is in $(BUILDDIR)/changes."
157 |
158 | linkcheck:
159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
160 | @echo
161 | @echo "Link check complete; look for any errors in the above output " \
162 | "or in $(BUILDDIR)/linkcheck/output.txt."
163 |
164 | doctest:
165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
166 | @echo "Testing of doctests in the sources finished, look at the " \
167 | "results in $(BUILDDIR)/doctest/output.txt."
168 |
169 | xml:
170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
171 | @echo
172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
173 |
174 | pseudoxml:
175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
176 | @echo
177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
178 |
--------------------------------------------------------------------------------
/docs/authors.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../AUTHORS.rst
2 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # complexity documentation build configuration file, created by
4 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013.
5 | #
6 | # This file is execfile()d with the current directory set to its containing dir.
7 | #
8 | # Note that not all possible configuration values are present in this
9 | # autogenerated file.
10 | #
11 | # All configuration values have a default; values that are commented out
12 | # serve to show the default.
13 |
14 | import sys, os
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #sys.path.insert(0, os.path.abspath('.'))
20 |
21 | cwd = os.getcwd()
22 | parent = os.path.dirname(cwd)
23 | sys.path.append(parent)
24 |
25 | import votes
26 |
27 | # -- General configuration -----------------------------------------------------
28 |
29 | # If your documentation needs a minimal Sphinx version, state it here.
30 | #needs_sphinx = '1.0'
31 |
32 | # Add any Sphinx extension module names here, as strings. They can be extensions
33 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
35 |
36 | # Add any paths that contain templates here, relative to this directory.
37 | templates_path = ['_templates']
38 |
39 | # The suffix of source filenames.
40 | source_suffix = '.rst'
41 |
42 | # The encoding of source files.
43 | #source_encoding = 'utf-8-sig'
44 |
45 | # The master toctree document.
46 | master_doc = 'index'
47 |
48 | # General information about the project.
49 | project = u'votes'
50 | copyright = u'You can read more about it on my blog., ayush jain'
51 |
52 | # The version info for the project you're documenting, acts as replacement for
53 | # |version| and |release|, also used in various other places throughout the
54 | # built documents.
55 | #
56 | # The short X.Y version.
57 | version = votes.__version__
58 | # The full version, including alpha/beta/rc tags.
59 | release = votes.__version__
60 |
61 | # The language for content autogenerated by Sphinx. Refer to documentation
62 | # for a list of supported languages.
63 | #language = None
64 |
65 | # There are two options for replacing |today|: either, you set today to some
66 | # non-false value, then it is used:
67 | #today = ''
68 | # Else, today_fmt is used as the format for a strftime call.
69 | #today_fmt = '%B %d, %Y'
70 |
71 | # List of patterns, relative to source directory, that match files and
72 | # directories to ignore when looking for source files.
73 | exclude_patterns = ['_build']
74 |
75 | # The reST default role (used for this markup: `text`) to use for all documents.
76 | #default_role = None
77 |
78 | # If true, '()' will be appended to :func: etc. cross-reference text.
79 | #add_function_parentheses = True
80 |
81 | # If true, the current module name will be prepended to all description
82 | # unit titles (such as .. function::).
83 | #add_module_names = True
84 |
85 | # If true, sectionauthor and moduleauthor directives will be shown in the
86 | # output. They are ignored by default.
87 | #show_authors = False
88 |
89 | # The name of the Pygments (syntax highlighting) style to use.
90 | pygments_style = 'sphinx'
91 |
92 | # A list of ignored prefixes for module index sorting.
93 | #modindex_common_prefix = []
94 |
95 | # If true, keep warnings as "system message" paragraphs in the built documents.
96 | #keep_warnings = False
97 |
98 |
99 | # -- Options for HTML output ---------------------------------------------------
100 |
101 | # The theme to use for HTML and HTML Help pages. See the documentation for
102 | # a list of builtin themes.
103 | html_theme = 'default'
104 |
105 | # Theme options are theme-specific and customize the look and feel of a theme
106 | # further. For a list of options available for each theme, see the
107 | # documentation.
108 | #html_theme_options = {}
109 |
110 | # Add any paths that contain custom themes here, relative to this directory.
111 | #html_theme_path = []
112 |
113 | # The name for this set of Sphinx documents. If None, it defaults to
114 | # " v documentation".
115 | #html_title = None
116 |
117 | # A shorter title for the navigation bar. Default is the same as html_title.
118 | #html_short_title = None
119 |
120 | # The name of an image file (relative to this directory) to place at the top
121 | # of the sidebar.
122 | #html_logo = None
123 |
124 | # The name of an image file (within the static path) to use as favicon of the
125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
126 | # pixels large.
127 | #html_favicon = None
128 |
129 | # Add any paths that contain custom static files (such as style sheets) here,
130 | # relative to this directory. They are copied after the builtin static files,
131 | # so a file named "default.css" will overwrite the builtin "default.css".
132 | html_static_path = ['_static']
133 |
134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
135 | # using the given strftime format.
136 | #html_last_updated_fmt = '%b %d, %Y'
137 |
138 | # If true, SmartyPants will be used to convert quotes and dashes to
139 | # typographically correct entities.
140 | #html_use_smartypants = True
141 |
142 | # Custom sidebar templates, maps document names to template names.
143 | #html_sidebars = {}
144 |
145 | # Additional templates that should be rendered to pages, maps page names to
146 | # template names.
147 | #html_additional_pages = {}
148 |
149 | # If false, no module index is generated.
150 | #html_domain_indices = True
151 |
152 | # If false, no index is generated.
153 | #html_use_index = True
154 |
155 | # If true, the index is split into individual pages for each letter.
156 | #html_split_index = False
157 |
158 | # If true, links to the reST sources are added to the pages.
159 | #html_show_sourcelink = True
160 |
161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
162 | #html_show_sphinx = True
163 |
164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
165 | #html_show_copyright = True
166 |
167 | # If true, an OpenSearch description file will be output, and all pages will
168 | # contain a tag referring to it. The value of this option must be the
169 | # base URL from which the finished HTML is served.
170 | #html_use_opensearch = ''
171 |
172 | # This is the file name suffix for HTML files (e.g. ".xhtml").
173 | #html_file_suffix = None
174 |
175 | # Output file base name for HTML help builder.
176 | htmlhelp_basename = 'votesdoc'
177 |
178 |
179 | # -- Options for LaTeX output --------------------------------------------------
180 |
181 | latex_elements = {
182 | # The paper size ('letterpaper' or 'a4paper').
183 | #'papersize': 'letterpaper',
184 |
185 | # The font size ('10pt', '11pt' or '12pt').
186 | #'pointsize': '10pt',
187 |
188 | # Additional stuff for the LaTeX preamble.
189 | #'preamble': '',
190 | }
191 |
192 | # Grouping the document tree into LaTeX files. List of tuples
193 | # (source start file, target name, title, author, documentclass [howto/manual]).
194 | latex_documents = [
195 | ('index', 'votes.tex', u'votes Documentation',
196 | u'ayush jain', 'manual'),
197 | ]
198 |
199 | # The name of an image file (relative to this directory) to place at the top of
200 | # the title page.
201 | #latex_logo = None
202 |
203 | # For "manual" documents, if this is true, then toplevel headings are parts,
204 | # not chapters.
205 | #latex_use_parts = False
206 |
207 | # If true, show page references after internal links.
208 | #latex_show_pagerefs = False
209 |
210 | # If true, show URL addresses after external links.
211 | #latex_show_urls = False
212 |
213 | # Documents to append as an appendix to all manuals.
214 | #latex_appendices = []
215 |
216 | # If false, no module index is generated.
217 | #latex_domain_indices = True
218 |
219 |
220 | # -- Options for manual page output --------------------------------------------
221 |
222 | # One entry per manual page. List of tuples
223 | # (source start file, name, description, authors, manual section).
224 | man_pages = [
225 | ('index', 'votes', u'votes Documentation',
226 | [u'ayush jain'], 1)
227 | ]
228 |
229 | # If true, show URL addresses after external links.
230 | #man_show_urls = False
231 |
232 |
233 | # -- Options for Texinfo output ------------------------------------------------
234 |
235 | # Grouping the document tree into Texinfo files. List of tuples
236 | # (source start file, target name, title, author,
237 | # dir menu entry, description, category)
238 | texinfo_documents = [
239 | ('index', 'votes', u'votes Documentation',
240 | u'ayush jain', 'votes', 'One line description of project.',
241 | 'Miscellaneous'),
242 | ]
243 |
244 | # Documents to append as an appendix to all manuals.
245 | #texinfo_appendices = []
246 |
247 | # If false, no module index is generated.
248 | #texinfo_domain_indices = True
249 |
250 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
251 | #texinfo_show_urls = 'footnote'
252 |
253 | # If true, do not generate a @detailmenu in the "Top" node's menu.
254 | #texinfo_no_detailmenu = False
255 |
--------------------------------------------------------------------------------
/docs/contributing.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../CONTRIBUTING.rst
2 |
--------------------------------------------------------------------------------
/docs/history.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../HISTORY.rst
2 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | .. complexity documentation master file, created by
2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | Welcome to votes's documentation!
7 | =================================================================
8 |
9 | Contents:
10 |
11 | .. toctree::
12 | :maxdepth: 2
13 |
14 | readme
15 | installation
16 | usage
17 | contributing
18 | authors
19 | history
20 |
--------------------------------------------------------------------------------
/docs/installation.rst:
--------------------------------------------------------------------------------
1 | ============
2 | Installation
3 | ============
4 |
5 | At the command line::
6 |
7 | $ easy_install votes
8 |
9 | Or, if you have virtualenvwrapper installed::
10 |
11 | $ mkvirtualenv votes
12 | $ pip install votes
13 |
--------------------------------------------------------------------------------
/docs/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | REM Command file for Sphinx documentation
4 |
5 | if "%SPHINXBUILD%" == "" (
6 | set SPHINXBUILD=sphinx-build
7 | )
8 | set BUILDDIR=_build
9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
10 | set I18NSPHINXOPTS=%SPHINXOPTS% .
11 | if NOT "%PAPER%" == "" (
12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
14 | )
15 |
16 | if "%1" == "" goto help
17 |
18 | if "%1" == "help" (
19 | :help
20 | echo.Please use `make ^` where ^ is one of
21 | echo. html to make standalone HTML files
22 | echo. dirhtml to make HTML files named index.html in directories
23 | echo. singlehtml to make a single large HTML file
24 | echo. pickle to make pickle files
25 | echo. json to make JSON files
26 | echo. htmlhelp to make HTML files and a HTML help project
27 | echo. qthelp to make HTML files and a qthelp project
28 | echo. devhelp to make HTML files and a Devhelp project
29 | echo. epub to make an epub
30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
31 | echo. text to make text files
32 | echo. man to make manual pages
33 | echo. texinfo to make Texinfo files
34 | echo. gettext to make PO message catalogs
35 | echo. changes to make an overview over all changed/added/deprecated items
36 | echo. xml to make Docutils-native XML files
37 | echo. pseudoxml to make pseudoxml-XML files for display purposes
38 | echo. linkcheck to check all external links for integrity
39 | echo. doctest to run all doctests embedded in the documentation if enabled
40 | goto end
41 | )
42 |
43 | if "%1" == "clean" (
44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
45 | del /q /s %BUILDDIR%\*
46 | goto end
47 | )
48 |
49 |
50 | %SPHINXBUILD% 2> nul
51 | if errorlevel 9009 (
52 | echo.
53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
54 | echo.installed, then set the SPHINXBUILD environment variable to point
55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you
56 | echo.may add the Sphinx directory to PATH.
57 | echo.
58 | echo.If you don't have Sphinx installed, grab it from
59 | echo.http://sphinx-doc.org/
60 | exit /b 1
61 | )
62 |
63 | if "%1" == "html" (
64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
65 | if errorlevel 1 exit /b 1
66 | echo.
67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html.
68 | goto end
69 | )
70 |
71 | if "%1" == "dirhtml" (
72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
73 | if errorlevel 1 exit /b 1
74 | echo.
75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
76 | goto end
77 | )
78 |
79 | if "%1" == "singlehtml" (
80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
81 | if errorlevel 1 exit /b 1
82 | echo.
83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
84 | goto end
85 | )
86 |
87 | if "%1" == "pickle" (
88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
89 | if errorlevel 1 exit /b 1
90 | echo.
91 | echo.Build finished; now you can process the pickle files.
92 | goto end
93 | )
94 |
95 | if "%1" == "json" (
96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
97 | if errorlevel 1 exit /b 1
98 | echo.
99 | echo.Build finished; now you can process the JSON files.
100 | goto end
101 | )
102 |
103 | if "%1" == "htmlhelp" (
104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
105 | if errorlevel 1 exit /b 1
106 | echo.
107 | echo.Build finished; now you can run HTML Help Workshop with the ^
108 | .hhp project file in %BUILDDIR%/htmlhelp.
109 | goto end
110 | )
111 |
112 | if "%1" == "qthelp" (
113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
114 | if errorlevel 1 exit /b 1
115 | echo.
116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^
117 | .qhcp project file in %BUILDDIR%/qthelp, like this:
118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp
119 | echo.To view the help file:
120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc
121 | goto end
122 | )
123 |
124 | if "%1" == "devhelp" (
125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
126 | if errorlevel 1 exit /b 1
127 | echo.
128 | echo.Build finished.
129 | goto end
130 | )
131 |
132 | if "%1" == "epub" (
133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
134 | if errorlevel 1 exit /b 1
135 | echo.
136 | echo.Build finished. The epub file is in %BUILDDIR%/epub.
137 | goto end
138 | )
139 |
140 | if "%1" == "latex" (
141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
142 | if errorlevel 1 exit /b 1
143 | echo.
144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
145 | goto end
146 | )
147 |
148 | if "%1" == "latexpdf" (
149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
150 | cd %BUILDDIR%/latex
151 | make all-pdf
152 | cd %BUILDDIR%/..
153 | echo.
154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex.
155 | goto end
156 | )
157 |
158 | if "%1" == "latexpdfja" (
159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
160 | cd %BUILDDIR%/latex
161 | make all-pdf-ja
162 | cd %BUILDDIR%/..
163 | echo.
164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex.
165 | goto end
166 | )
167 |
168 | if "%1" == "text" (
169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
170 | if errorlevel 1 exit /b 1
171 | echo.
172 | echo.Build finished. The text files are in %BUILDDIR%/text.
173 | goto end
174 | )
175 |
176 | if "%1" == "man" (
177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
178 | if errorlevel 1 exit /b 1
179 | echo.
180 | echo.Build finished. The manual pages are in %BUILDDIR%/man.
181 | goto end
182 | )
183 |
184 | if "%1" == "texinfo" (
185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
186 | if errorlevel 1 exit /b 1
187 | echo.
188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
189 | goto end
190 | )
191 |
192 | if "%1" == "gettext" (
193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
194 | if errorlevel 1 exit /b 1
195 | echo.
196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
197 | goto end
198 | )
199 |
200 | if "%1" == "changes" (
201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
202 | if errorlevel 1 exit /b 1
203 | echo.
204 | echo.The overview file is in %BUILDDIR%/changes.
205 | goto end
206 | )
207 |
208 | if "%1" == "linkcheck" (
209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
210 | if errorlevel 1 exit /b 1
211 | echo.
212 | echo.Link check complete; look for any errors in the above output ^
213 | or in %BUILDDIR%/linkcheck/output.txt.
214 | goto end
215 | )
216 |
217 | if "%1" == "doctest" (
218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
219 | if errorlevel 1 exit /b 1
220 | echo.
221 | echo.Testing of doctests in the sources finished, look at the ^
222 | results in %BUILDDIR%/doctest/output.txt.
223 | goto end
224 | )
225 |
226 | if "%1" == "xml" (
227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
228 | if errorlevel 1 exit /b 1
229 | echo.
230 | echo.Build finished. The XML files are in %BUILDDIR%/xml.
231 | goto end
232 | )
233 |
234 | if "%1" == "pseudoxml" (
235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
236 | if errorlevel 1 exit /b 1
237 | echo.
238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
239 | goto end
240 | )
241 |
242 | :end
243 |
--------------------------------------------------------------------------------
/docs/readme.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../README.rst
2 |
--------------------------------------------------------------------------------
/docs/usage.rst:
--------------------------------------------------------------------------------
1 | ========
2 | Usage
3 | ========
4 |
5 | To use votes in a project::
6 |
7 | import votes
8 |
--------------------------------------------------------------------------------
/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by Django 1.9.2 on 2016-02-26 06:05
3 | from __future__ import unicode_literals
4 |
5 | from django.conf import settings
6 | from django.db import migrations, models
7 | import django.db.models.deletion
8 |
9 |
10 | class Migration(migrations.Migration):
11 |
12 | initial = True
13 |
14 | dependencies = [
15 | ('contenttypes', '0002_remove_content_type_name'),
16 | migrations.swappable_dependency(settings.AUTH_USER_MODEL),
17 | ]
18 |
19 | operations = [
20 | migrations.CreateModel(
21 | name='Vote',
22 | fields=[
23 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
24 | ('object_id', models.PositiveIntegerField()),
25 | ('create_at', models.DateTimeField(auto_now_add=True)),
26 | ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
27 | ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
28 | ],
29 | ),
30 | migrations.AlterUniqueTogether(
31 | name='vote',
32 | unique_together=set([('user', 'content_type', 'object_id')]),
33 | ),
34 | ]
35 |
--------------------------------------------------------------------------------
/migrations/0002_vote_vote.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by Django 1.9.2 on 2016-03-10 05:59
3 | from __future__ import unicode_literals
4 |
5 | from django.db import migrations, models
6 |
7 |
8 | class Migration(migrations.Migration):
9 |
10 | dependencies = [
11 | ('votes', '0001_initial'),
12 | ]
13 |
14 | operations = [
15 | migrations.AddField(
16 | model_name='vote',
17 | name='vote',
18 | field=models.NullBooleanField(),
19 | ),
20 | ]
21 |
--------------------------------------------------------------------------------
/migrations/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thecodinghouse/votes/24aac2487f41cd07bfb54d4b854dcb32322ce955/migrations/__init__.py
--------------------------------------------------------------------------------
/migrations/__pycache__/0001_initial.cpython-35.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thecodinghouse/votes/24aac2487f41cd07bfb54d4b854dcb32322ce955/migrations/__pycache__/0001_initial.cpython-35.pyc
--------------------------------------------------------------------------------
/migrations/__pycache__/0002_vote_vote.cpython-35.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thecodinghouse/votes/24aac2487f41cd07bfb54d4b854dcb32322ce955/migrations/__pycache__/0002_vote_vote.cpython-35.pyc
--------------------------------------------------------------------------------
/migrations/__pycache__/__init__.cpython-35.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thecodinghouse/votes/24aac2487f41cd07bfb54d4b854dcb32322ce955/migrations/__pycache__/__init__.cpython-35.pyc
--------------------------------------------------------------------------------
/requirements-test.txt:
--------------------------------------------------------------------------------
1 | django>=1.9.1
2 | coverage
3 | mock>=1.0.1
4 | flake8>=2.1.0
5 | tox>=1.7.0
6 |
7 | # Additional test requirements go here
8 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | django>=1.9.1
2 | # Additional requirements go here
3 |
4 | djangorestframework==3.3.2
--------------------------------------------------------------------------------
/requirements_dev.txt:
--------------------------------------------------------------------------------
1 | bumpversion==0.5.3
2 | wheel==0.24.0
3 |
--------------------------------------------------------------------------------
/runtests.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | try:
4 | from django.conf import settings
5 | from django.test.utils import get_runner
6 |
7 | settings.configure(
8 | DEBUG=True,
9 | USE_TZ=True,
10 | DATABASES={
11 | "default": {
12 | "ENGINE": "django.db.backends.sqlite3",
13 | }
14 | },
15 | ROOT_URLCONF="votes.urls",
16 | INSTALLED_APPS=[
17 | "django.contrib.auth",
18 | "django.contrib.contenttypes",
19 | "django.contrib.sites",
20 | "votes",
21 | ],
22 | SITE_ID=1,
23 | MIDDLEWARE_CLASSES=(),
24 | )
25 |
26 | try:
27 | import django
28 | setup = django.setup
29 | except AttributeError:
30 | pass
31 | else:
32 | setup()
33 |
34 | except ImportError:
35 | import traceback
36 | traceback.print_exc()
37 | raise ImportError("To fix this error, run: pip install -r requirements-test.txt")
38 |
39 |
40 | def run_tests(*test_args):
41 | if not test_args:
42 | test_args = ['tests']
43 |
44 | # Run tests
45 | TestRunner = get_runner(settings)
46 | test_runner = TestRunner()
47 |
48 | failures = test_runner.run_tests(test_args)
49 |
50 | if failures:
51 | sys.exit(bool(failures))
52 |
53 |
54 | if __name__ == '__main__':
55 | run_tests(*sys.argv[1:])
56 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [bumpversion]
2 | current_version = 1.0.1
3 | commit = True
4 | tag = True
5 |
6 | [bumpversion:file:setup.py]
7 |
8 | [bumpversion:file:votes/__init__.py]
9 |
10 | [wheel]
11 | universal = 1
12 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | import os
4 | import re
5 | import sys
6 |
7 | try:
8 | from setuptools import setup
9 | except ImportError:
10 | from distutils.core import setup
11 |
12 |
13 | def get_version(*file_paths):
14 | filename = os.path.join(os.path.dirname(__file__), *file_paths)
15 | version_file = open(filename).read()
16 | version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
17 | version_file, re.M)
18 | if version_match:
19 | return version_match.group(1)
20 | raise RuntimeError('Unable to find version string.')
21 |
22 | version = get_version('votes', '__init__.py')
23 |
24 | if sys.argv[-1] == 'publish':
25 | try:
26 | import wheel
27 | except ImportError:
28 | print('Wheel library missing. Please run "pip install wheel"')
29 | sys.exit()
30 | os.system('python setup.py sdist upload')
31 | os.system('python setup.py bdist_wheel upload')
32 | sys.exit()
33 |
34 | if sys.argv[-1] == 'tag':
35 | print("Tagging the version on github:")
36 | os.system("git tag -a %s -m 'version %s'" % (version, version))
37 | os.system("git push --tags")
38 | sys.exit()
39 |
40 | readme = open('README.rst').read()
41 | history = open('HISTORY.rst').read().replace('.. :changelog:', '')
42 |
43 | setup(
44 | name='votes',
45 | version=version,
46 | description="""DRF Vote is a simple Django Rest Framework app to add ability to like/dislike a model.""",
47 | long_description=readme + '\n\n' + history,
48 | author='ayush jain',
49 | author_email='ayush.jain@consultadd.in',
50 | url='https://github.com/tixdo/votes',
51 | packages=[
52 | 'votes',
53 | ],
54 | include_package_data=True,
55 | install_requires=[
56 | ],
57 | license="BSD",
58 | zip_safe=False,
59 | keywords='votes',
60 | classifiers=[
61 | 'Development Status :: 3 - Alpha',
62 | 'Framework :: Django',
63 | 'Framework :: Django :: 1.8',
64 | 'Framework :: Django :: 1.9',
65 | 'Intended Audience :: Developers',
66 | 'License :: OSI Approved :: BSD License',
67 | 'Natural Language :: English',
68 | 'Programming Language :: Python :: 2',
69 | 'Programming Language :: Python :: 2.7',
70 | 'Programming Language :: Python :: 3',
71 | 'Programming Language :: Python :: 3.3',
72 | 'Programming Language :: Python :: 3.4',
73 | 'Programming Language :: Python :: 3.5',
74 | ],
75 | )
76 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thecodinghouse/votes/24aac2487f41cd07bfb54d4b854dcb32322ce955/tests/__init__.py
--------------------------------------------------------------------------------
/tests/test_models.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | test_votes
6 | ------------
7 |
8 | Tests for `votes` models module.
9 | """
10 |
11 | from django.test import TestCase
12 |
13 | from votes import models
14 |
15 |
16 | class TestVotes(TestCase):
17 |
18 | def setUp(self):
19 | pass
20 |
21 | def test_something(self):
22 | pass
23 |
24 | def tearDown(self):
25 | pass
26 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | envlist = py27, py33, py34, py35
3 |
4 | [testenv]
5 | setenv =
6 | PYTHONPATH = {toxinidir}:{toxinidir}/votes
7 | commands = python runtests.py
8 | deps =
9 | -r{toxinidir}/requirements-test.txt
10 |
--------------------------------------------------------------------------------
/votes/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = '1.0.1'
2 |
--------------------------------------------------------------------------------
/votes/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 |
3 | # Register your models here.
4 | from .models import Vote
5 |
6 |
7 | admin.site.register(
8 | Vote,
9 | raw_id_fields=["user"],
10 | list_filter=["create_at"],
11 | list_display=["user", "content_object", "create_at"],
12 | search_fields=["user__username", "user__email"]
13 | )
14 |
--------------------------------------------------------------------------------
/votes/api.py:
--------------------------------------------------------------------------------
1 | """
2 | APIs for votes against a model.
3 | """
4 | from collections import Counter
5 |
6 | # Core Django imports
7 | from django.contrib.contenttypes.models import ContentType
8 |
9 | # Third party imports
10 | from rest_framework import viewsets
11 | from rest_framework import filters
12 | from rest_framework.decorators import list_route
13 | from rest_framework.response import Response
14 |
15 | # Imports from local apps
16 | from .models import Vote
17 |
18 | from .serializers import VoteSerializer
19 |
20 |
21 | class VoteQueryset(viewsets.ModelViewSet):
22 | queryset = Vote.objects.all()
23 | serializer_class = VoteSerializer
24 | filter_backends = (filters.OrderingFilter, filters.SearchFilter)
25 |
26 | def get_serializer_class(self):
27 | if self.action in ["retrieve", "list", "update", "create"]:
28 | return self.serializer_class
29 |
30 | return self.serializer_class
31 |
32 | @list_route(methods=["POST", "GET"])
33 | def up(self, request):
34 | """
35 | Adds a new vote to the object.
36 | :param: model, id, vote i.e. model=movies&id=359&vote=true
37 | :vote=option[True for up-vote, False for down-vote, None for no-vote]
38 | """
39 | user = request.user
40 |
41 | vote_param = request.query_params.get("vote", None)
42 | vote_dict = {"true": True,
43 | "false": False}
44 | try:
45 | vote = vote_dict[vote_param]
46 | app_label = request.query_params.get("app_label", None)
47 | model = request.query_params.get("model", None)
48 | id = request.query_params.get("id", None)
49 |
50 | content_type = ContentType.objects.get(app_label=app_label, model=model)
51 | instance = content_type.get_object_for_this_type(pk=id)
52 | instance.votes.up(user, vote)
53 | message = "Successfully voted"
54 |
55 | except KeyError:
56 | message = "Please provide a like or dislike parameter."
57 | return Response({'message': message})
58 |
59 | @list_route(methods=["POST", "GET"])
60 | def down(self, request):
61 | """
62 | Removes vote to the object.
63 | :param: model, id i.e. model=movies&id=359
64 | """
65 | user = request.user
66 | app_label = request.query_params.get("app_label", None)
67 | model = request.query_params.get("model")
68 | id = request.query_params.get("id")
69 | content_type = ContentType.objects.get(app_label=app_label, model=model)
70 | instance = content_type.get_object_for_this_type(pk=id)
71 |
72 | instance.votes.down(user)
73 | return Response({'message': 'Successfully un-voted'})
74 |
75 | @list_route(methods=["GET"])
76 | def exists(self, request):
77 | """
78 | Check whether an object is already voted.
79 | :param: model, id i.e. model=movies&id=359
80 | """
81 | user = request.user
82 | app_label = request.query_params.get("app_label", None)
83 | model = request.query_params.get("model")
84 | id = request.query_params.get("id")
85 | content_type = ContentType.objects.get(app_label=app_label, model=model)
86 | instance = content_type.get_object_for_this_type(pk=id)
87 |
88 | voted = instance.votes.exists(user)
89 |
90 | return Response({'voted': voted})
91 |
92 | @list_route(methods=["GET"])
93 | def all(self, request):
94 | """
95 | Return all instances voted by user.
96 | :param: model, id i.e. model=movies&id=359
97 | """
98 | user = request.user
99 | app_label = request.query_params.get("app_label", None)
100 | model = request.query_params.get("model")
101 | id = request.query_params.get("id")
102 | content_type = ContentType.objects.get(app_label=app_label, model=model)
103 | instance = content_type.get_object_for_this_type(pk=id)
104 | all_instances = instance.votes.all(user).values()
105 |
106 | return Response(all_instances)
107 |
108 | @list_route(methods=["GET"])
109 | def count(self, request):
110 | """
111 | Returns the number of votes for the object.
112 | :param: model, id i.e. model=movies&id=359
113 | """
114 |
115 | app_label = request.query_params.get("app_label", None)
116 | model = request.query_params.get("model")
117 | id = request.query_params.get("id")
118 | content_type = ContentType.objects.get(app_label=app_label, model=model)
119 | instance = content_type.get_object_for_this_type(pk=id)
120 | vote_count = {'vote_count': instance.votes.count()}
121 |
122 | return Response(vote_count)
123 |
124 | @list_route(methods=["GET"])
125 | def users(self, request):
126 | """
127 | Returns a list of users who voted and their voting date.
128 | :param: model, id i.e. model=movies&id=359
129 | """
130 |
131 | app_label = request.query_params.get("app_label", None)
132 | model = request.query_params.get("model")
133 | id = request.query_params.get("id")
134 | content_type = ContentType.objects.get(app_label=app_label, model=model)
135 | instance = content_type.get_object_for_this_type(pk=id)
136 | users_count = {'users_count': instance.votes.users()}
137 |
138 | return Response(users_count)
139 |
140 | @list_route(methods=["GET"])
141 | def likes(self, request):
142 | """
143 | Returns the number of likes and dislikes for the object.
144 | :param: model, id i.e. model=movies&id=359
145 | """
146 |
147 | app_label = request.query_params.get("app_label", None)
148 | model = request.query_params.get("model")
149 | id = request.query_params.get("id")
150 | content_type = ContentType.objects.get(app_label=app_label, model=model)
151 | instance = content_type.get_object_for_this_type(pk=id)
152 | votes = instance.votes.likes()
153 | results = Counter(votes)
154 |
155 | return Response(results)
156 |
--------------------------------------------------------------------------------
/votes/compat.py:
--------------------------------------------------------------------------------
1 | import django
2 | from django.conf import settings
3 | from django.db import transaction, IntegrityError
4 |
5 | # Django 1.5 add support for custom auth user model
6 | if django.VERSION >= (1, 5):
7 | AUTH_USER_MODEL = settings.AUTH_USER_MODEL
8 | else:
9 | AUTH_USER_MODEL = 'auth.User'
10 |
11 | try:
12 | atomic = transaction.atomic
13 | except AttributeError:
14 | from contextlib import contextmanager
15 |
16 | @contextmanager
17 | def atomic(using=None):
18 | sid = transaction.savepoint(using=using)
19 | try:
20 | yield
21 | except IntegrityError:
22 | transaction.savepoint_rollback(sid, using=using)
23 | raise
24 | else:
25 | transaction.savepoint_commit(sid, using=using)
26 |
--------------------------------------------------------------------------------
/votes/managers.py:
--------------------------------------------------------------------------------
1 | from collections import defaultdict
2 | from django.db import models, transaction
3 | from django.db.models import Count, F
4 | from django.db.models.query import QuerySet
5 | from django.contrib.contenttypes.models import ContentType
6 | from django.utils.translation import ugettext_lazy as _
7 | try:
8 | from django.contrib.contenttypes.fields import GenericRelation
9 | except ImportError:
10 | from django.contrib.contenttypes.generic import GenericRelation
11 |
12 | from .models import Vote
13 | from .utils import instance_required
14 |
15 |
16 | class VotedQuerySet(QuerySet):
17 | """
18 | if call votes.annotate with an `user` argument then add `is_voted` to each instance
19 | """
20 |
21 | def __init__(self, model=None, query=None, using=None, user=None):
22 | self.user = user
23 | super(VotedQuerySet, self).__init__(model=model, query=query, using=using)
24 |
25 | def __iter__(self):
26 | super(VotedQuerySet, self).__iter__()
27 | if self.user is None:
28 | return iter(self._result_cache)
29 |
30 | objects = self._result_cache
31 | user_id = self.user.id
32 | contenttype = ContentType.objects.get_for_model(self.model)
33 | object_ids = [r.id for r in objects]
34 |
35 | voted_users = defaultdict(list)
36 | votes = Vote.objects.filter(content_type=contenttype, object_id__in=object_ids)
37 | for v in votes:
38 | voted_users[v.object_id].append(v.user_id)
39 |
40 | for r in objects:
41 | r.is_voted = user_id in voted_users.get(r.id, [])
42 |
43 | self._result_cache = objects
44 | return iter(objects)
45 |
46 | def _clone(self):
47 | c = super(VotedQuerySet, self)._clone()
48 | c.user = self.user
49 | return c
50 |
51 |
52 | class _VotableManager(models.Manager):
53 | def __init__(self, through, model, instance, field_name='votes', extra_field=None):
54 | self.through = through
55 | self.model = model
56 | self.instance = instance
57 | self.field_name = field_name
58 | self.extra_field = extra_field
59 |
60 | @instance_required
61 | def up(self, user, vote):
62 | with transaction.atomic():
63 | if self.through.objects.filter(user=user, content_object=self.instance).exists():
64 | c_type = ContentType.objects.get_for_model(self.instance)
65 | vote_obj = self.through.objects.get(user=user, object_id=self.instance.id, content_type=c_type)
66 | vote_obj.vote = vote
67 | vote_obj.save()
68 | self.instance.save()
69 | else:
70 | self.through(user=user, content_object=self.instance, vote=vote).save()
71 | if self.extra_field:
72 | setattr(self.instance, self.extra_field, F(self.extra_field)+1)
73 | self.instance.save()
74 |
75 | @instance_required
76 | def down(self, user):
77 | with transaction.atomic():
78 | self.through.objects.filter(user=user, content_object=self.instance).delete()
79 | if self.extra_field:
80 | setattr(self.instance, self.extra_field, F(self.extra_field)-1)
81 | self.instance.save()
82 |
83 | @instance_required
84 | def exists(self, user):
85 | return self.through.objects.filter(user=user, content_object=self.instance).exists()
86 |
87 | def all(self, user):
88 | content_type = ContentType.objects.get_for_model(self.model)
89 | object_ids = self.through.objects.filter(user=user, content_type=content_type).values_list('object_id', flat=True)
90 | return self.model.objects.filter(pk__in=list(object_ids))
91 |
92 | def count(self, vote = None):
93 | if vote is None:
94 | return self.through.votes_for(self.model, self.instance).count()
95 | else:
96 | return self.through.votes_for(self.model, self.instance).filter(vote = vote).count()
97 |
98 | def likes(self):
99 | return self.through.votes_for(self.model, self.instance).values_list("vote", flat=True)
100 |
101 | def users(self):
102 | return self.through.votes_for(self.model, self.instance).order_by('-create_at').values_list('user_id', 'create_at')
103 |
104 | def annotate(self, queryset=None, user=None, annotation='num_votes', reverse=True):
105 | order = reverse and '-%s' % annotation or annotation
106 | kwargs = {annotation:Count('%s__user' % self.field_name)}
107 | queryset = queryset if queryset is not None else self.model.objects.all()
108 | queryset = queryset.annotate(**kwargs).order_by(order, '-id')
109 | return VotedQuerySet(model=queryset.model, query=queryset.query, user=user)
110 |
111 |
112 | class VotableManager(GenericRelation):
113 | def __init__(self, through=Vote, manager=_VotableManager, **kwargs):
114 | self.through = through
115 | self.manager = manager
116 | kwargs['verbose_name'] = kwargs.get('verbose_name', _('Votes'))
117 | self.extra_field = kwargs.pop('extra_field', None)
118 | super(VotableManager, self).__init__(self.through, **kwargs)
119 |
120 | def __get__(self, instance, model):
121 | if instance is not None and instance.pk is None:
122 | raise ValueError("%s objects need to have a primary key value "
123 | "before you can access their votes." % model.__name__)
124 | manager = self.manager(
125 | through=self.through,
126 | model=model,
127 | instance=instance,
128 | field_name=self.name,
129 | extra_field=self.extra_field,
130 | )
131 | return manager
132 |
133 | def contribute_to_class(self, cls, name):
134 | super(VotableManager, self).contribute_to_class(cls, name)
135 | setattr(cls, name, self)
136 |
--------------------------------------------------------------------------------
/votes/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by Django 1.9.2 on 2016-02-26 06:05
3 | from __future__ import unicode_literals
4 |
5 | from django.conf import settings
6 | from django.db import migrations, models
7 | import django.db.models.deletion
8 |
9 |
10 | class Migration(migrations.Migration):
11 |
12 | initial = True
13 |
14 | dependencies = [
15 | ('contenttypes', '0002_remove_content_type_name'),
16 | migrations.swappable_dependency(settings.AUTH_USER_MODEL),
17 | ]
18 |
19 | operations = [
20 | migrations.CreateModel(
21 | name='Vote',
22 | fields=[
23 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
24 | ('object_id', models.PositiveIntegerField()),
25 | ('create_at', models.DateTimeField(auto_now_add=True)),
26 | ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
27 | ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
28 | ],
29 | ),
30 | migrations.AlterUniqueTogether(
31 | name='vote',
32 | unique_together=set([('user', 'content_type', 'object_id')]),
33 | ),
34 | ]
35 |
--------------------------------------------------------------------------------
/votes/migrations/0002_vote_vote.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by Django 1.9.2 on 2016-03-10 05:59
3 | from __future__ import unicode_literals
4 |
5 | from django.db import migrations, models
6 |
7 |
8 | class Migration(migrations.Migration):
9 |
10 | dependencies = [
11 | ('votes', '0001_initial'),
12 | ]
13 |
14 | operations = [
15 | migrations.AddField(
16 | model_name='vote',
17 | name='vote',
18 | field=models.NullBooleanField(),
19 | ),
20 | ]
21 |
--------------------------------------------------------------------------------
/votes/migrations/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thecodinghouse/votes/24aac2487f41cd07bfb54d4b854dcb32322ce955/votes/migrations/__init__.py
--------------------------------------------------------------------------------
/votes/models.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from django.db import models
3 | from django.contrib.contenttypes.models import ContentType
4 |
5 | try:
6 | from django.contrib.contenttypes.fields import GenericForeignKey
7 | except ImportError:
8 | from django.contrib.contenttypes.generic import GenericForeignKey
9 |
10 | from .compat import AUTH_USER_MODEL
11 |
12 |
13 | class VoteManager(models.Manager):
14 | def filter(self, *args, **kwargs):
15 | if 'content_object' in kwargs:
16 | content_object = kwargs.pop('content_object')
17 | content_type = ContentType.objects.get_for_model(content_object)
18 | kwargs.update({
19 | 'content_type': content_type,
20 | 'object_id': content_object.pk
21 | })
22 | return super(VoteManager, self).filter(*args, **kwargs)
23 |
24 |
25 | class Vote(models.Model):
26 | user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE)
27 | content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
28 | object_id = models.PositiveIntegerField()
29 | content_object = GenericForeignKey()
30 | create_at = models.DateTimeField(auto_now_add=True)
31 |
32 | vote = models.NullBooleanField()
33 |
34 | objects = VoteManager()
35 |
36 | class Meta:
37 | unique_together = ('user', 'content_type', 'object_id')
38 |
39 | @classmethod
40 | def votes_for(cls, model, instance=None):
41 |
42 | ct = ContentType.objects.get_for_model(model)
43 | kwargs = {
44 | "content_type": ct
45 | }
46 | if instance is not None:
47 | kwargs["object_id"] = instance.pk
48 |
49 | return cls.objects.filter(**kwargs)
50 |
--------------------------------------------------------------------------------
/votes/serializers.py:
--------------------------------------------------------------------------------
1 |
2 | """ Serializers for api support on Votes app. """
3 |
4 | # Core Django imports
5 | from django.db import transaction
6 |
7 | # Third party imports
8 | from rest_framework import serializers
9 |
10 | # Imports form Vote app
11 | from .models import Vote
12 |
13 |
14 | class VoteSerializer(serializers.ModelSerializer):
15 |
16 | """ Returns serialized data of Vote instances. """
17 |
18 | @transaction.atomic
19 | class Meta:
20 | model = Vote
21 | fields = '__all__'
22 |
--------------------------------------------------------------------------------
/votes/static/css/votes.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thecodinghouse/votes/24aac2487f41cd07bfb54d4b854dcb32322ce955/votes/static/css/votes.css
--------------------------------------------------------------------------------
/votes/static/img/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thecodinghouse/votes/24aac2487f41cd07bfb54d4b854dcb32322ce955/votes/static/img/.gitignore
--------------------------------------------------------------------------------
/votes/static/js/votes.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thecodinghouse/votes/24aac2487f41cd07bfb54d4b854dcb32322ce955/votes/static/js/votes.js
--------------------------------------------------------------------------------
/votes/templates/votes/base.html:
--------------------------------------------------------------------------------
1 |
2 | {% comment %}
3 | As the developer of this package, don't place anything here if you can help it
4 | since this allows developers to have interoperability between your template
5 | structure and their own.
6 |
7 | Example: Developer melding the 2SoD pattern to fit inside with another pattern::
8 |
9 | {% extends "base.html" %}
10 | {% load static %}
11 |
12 |
13 | {% block extra_js %}
14 |
15 |
16 | {% block javascript %}
17 |
18 | {% endblock javascript %}
19 |
20 | {% endblock extra_js %}
21 | {% endcomment %}
22 |
--------------------------------------------------------------------------------
/votes/tests/__init__.py:
--------------------------------------------------------------------------------
1 | __author__ = 'consultadd66'
2 |
--------------------------------------------------------------------------------
/votes/tests/test_api.py:
--------------------------------------------------------------------------------
1 | __author__ = 'consultadd66'
2 |
3 | from rest_framework import status
4 | from rest_framework.test import APITestCase, APIClient
5 | from tixdo.third_party_apps.votes.models import Vote
6 | from django.core.urlresolvers import reverse
7 | from tixdo.movies.models import Movies
8 | from tixdo.users.models import User
9 | from django.contrib.contenttypes.models import ContentType
10 |
11 |
12 | class CreateVoteTest(APITestCase):
13 |
14 | def setUp(self):
15 | self.username = 'admin'
16 | self.password = 'admin'
17 | self.email = 'admin@gmail.com'
18 | self.user = User.objects.create_user(self.username, self.email, self.password)
19 | self.content_type = ContentType.objects.get(app_label="users", model="user")
20 | self.data = {'content_type': self.content_type.id, 'object_id': 1, 'user': self.user.id}
21 |
22 | def test_can_create_vote(self):
23 | response = self.client.post(reverse('vote-list'), self.data)
24 | self.assertEqual(response.status_code, status.HTTP_201_CREATED)
25 |
26 |
27 | class ReadVoteTest(APITestCase):
28 | def setUp(self):
29 | self.vote = Vote.objects.create(content_type_id=1, object_id=1, user_id=1)
30 |
31 | def test_can_read_vote_list(self):
32 | response = self.client.get(reverse('vote-list'))
33 | self.assertEqual(response.status_code, status.HTTP_200_OK)
34 |
35 | def test_can_read_vote_detail(self):
36 | response = self.client.get(reverse('vote-detail', args=[self.vote.id]))
37 | self.assertEqual(response.status_code, status.HTTP_200_OK)
38 |
39 |
40 | class UpdateVoteTest(APITestCase):
41 | def setUp(self):
42 | self.username = 'admin'
43 | self.password = 'admin'
44 | self.email = 'admin@gmail.com'
45 | self.user = User.objects.create_user(self.username, self.email, self.password)
46 | self.content_type = ContentType.objects.get(app_label="users", model="user")
47 | self.data = {'content_type': self.content_type.id, 'object_id': 1, 'user': self.user.id}
48 | self.vote = Vote.objects.create(content_type_id=1, object_id=1, user_id=1)
49 |
50 | def test_can_update_vote(self):
51 | response = self.client.put(reverse('vote-detail', args=[self.vote.id]), self.data)
52 | self.assertEqual(response.status_code, status.HTTP_200_OK)
53 |
54 |
55 | class DeleteVoteTest(APITestCase):
56 | def setUp(self):
57 | self.vote = Vote.objects.create(content_type_id=1, object_id=1, user_id=1)
58 |
59 | def test_can_delete_vote(self):
60 | response = self.client.delete(reverse('vote-detail', args=[self.vote.id]))
61 | self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
62 |
63 |
64 | class VoteQuerysetTest(APITestCase):
65 | def setUp(self):
66 | self.username = 'admin'
67 | self.password = 'admin'
68 | self.email = 'admin@gmail.com'
69 | self.user = User.objects.create_user(self.username, self.email, self.password)
70 |
71 | self.movie = Movies.objects.create(title='movie_name', release_date='2016-01-01')
72 |
73 | def test_up(self):
74 | # user should be login to vote
75 | self.client.login(username=self.username, password=self.password)
76 | response = self.client.get(reverse('vote-list') + 'up/', {'model': 'movies', 'id': str(self.movie.id), 'vote': 'true'})
77 | assert response.status_code == 200
78 | assert response.data['message'] == 'Successfully voted'
79 |
80 | response = self.client.get(reverse('vote-list') + 'up/', {'model': 'movies', 'id': str(self.movie.id)})
81 | assert response.data['message'] == "Please provide a like or dislike parameter."
82 |
83 | def test_up_post(self):
84 | # user should be login to vote
85 | self.client.login(username=self.username, password=self.password)
86 | response = self.client.post(reverse('vote-list') + 'up/?model=movies&id='+str(self.movie.id)+'vote=true', content_type="application/json")
87 | assert response.status_code == 200
88 | assert response.data['message'] == 'Successfully voted'
89 |
90 | def test_down(self):
91 | # user should be login to down vote
92 | self.client.login(username=self.username, password=self.password)
93 | response = self.client.get(reverse('vote-list') + 'down/', {'model': 'movies', 'id': str(self.movie.id)})
94 | assert response.status_code == 200
95 | assert response.data['message'] == 'Successfully un-voted'
96 |
97 | def test_down_post(self):
98 | # user should be login to down vote
99 | self.client.login(username=self.username, password=self.password)
100 | response = self.client.post(reverse('vote-list') + 'down/?model=movies&id='+str(self.movie.id), content_type="application/json")
101 | assert response.status_code == 200
102 | assert response.data['message'] == 'Successfully un-voted'
103 |
104 | def test_exists(self):
105 | self.client.login(username=self.username, password=self.password)
106 | response = self.client.get(reverse('vote-list') + 'exists/', {'model': 'movies', 'id': str(self.movie.id)})
107 | assert response.status_code == 200
108 | assert response.data
109 |
110 | def test_all(self):
111 | self.client.login(username=self.username, password=self.password)
112 |
113 | # check after up-vote
114 | self.client.get(reverse('vote-list') + 'up/?model=movies&id='+str(self.movie.id)+'&vote=true')
115 | response = self.client.get(reverse('vote-list') + 'all/?model=movies&id='+str(self.movie.id))
116 | assert response.status_code == 200
117 | assert response.data
118 |
119 | # check after down-vote
120 | self.client.get(reverse('vote-list') + 'down/', {'model': 'movies', 'id': str(self.movie.id)})
121 | response = self.client.get(reverse('vote-list') + 'all/', {'model': 'movies', 'id': str(self.movie.id)})
122 | assert response.status_code == 200
123 | assert len(response.data) == 0
124 |
125 | def test_count(self):
126 | self.client.login(username=self.username, password=self.password)
127 |
128 | # check before vote
129 | response = self.client.get(reverse('vote-list') + 'count/', {'model': 'movies', 'id': str(self.movie.id)})
130 | assert response.status_code == 200
131 | self.assertDictEqual(response.data, {'vote_count': 0})
132 |
133 | # check after vote
134 | self.client.get(reverse('vote-list') + 'up/', {'model': 'movies', 'id': str(self.movie.id), 'vote': 'true'})
135 | response = self.client.get(reverse('vote-list') + 'count/', {'model': 'movies', 'id': str(self.movie.id)})
136 | assert response.status_code == 200
137 | self.assertDictEqual(response.data, {'vote_count': 1})
138 |
139 | def test_users(self):
140 | response = self.client.get(reverse('vote-list') + 'users/', {'model': 'movies', 'id': str(self.movie.id)})
141 | assert response.status_code == 200
142 |
143 | def test_likes(self):
144 | response = self.client.get(reverse('vote-list') + 'likes/?model=movies&id='+str(self.movie.id))
145 | assert response.status_code == 200
--------------------------------------------------------------------------------
/votes/tests/test_models.py:
--------------------------------------------------------------------------------
1 | __author__ = 'consultadd66'
2 | from django.test import TestCase
3 | from tixdo.third_party_apps.votes.models import Vote
4 |
5 |
6 | class TestVote(TestCase):
7 |
8 | def setUp(self):
9 | self.vote = Vote()
10 |
11 | def test_vote(self):
12 | self.assertIsInstance(self.vote, Vote)
13 |
--------------------------------------------------------------------------------
/votes/urls.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | # from django.conf.urls import url
5 | # from django.conf.urls import include
6 |
7 | from rest_framework.routers import DefaultRouter
8 |
9 | from .api import VoteQueryset
10 |
11 | router = DefaultRouter()
12 | router.register(r'votes', VoteQueryset)
13 |
14 | urlpatterns = router.urls
--------------------------------------------------------------------------------
/votes/utils.py:
--------------------------------------------------------------------------------
1 | from functools import wraps
2 |
3 |
4 | def instance_required(func):
5 | @wraps(func)
6 | def inner(self, *args, **kwargs):
7 | if self.instance is None:
8 | raise TypeError("Can't call %s with a non-instance manager" % func.__name__)
9 | return func(self, *args, **kwargs)
10 | return inner
11 |
--------------------------------------------------------------------------------
/votes/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render
2 |
3 | # Create your views here.
4 |
--------------------------------------------------------------------------------