├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── MANIFEST.in ├── README.md ├── docs ├── Makefile ├── make.bat └── source │ ├── conf.py │ └── index.rst ├── niji ├── __init__.py ├── admin.py ├── api.py ├── apps.py ├── context_processors.py ├── forms.py ├── locale │ └── zh_Hans │ │ └── LC_MESSAGES │ │ └── django.po ├── management │ ├── __init__.py │ └── commands │ │ ├── __init__.py │ │ └── rerender.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_auto_20160126_1209.py │ ├── 0003_forumavatar.py │ ├── 0004_auto_20160628_0609.py │ ├── 0005_topic_closed.py │ └── __init__.py ├── misc.py ├── models.py ├── serializers.py ├── static │ └── niji │ │ ├── css │ │ ├── editor.css │ │ └── main.css │ │ └── image │ │ └── bg.jpg ├── tasks.py ├── templates │ └── niji │ │ ├── base.html │ │ ├── create_appendix.html │ │ ├── create_topic.html │ │ ├── edit_topic.html │ │ ├── includes │ │ ├── list.html │ │ ├── pagination.html │ │ └── user_info_panel.html │ │ ├── index.html │ │ ├── login.html │ │ ├── node.html │ │ ├── notifications.html │ │ ├── reg.html │ │ ├── search.html │ │ ├── topic.html │ │ ├── upload_avatar.html │ │ ├── user_info.html │ │ ├── user_topics.html │ │ └── widgets │ │ ├── authenticated_user_panel.html │ │ ├── node_info.html │ │ ├── nodes.html │ │ ├── pagedown.html │ │ └── visitor_user_panel.html ├── templatetags │ ├── __init__.py │ └── niji_tags.py ├── tests.py ├── urls.py └── views.py ├── requirements.txt ├── runtests.py ├── setup.py ├── test_settings.py └── test_url.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | bin/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | 25 | # Installer logs 26 | pip-log.txt 27 | pip-delete-this-directory.txt 28 | 29 | # Unit test / coverage reports 30 | htmlcov/ 31 | .tox/ 32 | .coverage 33 | .cache 34 | nosetests.xml 35 | coverage.xml 36 | 37 | # Translations 38 | *.mo 39 | 40 | # Mr Developer 41 | .mr.developer.cfg 42 | .project 43 | .pydevproject 44 | 45 | # Rope 46 | .ropeproject 47 | 48 | # Django stuff: 49 | *.log 50 | *.pot 51 | 52 | # Sphinx documentation 53 | docs/_build/ 54 | 55 | 56 | # ========================= 57 | # Operating System Files 58 | # ========================= 59 | 60 | # OSX 61 | # ========================= 62 | 63 | .DS_Store 64 | .AppleDouble 65 | .LSOverride 66 | 67 | # Icon must ends with two \r. 68 | Icon 69 | 70 | 71 | # Thumbnails 72 | ._* 73 | 74 | # Files that might appear on external disk 75 | .Spotlight-V100 76 | .Trashes 77 | 78 | # Windows 79 | # ========================= 80 | 81 | # Windows image file caches 82 | Thumbs.db 83 | ehthumbs.db 84 | 85 | # Folder config file 86 | Desktop.ini 87 | 88 | # Recycle Bin used on file shares 89 | $RECYCLE.BIN/ 90 | 91 | # Windows Installer files 92 | *.cab 93 | *.msi 94 | *.msm 95 | *.msp 96 | 97 | # IDE and Editor related files 98 | .idea 99 | *.swp 100 | 101 | # Database 102 | *.sqlite3 103 | 104 | # Media Files 105 | media/* 106 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | sudo: false 4 | 5 | python: 6 | - "2.7" 7 | - "3.4" 8 | - "3.5" 9 | env: 10 | - DJANGO='django>=1.8.0,<1.9.0' 11 | - DJANGO='django>=1.9.0,<1.10.0' 12 | - DJANGO='django>=1.10.0' 13 | - DJANGO='https://github.com/django/django/archive/master.tar.gz' 14 | install: 15 | - pip install selenium 16 | - pip install requests 17 | - pip install -r requirements.txt 18 | - pip install $DJANGO 19 | script: 20 | - python runtests.py 21 | notifications: 22 | email: false 23 | before_script: 24 | - "export DISPLAY=:99.0" 25 | - "sh -e /etc/init.d/xvfb start" 26 | - sleep 3 # give xvfb some time to start 27 | matrix: 28 | exclude: 29 | - python: "3.2" 30 | env: DJANGO='https://github.com/django/django/archive/master.tar.gz' 31 | - python: "3.2" 32 | env: DJANGO='django>=1.9.0,<1.10.0' 33 | - python: "3.3" 34 | env: DJANGO='https://github.com/django/django/archive/master.tar.gz' 35 | - python: "3.3" 36 | env: DJANGO='django>=1.9.0,<1.10.0' 37 | - python: "3.4" 38 | env: DJANGO='https://github.com/django/django/archive/master.tar.gz' 39 | - python: "3.5" 40 | env: DJANGO='django>=1.7.0,<1.8.0' 41 | allow_failures: 42 | - env: DJANGO='https://github.com/django/django/archive/master.tar.gz' 43 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2016 Shen Li 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.md 3 | recursive-include niji/static * 4 | recursive-include niji/templates * 5 | recursive-include docs * -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NIJI 2 | 3 | [![Build Status](https://travis-ci.org/ericls/niji.svg?branch=master)](https://travis-ci.org/ericls/niji) [![Documentation Status](https://readthedocs.org/projects/django-niji/badge/?version=latest)](http://django-niji.readthedocs.io/en/latest/?badge=latest) 4 | 5 | Django-NIJI is a pluggable forum app for Django projects. 6 | 7 | #### Demo 8 | > https://demo.nijiforum.com/ 9 | 10 | #### Docs 11 | > http://django-niji.rtfd.io 12 | -------------------------------------------------------------------------------- /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 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 16 | 17 | .PHONY: help 18 | help: 19 | @echo "Please use \`make ' where is one of" 20 | @echo " html to make standalone HTML files" 21 | @echo " dirhtml to make HTML files named index.html in directories" 22 | @echo " singlehtml to make a single large HTML file" 23 | @echo " pickle to make pickle files" 24 | @echo " json to make JSON files" 25 | @echo " htmlhelp to make HTML files and a HTML help project" 26 | @echo " qthelp to make HTML files and a qthelp project" 27 | @echo " applehelp to make an Apple Help Book" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " epub3 to make an epub3" 31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 32 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 33 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 34 | @echo " text to make text files" 35 | @echo " man to make manual pages" 36 | @echo " texinfo to make Texinfo files" 37 | @echo " info to make Texinfo files and run them through makeinfo" 38 | @echo " gettext to make PO message catalogs" 39 | @echo " changes to make an overview of all changed/added/deprecated items" 40 | @echo " xml to make Docutils-native XML files" 41 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 42 | @echo " linkcheck to check all external links for integrity" 43 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 44 | @echo " coverage to run coverage check of the documentation (if enabled)" 45 | @echo " dummy to check syntax errors of document sources" 46 | 47 | .PHONY: clean 48 | clean: 49 | rm -rf $(BUILDDIR)/* 50 | 51 | .PHONY: html 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | .PHONY: dirhtml 58 | dirhtml: 59 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 60 | @echo 61 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 62 | 63 | .PHONY: singlehtml 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | .PHONY: pickle 70 | pickle: 71 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 72 | @echo 73 | @echo "Build finished; now you can process the pickle files." 74 | 75 | .PHONY: json 76 | json: 77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 78 | @echo 79 | @echo "Build finished; now you can process the JSON files." 80 | 81 | .PHONY: htmlhelp 82 | htmlhelp: 83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 84 | @echo 85 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 86 | ".hhp project file in $(BUILDDIR)/htmlhelp." 87 | 88 | .PHONY: qthelp 89 | qthelp: 90 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 91 | @echo 92 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 93 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 94 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-niji.qhcp" 95 | @echo "To view the help file:" 96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-niji.qhc" 97 | 98 | .PHONY: applehelp 99 | applehelp: 100 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 101 | @echo 102 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 103 | @echo "N.B. You won't be able to view it unless you put it in" \ 104 | "~/Library/Documentation/Help or install it in your application" \ 105 | "bundle." 106 | 107 | .PHONY: devhelp 108 | devhelp: 109 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 110 | @echo 111 | @echo "Build finished." 112 | @echo "To view the help file:" 113 | @echo "# mkdir -p $$HOME/.local/share/devhelp/django-niji" 114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-niji" 115 | @echo "# devhelp" 116 | 117 | .PHONY: epub 118 | epub: 119 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 120 | @echo 121 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 122 | 123 | .PHONY: epub3 124 | epub3: 125 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 126 | @echo 127 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." 128 | 129 | .PHONY: latex 130 | latex: 131 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 132 | @echo 133 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 134 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 135 | "(use \`make latexpdf' here to do that automatically)." 136 | 137 | .PHONY: latexpdf 138 | latexpdf: 139 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 140 | @echo "Running LaTeX files through pdflatex..." 141 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 142 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 143 | 144 | .PHONY: latexpdfja 145 | latexpdfja: 146 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 147 | @echo "Running LaTeX files through platex and dvipdfmx..." 148 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 149 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 150 | 151 | .PHONY: text 152 | text: 153 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 154 | @echo 155 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 156 | 157 | .PHONY: man 158 | man: 159 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 160 | @echo 161 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 162 | 163 | .PHONY: texinfo 164 | texinfo: 165 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 166 | @echo 167 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 168 | @echo "Run \`make' in that directory to run these through makeinfo" \ 169 | "(use \`make info' here to do that automatically)." 170 | 171 | .PHONY: info 172 | info: 173 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 174 | @echo "Running Texinfo files through makeinfo..." 175 | make -C $(BUILDDIR)/texinfo info 176 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 177 | 178 | .PHONY: gettext 179 | gettext: 180 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 181 | @echo 182 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 183 | 184 | .PHONY: changes 185 | changes: 186 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 187 | @echo 188 | @echo "The overview file is in $(BUILDDIR)/changes." 189 | 190 | .PHONY: linkcheck 191 | linkcheck: 192 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 193 | @echo 194 | @echo "Link check complete; look for any errors in the above output " \ 195 | "or in $(BUILDDIR)/linkcheck/output.txt." 196 | 197 | .PHONY: doctest 198 | doctest: 199 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 200 | @echo "Testing of doctests in the sources finished, look at the " \ 201 | "results in $(BUILDDIR)/doctest/output.txt." 202 | 203 | .PHONY: coverage 204 | coverage: 205 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 206 | @echo "Testing of coverage in the sources finished, look at the " \ 207 | "results in $(BUILDDIR)/coverage/python.txt." 208 | 209 | .PHONY: xml 210 | xml: 211 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 212 | @echo 213 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 214 | 215 | .PHONY: pseudoxml 216 | pseudoxml: 217 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 218 | @echo 219 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 220 | 221 | .PHONY: dummy 222 | dummy: 223 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy 224 | @echo 225 | @echo "Build finished. Dummy builder generates no files." 226 | -------------------------------------------------------------------------------- /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% source 10 | set I18NSPHINXOPTS=%SPHINXOPTS% source 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. epub3 to make an epub3 31 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 32 | echo. text to make text files 33 | echo. man to make manual pages 34 | echo. texinfo to make Texinfo files 35 | echo. gettext to make PO message catalogs 36 | echo. changes to make an overview over all changed/added/deprecated items 37 | echo. xml to make Docutils-native XML files 38 | echo. pseudoxml to make pseudoxml-XML files for display purposes 39 | echo. linkcheck to check all external links for integrity 40 | echo. doctest to run all doctests embedded in the documentation if enabled 41 | echo. coverage to run coverage check of the documentation if enabled 42 | echo. dummy to check syntax errors of document sources 43 | goto end 44 | ) 45 | 46 | if "%1" == "clean" ( 47 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 48 | del /q /s %BUILDDIR%\* 49 | goto end 50 | ) 51 | 52 | 53 | REM Check if sphinx-build is available and fallback to Python version if any 54 | %SPHINXBUILD% 1>NUL 2>NUL 55 | if errorlevel 9009 goto sphinx_python 56 | goto sphinx_ok 57 | 58 | :sphinx_python 59 | 60 | set SPHINXBUILD=python -m sphinx.__init__ 61 | %SPHINXBUILD% 2> nul 62 | if errorlevel 9009 ( 63 | echo. 64 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 65 | echo.installed, then set the SPHINXBUILD environment variable to point 66 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 67 | echo.may add the Sphinx directory to PATH. 68 | echo. 69 | echo.If you don't have Sphinx installed, grab it from 70 | echo.http://sphinx-doc.org/ 71 | exit /b 1 72 | ) 73 | 74 | :sphinx_ok 75 | 76 | 77 | if "%1" == "html" ( 78 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 79 | if errorlevel 1 exit /b 1 80 | echo. 81 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 82 | goto end 83 | ) 84 | 85 | if "%1" == "dirhtml" ( 86 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 87 | if errorlevel 1 exit /b 1 88 | echo. 89 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 90 | goto end 91 | ) 92 | 93 | if "%1" == "singlehtml" ( 94 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 95 | if errorlevel 1 exit /b 1 96 | echo. 97 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 98 | goto end 99 | ) 100 | 101 | if "%1" == "pickle" ( 102 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 103 | if errorlevel 1 exit /b 1 104 | echo. 105 | echo.Build finished; now you can process the pickle files. 106 | goto end 107 | ) 108 | 109 | if "%1" == "json" ( 110 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 111 | if errorlevel 1 exit /b 1 112 | echo. 113 | echo.Build finished; now you can process the JSON files. 114 | goto end 115 | ) 116 | 117 | if "%1" == "htmlhelp" ( 118 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 119 | if errorlevel 1 exit /b 1 120 | echo. 121 | echo.Build finished; now you can run HTML Help Workshop with the ^ 122 | .hhp project file in %BUILDDIR%/htmlhelp. 123 | goto end 124 | ) 125 | 126 | if "%1" == "qthelp" ( 127 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 128 | if errorlevel 1 exit /b 1 129 | echo. 130 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 131 | .qhcp project file in %BUILDDIR%/qthelp, like this: 132 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-niji.qhcp 133 | echo.To view the help file: 134 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-niji.ghc 135 | goto end 136 | ) 137 | 138 | if "%1" == "devhelp" ( 139 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 140 | if errorlevel 1 exit /b 1 141 | echo. 142 | echo.Build finished. 143 | goto end 144 | ) 145 | 146 | if "%1" == "epub" ( 147 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 148 | if errorlevel 1 exit /b 1 149 | echo. 150 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 151 | goto end 152 | ) 153 | 154 | if "%1" == "epub3" ( 155 | %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 156 | if errorlevel 1 exit /b 1 157 | echo. 158 | echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. 159 | goto end 160 | ) 161 | 162 | if "%1" == "latex" ( 163 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 164 | if errorlevel 1 exit /b 1 165 | echo. 166 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdf" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "latexpdfja" ( 181 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 182 | cd %BUILDDIR%/latex 183 | make all-pdf-ja 184 | cd %~dp0 185 | echo. 186 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 187 | goto end 188 | ) 189 | 190 | if "%1" == "text" ( 191 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 192 | if errorlevel 1 exit /b 1 193 | echo. 194 | echo.Build finished. The text files are in %BUILDDIR%/text. 195 | goto end 196 | ) 197 | 198 | if "%1" == "man" ( 199 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 200 | if errorlevel 1 exit /b 1 201 | echo. 202 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 203 | goto end 204 | ) 205 | 206 | if "%1" == "texinfo" ( 207 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 208 | if errorlevel 1 exit /b 1 209 | echo. 210 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 211 | goto end 212 | ) 213 | 214 | if "%1" == "gettext" ( 215 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 216 | if errorlevel 1 exit /b 1 217 | echo. 218 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 219 | goto end 220 | ) 221 | 222 | if "%1" == "changes" ( 223 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 224 | if errorlevel 1 exit /b 1 225 | echo. 226 | echo.The overview file is in %BUILDDIR%/changes. 227 | goto end 228 | ) 229 | 230 | if "%1" == "linkcheck" ( 231 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 232 | if errorlevel 1 exit /b 1 233 | echo. 234 | echo.Link check complete; look for any errors in the above output ^ 235 | or in %BUILDDIR%/linkcheck/output.txt. 236 | goto end 237 | ) 238 | 239 | if "%1" == "doctest" ( 240 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 241 | if errorlevel 1 exit /b 1 242 | echo. 243 | echo.Testing of doctests in the sources finished, look at the ^ 244 | results in %BUILDDIR%/doctest/output.txt. 245 | goto end 246 | ) 247 | 248 | if "%1" == "coverage" ( 249 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 250 | if errorlevel 1 exit /b 1 251 | echo. 252 | echo.Testing of coverage in the sources finished, look at the ^ 253 | results in %BUILDDIR%/coverage/python.txt. 254 | goto end 255 | ) 256 | 257 | if "%1" == "xml" ( 258 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 259 | if errorlevel 1 exit /b 1 260 | echo. 261 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 262 | goto end 263 | ) 264 | 265 | if "%1" == "pseudoxml" ( 266 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 267 | if errorlevel 1 exit /b 1 268 | echo. 269 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 270 | goto end 271 | ) 272 | 273 | if "%1" == "dummy" ( 274 | %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy 275 | if errorlevel 1 exit /b 1 276 | echo. 277 | echo.Build finished. Dummy builder generates no files. 278 | goto end 279 | ) 280 | 281 | :end 282 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # django-niji documentation build configuration file, created by 5 | # sphinx-quickstart on Sun Aug 21 16:17:55 2016. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 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 | # 20 | # import os 21 | # import sys 22 | # sys.path.insert(0, os.path.abspath('.')) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | # 28 | # needs_sphinx = '1.0' 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be 31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 32 | # ones. 33 | extensions = [ 34 | 'sphinx.ext.autodoc', 35 | ] 36 | 37 | # Add any paths that contain templates here, relative to this directory. 38 | templates_path = ['_templates'] 39 | 40 | # The suffix(es) of source filenames. 41 | # You can specify multiple suffix as a list of string: 42 | # 43 | # source_suffix = ['.rst', '.md'] 44 | source_suffix = '.rst' 45 | 46 | # The encoding of source files. 47 | # 48 | # source_encoding = 'utf-8-sig' 49 | 50 | # The master toctree document. 51 | master_doc = 'index' 52 | 53 | # General information about the project. 54 | project = 'django-niji' 55 | copyright = '2016, Shen Li' 56 | author = 'Shen Li' 57 | 58 | # The version info for the project you're documenting, acts as replacement for 59 | # |version| and |release|, also used in various other places throughout the 60 | # built documents. 61 | # 62 | # The short X.Y version. 63 | version = '0.1.0' 64 | # The full version, including alpha/beta/rc tags. 65 | release = '0.1.0' 66 | 67 | # The language for content autogenerated by Sphinx. Refer to documentation 68 | # for a list of supported languages. 69 | # 70 | # This is also used if you do content translation via gettext catalogs. 71 | # Usually you set "language" from the command line for these cases. 72 | language = None 73 | 74 | # There are two options for replacing |today|: either, you set today to some 75 | # non-false value, then it is used: 76 | # 77 | # today = '' 78 | # 79 | # Else, today_fmt is used as the format for a strftime call. 80 | # 81 | # today_fmt = '%B %d, %Y' 82 | 83 | # List of patterns, relative to source directory, that match files and 84 | # directories to ignore when looking for source files. 85 | # This patterns also effect to html_static_path and html_extra_path 86 | exclude_patterns = [] 87 | 88 | # The reST default role (used for this markup: `text`) to use for all 89 | # documents. 90 | # 91 | # default_role = None 92 | 93 | # If true, '()' will be appended to :func: etc. cross-reference text. 94 | # 95 | # add_function_parentheses = True 96 | 97 | # If true, the current module name will be prepended to all description 98 | # unit titles (such as .. function::). 99 | # 100 | # add_module_names = True 101 | 102 | # If true, sectionauthor and moduleauthor directives will be shown in the 103 | # output. They are ignored by default. 104 | # 105 | # show_authors = False 106 | 107 | # The name of the Pygments (syntax highlighting) style to use. 108 | pygments_style = 'sphinx' 109 | 110 | # A list of ignored prefixes for module index sorting. 111 | # modindex_common_prefix = [] 112 | 113 | # If true, keep warnings as "system message" paragraphs in the built documents. 114 | # keep_warnings = False 115 | 116 | # If true, `todo` and `todoList` produce output, else they produce nothing. 117 | todo_include_todos = False 118 | 119 | 120 | # -- Options for HTML output ---------------------------------------------- 121 | 122 | # The theme to use for HTML and HTML Help pages. See the documentation for 123 | # a list of builtin themes. 124 | # 125 | html_theme = 'alabaster' 126 | 127 | # Theme options are theme-specific and customize the look and feel of a theme 128 | # further. For a list of options available for each theme, see the 129 | # documentation. 130 | # 131 | html_theme_options = { 132 | 'nosidebar': True 133 | } 134 | 135 | # Add any paths that contain custom themes here, relative to this directory. 136 | # html_theme_path = [] 137 | 138 | # The name for this set of Sphinx documents. 139 | # " v documentation" by default. 140 | # 141 | # html_title = 'django-niji v0.1.0' 142 | 143 | # A shorter title for the navigation bar. Default is the same as html_title. 144 | # 145 | # html_short_title = None 146 | 147 | # The name of an image file (relative to this directory) to place at the top 148 | # of the sidebar. 149 | # 150 | # html_logo = None 151 | 152 | # The name of an image file (relative to this directory) to use as a favicon of 153 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 154 | # pixels large. 155 | # 156 | # html_favicon = None 157 | 158 | # Add any paths that contain custom static files (such as style sheets) here, 159 | # relative to this directory. They are copied after the builtin static files, 160 | # so a file named "default.css" will overwrite the builtin "default.css". 161 | html_static_path = ['_static'] 162 | 163 | # Add any extra paths that contain custom files (such as robots.txt or 164 | # .htaccess) here, relative to this directory. These files are copied 165 | # directly to the root of the documentation. 166 | # 167 | # html_extra_path = [] 168 | 169 | # If not None, a 'Last updated on:' timestamp is inserted at every page 170 | # bottom, using the given strftime format. 171 | # The empty string is equivalent to '%b %d, %Y'. 172 | # 173 | # html_last_updated_fmt = None 174 | 175 | # If true, SmartyPants will be used to convert quotes and dashes to 176 | # typographically correct entities. 177 | # 178 | # html_use_smartypants = True 179 | 180 | # Custom sidebar templates, maps document names to template names. 181 | # 182 | # html_sidebars = {} 183 | 184 | # Additional templates that should be rendered to pages, maps page names to 185 | # template names. 186 | # 187 | # html_additional_pages = {} 188 | 189 | # If false, no module index is generated. 190 | # 191 | # html_domain_indices = True 192 | 193 | # If false, no index is generated. 194 | # 195 | # html_use_index = True 196 | 197 | # If true, the index is split into individual pages for each letter. 198 | # 199 | # html_split_index = False 200 | 201 | # If true, links to the reST sources are added to the pages. 202 | # 203 | # html_show_sourcelink = True 204 | 205 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 206 | # 207 | # html_show_sphinx = True 208 | 209 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 210 | # 211 | # html_show_copyright = True 212 | 213 | # If true, an OpenSearch description file will be output, and all pages will 214 | # contain a tag referring to it. The value of this option must be the 215 | # base URL from which the finished HTML is served. 216 | # 217 | # html_use_opensearch = '' 218 | 219 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 220 | # html_file_suffix = None 221 | 222 | # Language to be used for generating the HTML full-text search index. 223 | # Sphinx supports the following languages: 224 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' 225 | # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' 226 | # 227 | # html_search_language = 'en' 228 | 229 | # A dictionary with options for the search language support, empty by default. 230 | # 'ja' uses this config value. 231 | # 'zh' user can custom change `jieba` dictionary path. 232 | # 233 | # html_search_options = {'type': 'default'} 234 | 235 | # The name of a javascript file (relative to the configuration directory) that 236 | # implements a search results scorer. If empty, the default will be used. 237 | # 238 | # html_search_scorer = 'scorer.js' 239 | 240 | # Output file base name for HTML help builder. 241 | htmlhelp_basename = 'django-nijidoc' 242 | 243 | # -- Options for LaTeX output --------------------------------------------- 244 | 245 | latex_elements = { 246 | # The paper size ('letterpaper' or 'a4paper'). 247 | # 248 | # 'papersize': 'letterpaper', 249 | 250 | # The font size ('10pt', '11pt' or '12pt'). 251 | # 252 | # 'pointsize': '10pt', 253 | 254 | # Additional stuff for the LaTeX preamble. 255 | # 256 | # 'preamble': '', 257 | 258 | # Latex figure (float) alignment 259 | # 260 | # 'figure_align': 'htbp', 261 | } 262 | 263 | # Grouping the document tree into LaTeX files. List of tuples 264 | # (source start file, target name, title, 265 | # author, documentclass [howto, manual, or own class]). 266 | latex_documents = [ 267 | (master_doc, 'django-niji.tex', 'django-niji Documentation', 268 | 'Shen Li', 'manual'), 269 | ] 270 | 271 | # The name of an image file (relative to this directory) to place at the top of 272 | # the title page. 273 | # 274 | # latex_logo = None 275 | 276 | # For "manual" documents, if this is true, then toplevel headings are parts, 277 | # not chapters. 278 | # 279 | # latex_use_parts = False 280 | 281 | # If true, show page references after internal links. 282 | # 283 | # latex_show_pagerefs = False 284 | 285 | # If true, show URL addresses after external links. 286 | # 287 | # latex_show_urls = False 288 | 289 | # Documents to append as an appendix to all manuals. 290 | # 291 | # latex_appendices = [] 292 | 293 | # It false, will not define \strong, \code, itleref, \crossref ... but only 294 | # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added 295 | # packages. 296 | # 297 | # latex_keep_old_macro_names = True 298 | 299 | # If false, no module index is generated. 300 | # 301 | # latex_domain_indices = True 302 | 303 | 304 | # -- Options for manual page output --------------------------------------- 305 | 306 | # One entry per manual page. List of tuples 307 | # (source start file, name, description, authors, manual section). 308 | man_pages = [ 309 | (master_doc, 'django-niji', 'django-niji Documentation', 310 | [author], 1) 311 | ] 312 | 313 | # If true, show URL addresses after external links. 314 | # 315 | # man_show_urls = False 316 | 317 | 318 | # -- Options for Texinfo output ------------------------------------------- 319 | 320 | # Grouping the document tree into Texinfo files. List of tuples 321 | # (source start file, target name, title, author, 322 | # dir menu entry, description, category) 323 | texinfo_documents = [ 324 | (master_doc, 'django-niji', 'django-niji Documentation', 325 | author, 'django-niji', 'One line description of project.', 326 | 'Miscellaneous'), 327 | ] 328 | 329 | # Documents to append as an appendix to all manuals. 330 | # 331 | # texinfo_appendices = [] 332 | 333 | # If false, no module index is generated. 334 | # 335 | # texinfo_domain_indices = True 336 | 337 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 338 | # 339 | # texinfo_show_urls = 'footnote' 340 | 341 | # If true, do not generate a @detailmenu in the "Top" node's menu. 342 | # 343 | # texinfo_no_detailmenu = False -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | Django-Niji 2 | =========== 3 | 4 | Django-NIJI is a pluggable forum APP for Django projects 5 | 6 | Demo 7 | ---- 8 | https://demo.nijiforum.com/ 9 | 10 | Installation 11 | ------------ 12 | 13 | Requirements 14 | ~~~~~~~~~~~~ 15 | 16 | Django-NIJI is tested with the following Django and Python versions 17 | 18 | :: 19 | 20 | Django from 1.8 to 1.10 21 | Python from 2.7 3.4 3.5 22 | 23 | Get the package 24 | ~~~~~~~~~~~~~~~ 25 | 26 | Django-NIJI is available on pypi, so just run 27 | 28 | :: 29 | 30 | pip install django-niji 31 | 32 | Configuration 33 | ~~~~~~~~~~~~~ 34 | 35 | Tweak project settings 36 | ^^^^^^^^^^^^^^^^^^^^^^ 37 | 38 | Required Settings: 39 | 40 | .. code:: python 41 | 42 | INSTALLED_APPS += [ 43 | 'django.contrib.humanize', 44 | 'crispy_forms', 45 | 'niji', 46 | 'rest_framework', 47 | ] 48 | 49 | # Template context_processors 50 | TEMPLATES[0]['OPTIONS']['context_processors'].append("niji.context_processors.niji_processor") 51 | 52 | # Media related settings are required for avatar uploading to function properly 53 | MEDIA_ROOT = os.path.join(BASE_DIR, 'media') 54 | MEDIA_URL = '/media/' 55 | 56 | Other Settings: 57 | 58 | .. code:: python 59 | 60 | # Form UI Settings 61 | CRISPY_TEMPLATE_PACK = 'bootstrap3' 62 | 63 | # Configure where to link to from the Login and Reg buttons in the forum 64 | NIJI_LOGIN_URL_NAME = "account:login" 65 | NIJI_REG_URL_NAME = "account:reg" 66 | 67 | # Site Name 68 | NIJI_SITE_NAME = "A lovely forum" 69 | 70 | Configure URLs 71 | ^^^^^^^^^^^^^^ 72 | 73 | Simply include the urls 74 | 75 | .. code:: python 76 | 77 | from django.conf.urls import url, include 78 | from niji import urls as niji_urls 79 | 80 | urlpatterns = [ 81 | ... 82 | url(r'', include(niji_urls, namespace="niji")), 83 | ] 84 | 85 | Configure Celery 86 | ^^^^^^^^^^^^^^^^ 87 | 88 | Django-NIJI requires celery to send notifications. 89 | 90 | **If you already have a celery configured for you Django project, you can use just that.** 91 | 92 | Otherwise, follow these simple steps: 93 | 94 | Create ``celery.py`` inside project directory 95 | ''''''''''''''''''''''''''''''''''''''''''''' 96 | 97 | **Please replace ``project_name`` with your project's name** 98 | 99 | .. code:: python 100 | 101 | from __future__ import absolute_import 102 | 103 | import os 104 | from celery import Celery 105 | from django.conf import settings 106 | 107 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') # Change this to the project name 108 | 109 | app = Celery('project_name') 110 | 111 | app.config_from_object('django.conf:settings') 112 | app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) 113 | 114 | Modify project ``__init__.py`` 115 | '''''''''''''''''''''''''''''' 116 | 117 | .. code:: python 118 | 119 | from __future__ import absolute_import 120 | from .celery import app as celery_app 121 | 122 | Add setting entries 123 | ''''''''''''''''''' 124 | 125 | **Please adjust some of the settings according to your case** 126 | 127 | .. code:: python 128 | 129 | BROKER_URL = 'redis://localhost:6379/0' 130 | CELERY_ACCEPT_CONTENT = ['json'] 131 | CELERY_TASK_SERIALIZER = 'json' 132 | CELERY_RESULT_SERIALIZER = 'json' 133 | 134 | If you don't want to run a celery worker separately, include these 135 | entries: 136 | 137 | .. code:: python 138 | 139 | BROKER_BACKEND = 'memory' 140 | CELERY_EAGER_PROPAGATES_EXCEPTIONS = True 141 | CELERY_ALWAYS_EAGER = True 142 | 143 | Otherwise, you'll need to run ``celery -A project_name worker -l INFO`` 144 | 145 | Configure Editor (Optional) 146 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 147 | 148 | If you have ``pagedown`` in your ``settings.py``, Django-NIJI will 149 | enable that editor automatically. 150 | 151 | In order not to break the layout you may need to include the following 152 | settings: 153 | 154 | .. code:: python 155 | 156 | # Pagedown Editor 157 | PAGEDOWN_WIDGET_CSS = ('pagedown/demo/browser/demo.css', "css/editor.css",) 158 | PAGEDOWN_WIDGET_TEMPLATE = 'niji/widgets/pagedown.html' 159 | 160 | Migrate 161 | ~~~~~~~ 162 | 163 | :: 164 | 165 | python manage.py migrate 166 | 167 | Collect Static Assets 168 | ~~~~~~~~~~~~~~~~~~~~~ 169 | 170 | :: 171 | 172 | python manage.py collectstatic 173 | 174 | 175 | 176 | Now, login to your project's admin page and add some Nodes before you can post anything. 177 | -------------------------------------------------------------------------------- /niji/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericls/niji/df39b6d32d37bd7725321adc7b7ca739fd0cfc43/niji/__init__.py -------------------------------------------------------------------------------- /niji/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.contrib import admin 3 | from django.utils.safestring import mark_safe 4 | from .models import Topic, Node, Post, Appendix 5 | 6 | 7 | class PostInline(admin.TabularInline): 8 | model = Post 9 | raw_id_fields = ( 10 | 'user', 11 | ) 12 | fields = ( 13 | 'user', 14 | 'content_raw', 15 | 'hidden', 16 | ) 17 | extra = 1 18 | 19 | 20 | class AppendixInline(admin.TabularInline): 21 | model = Appendix 22 | fields = ( 23 | 'content_raw', 24 | ) 25 | extra = 1 26 | 27 | 28 | class TopicAdmin(admin.ModelAdmin): 29 | 30 | def is_top_topic(self, obj): 31 | return obj.order < 10 32 | 33 | is_top_topic.boolean = True 34 | 35 | list_display = ( 36 | 'title', 37 | 'user', 38 | 'pub_date', 39 | 'last_replied', 40 | 'view_count', 41 | 'reply_count', 42 | 'hidden', 43 | 'closed', 44 | 'is_top_topic', 45 | ) 46 | fields = ( 47 | 'user', 48 | 'title', 49 | 'content_raw', 50 | 'hidden', 51 | 'closed' 52 | ) 53 | 54 | search_fields = ( 55 | 'title', 56 | 'user__username', 57 | 'user__email' 58 | ) 59 | raw_id_fields = ( 60 | 'user', 61 | ) 62 | inlines = [ 63 | PostInline, 64 | AppendixInline 65 | ] 66 | 67 | 68 | class NodeAdmin(admin.ModelAdmin): 69 | 70 | def number_of_topics(self, obj): 71 | topics = Topic.objects.filter(node=obj) 72 | return "{}({})".format(topics.count(), topics.visible().count()) 73 | 74 | number_of_topics.short_description = "Number of Topics [total(visible)]" 75 | 76 | list_display = ( 77 | 'title', 78 | 'number_of_topics' 79 | ) 80 | search_fields = ( 81 | 'title', 82 | ) 83 | 84 | admin.site.register(Topic, TopicAdmin) 85 | admin.site.register(Node, NodeAdmin) 86 | -------------------------------------------------------------------------------- /niji/api.py: -------------------------------------------------------------------------------- 1 | from rest_framework import viewsets 2 | from rest_framework.authentication import SessionAuthentication 3 | from niji.models import Topic, Post 4 | from niji.serializers import TopicSerializer, PostSerializer 5 | 6 | 7 | class SessionAuthenticationExemptCSRF(SessionAuthentication): 8 | 9 | def enforce_csrf(self, request): 10 | return 11 | 12 | 13 | class TopicApiView(viewsets.ModelViewSet): 14 | authentication_classes = (SessionAuthenticationExemptCSRF,) 15 | queryset = Topic.objects.all() 16 | serializer_class = TopicSerializer 17 | 18 | 19 | class PostApiView(viewsets.ModelViewSet): 20 | authentication_classes = (SessionAuthenticationExemptCSRF,) 21 | queryset = Post.objects.all() 22 | serializer_class = PostSerializer 23 | -------------------------------------------------------------------------------- /niji/apps.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.apps import AppConfig 3 | 4 | 5 | class NijiConfig(AppConfig): 6 | name = 'niji' 7 | -------------------------------------------------------------------------------- /niji/context_processors.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from .models import Node 3 | from django.utils.translation import ugettext as _ 4 | from django.conf import settings 5 | 6 | 7 | def niji_processor(request): 8 | nodes = Node.objects.all() 9 | site_name = _(getattr(settings, 'NIJI_SITE_NAME', '')) 10 | niji_login_url_name = getattr(settings, 'NIJI_LOGIN_URL_NAME', 'niji:login') 11 | niji_reg_url_name = getattr(settings, 'NIJI_REG_URL_NAME', 'niji:reg') 12 | try: 13 | unread_count = request.user.received_notifications.filter(read=False).count() 14 | except AttributeError: 15 | unread_count = None 16 | return { 17 | 'nodes': nodes, 18 | 'unread_count': unread_count, 19 | 'site_name': site_name, 20 | 'niji_login_url_name': niji_login_url_name, 21 | 'niji_reg_url_name': niji_reg_url_name 22 | } 23 | -------------------------------------------------------------------------------- /niji/forms.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.forms import ModelForm 3 | from django.conf import settings 4 | from crispy_forms.layout import Submit 5 | from crispy_forms.helper import FormHelper 6 | from .models import Topic, Appendix, ForumAvatar, Post 7 | from django.utils.translation import ugettext as _ 8 | 9 | if 'pagedown' in settings.INSTALLED_APPS: 10 | use_pagedown = True 11 | from django import forms 12 | from pagedown.widgets import PagedownWidget 13 | else: 14 | use_pagedown = False 15 | 16 | 17 | class TopicForm(ModelForm): 18 | 19 | if use_pagedown: 20 | content_raw = forms.CharField(label=_('Content'), widget=PagedownWidget()) 21 | 22 | def __init__(self, *args, **kwargs): 23 | self.user = kwargs.pop('user', None) 24 | super(TopicForm, self).__init__(*args, **kwargs) 25 | self.helper = FormHelper() 26 | self.helper.add_input(Submit('submit', _('Submit'))) 27 | 28 | class Meta: 29 | model = Topic 30 | fields = ['node', 'title', 'content_raw'] 31 | labels = { 32 | 'content_raw': _('Content'), 33 | 'node': _('Node'), 34 | 'title': _('Title'), 35 | } 36 | 37 | def save(self, commit=True): 38 | inst = super(TopicForm, self).save(commit=False) 39 | inst.user = self.user 40 | if commit: 41 | inst.save() 42 | self.save_m2m() 43 | return inst 44 | 45 | 46 | class TopicEditForm(ModelForm): 47 | 48 | if use_pagedown: 49 | content_raw = forms.CharField(label=_('Content'), widget=PagedownWidget()) 50 | 51 | def __init__(self, *args, **kwargs): 52 | super(TopicEditForm, self).__init__(*args, **kwargs) 53 | self.helper = FormHelper() 54 | self.helper.add_input(Submit('submit', _('Submit'))) 55 | 56 | class Meta: 57 | model = Topic 58 | fields = ('content_raw', ) 59 | labels = { 60 | 'content_raw': _('Content'), 61 | } 62 | 63 | 64 | class AppendixForm(ModelForm): 65 | 66 | def __init__(self, *args, **kwargs): 67 | self.topic = kwargs.pop('topic', None) 68 | super(AppendixForm, self).__init__(*args, **kwargs) 69 | self.helper = FormHelper() 70 | self.helper.add_input(Submit('submit', _('Submit'))) 71 | 72 | class Meta: 73 | model = Appendix 74 | fields = ('content_raw', ) 75 | labels = { 76 | 'content_raw': _('Content'), 77 | } 78 | 79 | def save(self, commit=True): 80 | inst = super(AppendixForm, self).save(commit=False) 81 | inst.topic = self.topic 82 | if commit: 83 | inst.save() 84 | self.save_m2m() 85 | return inst 86 | 87 | 88 | class ForumAvatarForm(ModelForm): 89 | 90 | def __init__(self, *args, **kwargs): 91 | self.user = kwargs.pop('user', None) 92 | super(ForumAvatarForm, self).__init__(*args, **kwargs) 93 | self.helper = FormHelper() 94 | self.helper.add_input(Submit('submit', _('Submit'))) 95 | 96 | class Meta: 97 | model = ForumAvatar 98 | fields = ('image', 'use_gravatar') 99 | labels = { 100 | 'image': _('Avatar Image'), 101 | 'use_gravatar': _("Always Use Gravatar") 102 | } 103 | 104 | def save(self, commit=True): 105 | inst = super(ForumAvatarForm, self).save(commit=False) 106 | inst.user = self.user 107 | if commit: 108 | inst.save() 109 | self.save_m2m() 110 | return inst 111 | 112 | 113 | class ReplyForm(ModelForm): 114 | 115 | if use_pagedown: 116 | content_raw = forms.CharField(label='', widget=PagedownWidget()) 117 | 118 | def __init__(self, *args, **kwargs): 119 | self.user = kwargs.pop('user', None) 120 | self.topic_id = kwargs.pop('topic_id', None) 121 | super(ReplyForm, self).__init__(*args, **kwargs) 122 | self.helper = FormHelper() 123 | self.helper.add_input(Submit('submit', _('Submit'))) 124 | 125 | class Meta: 126 | model = Post 127 | fields = ('content_raw',) 128 | labels = { 129 | 'content_raw': '', 130 | } 131 | 132 | def save(self, commit=True): 133 | inst = super(ReplyForm, self).save(commit=False) 134 | inst.user = self.user 135 | inst.topic_id = self.topic_id 136 | if commit: 137 | inst.save() 138 | self.save_m2m() 139 | return inst 140 | -------------------------------------------------------------------------------- /niji/locale/zh_Hans/LC_MESSAGES/django.po: -------------------------------------------------------------------------------- 1 | # SOME DESCRIPTIVE TITLE. 2 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER 3 | # This file is distributed under the same license as the PACKAGE package. 4 | # FIRST AUTHOR , YEAR. 5 | # 6 | #, fuzzy 7 | msgid "" 8 | msgstr "" 9 | "Project-Id-Version: PACKAGE VERSION\n" 10 | "Report-Msgid-Bugs-To: \n" 11 | "POT-Creation-Date: 2016-07-18 03:48+0000\n" 12 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" 13 | "Last-Translator: FULL NAME \n" 14 | "Language-Team: LANGUAGE \n" 15 | "Language: \n" 16 | "MIME-Version: 1.0\n" 17 | "Content-Type: text/plain; charset=UTF-8\n" 18 | "Content-Transfer-Encoding: 8bit\n" 19 | "Plural-Forms: nplurals=1; plural=0;\n" 20 | 21 | #: forms.py:20 forms.py:32 forms.py:49 forms.py:60 forms.py:76 22 | msgid "Content" 23 | msgstr "内容" 24 | 25 | #: forms.py:26 forms.py:54 forms.py:70 forms.py:94 forms.py:123 26 | #: templates/niji/login.html:23 templates/niji/reg.html:31 27 | msgid "Submit" 28 | msgstr "提交" 29 | 30 | #: forms.py:33 31 | msgid "Node" 32 | msgstr "节点" 33 | 34 | #: forms.py:34 35 | msgid "Title" 36 | msgstr "标题" 37 | 38 | #: forms.py:100 39 | msgid "Avatar Image" 40 | msgstr "头像图片" 41 | 42 | #: forms.py:101 43 | msgid "Always Use Gravatar" 44 | msgstr "始终使用 Gravatar" 45 | 46 | #: templates/niji/base.html:36 templates/niji/base.html:38 47 | msgid "Search" 48 | msgstr "搜索" 49 | 50 | #: templates/niji/includes/list.html:39 templates/niji/user_info.html:35 51 | msgid "Last Replied" 52 | msgstr "最后回复" 53 | 54 | #: templates/niji/login.html:16 templates/niji/reg.html:16 55 | msgid "Username" 56 | msgstr "用户名" 57 | 58 | #: templates/niji/login.html:20 templates/niji/reg.html:24 59 | msgid "Password" 60 | msgstr "密码" 61 | 62 | #: templates/niji/notifications.html:9 views.py:252 views.py:276 63 | msgid "Notifications" 64 | msgstr "提醒" 65 | 66 | #: templates/niji/notifications.html:24 67 | #, python-format 68 | msgid "" 69 | "\n" 70 | " \n" 71 | " %(username)s\n" 72 | " \n" 73 | " mentioned you in topic\n" 74 | " \n" 75 | " %(topic_title)s\n" 76 | " \n" 77 | " " 78 | msgstr "" 79 | "\n" 80 | " 用户\n" 81 | " %(username)s\n" 82 | " \n" 83 | " 在主题\n" 84 | " \n" 85 | " %(topic_title)s\n" 86 | " \n" 87 | " 中@了你" 88 | 89 | #: templates/niji/notifications.html:35 90 | #, python-format 91 | msgid "" 92 | "\n" 93 | " \n" 94 | " %(username)s\n" 95 | " \n" 96 | " mentioned you when replying to\n" 97 | " \n" 98 | " %(topic_title)s\n" 99 | " \n" 100 | " " 101 | msgstr "" 102 | "\n" 103 | " 用户\n" 104 | " %(username)s\n" 105 | " \n" 106 | " 在回复主题\n" 107 | " \n" 108 | " %(topic_title)s\n" 109 | " \n" 110 | " 时@了你" 111 | 112 | #: templates/niji/reg.html:20 113 | msgid "Email" 114 | msgstr "Email" 115 | 116 | #: templates/niji/reg.html:28 117 | msgid "Repeat Password" 118 | msgstr "重复密码" 119 | 120 | #: templates/niji/topic.html:25 121 | #, python-format 122 | msgid "viewed %(view_count)s times" 123 | msgstr "%(view_count)s次浏览" 124 | 125 | #: templates/niji/topic.html:38 126 | #, python-format 127 | msgid "appendix %(number)s" 128 | msgstr "第%(number)s条附言" 129 | 130 | #: templates/niji/topic.html:48 131 | msgid "Edit" 132 | msgstr "编辑" 133 | 134 | #: templates/niji/topic.html:50 135 | msgid "Append" 136 | msgstr "添加附言" 137 | 138 | #: templates/niji/topic.html:57 139 | #, python-format 140 | msgid "%(reply_count)s Reply" 141 | msgid_plural "%(reply_count)s Replies" 142 | msgstr[0] "%(reply_count)s条回复" 143 | 144 | #: templates/niji/topic.html:59 145 | msgid "No Replies" 146 | msgstr "暂无回复" 147 | 148 | #: templates/niji/topic.html:83 149 | msgid "Reply" 150 | msgstr "回复" 151 | 152 | #: templates/niji/topic.html:88 153 | msgid "Be the first to reply!" 154 | msgstr "暂无回复" 155 | 156 | #: templates/niji/topic.html:96 157 | msgid "Leave a Reply" 158 | msgstr "添加回复" 159 | 160 | #: templates/niji/topic.html:106 161 | #, python-format 162 | msgid "" 163 | "\n" 164 | " Please Login or Create a New User to reply\n" 166 | " " 167 | msgstr "" 168 | "\n" 169 | " 请先登录注册\n" 171 | " " 172 | 173 | #: templates/niji/user_info.html:11 174 | #, python-format 175 | msgid "" 176 | "\n" 177 | " Topics created by %(username)s\n" 178 | " " 179 | msgstr "" 180 | "\n" 181 | " %(username)s创建的主题\n" 182 | " " 183 | 184 | #: templates/niji/user_info.html:46 185 | msgid "More topics from this user" 186 | msgstr "该用户的更多主题" 187 | 188 | #: templates/niji/user_info.html:54 189 | #, python-format 190 | msgid "" 191 | "\n" 192 | " Replies from %(username)s\n" 193 | " " 194 | msgstr "" 195 | "\n" 196 | " %(username)s发表的回复\n" 197 | " " 198 | 199 | #: templates/niji/user_info.html:63 200 | msgid "Replied to" 201 | msgstr "回复" 202 | 203 | #: templates/niji/widgets/authenticated_user_panel.html:47 views.py:177 204 | msgid "Create Topic" 205 | msgstr "创建主题" 206 | 207 | #: templates/niji/widgets/authenticated_user_panel.html:54 208 | #, python-format 209 | msgid "" 210 | "\n" 211 | " %(unread_count)s new notification\n" 212 | " " 213 | msgid_plural "" 214 | "\n" 215 | " %(unread_count)s new notifications\n" 216 | " " 217 | msgstr[0] "" 218 | "\n" 219 | " %(unread_count)s条未读提醒\n" 220 | " " 221 | msgstr[1] "" 222 | "\n" 223 | " %(unread_count)s条未读提醒\n" 224 | " " 225 | 226 | #: templates/niji/widgets/authenticated_user_panel.html:60 227 | msgid "No new nofitications" 228 | msgstr "暂无未读提醒" 229 | 230 | #: templates/niji/widgets/authenticated_user_panel.html:67 231 | msgid "Log out" 232 | msgstr "登出" 233 | 234 | #: templates/niji/widgets/nodes.html:3 235 | msgid "Nodes" 236 | msgstr "节点" 237 | 238 | #: templates/niji/widgets/pagedown.html:9 239 | msgid "Preview" 240 | msgstr "预览" 241 | 242 | #: templates/niji/widgets/visitor_user_panel.html:9 243 | msgid "Log in" 244 | msgstr "登入" 245 | 246 | #: templates/niji/widgets/visitor_user_panel.html:12 views.py:311 247 | msgid "Reg" 248 | msgstr "注册" 249 | 250 | #: views.py:37 251 | msgid "New Topics" 252 | msgstr "最新主题" 253 | 254 | #: views.py:38 255 | msgid "Index" 256 | msgstr "首页" 257 | 258 | #: views.py:155 259 | msgid "Search: " 260 | msgstr "搜索: " 261 | 262 | #: views.py:184 263 | msgid "Editing is not allowed when topic has been replied" 264 | msgstr "主题被回复后不可编辑" 265 | 266 | #: views.py:186 267 | msgid "You are not allowed to edit other's topic" 268 | msgstr "你不能编辑他人的主题" 269 | 270 | #: views.py:195 271 | msgid "Edit Topic" 272 | msgstr "编辑主题" 273 | 274 | #: views.py:202 275 | msgid "You are not allowed to append other's topic" 276 | msgstr "你不能给他人的主题添加附言" 277 | 278 | #: views.py:212 279 | msgid "Create Appendix" 280 | msgstr "添加附言" 281 | 282 | #: views.py:244 283 | msgid "Upload Avatar" 284 | msgstr "上传头像" 285 | 286 | #: views.py:282 287 | msgid "Login" 288 | msgstr "登入" 289 | 290 | #: views.py:289 291 | msgid "Username and password cannot be empty" 292 | msgstr "用户名和密码不能为空" 293 | 294 | #: views.py:293 295 | msgid "User does not exist" 296 | msgstr "该用户不存在" 297 | 298 | #: views.py:301 299 | msgid "User deactivated" 300 | msgstr "该用户被禁用" 301 | 302 | #: views.py:304 303 | msgid "Incorrect password" 304 | msgstr "密码错误" 305 | 306 | #: views.py:320 307 | msgid "User already exists" 308 | msgstr "用户已存在" 309 | 310 | #: views.py:323 311 | msgid "Password does not match" 312 | msgstr "两次密码不匹配" 313 | 314 | #: views.py:326 315 | msgid "Invalid Email" 316 | msgstr "邮箱格式不正确" 317 | 318 | #~ msgid "Markdown enabled" 319 | #~ msgstr "可使用 Markdown" 320 | -------------------------------------------------------------------------------- /niji/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericls/niji/df39b6d32d37bd7725321adc7b7ca739fd0cfc43/niji/management/__init__.py -------------------------------------------------------------------------------- /niji/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericls/niji/df39b6d32d37bd7725321adc7b7ca739fd0cfc43/niji/management/commands/__init__.py -------------------------------------------------------------------------------- /niji/management/commands/rerender.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand, CommandError 2 | from niji.models import Topic, Post, render_content 3 | import logging 4 | import sys 5 | 6 | 7 | class Command(BaseCommand): 8 | help = "Re-render topics and posts" 9 | 10 | def add_arguments(self, parser): 11 | parser.add_argument('--all', action="store_true") 12 | parser.add_argument('--topics', action="store", nargs="+", default=[]) 13 | parser.add_argument('--posts', action="store", nargs="+", default=[]) 14 | 15 | def handle(self, *args, **options): 16 | for_all = options['all'] 17 | topic_ids = options['topics'] 18 | post_ids = options['posts'] 19 | 20 | if (not for_all) and (not topic_ids) and (not post_ids): 21 | self.stdout.write(self.style.ERROR("At least one of '--all', '--topics', '--posts' is required")) 22 | return 23 | 24 | if not for_all: 25 | topics = Topic.objects.filter(pk__in=topic_ids).select_related('user') 26 | posts = Post.objects.filter(pk__in=post_ids).select_related('user') 27 | else: 28 | topics = Topic.objects.select_related('user').all() 29 | posts = Post.objects.select_related('user').all() 30 | 31 | for topic in topics: 32 | topic.content_rendered, _ = render_content(topic.content_raw, topic.user.username) 33 | topic.save() 34 | self.stdout.write(self.style.SUCCESS('Re-rendered topic {0.id}: {0.title}'.format(topic))) 35 | 36 | for post in posts: 37 | post.content_rendered, _ = render_content(post.content_raw, post.user.username) 38 | post.save() 39 | self.stdout.write(self.style.SUCCESS('Re-rendered post {0.id}, in topic {0.topic.id}: {0.topic.title}'.format(post))) 40 | -------------------------------------------------------------------------------- /niji/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.1 on 2016-01-21 04:22 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 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 16 | ] 17 | 18 | operations = [ 19 | migrations.CreateModel( 20 | name='Appendix', 21 | fields=[ 22 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 23 | ('pub_date', models.DateTimeField(auto_now_add=True)), 24 | ('content_raw', models.TextField()), 25 | ('content_rendered', models.TextField(blank=True, default='')), 26 | ], 27 | ), 28 | migrations.CreateModel( 29 | name='Node', 30 | fields=[ 31 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 32 | ('title', models.CharField(max_length=30)), 33 | ('description', models.TextField(blank=True, default='')), 34 | ], 35 | ), 36 | migrations.CreateModel( 37 | name='NodeGroup', 38 | fields=[ 39 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 40 | ('title', models.CharField(max_length=30)), 41 | ('node', models.ManyToManyField(to='niji.Node')), 42 | ], 43 | ), 44 | migrations.CreateModel( 45 | name='Notification', 46 | fields=[ 47 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 48 | ('read', models.BooleanField(default=False)), 49 | ('pub_date', models.DateTimeField(auto_now_add=True)), 50 | ], 51 | ), 52 | migrations.CreateModel( 53 | name='Post', 54 | fields=[ 55 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 56 | ('content_raw', models.TextField()), 57 | ('content_rendered', models.TextField(default='')), 58 | ('pub_date', models.DateTimeField(auto_now_add=True)), 59 | ('hidden', models.BooleanField(default=False)), 60 | ], 61 | ), 62 | migrations.CreateModel( 63 | name='Topic', 64 | fields=[ 65 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 66 | ('title', models.CharField(max_length=120)), 67 | ('content_raw', models.TextField()), 68 | ('content_rendered', models.TextField(blank=True, default='')), 69 | ('view_count', models.IntegerField(default=0)), 70 | ('reply_count', models.IntegerField(default=0)), 71 | ('pub_date', models.DateTimeField(auto_now_add=True, db_index=True)), 72 | ('last_replied', models.DateTimeField(auto_now_add=True, db_index=True)), 73 | ('order', models.IntegerField(default=10)), 74 | ('hidden', models.BooleanField(default=False)), 75 | ('node', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='topics', to='niji.Node')), 76 | ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='topics', to=settings.AUTH_USER_MODEL)), 77 | ], 78 | options={ 79 | 'ordering': ['order', '-pub_date'], 80 | }, 81 | ), 82 | migrations.AddField( 83 | model_name='post', 84 | name='topic', 85 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='replies', to='niji.Topic'), 86 | ), 87 | migrations.AddField( 88 | model_name='post', 89 | name='user', 90 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to=settings.AUTH_USER_MODEL), 91 | ), 92 | migrations.AddField( 93 | model_name='notification', 94 | name='post', 95 | field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='niji.Post'), 96 | ), 97 | migrations.AddField( 98 | model_name='notification', 99 | name='sender', 100 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sent_notifications', to=settings.AUTH_USER_MODEL), 101 | ), 102 | migrations.AddField( 103 | model_name='notification', 104 | name='to', 105 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='received_notifications', to=settings.AUTH_USER_MODEL), 106 | ), 107 | migrations.AddField( 108 | model_name='notification', 109 | name='topic', 110 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='niji.Topic'), 111 | ), 112 | migrations.AddField( 113 | model_name='appendix', 114 | name='topic', 115 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='niji.Topic'), 116 | ), 117 | ] 118 | -------------------------------------------------------------------------------- /niji/migrations/0002_auto_20160126_1209.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.1 on 2016-01-26 12:09 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | import django.db.models.deletion 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | dependencies = [ 12 | ('niji', '0001_initial'), 13 | ] 14 | 15 | operations = [ 16 | migrations.AlterField( 17 | model_name='notification', 18 | name='topic', 19 | field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='niji.Topic'), 20 | ), 21 | ] 22 | -------------------------------------------------------------------------------- /niji/migrations/0003_forumavatar.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.2 on 2016-06-08 19:38 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 | dependencies = [ 13 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 14 | ('niji', '0002_auto_20160126_1209'), 15 | ] 16 | 17 | operations = [ 18 | migrations.CreateModel( 19 | name='ForumAvatar', 20 | fields=[ 21 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 22 | ('use_gravatar', models.BooleanField(default=False)), 23 | ('image', models.ImageField(blank=True, default='', max_length=255, upload_to='uploads/forum/avatars/')), 24 | ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='forum_avatar', to=settings.AUTH_USER_MODEL)), 25 | ], 26 | ), 27 | ] 28 | -------------------------------------------------------------------------------- /niji/migrations/0004_auto_20160628_0609.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.2 on 2016-06-28 06:09 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 | ('niji', '0003_forumavatar'), 12 | ] 13 | 14 | operations = [ 15 | migrations.AlterField( 16 | model_name='forumavatar', 17 | name='image', 18 | field=models.ImageField(blank=True, default='', max_length=255, null=True, upload_to='uploads/forum/avatars/'), 19 | ), 20 | ] 21 | -------------------------------------------------------------------------------- /niji/migrations/0005_topic_closed.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.10 on 2016-08-20 17:34 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 | ('niji', '0004_auto_20160628_0609'), 12 | ] 13 | 14 | operations = [ 15 | migrations.AddField( 16 | model_name='topic', 17 | name='closed', 18 | field=models.BooleanField(default=False), 19 | ), 20 | ] 21 | -------------------------------------------------------------------------------- /niji/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericls/niji/df39b6d32d37bd7725321adc7b7ca739fd0cfc43/niji/migrations/__init__.py -------------------------------------------------------------------------------- /niji/misc.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.db.models import Q 3 | import re 4 | 5 | 6 | def normalize_query(query_string, 7 | findterms=re.compile(r'"([^"]+)"|(\S+)').findall, 8 | normspace=re.compile(r'\s{2,}').sub): 9 | return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] 10 | 11 | 12 | def get_query(query_string, search_fields): 13 | query = None # Query to search for every search term 14 | terms = normalize_query(query_string) 15 | for term in terms: 16 | or_query = None # Query to search for a given term in each field 17 | for field_name in search_fields: 18 | q = Q(**{"%s__icontains" % field_name: term}) 19 | if or_query is None: 20 | or_query = q 21 | else: 22 | or_query = or_query | q 23 | if query is None: 24 | query = or_query 25 | else: 26 | query = query & or_query 27 | return query -------------------------------------------------------------------------------- /niji/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.db import models 3 | from django.db.models import F 4 | from django.contrib.auth import get_user_model 5 | from django.conf import settings 6 | from django.core.files.uploadedfile import InMemoryUploadedFile 7 | from django.core.urlresolvers import reverse 8 | from django.utils.encoding import python_2_unicode_compatible 9 | from django.utils.translation import ugettext as _ 10 | from functools import partial 11 | from niji.tasks import notify 12 | from PIL import Image 13 | from io import BytesIO 14 | import xxhash 15 | import mistune 16 | import re 17 | import six 18 | if six.PY2: 19 | import sys 20 | reload(sys) 21 | sys.setdefaultencoding('utf-8') 22 | 23 | 24 | MENTION_REGEX = re.compile(r'@(\S+)', re.M) 25 | USER_MODEL = settings.AUTH_USER_MODEL 26 | 27 | 28 | def _replace_username(link, matchobj): 29 | return "@{username}{whitespace}".format( 30 | username=matchobj.group("username")[1:], 31 | whitespace=matchobj.group("whitespace"), 32 | link=link 33 | ) 34 | 35 | 36 | def render_content(content_raw, sender): 37 | """ 38 | :param content_raw: Raw content 39 | :param sender: user as username 40 | :return: (rendered_content, mentioned_user_list) 41 | """ 42 | content_rendered = mistune.markdown(content_raw) 43 | mentioned = list(set(re.findall(MENTION_REGEX, content_raw))) 44 | mentioned = [x for x in mentioned if x != sender] 45 | mentioned_users = get_user_model().objects.filter(username__in=mentioned) 46 | for user in mentioned_users: 47 | content_rendered = re.sub( 48 | r'(?P@%s)(?P\s|<\/p>)' % user.username, 49 | partial(_replace_username, reverse('niji:user_info', kwargs={"pk": user.pk})), 50 | content_rendered, 51 | re.M 52 | ) 53 | return content_rendered, mentioned_users 54 | 55 | 56 | class TopicQueryset(models.QuerySet): 57 | 58 | def visible(self): 59 | return self.filter(hidden=False) 60 | 61 | 62 | @python_2_unicode_compatible 63 | class Topic(models.Model): 64 | user = models.ForeignKey(USER_MODEL, related_name='topics', verbose_name=_("user")) 65 | title = models.CharField(max_length=120, verbose_name=_("title")) 66 | content_raw = models.TextField(verbose_name=_("raw content")) 67 | content_rendered = models.TextField(default='', blank=True, verbose_name=_("rendered content")) 68 | view_count = models.IntegerField(default=0, verbose_name=_("view count")) 69 | reply_count = models.IntegerField(default=0, verbose_name=_("reply count")) 70 | node = models.ForeignKey('Node', related_name='topics', verbose_name=_("node")) 71 | pub_date = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name=_("published time")) 72 | last_replied = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name=_("last replied time")) 73 | order = models.IntegerField(default=10, verbose_name=_("order")) 74 | hidden = models.BooleanField(default=False, verbose_name=_("hidden")) 75 | closed = models.BooleanField(default=False, verbose_name=_("closed")) 76 | objects = TopicQueryset.as_manager() 77 | 78 | raw_content_hash = None 79 | 80 | def __init__(self, *args, **kwargs): 81 | super(Topic, self).__init__(*args, **kwargs) 82 | self.raw_content_hash = xxhash.xxh64(self.content_raw).hexdigest() 83 | 84 | def get_reply_count(self): 85 | return self.replies.visible().count() 86 | 87 | def get_last_replied(self): 88 | last_visible_reply = self.replies.visible().order_by('-pub_date').first() 89 | if last_visible_reply: 90 | return last_visible_reply.pub_date 91 | return self.pub_date 92 | 93 | def increase_view_count(self): 94 | Topic.objects.filter(pk=self.id).update(view_count=F('view_count') + 1) 95 | 96 | def save(self, *args, **kwargs): 97 | new_hash = xxhash.xxh64(self.content_raw).hexdigest() 98 | mentioned_users = [] 99 | if new_hash != self.raw_content_hash or (not self.pk): 100 | # To (re-)render the content if content changed or topic is newly created 101 | self.content_rendered, mentioned_users = render_content(self.content_raw, sender=self.user.username) 102 | super(Topic, self).save(*args, **kwargs) 103 | self.raw_content_hash = new_hash 104 | for to in mentioned_users: 105 | notify.delay(to=to.username, sender=self.user.username, topic=self.pk) 106 | 107 | class Meta: 108 | ordering = ['order', '-pub_date'] 109 | 110 | def __str__(self): 111 | return self.title 112 | 113 | 114 | class PostQueryset(models.QuerySet): 115 | 116 | use_for_related_fields = True 117 | 118 | def visible(self): 119 | return self.filter(hidden=False) 120 | 121 | 122 | @python_2_unicode_compatible 123 | class Post(models.Model): 124 | topic = models.ForeignKey('Topic', related_name='replies', verbose_name=_("topic")) 125 | user = models.ForeignKey(USER_MODEL, related_name='posts', verbose_name=_("user")) 126 | content_raw = models.TextField(verbose_name=_("raw content")) 127 | content_rendered = models.TextField(default='', verbose_name=_("rendered content")) 128 | pub_date = models.DateTimeField(auto_now_add=True, verbose_name=_("published time")) 129 | hidden = models.BooleanField(default=False, verbose_name=_("hidden")) 130 | objects = PostQueryset.as_manager() 131 | 132 | raw_content_hash = None 133 | 134 | def __init__(self, *args, **kwargs): 135 | super(Post, self).__init__(*args, **kwargs) 136 | self.raw_content_hash = xxhash.xxh64(self.content_raw).hexdigest() 137 | 138 | def __str__(self): 139 | return 'Reply to %s' % self.topic.title 140 | 141 | def save(self, *args, **kwargs): 142 | new_hash = xxhash.xxh64(self.content_raw).hexdigest() 143 | mentioned_users = [] 144 | if new_hash != self.raw_content_hash or (not self.pk): 145 | self.content_rendered, mentioned_users = render_content(self.content_raw, sender=self.user.username) 146 | super(Post, self).save(*args, **kwargs) 147 | t = self.topic 148 | t.reply_count = t.get_reply_count() 149 | t.last_replied = t.get_last_replied() 150 | t.save(update_fields=['last_replied', 'reply_count']) 151 | for to in mentioned_users: 152 | notify.delay(to=to.username, sender=self.user.username, post=self.pk) 153 | 154 | def delete(self, *args, **kwargs): 155 | super(Post, self).delete(*args, **kwargs) 156 | t = self.topic 157 | t.reply_count = t.get_reply_count() 158 | t.last_replied = t.get_last_replied() 159 | t.save(update_fields=['last_replied', 'reply_count']) 160 | 161 | 162 | @python_2_unicode_compatible 163 | class Notification(models.Model): 164 | sender = models.ForeignKey(USER_MODEL, related_name='sent_notifications', verbose_name=_("sender")) 165 | to = models.ForeignKey(USER_MODEL, related_name='received_notifications', verbose_name=_("recipient")) 166 | topic = models.ForeignKey('Topic', null=True, verbose_name=_("topic")) 167 | post = models.ForeignKey('Post', null=True, verbose_name=_("reply")) 168 | read = models.BooleanField(default=False, verbose_name=_("read")) 169 | pub_date = models.DateTimeField(auto_now_add=True, verbose_name=_("published time")) 170 | 171 | def __str__(self): 172 | return 'Notification from %s to %s' % (self.sender.username, self.to.username) 173 | 174 | 175 | @python_2_unicode_compatible 176 | class Appendix(models.Model): 177 | topic = models.ForeignKey('Topic', verbose_name=_("topic")) 178 | pub_date = models.DateTimeField(auto_now_add=True, verbose_name=_("published time")) 179 | content_raw = models.TextField(verbose_name=_("raw content")) 180 | content_rendered = models.TextField(default='', blank=True, verbose_name=_("rendered content")) 181 | 182 | raw_content_hash = None 183 | 184 | def __init__(self, *args, **kwargs): 185 | super(Appendix, self).__init__(*args, **kwargs) 186 | self.raw_content_hash = xxhash.xxh64(self.content_raw).hexdigest() 187 | 188 | def save(self, *args, **kwargs): 189 | new_hash = xxhash.xxh64(self.content_raw).hexdigest() 190 | if new_hash != self.raw_content_hash or (not self.pk): 191 | self.content_rendered = mistune.markdown(self.content_raw) 192 | super(Appendix, self).save(*args, **kwargs) 193 | self.raw_content_hash = new_hash 194 | 195 | def __str__(self): 196 | return 'Appendix to %s' % self.topic.title 197 | 198 | 199 | @python_2_unicode_compatible 200 | class Node(models.Model): 201 | title = models.CharField(max_length=30, verbose_name=_("title")) 202 | description = models.TextField(default='', blank=True, verbose_name=_("description")) 203 | 204 | def __str__(self): 205 | return self.title 206 | 207 | 208 | @python_2_unicode_compatible 209 | class NodeGroup(models.Model): 210 | title = models.CharField(max_length=30) 211 | node = models.ManyToManyField('Node') 212 | 213 | def __str__(self): 214 | return self.title 215 | 216 | 217 | @python_2_unicode_compatible 218 | class ForumAvatar(models.Model): 219 | user = models.OneToOneField(USER_MODEL, related_name='forum_avatar') 220 | use_gravatar = models.BooleanField(default=False) 221 | image = models.ImageField(max_length=255, 222 | upload_to='uploads/forum/avatars/', 223 | blank=True, 224 | default="", 225 | null=True) 226 | 227 | def save(self, *args, **kwargs): 228 | existing_avatar = ForumAvatar.objects.filter(user=self.user).first() 229 | if existing_avatar: 230 | self.id = existing_avatar.id 231 | if not self.image: 232 | self.use_gravatar = True 233 | else: 234 | i = Image.open(self.image) 235 | i.thumbnail((120, 120), Image.ANTIALIAS) 236 | i_io = BytesIO() 237 | i.save(i_io, format='PNG') 238 | self.image = InMemoryUploadedFile( 239 | i_io, None, '%s.png' % self.user_id, 'image/png', None, None 240 | ) 241 | print(self.image) 242 | super(ForumAvatar, self).save(*args, **kwargs) 243 | 244 | def __str__(self): 245 | return "Avatar for user: %s" % self.user.username 246 | -------------------------------------------------------------------------------- /niji/serializers.py: -------------------------------------------------------------------------------- 1 | from rest_framework import serializers 2 | from niji.models import Topic, Post 3 | 4 | 5 | class TopicSerializer(serializers.HyperlinkedModelSerializer): 6 | class Meta: 7 | model = Topic 8 | fields = ('title', 'content_raw', 'order', 'hidden', 'closed') 9 | 10 | 11 | class PostSerializer(serializers.HyperlinkedModelSerializer): 12 | class Meta: 13 | model = Post 14 | fields = ('content_raw', 'hidden') 15 | -------------------------------------------------------------------------------- /niji/static/niji/css/editor.css: -------------------------------------------------------------------------------- 1 | .wmd-panel 2 | { 3 | margin-left: 0; 4 | margin-right: 0; 5 | width: 100%; 6 | min-width: 0; 7 | } 8 | .wmd-input { 9 | height: 300px; 10 | width: 100%; 11 | background-color: white; 12 | border: solid 1px #cccccc; 13 | } 14 | .wmd-preview { 15 | background-color: white; 16 | border: solid 1px #cccccc; 17 | padding: 10px; 18 | } 19 | .wmd-preview-title { 20 | margin-top: 10px; 21 | } 22 | #id_content_raw_wmd_button_bar { 23 | overflow: auto; 24 | } 25 | -------------------------------------------------------------------------------- /niji/static/niji/css/main.css: -------------------------------------------------------------------------------- 1 | a:hover { 2 | text-decoration: none; 3 | } 4 | body { 5 | background: url("/static/niji/image/bg.jpg"); 6 | } 7 | 8 | 9 | /* topic entry list*/ 10 | div.panel-subtitle > span.label { 11 | color: #666; 12 | background: none; 13 | border-radius: 0; 14 | border-left: solid 5px #5cb85c; 15 | } 16 | 17 | div.entry { 18 | padding: 0 10px; 19 | } 20 | 21 | p.entry-meta { 22 | font-size: 0.8em; 23 | margin: 0; 24 | } 25 | 26 | li.topic-entry { 27 | padding: 5px 0; 28 | border-bottom: solid 1px rgb(51, 51, 51); 29 | display: block; 30 | } 31 | li.topic-entry:hover { 32 | background-color: #fbfbff; 33 | } 34 | .entry-reply-count { 35 | line-height: 40px; 36 | } 37 | 38 | span.meta{ 39 | color: grey; 40 | } 41 | .entry-meta .meta+.meta:before { 42 | content: "\2022"; 43 | padding: 0 3px; 44 | } 45 | 46 | .badge-success { 47 | background-color: #5cb85c; 48 | } 49 | 50 | .pagination{ 51 | margin: 0; 52 | padding: 0; 53 | border: none; 54 | } 55 | 56 | img.user-avatar { 57 | width: 48px; 58 | height: 48px; 59 | } 60 | 61 | span.ordering { 62 | font-size: 80%; 63 | line-height: 200%; 64 | } 65 | 66 | span.ordering span:first-of-type::after { 67 | content: "\007C"; 68 | } 69 | 70 | /** User Panel **/ 71 | .panel-username{ 72 | margin-left: 1em; 73 | } 74 | 75 | .panel-user-meta { 76 | margin-top: 1em; 77 | } 78 | 79 | .panel-user-meta p{ 80 | margin: 0; 81 | } 82 | 83 | .panel-user-meta-item+.panel-user-meta-item { 84 | border-left: solid 1px #ddd; 85 | } 86 | 87 | .panel-user-meta-item-value { 88 | color: #666; 89 | font-size: 1.2em; 90 | line-height: 1.4em; 91 | } 92 | 93 | .panel-user-meta-item-title { 94 | color: #ccc; 95 | line-height: 0.8em; 96 | font-size: 0.8em; 97 | } 98 | 99 | .user-panel{ 100 | padding: 0.6em; 101 | } 102 | 103 | /* TOPIC */ 104 | h1.topic-title { 105 | font-size: 1.3em; 106 | font-weight: bold; 107 | line-height: 1.3em; 108 | } 109 | 110 | div.topic-content p { 111 | margin-top: 1em; 112 | line-height: 1.5em; 113 | } 114 | 115 | div.reply-content p{ 116 | margin-top: 1em; 117 | } 118 | 119 | .appendix-meta { 120 | font-size: 12px; 121 | line-height: 120%; 122 | text-align: left; 123 | color: #ccc; 124 | } 125 | 126 | .list-appendix-item { 127 | background: #FFFFF9; 128 | border-left: 3px solid #FFFBC1 !important; 129 | } 130 | 131 | /*User Info*/ 132 | .reply-entry-title{ 133 | background: #edf3f5; 134 | color: #999; 135 | } 136 | 137 | /*Notifications*/ 138 | div.notification-meta{ 139 | color: #999; 140 | } 141 | div.notification-content{ 142 | background-color: #f5f5f5; 143 | } 144 | -------------------------------------------------------------------------------- /niji/static/niji/image/bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericls/niji/df39b6d32d37bd7725321adc7b7ca739fd0cfc43/niji/static/niji/image/bg.jpg -------------------------------------------------------------------------------- /niji/tasks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import 3 | from celery import shared_task 4 | from celery.utils.log import get_task_logger 5 | from django.contrib.auth import get_user_model 6 | 7 | 8 | logger = get_task_logger(__name__) 9 | 10 | 11 | @shared_task 12 | def notify(sender, to, topic=None, post=None): 13 | from niji.models import Notification, Topic, Post 14 | User = get_user_model() 15 | 16 | if not any([topic, post]): 17 | logger.warning('No topic or post provided, ignored') 18 | 19 | ntf, created = Notification.objects.get_or_create( 20 | topic=Topic.objects.filter(pk=topic).first(), 21 | post=Post.objects.filter(pk=post).first(), 22 | sender=User.objects.get(username=sender), 23 | to=User.objects.get(username=to) 24 | ) 25 | if created: 26 | logger.info('Successfully created notification from {0.sender.username} to {0.to.username}'.format(ntf)) 27 | else: 28 | logger.info('Ignored duplicated notification from {0.sender.username} to {0.to.username}'.format(ntf)) 29 | return True 30 | -------------------------------------------------------------------------------- /niji/templates/niji/base.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 | {% load staticfiles %} 3 | 4 | {% get_current_language as LANGUAGE_CODE %} 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {{ title }}{% if site_name %}-{{ site_name }}{% endif %} 15 | 16 | 17 | 18 | 44 | 45 |
46 |
47 |
48 | {% block left %}{% endblock %} 49 |
50 |
51 | {% block widgtet_before %}{% endblock %} 52 | {% if request.user.is_authenticated %} 53 | {% include 'niji/widgets/authenticated_user_panel.html' %} 54 | {% else %} 55 | {% include 'niji/widgets/visitor_user_panel.html' %} 56 | {% endif %} 57 | {% include 'niji/widgets/nodes.html' %} 58 | {% block widget_after %}{% endblock %} 59 |
60 |
61 |
62 | 63 | 64 | 65 | 76 | {% block footer_ext %}{% endblock %} 77 | 78 | 79 | -------------------------------------------------------------------------------- /niji/templates/niji/create_appendix.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/base.html' %} 2 | {% load i18n %} 3 | {% load crispy_forms_tags %} 4 | 5 | {% block left %} 6 |
7 |
8 |
9 | {% crispy form %} 10 |
11 |
12 |
13 | {% endblock %} -------------------------------------------------------------------------------- /niji/templates/niji/create_topic.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/base.html' %} 2 | {% load i18n %} 3 | {% load crispy_forms_tags %} 4 | 5 | {% block left %} 6 |
7 |
8 |
9 | {% crispy form %} 10 |
11 |
12 |
13 | {% endblock %} -------------------------------------------------------------------------------- /niji/templates/niji/edit_topic.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/base.html' %} 2 | {% load i18n %} 3 | {% load crispy_forms_tags %} 4 | 5 | {% block left %} 6 |
7 |
8 |
9 | {% crispy form %} 10 |
11 |
12 |
13 | {% endblock %} -------------------------------------------------------------------------------- /niji/templates/niji/includes/list.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/base.html' %} 2 | {% load i18n %} 3 | {% load niji_tags %} 4 | {% load humanize %} 5 | 6 | {% block left %} 7 | {% block before_main_left %}{% endblock %} 8 |
9 |
10 | {{ panel_title }} 11 | {% if show_order %} 12 | 13 | Order: 14 | 15 | Last Replied 16 | 17 | 18 | Topic Date 19 | 20 | 21 | {% endif %} 22 |
23 | 24 | 70 | 73 |
74 | {% endblock %} 75 | -------------------------------------------------------------------------------- /niji/templates/niji/includes/pagination.html: -------------------------------------------------------------------------------- 1 | {% load niji_tags %} 2 | {% if is_paginated %} 3 | 32 | {% endif %} -------------------------------------------------------------------------------- /niji/templates/niji/includes/user_info_panel.html: -------------------------------------------------------------------------------- 1 | {% load niji_tags %} 2 |
3 |
4 |
5 |
6 | 7 |
8 |
9 |

{{ user.username }}

10 |

UID: {{ user.pk }}

11 |
12 |
13 |
14 |
-------------------------------------------------------------------------------- /niji/templates/niji/index.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/includes/list.html' %} -------------------------------------------------------------------------------- /niji/templates/niji/login.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/base.html' %} 2 | {% load i18n %} 3 | {% block left %} 4 |
5 |
6 | {% if messages %} 7 |
    8 | {% for message in messages %} 9 |
  • {{ message }}
  • 10 | {% endfor %} 11 |
12 | {% endif %} 13 |
14 | {% csrf_token %} 15 |
16 | 17 | 18 |
19 |
20 | 21 | 22 |
23 | 24 |
25 |
26 |
27 | {% endblock %} -------------------------------------------------------------------------------- /niji/templates/niji/node.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/includes/list.html' %} 2 | 3 | {% block widgtet_before %} 4 | {% include 'niji/widgets/node_info.html' %} 5 | {% endblock %} -------------------------------------------------------------------------------- /niji/templates/niji/notifications.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/base.html' %} 2 | {% load i18n %} 3 | {% load niji_tags %} 4 | {% load humanize %} 5 | 6 | {% block left %} 7 |
8 |
9 | {% trans "Notifications" %} 10 |
11 | 12 |
    13 | {% for notification in notifications %} 14 |
  • 15 |
    16 |
    17 | 18 |
    19 |
    20 |
    21 | {% url 'niji:user_info' notification.sender_id as user_url %} 22 | {% if notification.topic %} 23 | {% url 'niji:topic' notification.topic_id as topic_url %} 24 | {%blocktrans with username=notification.sender.username topic_title=notification.topic.title%} 25 | 26 | {{ username }} 27 | 28 | mentioned you in topic 29 | 30 | {{ topic_title }} 31 | 32 | {% endblocktrans %} 33 | {% else %} 34 | {% url 'niji:topic' notification.post.topic_id as topic_url %} 35 | {% blocktrans with username=notification.sender.username topic_title=notification.post.topic.title%} 36 | 37 | {{ username }} 38 | 39 | mentioned you when replying to 40 | 41 | {{ topic_title }} 42 | 43 | {% endblocktrans %} 44 | {% endif %} 45 |
    46 |
    47 | {% if notification.topic_id %} 48 | {{ notification.topic.content_rendered | safe | truncatewords_html:30 }} 49 | {% endif %} 50 | {% if notification.post_id %} 51 | {{ notification.post.content_rendered | safe | truncatewords_html:30 }} 52 | {% endif %} 53 |
    54 |
    55 |
    56 |
  • 57 | {% endfor %} 58 |
59 | 62 |
63 | {% endblock %} -------------------------------------------------------------------------------- /niji/templates/niji/reg.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/base.html' %} 2 | {% load i18n %} 3 | {% block left %} 4 |
5 |
6 | {% if messages %} 7 |
    8 | {% for message in messages %} 9 |
  • {{ message }}
  • 10 | {% endfor %} 11 |
12 | {% endif %} 13 |
14 | {% csrf_token %} 15 |
16 | 17 | 18 |
19 |
20 | 21 | 22 |
23 |
24 | 25 | 26 |
27 |
28 | 29 | 30 |
31 | 32 |
33 |
34 |
35 | {% endblock %} -------------------------------------------------------------------------------- /niji/templates/niji/search.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/includes/list.html' %} -------------------------------------------------------------------------------- /niji/templates/niji/topic.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/base.html' %} 2 | {% load i18n %} 3 | {% load niji_tags %} 4 | {% load humanize %} 5 | {% load crispy_forms_tags %} 6 | 7 | {% block left %} 8 |
9 | 10 |
11 | 16 |

{{ topic.title }}

17 |
18 |
19 | 20 |
21 |
22 |

23 | {{ topic.user.username }} 24 |
25 | Posted {{ topic.pub_date | naturaltime }} in {{ topic.node.title }}, 26 | {% blocktrans with view_count=topic.view_count %}viewed {{ view_count }} times{% endblocktrans %} 27 |

28 |
29 |
30 |
31 |

{{ topic.content_rendered | safe}}

32 |
33 |
34 | {% if topic.appendix_set %} 35 |
    36 | {% for appendix in topic.appendix_set.all %} 37 |
    38 |

    39 | {% blocktrans with number=forloop.counter %}appendix {{number}}{% endblocktrans %} {{appendix.pub_date|naturaltime}} 40 |

    41 | {{appendix.content_rendered | safe}} 42 |
    43 | {% endfor %} 44 |
45 | {% endif %} 46 | {% if request.user == topic.user %} 47 | 53 | {% endif %} 54 | {% if request.user.is_superuser %} 55 | 73 | {% endif %} 74 |
75 |
76 |
77 | {% if topic.reply_count %} 78 | {% blocktrans count reply_count=topic.reply_count %}{{ reply_count }} Reply{% plural %}{{ reply_count }} Replies{% endblocktrans %} 79 | {% else %} 80 | {% trans "No Replies" %} 81 | {% endif %} 82 |
83 | 84 |
    85 | {% for post in posts %} 86 |
  • 87 |
    88 |
    89 | 90 |
    91 |
    92 |

    93 | {{ post.user }}
    94 | {{ post.pub_date | naturaltime }} 95 |

    96 |
    97 |
    98 |
    99 |

    100 | {{ post.content_rendered | safe}} 101 |

    102 |
    103 | 106 | {% if request.user.is_superuser %} 107 |
    108 | 113 | {% endif %} 114 |
  • 115 | {% endfor %} 116 | {% if not posts %} 117 |
  • {% trans "Be the first to reply!" %}

  • 118 | {% endif %} 119 |
120 | 123 |
124 |
125 |
{% trans "Leave a Reply"%}
126 |
127 | {% if topic.closed %} 128 | 131 | {% else %} 132 | {% if request.user.is_authenticated %} 133 |
134 | {% crispy form %} 135 |
136 | {% else %} 137 | 144 | {% endif %} 145 | {% endif %} 146 |
147 |
148 | {% endblock %} 149 | 150 | {% block widget_after %} 151 | {% include 'niji/widgets/node_info.html' %} 152 | {% endblock %} 153 | 154 | {% block footer_ext %} 155 | 164 | {% if request.user.is_superuser %} 165 | 166 | 183 | 270 | {% endif %} 271 | {% endblock %} 272 | -------------------------------------------------------------------------------- /niji/templates/niji/upload_avatar.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/base.html' %} 2 | {% load i18n %} 3 | {% load crispy_forms_tags %} 4 | {% load niji_tags %} 5 | 6 | {% block left %} 7 |
8 |
9 |

Change Avatar

10 |

Current Avatar

11 | 12 |
13 | {% crispy form %} 14 |
15 |
16 |
17 | {% endblock %} -------------------------------------------------------------------------------- /niji/templates/niji/user_info.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/base.html' %} 2 | {% load i18n %} 3 | {% load humanize %} 4 | {% load niji_tags %} 5 | 6 | {% block left %} 7 | {% include 'niji/includes/user_info_panel.html' %} 8 |
9 |
10 | 11 | {% blocktrans with username=user.username%} 12 | Topics created by {{ username }} 13 | {% endblocktrans %} 14 | 15 |
16 | 17 | 49 |
50 | 51 |
52 |
53 | 54 | {% blocktrans with username=user.username%} 55 | Replies from {{ username }} 56 | {% endblocktrans %} 57 | 58 |
59 | 60 |
    61 | {% for reply in replies %} 62 |
  • 63 | {% trans "Replied to" %} 64 | {{ reply.topic.title }} 65 | {{ reply.pub_date | naturaltime }} 66 |
  • 67 |
  • 68 |

    {{ reply.content_rendered | safe }}

    69 |
  • 70 | {% endfor %} 71 |
72 |
73 | {% endblock %} -------------------------------------------------------------------------------- /niji/templates/niji/user_topics.html: -------------------------------------------------------------------------------- 1 | {% extends 'niji/includes/list.html' %} 2 | {% block before_main_left %} 3 | {% include 'niji/includes/user_info_panel.html' %} 4 | {% endblock %} -------------------------------------------------------------------------------- /niji/templates/niji/widgets/authenticated_user_panel.html: -------------------------------------------------------------------------------- 1 | {% load niji_tags %} 2 | {% load i18n %} 3 | -------------------------------------------------------------------------------- /niji/templates/niji/widgets/node_info.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 |
3 |
{{ node.title }}
4 |
5 |

6 | {{ node.description | safe }} 7 |

8 |
9 |
-------------------------------------------------------------------------------- /niji/templates/niji/widgets/nodes.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 |
3 |
{% trans "Nodes" %}
4 |
5 | {% for node in nodes %} 6 | 7 | {{ node.title }} 8 | 9 | {% endfor %} 10 |
11 |
-------------------------------------------------------------------------------- /niji/templates/niji/widgets/pagedown.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 | 3 |
4 |
5 |
6 | {{ body }} 7 |
8 | {% if show_preview %} 9 |

{% trans 'Preview' %}:

10 |
11 | {% endif %} 12 |
-------------------------------------------------------------------------------- /niji/templates/niji/widgets/visitor_user_panel.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 |
3 |
NIJI APP
4 |
5 | NIJI is a forum app built with Django 6 |
7 |
8 | 11 |
12 | {% trans 'Reg' %} 13 |
14 |
15 |
16 | {#

#} 17 | {# Reset Password#} 18 | {#

#} 19 |
20 |
21 | -------------------------------------------------------------------------------- /niji/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericls/niji/df39b6d32d37bd7725321adc7b7ca739fd0cfc43/niji/templatetags/__init__.py -------------------------------------------------------------------------------- /niji/templatetags/niji_tags.py: -------------------------------------------------------------------------------- 1 | from django import template 2 | from django.utils.html import escape 3 | from django.contrib.auth.models import User 4 | from six.moves.urllib.parse import urlencode, urlparse, parse_qs 5 | from django.core.urlresolvers import reverse 6 | from niji.models import ForumAvatar 7 | import hashlib 8 | 9 | register = template.Library() 10 | 11 | 12 | @register.simple_tag 13 | def gravatar_url(user, size=48): 14 | if isinstance(user, User): 15 | email = user.email 16 | else: 17 | email = user 18 | 19 | default = "" 20 | 21 | avatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5( 22 | email.lower().encode('utf-8') 23 | ).hexdigest() + "?" 24 | avatar_url += urlencode({'d': default, 's': str(size)}) 25 | 26 | return escape(avatar_url) 27 | 28 | 29 | @register.simple_tag 30 | def avatar_url(user, size=48, no_gravatar=False): 31 | try: 32 | avatar = user.forum_avatar 33 | except ForumAvatar.DoesNotExist: 34 | return gravatar_url(user, size) 35 | else: 36 | if avatar.use_gravatar and not no_gravatar or not avatar.image: 37 | return gravatar_url(user, size) 38 | else: 39 | return avatar.image.url 40 | 41 | 42 | @register.simple_tag 43 | def change_url(request, kwargs=None, query=None): 44 | kwargs = kwargs or {} 45 | query = query or {} 46 | rm = request.resolver_match 47 | _kwargs = rm.kwargs.copy() 48 | _kwargs.update(kwargs) 49 | if _kwargs.get("page") == 1: 50 | _kwargs.pop('page', None) 51 | qs = parse_qs(urlparse(request.get_full_path()).query) 52 | qs.update(query) 53 | path = reverse( 54 | '%s:%s' % (rm.namespace, rm.url_name), 55 | args=rm.args, 56 | kwargs=_kwargs, 57 | ) 58 | if (qs): 59 | return "%s?%s" % (path, urlencode(qs, True)) 60 | else: 61 | return path 62 | 63 | 64 | @register.simple_tag 65 | def change_page(request, page=1): 66 | return change_url(request, {"page": page}) 67 | 68 | 69 | @register.simple_tag 70 | def change_topic_ordering(request, ordering): 71 | return change_url(request, None, {"order": ordering}) 72 | 73 | 74 | @register.inclusion_tag('niji/includes/pagination.html', takes_context=True) 75 | def get_pagination(context, first_last_amount=2, before_after_amount=4): 76 | page_obj = context['page_obj'] 77 | paginator = context['paginator'] 78 | is_paginated = context['is_paginated'] 79 | page_numbers = [] 80 | 81 | # Pages before current page 82 | if page_obj.number > first_last_amount + before_after_amount: 83 | for i in range(1, first_last_amount + 1): 84 | page_numbers.append(i) 85 | 86 | if first_last_amount + before_after_amount + 1 != paginator.num_pages: 87 | page_numbers.append(None) 88 | 89 | for i in range(page_obj.number - before_after_amount, page_obj.number): 90 | page_numbers.append(i) 91 | 92 | else: 93 | for i in range(1, page_obj.number): 94 | page_numbers.append(i) 95 | 96 | # Current page and pages after current page 97 | if page_obj.number + first_last_amount + before_after_amount < paginator.num_pages: 98 | for i in range(page_obj.number, page_obj.number + before_after_amount + 1): 99 | page_numbers.append(i) 100 | 101 | page_numbers.append(None) 102 | 103 | for i in range(paginator.num_pages - first_last_amount + 1, paginator.num_pages + 1): 104 | page_numbers.append(i) 105 | 106 | else: 107 | for i in range(page_obj.number, paginator.num_pages + 1): 108 | page_numbers.append(i) 109 | 110 | return { 111 | 'paginator': paginator, 112 | 'page_obj': page_obj, 113 | 'page_numbers': page_numbers, 114 | 'is_paginated': is_paginated, 115 | 'request': context['request'], 116 | } 117 | -------------------------------------------------------------------------------- /niji/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.test import TestCase, LiveServerTestCase 3 | from django.utils.translation import ugettext as _ 4 | from selenium.webdriver.common.keys import Keys 5 | from selenium.webdriver.common.by import By 6 | from selenium.webdriver.support.ui import Select 7 | from selenium.webdriver.support.ui import WebDriverWait 8 | from selenium.webdriver.support import expected_conditions 9 | from django.core.urlresolvers import reverse 10 | from rest_framework.reverse import reverse as api_reverse 11 | from django.contrib.auth.models import User 12 | from .models import Topic, Node, Post, Notification, Appendix 13 | from django.test.utils import override_settings 14 | import random 15 | import requests 16 | import json 17 | import time 18 | import os 19 | 20 | if os.environ.get('TEST_USE_FIREFOX'): 21 | from selenium.webdriver.firefox.webdriver import WebDriver 22 | elif os.environ.get('TEST_USE_CHROME'): 23 | from selenium.webdriver.chrome.webdriver import WebDriver 24 | else: 25 | from selenium.webdriver.phantomjs.webdriver import WebDriver 26 | 27 | 28 | def login(browser, username_text, password_text): 29 | login_btn = browser.find_element_by_xpath( 30 | "//*[@id=\"main\"]/div/div[2]/div[1]/div[2]/div/div[1]/a" 31 | ) 32 | login_btn.click() 33 | username = browser.find_element_by_name('username') 34 | password = browser.find_element_by_name('password') 35 | username.send_keys(username_text) 36 | password.send_keys(password_text) 37 | password.send_keys(Keys.RETURN) 38 | 39 | 40 | class APITest(LiveServerTestCase): 41 | 42 | def setUp(self): 43 | self.browser = WebDriver() 44 | self.browser.implicitly_wait(3) 45 | self.n1 = Node.objects.create( 46 | title='TestNodeOne', 47 | description='The first test node' 48 | ) 49 | self.u1 = User.objects.create_user( 50 | username='test1', email='1@q.com', password='111' 51 | ) 52 | self.u1 = User.objects.create_user( 53 | username='test2', email='2@q.com', password='222' 54 | ) 55 | self.super_user = User.objects.create_user( 56 | username='super', email='super@example.com', password='123' 57 | ) 58 | self.super_user.is_superuser = True 59 | self.super_user.is_staff = True 60 | self.super_user.save() 61 | # Create 99 topics 62 | for i in range(1, 100): 63 | setattr( 64 | self, 65 | 't%s' % i, 66 | Topic.objects.create( 67 | title='Test Topic %s' % i, 68 | user=self.u1, 69 | content_raw='This is test topic __%s__' % i, 70 | node=self.n1 71 | ) 72 | ) 73 | # Create 99 replies to self.t1 74 | for i in range(1, 100): 75 | Post.objects.create( 76 | topic=self.t1, 77 | user=self.u1, 78 | content_raw='This is reply to topic 1 (__%s__)' % i 79 | ) 80 | 81 | def tearDown(self): 82 | self.browser.quit() 83 | 84 | def test_unauthorized_access(self): 85 | d = requests.get(self.live_server_url+api_reverse('niji:topic-list')) 86 | self.assertEqual(d.status_code, 403) 87 | d = requests.get(self.live_server_url+api_reverse('niji:topic-detail', kwargs={"pk": self.t1.pk})) 88 | self.assertEqual(d.status_code, 403) 89 | 90 | self.browser.get(self.live_server_url+reverse("niji:index")) 91 | login(self.browser, 'test1', '111') 92 | cookies = self.browser.get_cookies() 93 | s = requests.Session() 94 | s.headers = {'Content-Type': 'application/json'} 95 | for cookie in cookies: 96 | if cookie['name'] == 'csrftoken': 97 | continue 98 | s.cookies.set(cookie['name'], cookie['value']) 99 | d = s.get(self.live_server_url + api_reverse('niji:topic-list')) 100 | self.assertEqual(d.status_code, 403) 101 | d = s.get(self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": self.t1.pk})) 102 | self.assertEqual(d.status_code, 403) 103 | 104 | def test_move_topic_up(self): 105 | lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50)) 106 | d = requests.patch( 107 | self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), 108 | json.dumps({"order": 1}) 109 | ) 110 | self.assertEqual(d.status_code, 403) 111 | self.browser.get(self.live_server_url + reverse("niji:index")) 112 | login(self.browser, 'super', '123') 113 | cookies = self.browser.get_cookies() 114 | s = requests.Session() 115 | s.headers = {'Content-Type': 'application/json'} 116 | for cookie in cookies: 117 | if cookie['name'] == 'csrftoken': 118 | continue 119 | s.cookies.set(cookie['name'], cookie['value']) 120 | d = s.patch( 121 | self.live_server_url+api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), 122 | json.dumps({"order": 1}) 123 | ).json() 124 | self.assertEqual(d["order"], 1) 125 | 126 | def test_close_open_topic(self): 127 | lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50)) 128 | d = requests.patch( 129 | self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), 130 | json.dumps({"closed": True}) 131 | ) 132 | self.assertEqual(d.status_code, 403) 133 | self.browser.get(self.live_server_url + reverse("niji:index")) 134 | login(self.browser, 'super', '123') 135 | cookies = self.browser.get_cookies() 136 | s = requests.Session() 137 | s.headers = {'Content-Type': 'application/json'} 138 | for cookie in cookies: 139 | if cookie['name'] == 'csrftoken': 140 | continue 141 | s.cookies.set(cookie['name'], cookie['value']) 142 | d = s.patch( 143 | self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), 144 | json.dumps({"closed": True}) 145 | ).json() 146 | self.assertEqual(d["closed"], True) 147 | d = s.patch( 148 | self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), 149 | json.dumps({"closed": False}) 150 | ).json() 151 | self.assertEqual(d["closed"], False) 152 | 153 | def test_hide_topic(self): 154 | lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50)) 155 | d = requests.patch( 156 | self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), 157 | json.dumps({"closed": True}) 158 | ) 159 | self.assertEqual(d.status_code, 403) 160 | self.browser.get(self.live_server_url + reverse("niji:index")) 161 | login(self.browser, 'super', '123') 162 | cookies = self.browser.get_cookies() 163 | s = requests.Session() 164 | s.headers = {'Content-Type': 'application/json'} 165 | for cookie in cookies: 166 | if cookie['name'] == 'csrftoken': 167 | continue 168 | s.cookies.set(cookie['name'], cookie['value']) 169 | d = s.patch( 170 | self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), 171 | json.dumps({"hidden": True}) 172 | ).json() 173 | self.assertEqual(d["hidden"], True) 174 | 175 | def test_hide_post(self): 176 | lucky_post = random.choice(Post.objects.visible().all()) 177 | d = requests.patch( 178 | self.live_server_url + api_reverse('niji:post-detail', kwargs={"pk": lucky_post.pk}), 179 | json.dumps({"hidden": True}) 180 | ) 181 | self.assertEqual(d.status_code, 403) 182 | self.browser.get(self.live_server_url + reverse("niji:index")) 183 | login(self.browser, 'super', '123') 184 | self.assertIn("Log out", self.browser.page_source) 185 | cookies = self.browser.get_cookies() 186 | s = requests.Session() 187 | s.headers = {'Content-Type': 'application/json'} 188 | for cookie in cookies: 189 | if cookie['name'] == 'csrftoken': 190 | continue 191 | s.cookies.set(cookie['name'], cookie['value']) 192 | d = s.patch( 193 | self.live_server_url + api_reverse('niji:post-detail', kwargs={"pk": lucky_post.pk}), 194 | json.dumps({"hidden": True}) 195 | ).json() 196 | self.assertEqual(d["hidden"], True) 197 | 198 | 199 | class StickToTopTest(LiveServerTestCase): 200 | 201 | def setUp(self): 202 | self.browser = WebDriver() 203 | self.browser.implicitly_wait(3) 204 | self.n1 = Node.objects.create( 205 | title='TestNodeOne', 206 | description='The first test node' 207 | ) 208 | self.u1 = User.objects.create_user( 209 | username='test1', email='1@q.com', password='111' 210 | ) 211 | self.super_user = User.objects.create_user( 212 | username='super', email='super@example.com', password='123' 213 | ) 214 | self.super_user.is_superuser = True 215 | self.super_user.is_staff = True 216 | self.super_user.save() 217 | # Create 99 topics 218 | for i in range(1, 100): 219 | setattr( 220 | self, 221 | 't%s' % i, 222 | Topic.objects.create( 223 | title='Test Topic %s' % i, 224 | user=self.u1, 225 | content_raw='This is test topic __%s__' % i, 226 | node=self.n1 227 | ) 228 | ) 229 | 230 | def tearDown(self): 231 | self.browser.quit() 232 | 233 | def test_stick_to_top_admin(self): 234 | self.browser.get(self.live_server_url + reverse("niji:index")) 235 | login(self.browser, 'super', '123') 236 | self.assertIn("Log out", self.browser.page_source) 237 | 238 | lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50)) 239 | 240 | self.browser.get(self.live_server_url+reverse('niji:topic', kwargs={"pk": lucky_topic1.pk})) 241 | self.browser.find_element_by_class_name('move-topic-up').click() 242 | up_level = WebDriverWait( 243 | self.browser, 10 244 | ).until( 245 | expected_conditions.presence_of_element_located( 246 | (By.NAME, 'move-topic-up-level') 247 | ) 248 | ) 249 | up_level = Select(up_level) 250 | up_level.select_by_visible_text('1') 251 | time.sleep(1) 252 | self.browser.execute_script("$('.modal-confirm').click()") 253 | self.browser.get(self.live_server_url+reverse('niji:index')) 254 | first_topic_title = self.browser.find_elements_by_class_name('entry-link')[0].text 255 | 256 | self.assertEqual(first_topic_title, lucky_topic1.title) 257 | 258 | 259 | class TopicOrderingTest(LiveServerTestCase): 260 | 261 | def setUp(self): 262 | self.browser = WebDriver() 263 | self.browser.implicitly_wait(3) 264 | self.n1 = Node.objects.create( 265 | title='TestNodeOne', 266 | description='The first test node' 267 | ) 268 | self.u1 = User.objects.create_user( 269 | username='test1', email='1@q.com', password='111' 270 | ) 271 | # Create 99 topics 272 | for i in range(1, 100): 273 | setattr( 274 | self, 275 | 't%s' % i, 276 | Topic.objects.create( 277 | title='Test Topic %s' % i, 278 | user=self.u1, 279 | content_raw='This is test topic __%s__' % i, 280 | node=self.n1 281 | ) 282 | ) 283 | 284 | def tearDown(self): 285 | self.browser.quit() 286 | 287 | def test_default_ordering_without_settings(self): 288 | self.browser.get(self.live_server_url+reverse("niji:index")) 289 | first_topic_title = self.browser.find_element_by_class_name( 290 | "entry-link" 291 | ).text 292 | self.assertEqual(first_topic_title, self.t99.title) 293 | Post.objects.create( 294 | topic=self.t1, 295 | content_raw='reply to post __1__', 296 | user=self.u1, 297 | ) 298 | self.browser.get(self.browser.current_url) 299 | first_topic_title = self.browser.find_element_by_class_name( 300 | "entry-link" 301 | ).text 302 | self.assertEqual(first_topic_title, self.t1.title) 303 | 304 | @override_settings(NIJI_DEFAULT_TOPIC_ORDERING="-pub_date") 305 | def test_default_ordering_with_settings(self): 306 | self.browser.get(self.live_server_url+reverse("niji:index")) 307 | first_topic_title = self.browser.find_element_by_class_name( 308 | "entry-link" 309 | ).text 310 | self.assertEqual(first_topic_title, self.t99.title) 311 | Post.objects.create( 312 | topic=self.t1, 313 | content_raw='reply to post __1__', 314 | user=self.u1, 315 | ) 316 | self.browser.get(self.browser.current_url) 317 | first_topic_title = self.browser.find_element_by_class_name( 318 | "entry-link" 319 | ).text 320 | self.assertEqual(first_topic_title, self.t99.title) 321 | 322 | def test_user_specified_ordering_last_replied(self): 323 | self.browser.get(self.live_server_url+reverse("niji:index")) 324 | self.browser.find_element_by_link_text( 325 | "Last Replied" 326 | ).click() 327 | first_topic_title = self.browser.find_element_by_class_name( 328 | "entry-link" 329 | ).text 330 | self.assertEqual(first_topic_title, self.t99.title) 331 | 332 | def test_user_specified_ordering_pub_date(self): 333 | Post.objects.create( 334 | topic=self.t1, 335 | content_raw='reply to post __1__', 336 | user=self.u1, 337 | ) 338 | self.browser.get(self.live_server_url+reverse("niji:index")) 339 | self.browser.find_element_by_link_text( 340 | "Topic Date" 341 | ).click() 342 | first_topic_title = self.browser.find_element_by_class_name( 343 | "entry-link" 344 | ).text 345 | self.assertEqual(first_topic_title, self.t99.title) 346 | 347 | def test_user_specified_ordering_last_replied_pagination(self): 348 | self.browser.get(self.live_server_url+reverse("niji:index")) 349 | self.browser.find_element_by_link_text( 350 | "Last Replied" 351 | ).click() 352 | res = self.client.get(self.browser.current_url) 353 | request = res.wsgi_request 354 | self.assertEqual(request.GET.get("order"), "-last_replied") 355 | self.browser.find_element_by_link_text("»").click() 356 | res = self.client.get(self.browser.current_url) 357 | request = res.wsgi_request 358 | self.assertEqual(request.GET.get("order"), "-last_replied") 359 | 360 | def test_user_specified_ordering_node_view(self): 361 | Post.objects.create( 362 | topic=self.t1, 363 | content_raw='reply to post __1__', 364 | user=self.u1, 365 | ) 366 | self.browser.get( 367 | self.live_server_url+reverse( 368 | "niji:node", 369 | kwargs={"pk": self.n1.pk} 370 | ) 371 | ) 372 | self.browser.find_element_by_link_text( 373 | "Topic Date" 374 | ).click() 375 | first_topic_title = self.browser.find_element_by_class_name( 376 | "entry-link" 377 | ).text 378 | self.assertEqual(first_topic_title, self.t99.title) 379 | 380 | def test_user_specified_ordering_search_view(self): 381 | Post.objects.create( 382 | topic=self.t1, 383 | content_raw='reply to post __1__', 384 | user=self.u1, 385 | ) 386 | self.browser.get( 387 | self.live_server_url+reverse( 388 | "niji:search", 389 | kwargs={"keyword": "test"} 390 | ) 391 | ) 392 | self.browser.find_element_by_link_text( 393 | "Topic Date" 394 | ).click() 395 | first_topic_title = self.browser.find_element_by_class_name( 396 | "entry-link" 397 | ).text 398 | self.assertEqual(first_topic_title, self.t99.title) 399 | 400 | 401 | class LoginRegUrlSettingsTest(LiveServerTestCase): 402 | 403 | def setUp(self): 404 | self.browser = WebDriver() 405 | self.browser.implicitly_wait(3) 406 | self.n1 = Node.objects.create( 407 | title='TestNodeOne', 408 | description='The first test node' 409 | ) 410 | self.u1 = User.objects.create_user( 411 | username='test1', email='1@q.com', password='111' 412 | ) 413 | self.t1 = Topic.objects.create( 414 | title='Test Topic 1', 415 | user=self.u1, 416 | content_raw='This is test topic __1__', 417 | node=self.n1, 418 | ) 419 | 420 | def tearDown(self): 421 | self.browser.quit() 422 | 423 | @override_settings(NIJI_LOGIN_URL_NAME="niji:reg") 424 | def test_login_url_name(self): 425 | self.browser.get(self.live_server_url+reverse("niji:index")) 426 | login_btn = self.browser.find_element_by_link_text("Log in") 427 | self.assertEqual(login_btn.get_attribute("href"), self.live_server_url+reverse("niji:reg")) 428 | 429 | self.browser.get(self.live_server_url+reverse("niji:topic", kwargs={"pk": self.t1.pk})) 430 | login_link = self.browser.find_element_by_link_text("Login") 431 | self.assertEqual(login_link.get_attribute("href"), self.live_server_url+reverse("niji:reg")) 432 | 433 | @override_settings(NIJI_REG_URL_NAME="niji:login") 434 | def test_reg_url_name(self): 435 | self.browser.get(self.live_server_url+reverse("niji:index")) 436 | reg_btn = self.browser.find_element_by_link_text("Reg") 437 | self.assertEqual(reg_btn.get_attribute("href"), self.live_server_url+reverse("niji:login")) 438 | 439 | self.browser.get(self.live_server_url+reverse("niji:topic", kwargs={"pk": self.t1.pk})) 440 | reg_link = self.browser.find_element_by_link_text("Create a New User") 441 | self.assertEqual(reg_link.get_attribute("href"), self.live_server_url+reverse("niji:login")) 442 | 443 | 444 | class TopicModelTest(TestCase): 445 | 446 | def setUp(self): 447 | self.n1 = Node.objects.create( 448 | title='TestNodeOne', 449 | description='The first test node' 450 | ) 451 | self.u1 = User.objects.create_user( 452 | username='test1', email='1@q.com', password='111' 453 | ) 454 | self.u2 = User.objects.create_user( 455 | username='test2', email='2@q.com', password='222' 456 | ) 457 | self.t1 = Topic.objects.create( 458 | title='Test Topic 1', 459 | user=self.u1, 460 | content_raw='This is test topic __1__', 461 | node=self.n1, 462 | ) 463 | self.t2 = Topic.objects.create( 464 | title='Test Topic 2', 465 | user=self.u1, 466 | content_raw='This is test topic __2__', 467 | node=self.n1, 468 | ) 469 | 470 | def test_hidden_topic(self): 471 | self.assertEqual(Topic.objects.visible().count(), 2) 472 | self.t1.hidden = True 473 | self.t1.save() 474 | self.assertEqual(Topic.objects.visible().count(), 1) 475 | 476 | def test_topic_order(self): 477 | self.assertEqual(Topic.objects.visible().first(), self.t2) 478 | self.t1.order = 9 479 | self.t1.save() 480 | self.assertEqual(Topic.objects.visible().first(), self.t1) 481 | 482 | def test_topic_content_hash(self): 483 | original_hash = self.t1.raw_content_hash 484 | self.t1.content_raw = 'fdsfds' 485 | self.t1.save() 486 | self.assertNotEqual(original_hash, self.t1.raw_content_hash) 487 | self.t1.content_raw = 'This is test topic __1__' 488 | self.t1.save() 489 | self.assertEqual(original_hash, self.t1.raw_content_hash) 490 | 491 | def test_content_render(self): 492 | self.assertIn('1', self.t1.content_rendered) 493 | self.t1.content_raw = 'This is the __first__ topic' 494 | self.t1.save() 495 | self.assertIn('first', self.t1.content_rendered) 496 | 497 | def test_last_replied(self): 498 | p = Post() 499 | p.topic = self.t1 500 | p.content_raw = 'reply to post __1__' 501 | p.user = self.u1 502 | p.save() 503 | self.assertEqual(self.t1.last_replied, p.pub_date) 504 | p2 = Post() 505 | p2.topic = self.t1 506 | p2.content_raw = '2nd reply to post __1__' 507 | p2.user = self.u1 508 | p2.save() 509 | self.assertEqual(self.t1.last_replied, p2.pub_date) 510 | p2.delete() 511 | self.assertEqual(self.t1.last_replied, p.pub_date) 512 | p.delete() 513 | self.assertEqual(self.t1.last_replied, self.t1.pub_date) 514 | 515 | def test_reply_count(self): 516 | p = Post() 517 | p.topic = self.t1 518 | p.content_raw = '2nd reply to post __1__' 519 | p.user = self.u1 520 | p.save() 521 | self.assertEqual(self.t1.reply_count, 1) 522 | p.pk += 1 523 | p.save() 524 | self.assertEqual(self.t1.reply_count, 2) 525 | p.hidden = True 526 | p.save() 527 | self.assertEqual(self.t1.reply_count, 1) 528 | p.hidden = False 529 | p.save() 530 | self.assertEqual(self.t1.reply_count, 2) 531 | p.delete() 532 | self.assertEqual(self.t1.reply_count, 1) 533 | 534 | @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, 535 | CELERY_ALWAYS_EAGER=True, 536 | BROKER_BACKEND='memory') 537 | def test_other_user_mention(self): 538 | t = Topic.objects.create( 539 | title='topic mention test', 540 | user=self.u1, 541 | content_raw='test mention @test2', 542 | node=self.n1, 543 | ) 544 | self.assertEqual(self.u2.received_notifications.count(), 1) 545 | notification = Notification.objects.get(pk=1) 546 | self.assertIn( 547 | 'test2' % (reverse("niji:user_info", kwargs={"pk": self.u2.pk})), 548 | t.content_rendered 549 | ) 550 | self.assertEqual(notification.topic_id, t.pk) 551 | self.assertEqual(notification.sender_id, self.u1.pk) 552 | self.assertEqual(notification.to_id, self.u2.pk) 553 | 554 | @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, 555 | CELERY_ALWAYS_EAGER=True, 556 | BROKER_BACKEND='memory') 557 | def test_self_mention(self): 558 | Topic.objects.create( 559 | title='topic mention test', 560 | user=self.u1, 561 | content_raw='test mention myself @test1', 562 | node=self.n1, 563 | ) 564 | self.assertEqual(self.u1.received_notifications.count(), 0) 565 | 566 | 567 | class PostModelTest(TestCase): 568 | 569 | def setUp(self): 570 | self.n1 = Node.objects.create( 571 | title='TestNodeOne', 572 | description='The first test node' 573 | ) 574 | self.u1 = User.objects.create_user( 575 | username='test1', email='1@q.com', password='111' 576 | ) 577 | self.u2 = User.objects.create_user( 578 | username='test2', email='2@q.com', password='222' 579 | ) 580 | self.t1 = Topic.objects.create( 581 | title='Test Topic 1', 582 | user=self.u1, 583 | content_raw='This is test topic __1__', 584 | node=self.n1, 585 | ) 586 | self.p1 = Post.objects.create( 587 | topic=self.t1, 588 | content_raw='reply to post __1__', 589 | user=self.u1, 590 | ) 591 | self.p2 = Post.objects.create( 592 | topic=self.t1, 593 | content_raw='reply to post __2__', 594 | user=self.u1, 595 | ) 596 | 597 | def test_content_render(self): 598 | self.assertIn('1', self.p1.content_rendered) 599 | self.p1.content_raw = 'This is the __first__ reply' 600 | self.p1.save() 601 | self.assertIn('first', self.p1.content_rendered) 602 | 603 | def test_hidden(self): 604 | self.assertEqual(self.t1.replies.visible().count(), 2) 605 | self.p1.hidden = True 606 | self.p1.save() 607 | self.assertEqual(self.t1.replies.visible().count(), 1) 608 | 609 | @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, 610 | CELERY_ALWAYS_EAGER=True, 611 | BROKER_BACKEND='memory') 612 | def test_other_user_mention(self): 613 | p = Post.objects.create( 614 | user=self.u1, 615 | content_raw='test mention @test2', 616 | topic=self.t1, 617 | ) 618 | self.assertEqual(self.u2.received_notifications.count(), 1) 619 | notification = Notification.objects.get(pk=1) 620 | self.assertEqual(notification.post_id, p.pk) 621 | self.assertEqual(notification.sender_id, self.u1.pk) 622 | self.assertEqual(notification.to_id, self.u2.pk) 623 | 624 | @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, 625 | CELERY_ALWAYS_EAGER=True, 626 | BROKER_BACKEND='memory') 627 | def test_self_mention(self): 628 | Post.objects.create( 629 | user=self.u1, 630 | content_raw='test to mention myself @test1', 631 | topic=self.t1, 632 | ) 633 | self.assertEqual(self.u1.received_notifications.count(), 0) 634 | 635 | 636 | class AppendixModelTest(TestCase): 637 | 638 | def setUp(self): 639 | self.n1 = Node.objects.create( 640 | title='TestNodeOne', 641 | description='The first test node' 642 | ) 643 | self.u1 = User.objects.create_user( 644 | username='test1', email='1@q.com', password='111' 645 | ) 646 | self.t1 = Topic.objects.create( 647 | title='Test Topic 1', 648 | user=self.u1, 649 | content_raw='This is test topic __1__', 650 | node=self.n1, 651 | ) 652 | self.a1 = Appendix.objects.create( 653 | topic=self.t1, 654 | content_raw='appendix to topic __1__', 655 | ) 656 | 657 | def test_content_render(self): 658 | self.assertIn('1', self.a1.content_rendered) 659 | self.a1.content_raw = 'appendix to the __first__ topic' 660 | self.a1.save() 661 | self.assertIn('first', self.a1.content_rendered) 662 | 663 | 664 | class VisitorTest(LiveServerTestCase): 665 | """ 666 | Test as a visitor (unregistered user) 667 | """ 668 | 669 | def setUp(self): 670 | self.browser = WebDriver() 671 | self.browser.implicitly_wait(3) 672 | self.n1 = Node.objects.create( 673 | title='TestNodeOne', 674 | description='The first test node' 675 | ) 676 | self.u1 = User.objects.create_user( 677 | username='test1', email='1@q.com', password='111' 678 | ) 679 | self.u2 = User.objects.create_user( 680 | username='test2', email='2@q.com', password='222' 681 | ) 682 | 683 | # Create 99 topics 684 | for i in range(1, 100): 685 | setattr( 686 | self, 687 | 't%s' % i, 688 | Topic.objects.create( 689 | title='Test Topic %s' % i, 690 | user=self.u1, 691 | content_raw='This is test topic __%s__' % i, 692 | node=self.n1 693 | ) 694 | ) 695 | 696 | def tearDown(self): 697 | self.browser.quit() 698 | 699 | def test_index(self): 700 | self.browser.get(self.live_server_url+reverse('niji:index')) 701 | self.assertIn('niji', self.browser.page_source.lower()) 702 | 703 | def test_topic_page_content(self): 704 | self.browser.get(self.live_server_url+reverse('niji:topic', kwargs={'pk': self.t88.pk})) 705 | self.assertIn('This is test topic 88', self.browser.page_source) 706 | 707 | def test_hidden_post(self): 708 | hidden_post = Post.objects.create( 709 | topic=self.t1, 710 | content_raw="i'm a reply 12138", 711 | user=self.u1 712 | ) 713 | self.browser.get(self.live_server_url+reverse('niji:topic', kwargs={'pk': self.t1.pk})) 714 | self.assertIn("i'm a reply 12138", self.browser.page_source) 715 | hidden_post.hidden = True 716 | hidden_post.save() 717 | self.browser.get(self.browser.current_url) 718 | self.assertNotIn("i'm a reply 12138", self.browser.page_source) 719 | 720 | def test_node_page(self): 721 | self.browser.get(self.live_server_url+reverse('niji:node', kwargs={'pk': self.n1.pk})) 722 | topics = self.browser.find_elements_by_css_selector('ul.topic-list > li') 723 | self.assertEqual(len(topics), 30) 724 | 725 | def test_user_login(self): 726 | self.browser.get(self.live_server_url+reverse('niji:index')) 727 | self.assertNotIn("Log out", self.browser.page_source) 728 | login(self.browser, "test1", "111") 729 | self.assertEqual(self.browser.current_url, self.live_server_url+reverse("niji:index")) 730 | self.assertIn("Log out", self.browser.page_source) 731 | 732 | def test_usr_reg(self): 733 | self.browser.get(self.live_server_url+reverse('niji:index')) 734 | self.browser.find_element_by_link_text("Reg").click() 735 | self.assertEqual(self.browser.current_url, self.live_server_url+reverse("niji:reg")) 736 | username = self.browser.find_element_by_name('username') 737 | email = self.browser.find_element_by_name('email') 738 | password1 = self.browser.find_element_by_name('password1') 739 | password2 = self.browser.find_element_by_name('password2') 740 | username.send_keys("test3") 741 | password1.send_keys("333") 742 | password2.send_keys("333") 743 | email.send_keys("test3@example.com") 744 | password1.send_keys(Keys.RETURN) 745 | self.assertEqual(self.browser.current_url, self.live_server_url+reverse("niji:index")) 746 | self.assertIn("Log out", self.browser.page_source) 747 | self.assertIn("test3", self.browser.page_source) 748 | 749 | def test_user_topic(self): 750 | self.browser.get(self.live_server_url+reverse("niji:user_topics", kwargs={"pk": self.u1.id})) 751 | self.assertIn("UID:", self.browser.page_source) 752 | 753 | def test_user_info(self): 754 | self.browser.get(self.live_server_url+reverse("niji:user_info", kwargs={"pk": self.u1.id})) 755 | self.assertIn("Topics created by %s" % self.u1.username, self.browser.page_source) 756 | 757 | def test_search(self): 758 | self.browser.get(self.live_server_url+reverse("niji:search", kwargs={"keyword": "test"})) 759 | self.assertIn("Search: test", self.browser.page_source) 760 | 761 | def test_pagination(self): 762 | self.browser.get(self.live_server_url+reverse("niji:index", kwargs={"page": 2})) 763 | self.assertIn("«", self.browser.page_source) 764 | prev = self.browser.find_element_by_link_text("«") 765 | prev.click() 766 | self.assertNotIn("«", self.browser.page_source) 767 | self.assertIn("»", self.browser.page_source) 768 | nxt = self.browser.find_element_by_link_text("»") 769 | nxt.click() 770 | self.assertEqual(self.browser.current_url, self.live_server_url+reverse("niji:index", kwargs={"page": 2})) 771 | 772 | 773 | class RegisteredUserTest(LiveServerTestCase): 774 | """ 775 | Test as a registered user 776 | """ 777 | 778 | def setUp(self): 779 | self.browser = WebDriver() 780 | self.browser.implicitly_wait(3) 781 | self.n1 = Node.objects.create( 782 | title='TestNodeOne', 783 | description='The first test node' 784 | ) 785 | self.u1 = User.objects.create_user( 786 | username='test1', email='1@q.com', password='111' 787 | ) 788 | self.u2 = User.objects.create_user( 789 | username='test2', email='2@q.com', password='222' 790 | ) 791 | 792 | # Create 198 topics 793 | for i in range(1, 100): 794 | setattr( 795 | self, 796 | 't%s' % i, 797 | Topic.objects.create( 798 | title='Test Topic %s' % i, 799 | user=self.u1, 800 | content_raw='This is test topic __%s__' % i, 801 | node=self.n1 802 | ) 803 | ) 804 | 805 | for i in range(100, 199): 806 | setattr( 807 | self, 808 | 't%s' % i, 809 | Topic.objects.create( 810 | title='Test Topic %s' % i, 811 | user=self.u2, 812 | content_raw='This is test topic __%s__' % i, 813 | node=self.n1 814 | ) 815 | ) 816 | 817 | def tearDown(self): 818 | self.browser.quit() 819 | 820 | def test_edit_own_topic(self): 821 | self.browser.get(self.live_server_url+reverse('niji:index')) 822 | login(self.browser, "test1", "111") 823 | self.assertIn("Log out", self.browser.page_source) 824 | own_topic = getattr(self, "t%s" % (random.choice(range(1, 100)))) 825 | self.browser.get(self.live_server_url+reverse("niji:topic", kwargs={"pk": own_topic.id})) 826 | self.browser.find_element_by_link_text("Edit").click() 827 | content_raw = self.browser.find_element_by_name("content_raw") 828 | content_raw.clear() 829 | content_raw.send_keys("This topic is edited") 830 | self.browser.find_element_by_name("submit").click() 831 | self.assertIn("This topic is edited", self.browser.page_source) 832 | 833 | def test_edit_others_topic(self): 834 | self.browser.get(self.live_server_url+reverse('niji:index')) 835 | login(self.browser, "test1", "111") 836 | self.assertIn("Log out", self.browser.page_source) 837 | others_topic = getattr(self, "t%s" % (random.choice(range(100, 199)))) 838 | self.browser.get(self.live_server_url+reverse("niji:topic", kwargs={"pk": others_topic.id})) 839 | self.assertNotIn( 840 | "Edit", 841 | self.browser.page_source 842 | ) 843 | self.browser.get( 844 | self.live_server_url+reverse("niji:edit_topic", kwargs={"pk": others_topic.id}) 845 | ) 846 | self.assertIn("You are not allowed to edit other's topic", self.browser.page_source) 847 | 848 | def test_reply_topic(self): 849 | self.browser.get(self.live_server_url+reverse('niji:index')) 850 | login(self.browser, "test1", "111") 851 | self.assertIn("Log out", self.browser.page_source) 852 | topic = getattr(self, "t%s" % (random.choice(range(1, 199)))) 853 | self.browser.get(self.live_server_url+reverse("niji:topic", kwargs={"pk": topic.id})) 854 | content_raw = self.browser.find_element_by_name("content_raw") 855 | content_raw.clear() 856 | content_raw.send_keys("This is a reply") 857 | self.browser.find_element_by_name("submit").click() 858 | self.assertIn("This is a reply", self.browser.page_source) 859 | 860 | def test_closed_topic(self): 861 | self.browser.get(self.live_server_url + reverse('niji:index')) 862 | login(self.browser, "test1", "111") 863 | self.assertIn("Log out", self.browser.page_source) 864 | topic = getattr(self, "t%s" % (random.choice(range(1, 199)))) 865 | topic.closed = True 866 | topic.save() 867 | self.browser.get(self.live_server_url + reverse("niji:topic", kwargs={"pk": topic.id})) 868 | self.assertIn(_("This topic is closed"), self.browser.page_source) 869 | 870 | def test_create_topic(self): 871 | self.browser.get(self.live_server_url+reverse('niji:index')) 872 | login(self.browser, "test1", "111") 873 | self.assertIn("Log out", self.browser.page_source) 874 | self.browser.get(self.live_server_url+reverse("niji:create_topic")) 875 | node = self.browser.find_element_by_name("node") 876 | node = Select(node) 877 | title = self.browser.find_element_by_name("title") 878 | content_raw = self.browser.find_element_by_name("content_raw") 879 | node.select_by_visible_text(self.n1.title) 880 | title.send_keys("test title") 881 | content_raw.send_keys("this is content") 882 | self.browser.find_element_by_name("submit").click() 883 | self.assertIn("this is content", self.browser.page_source) 884 | 885 | def test_create_appendix(self): 886 | self.browser.get(self.live_server_url+reverse('niji:index')) 887 | login(self.browser, "test1", "111") 888 | self.assertIn("Log out", self.browser.page_source) 889 | own_topic = getattr(self, "t%s" % (random.choice(range(1, 100)))) 890 | self.browser.get(self.live_server_url+reverse("niji:topic", kwargs={"pk": own_topic.id})) 891 | self.browser.find_element_by_link_text("Append").click() 892 | content_raw = self.browser.find_element_by_name("content_raw") 893 | content_raw.clear() 894 | content_raw.send_keys("This is an appendix") 895 | self.browser.find_element_by_name("submit").click() 896 | self.assertIn("This is an appendix", self.browser.page_source) 897 | -------------------------------------------------------------------------------- /niji/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.conf.urls import url, include 3 | from django.views.decorators.csrf import csrf_exempt 4 | from rest_framework import routers 5 | from . import api 6 | from . import views 7 | 8 | api_router = routers.DefaultRouter() 9 | api_router.register(r'topics', api.TopicApiView) 10 | api_router.register(r'post', api.PostApiView) 11 | 12 | urlpatterns = [ 13 | url(r'^page/(?P[0-9]+)/$', views.Index.as_view(), name='index'), 14 | url(r'^$', views.Index.as_view(), name='index'), 15 | url(r'^n/(?P\d+)/page/(?P[0-9]+)/$', views.NodeView.as_view(), name='node'), 16 | url(r'^n/(?P\d+)/$', views.NodeView.as_view(), name='node'), 17 | url(r'^t/(?P\d+)/edit/$', views.edit_topic, name='edit_topic'), 18 | url(r'^t/(?P\d+)/append/$', views.create_appendix, name='create_appendix'), 19 | url(r'^t/(?P\d+)/page/(?P[0-9]+)/$', views.TopicView.as_view(), name='topic'), 20 | url(r'^t/(?P\d+)/$', views.TopicView.as_view(), name='topic'), 21 | url(r'^u/(?P\d+)/$', views.user_info, name='user_info'), 22 | url(r'^u/(?P\d+)/topics/page/(?P[0-9]+)/$', views.UserTopics.as_view(), name='user_topics'), 23 | url(r'^u/(?P\d+)/topics/$', views.UserTopics.as_view(), name='user_topics'), 24 | url(r'^login/$', views.login_view, name='login'), 25 | url(r'^reg/$', views.reg_view, name='reg'), 26 | url(r'^logout/$', views.logout_view, name="logout"), 27 | url(r'^search/$', views.search_redirect, name='search_redirect'), 28 | url(r'^search/(?P.*?)/page/(?P[0-9]+)/$', views.SearchView.as_view(), name='search'), 29 | url(r'^search/(?P.*?)/$', views.SearchView.as_view(), name='search'), 30 | url(r'^t/create/$', views.create_topic, name='create_topic'), 31 | url(r'^notifications/$', views.NotificationView.as_view(), name='notifications'), 32 | url(r'^avatar/$', views.upload_avatar, name="upload_avatar"), 33 | url(r'^api/', include(api_router.urls)), 34 | ] 35 | -------------------------------------------------------------------------------- /niji/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.shortcuts import render 3 | from django.http import HttpResponseRedirect, HttpResponseForbidden 4 | from django.core.urlresolvers import reverse 5 | from django.contrib.auth import authenticate, login, logout 6 | from django.contrib import messages 7 | from django.contrib.auth import get_user_model 8 | from django.conf import settings 9 | from django.views.generic import ListView 10 | from django.utils.translation import ugettext as _ 11 | from django.utils.decorators import method_decorator 12 | from django.contrib.auth.decorators import login_required 13 | from .models import Topic, Node, Post, Notification, ForumAvatar 14 | from .forms import TopicForm, TopicEditForm, AppendixForm, ForumAvatarForm, ReplyForm 15 | from .misc import get_query 16 | import re 17 | 18 | EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+") 19 | User = get_user_model() 20 | 21 | 22 | def get_default_ordering(): 23 | return getattr( 24 | settings, 25 | "NIJI_DEFAULT_TOPIC_ORDERING", 26 | "-last_replied" 27 | ) 28 | 29 | 30 | def get_topic_ordering(request): 31 | query_order = request.GET.get("order", "") 32 | if query_order in ["-last_replied", "last_replied", "pub_date", "-pub_date"]: 33 | return query_order 34 | return get_default_ordering() 35 | 36 | 37 | # Create your views here. 38 | class Index(ListView): 39 | model = Topic 40 | paginate_by = 30 41 | template_name = 'niji/index.html' 42 | context_object_name = 'topics' 43 | 44 | def get_queryset(self): 45 | return Topic.objects.visible().select_related( 46 | 'user', 'node' 47 | ).prefetch_related( 48 | 'user__forum_avatar' 49 | ).order_by( 50 | *['order', get_topic_ordering(self.request)] 51 | ) 52 | 53 | def get_context_data(self, **kwargs): 54 | context = super(ListView, self).get_context_data(**kwargs) 55 | context['panel_title'] = _('New Topics') 56 | context['title'] = _('Index') 57 | context['show_order'] = True 58 | return context 59 | 60 | 61 | class NodeView(ListView): 62 | model = Topic 63 | paginate_by = 30 64 | template_name = 'niji/node.html' 65 | context_object_name = 'topics' 66 | 67 | def get_queryset(self): 68 | return Topic.objects.visible().filter( 69 | node__id=self.kwargs.get('pk') 70 | ).select_related( 71 | 'user', 'node' 72 | ).prefetch_related( 73 | 'user__forum_avatar' 74 | ).order_by( 75 | *['order', get_topic_ordering(self.request)] 76 | ) 77 | 78 | def get_context_data(self, **kwargs): 79 | context = super(ListView, self).get_context_data(**kwargs) 80 | context['node'] = node = Node.objects.get(pk=self.kwargs.get('pk')) 81 | context['title'] = context['panel_title'] = node.title 82 | context['show_order'] = True 83 | return context 84 | 85 | 86 | class TopicView(ListView): 87 | model = Post 88 | paginate_by = 30 89 | template_name = 'niji/topic.html' 90 | context_object_name = 'posts' 91 | 92 | def get_queryset(self): 93 | return Post.objects.visible().filter( 94 | topic_id=self.kwargs.get('pk') 95 | ).select_related( 96 | 'user' 97 | ).prefetch_related( 98 | 'user__forum_avatar' 99 | ).order_by('pub_date') 100 | 101 | def get_context_data(self, **kwargs): 102 | context = super(ListView, self).get_context_data(**kwargs) 103 | current = Topic.objects.visible().get(pk=self.kwargs.get('pk')) 104 | current.increase_view_count() 105 | context['topic'] = current 106 | context['title'] = context['topic'].title 107 | context['node'] = context['topic'].node 108 | context['form'] = ReplyForm() 109 | return context 110 | 111 | @method_decorator(login_required) 112 | def post(self, request, *args, **kwargs): 113 | current = Topic.objects.visible().get(pk=self.kwargs.get('pk')) 114 | if current.closed: 115 | return HttpResponseForbidden("Topic closed") 116 | topic_id = self.kwargs.get('pk') 117 | form = ReplyForm( 118 | request.POST, 119 | user=request.user, 120 | topic_id=topic_id 121 | ) 122 | if form.is_valid(): 123 | form.save() 124 | return HttpResponseRedirect( 125 | reverse('niji:topic', kwargs={'pk': topic_id}) 126 | ) 127 | 128 | 129 | def user_info(request, pk): 130 | u = User.objects.get(pk=pk) 131 | return render(request, 'niji/user_info.html', { 132 | 'title': u.username, 133 | 'user': u, 134 | 'topics': u.topics.visible().select_related('node')[:10], 135 | 'replies': u.posts.visible().select_related('topic', 'user').order_by('-pub_date')[:30], 136 | }) 137 | 138 | 139 | class UserTopics(ListView): 140 | model = Post 141 | paginate_by = 30 142 | template_name = 'niji/user_topics.html' 143 | context_object_name = 'topics' 144 | 145 | def get_queryset(self): 146 | return Topic.objects.visible().filter( 147 | user_id=self.kwargs.get('pk') 148 | ).select_related( 149 | 'user', 'node' 150 | ).prefetch_related( 151 | 'user__forum_avatar' 152 | ) 153 | 154 | def get_context_data(self, **kwargs): 155 | context = super(ListView, self).get_context_data(**kwargs) 156 | context['user'] = User.objects.get(pk=self.kwargs.get('pk')) 157 | context['panel_title'] = context['title'] = context['user'].username 158 | return context 159 | 160 | 161 | class SearchView(ListView): 162 | model = Topic 163 | paginate_by = 30 164 | template_name = 'niji/search.html' 165 | context_object_name = 'topics' 166 | 167 | def get_queryset(self): 168 | keywords = self.kwargs.get('keyword') 169 | query = get_query(keywords, ['title']) 170 | return Topic.objects.visible().filter( 171 | query 172 | ).select_related( 173 | 'user', 'node' 174 | ).prefetch_related( 175 | 'user__forum_avatar' 176 | ).order_by( 177 | get_topic_ordering(self.request) 178 | ) 179 | 180 | def get_context_data(self, **kwargs): 181 | context = super(ListView, self).get_context_data(**kwargs) 182 | context['title'] = context['panel_title'] = _('Search: ') + self.kwargs.get('keyword') 183 | context['show_order'] = True 184 | return context 185 | 186 | 187 | def search_redirect(request): 188 | if request.method == 'GET': 189 | keyword = request.GET.get('keyword') 190 | return HttpResponseRedirect(reverse('niji:search', kwargs={'keyword': keyword})) 191 | else: 192 | return HttpResponseForbidden('Post you cannot') 193 | 194 | 195 | @login_required 196 | def create_topic(request): 197 | if request.method == 'POST': 198 | form = TopicForm(request.POST, user=request.user) 199 | if form.is_valid(): 200 | t = form.save() 201 | return HttpResponseRedirect(reverse('niji:topic', kwargs={'pk': t.pk})) 202 | else: 203 | form = TopicForm() 204 | 205 | return render(request, 'niji/create_topic.html', {'form': form, 'title': _('Create Topic')}) 206 | 207 | 208 | @login_required 209 | def edit_topic(request, pk): 210 | topic = Topic.objects.get(pk=pk) 211 | if topic.reply_count > 0: 212 | return HttpResponseForbidden(_('Editing is not allowed when topic has been replied')) 213 | if not topic.user == request.user: 214 | return HttpResponseForbidden(_('You are not allowed to edit other\'s topic')) 215 | if request.method == 'POST': 216 | form = TopicEditForm(request.POST, instance=topic) 217 | if form.is_valid(): 218 | t = form.save() 219 | return HttpResponseRedirect(reverse('niji:topic', kwargs={'pk': t.pk})) 220 | else: 221 | form = TopicEditForm(instance=topic) 222 | 223 | return render(request, 'niji/edit_topic.html', {'form': form, 'title': _('Edit Topic')}) 224 | 225 | 226 | @login_required 227 | def create_appendix(request, pk): 228 | topic = Topic.objects.get(pk=pk) 229 | if not topic.user == request.user: 230 | return HttpResponseForbidden(_('You are not allowed to append other\'s topic')) 231 | if request.method == 'POST': 232 | form = AppendixForm(request.POST, topic=topic) 233 | if form.is_valid(): 234 | form.save() 235 | return HttpResponseRedirect(reverse('niji:topic', kwargs={'pk': topic.pk})) 236 | else: 237 | form = AppendixForm() 238 | 239 | return render(request, 'niji/create_appendix.html', { 240 | 'form': form, 'title': _('Create Appendix'), 'pk': pk 241 | }) 242 | 243 | 244 | @login_required 245 | def upload_avatar(request): 246 | avatar = ForumAvatar.objects.filter(user_id=request.user.id).first() 247 | if request.method == 'POST': 248 | if avatar: 249 | form = ForumAvatarForm(request.POST, request.FILES, instance=avatar, user=request.user) 250 | else: 251 | form = ForumAvatarForm(request.POST, request.FILES, user=request.user) 252 | if form.is_valid(): 253 | form.save() 254 | return HttpResponseRedirect(reverse('niji:index')) 255 | else: 256 | if avatar: 257 | form = ForumAvatarForm(instance=request.user.forum_avatar) 258 | else: 259 | form = ForumAvatarForm() 260 | 261 | return render(request, 'niji/upload_avatar.html', {'form': form, 'title': _('Upload Avatar')}) 262 | 263 | 264 | @login_required 265 | def notification_view(request): 266 | notifications = request.user.received_notifications.all().order_by('-pub_date') 267 | Notification.objects.filter(to=request.user).update(read=True) 268 | return render(request, 'niji/notifications.html', { 269 | 'title': _("Notifications"), 270 | 'notifications': notifications, 271 | }) 272 | 273 | 274 | class NotificationView(ListView): 275 | 276 | model = Notification 277 | paginate_by = 30 278 | template_name = 'niji/notifications.html' 279 | context_object_name = 'notifications' 280 | 281 | def get_queryset(self): 282 | Notification.objects.filter(to=self.request.user).update(read=True) 283 | return Notification.objects.filter( 284 | to=self.request.user 285 | ).select_related( 286 | 'sender', 'topic', 'post' 287 | ).prefetch_related( 288 | 'sender__forum_avatar', 'post__topic' 289 | ).order_by('-pub_date') 290 | 291 | def get_context_data(self, **kwargs): 292 | context = super(ListView, self).get_context_data(**kwargs) 293 | context['title'] = _("Notifications") 294 | return context 295 | 296 | 297 | def login_view(request): 298 | if request.method == "GET": 299 | return render(request, 'niji/login.html', {'title': _("Login")}) 300 | if request.method == "POST": 301 | username = request.POST.get('username') 302 | password = request.POST.get('password') 303 | valid = True 304 | if not username or not password: 305 | valid = False 306 | messages.add_message(request, messages.INFO, _("Username and password cannot be empty")) 307 | user = User.objects.filter(username=username).first() 308 | if not user: 309 | valid = False 310 | messages.add_message(request, messages.INFO, _("User does not exist")) 311 | user = authenticate(username=username, password=password) 312 | if (user is not None) and valid: 313 | if user.is_active: 314 | login(request, user) 315 | return HttpResponseRedirect(reverse('niji:index')) 316 | else: 317 | valid = False 318 | messages.add_message(request, messages.INFO, _("User deactivated")) 319 | else: 320 | valid = False 321 | messages.add_message(request, messages.INFO, _("Incorrect password")) 322 | if not valid: 323 | return HttpResponseRedirect(reverse("niji:login")) 324 | 325 | 326 | def reg_view(request): 327 | if request.method == "GET": 328 | return render(request, 'niji/reg.html', {'title': _("Reg")}) 329 | if request.method == "POST": 330 | username = request.POST.get("username") 331 | email = request.POST.get("email") 332 | password = request.POST.get("password1") 333 | password2 = request.POST.get("password2") 334 | valid = True 335 | if User.objects.filter(username=username).exists(): 336 | valid = False 337 | messages.add_message(request, messages.INFO, _("User already exists")) 338 | if password != password2: 339 | valid = False 340 | messages.add_message(request, messages.INFO, _("Password does not match")) 341 | if not EMAIL_REGEX.match(email): 342 | valid = False 343 | messages.add_message(request, messages.INFO, _("Invalid Email")) 344 | if not valid: 345 | return HttpResponseRedirect(reverse("niji:reg")) 346 | else: 347 | User.objects.create_user( 348 | username=username, 349 | password=password, 350 | email=email 351 | ) 352 | user = authenticate( 353 | username=username, 354 | password=password 355 | ) 356 | login(request, user) 357 | return HttpResponseRedirect(reverse("niji:index")) 358 | 359 | 360 | @login_required 361 | def logout_view(request): 362 | logout(request) 363 | return HttpResponseRedirect(reverse("niji:index")) 364 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | mistune 2 | wheel>=0.24.0 3 | Django>=1.9 4 | xxhash==0.6.1 5 | celery[redis] 6 | django-crispy-forms>=1.6.0 7 | six 8 | pillow 9 | djangorestframework 10 | -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings' 3 | current_dir = os.path.dirname(__file__) 4 | sys.path.insert(0, current_dir) 5 | 6 | from django.test.utils import get_runner 7 | from django.conf import settings 8 | 9 | import django 10 | django.setup() 11 | 12 | from celery import Celery 13 | app = Celery('project_name') 14 | 15 | app.config_from_object('django.conf:settings') 16 | app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) 17 | 18 | 19 | def runtests(): 20 | TestRunner = get_runner(settings) 21 | test_runner = TestRunner(verbosity=1, interactive=True) 22 | failures = test_runner.run_tests(['niji']) 23 | sys.exit(bool(failures)) 24 | 25 | 26 | if __name__ == "__main__": 27 | runtests() 28 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | import os 3 | 4 | try: 5 | import pypandoc 6 | long_description = pypandoc.convert('README.md', 'rst', 'md') 7 | except(IOError, ImportError): 8 | long_description = open('README.md').read() 9 | 10 | os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) 11 | 12 | setup( 13 | name='django-niji', 14 | version='0.1.0', 15 | packages=find_packages(), 16 | include_package_data=True, 17 | license='MIT License', 18 | description='A pluggable forum APP for Django', 19 | long_description=long_description, 20 | url='https://github.com/ericls/niji', 21 | author='Shen Li', 22 | author_email='dustet@gmail.com', 23 | install_requires=[ 24 | "Django>=1.8.1,<1.11", 25 | "mistune>=0.7.3", 26 | "celery>=3.1", 27 | "redis", 28 | "django-crispy-forms", 29 | "six", 30 | "Pillow", 31 | "xxhash==0.6.1", 32 | "djangorestframework", 33 | ], 34 | classifiers=[ 35 | 'Environment :: Web Environment', 36 | 'Framework :: Django', 37 | 'Intended Audience :: Developers', 38 | 'License :: OSI Approved :: MIT License', 39 | 'Operating System :: OS Independent', 40 | 'Programming Language :: Python', 41 | "Programming Language :: Python :: 2.7", 42 | "Programming Language :: Python :: 3.4", 43 | "Programming Language :: Python :: 3.5", 44 | 'Topic :: Internet :: WWW/HTTP', 45 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 46 | ], 47 | ) -------------------------------------------------------------------------------- /test_settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | A settings file for running tests 3 | """ 4 | 5 | import os 6 | 7 | BASE_DIR = os.path.dirname(os.path.abspath(__file__)) 8 | 9 | SECRET_KEY = 'testsettings' 10 | DEBUG = True 11 | 12 | ALLOWED_HOSTS = [] 13 | 14 | INSTALLED_APPS = [ 15 | 'django.contrib.admin', 16 | 'django.contrib.auth', 17 | 'django.contrib.contenttypes', 18 | 'django.contrib.sessions', 19 | 'django.contrib.messages', 20 | 'django.contrib.staticfiles', 21 | 'django.contrib.humanize', 22 | 'crispy_forms', 23 | 'niji', 24 | 'rest_framework', 25 | ] 26 | 27 | MIDDLEWARE_CLASSES = [ 28 | 'django.middleware.security.SecurityMiddleware', 29 | 'django.contrib.sessions.middleware.SessionMiddleware', 30 | 'django.middleware.common.CommonMiddleware', 31 | 'django.middleware.csrf.CsrfViewMiddleware', 32 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 33 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 34 | 'django.contrib.messages.middleware.MessageMiddleware', 35 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 36 | ] 37 | 38 | ROOT_URLCONF = 'test_url' 39 | 40 | TEMPLATES = [ 41 | { 42 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 43 | 'DIRS': [], 44 | 'APP_DIRS': True, 45 | 'OPTIONS': { 46 | 'context_processors': [ 47 | 'django.template.context_processors.debug', 48 | 'django.template.context_processors.request', 49 | 'django.contrib.auth.context_processors.auth', 50 | 'django.contrib.messages.context_processors.messages', 51 | ], 52 | }, 53 | }, 54 | ] 55 | 56 | DATABASES = { 57 | 'default': { 58 | 'ENGINE': 'django.db.backends.sqlite3', 59 | 'NAME': ':memory:', 60 | } 61 | } 62 | 63 | AUTH_PASSWORD_VALIDATORS = [ 64 | { 65 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 66 | }, 67 | { 68 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 69 | }, 70 | { 71 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 72 | }, 73 | { 74 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 75 | }, 76 | ] 77 | 78 | TEMPLATES[0]['OPTIONS']['context_processors'].append("niji.context_processors.niji_processor") 79 | 80 | CELERY_ACCEPT_CONTENT = ['json'] 81 | CELERY_TASK_SERIALIZER = 'json' 82 | CELERY_RESULT_SERIALIZER = 'json' 83 | BROKER_BACKEND = 'memory' 84 | CELERY_EAGER_PROPAGATES_EXCEPTIONS = True 85 | CELERY_ALWAYS_EAGER = True 86 | 87 | STATIC_URL = "/static/" 88 | STATIC_ROOT = os.path.join(BASE_DIR, "niji/static") 89 | 90 | REST_FRAMEWORK = { 91 | 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',), 92 | 'PAGE_SIZE': 10 93 | } 94 | -------------------------------------------------------------------------------- /test_url.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url, include 2 | from niji import urls as niji_urls 3 | 4 | urlpatterns = [ 5 | url(r'testurl', include(niji_urls, namespace="niji")), 6 | ] 7 | --------------------------------------------------------------------------------