├── .gitignore ├── AUTHORS.txt ├── LICENSE.txt ├── MANIFEST.in ├── README.rst ├── dev-requirements.txt ├── docs ├── Makefile ├── conf.py ├── customization.rst ├── getting-started.rst ├── index.rst └── make.bat ├── example ├── __init__.py ├── manage.py ├── settings.py ├── templates │ └── home.html └── urls.py ├── fack ├── __init__.py ├── _testrunner.py ├── admin.py ├── fixtures │ └── faq_test_data.json ├── forms.py ├── managers.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── templates │ └── faq │ │ ├── base.html │ │ ├── question_detail.html │ │ ├── submit_question.html │ │ ├── submit_thanks.html │ │ ├── topic_detail.html │ │ └── topic_list.html ├── templatetags │ ├── __init__.py │ └── faqtags.py ├── tests │ ├── __init__.py │ ├── templates │ │ ├── 404.html │ │ └── 500.html │ ├── test_admin.py │ ├── test_models.py │ ├── test_templatetags.py │ └── test_views.py ├── urls.py └── views.py ├── setup.cfg ├── setup.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.bak 3 | *.db 4 | *.egg-info 5 | .tox/ 6 | .coverage 7 | htmlcov/ 8 | docs/_build 9 | dist/ 10 | -------------------------------------------------------------------------------- /AUTHORS.txt: -------------------------------------------------------------------------------- 1 | Django-FAQ was originally created by Kevin Fricovsky. 2 | 3 | Other contributors: 4 | 5 | * Brian Rosner 6 | * Greg Newman 7 | * Jacob Kaplan-Moss 8 | * Jannis Leidel 9 | * Justin Lilly 10 | * Peter Baumgartner 11 | * Rock Howard 12 | * Sean O'Connor 13 | * Frank Wiles 14 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011 Kevin Fricovsky and contributors. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | 1. Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | 10 | 2. Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | 3. Neither the name of this project nor the names of its contributors may 15 | be used to endorse or promote products derived from this software without 16 | specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.txt 2 | include LICENSE.txt 3 | include README.rst 4 | include MANIFEST.in 5 | recursive-include fack/fixtures * 6 | recursive-include fack/templates * 7 | recursive-include docs *.rst *.py *.bat Makefile 8 | recursive-include example *.py *.html -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =========== 2 | Django-Fack 3 | =========== 4 | 5 | This is a simple FAQ application for a Django powered site, featuring: 6 | 7 | * The basic Q&A model you'd expect. 8 | 9 | * Question are grouped into topics. 10 | 11 | * Topics can be ordered and arranged, as can questions within topics. 12 | 13 | * Built-in views to drill down by topic and question, and individual 14 | question detail pages (for permalinks). 15 | 16 | * A view for users to submit new questions (with or without answers). These 17 | go into moderation queue and need to be marked "active" before they'll 18 | show up on the site. 19 | 20 | There's an example app (distributed with the source) to try out if you'd like 21 | to get a taste of the app. 22 | 23 | For more details, `see the documentation`__ 24 | 25 | __ http://django-fack.rtfd.org/ 26 | 27 | Requirements 28 | ============ 29 | 30 | Django 1.3+, Python 2.6+. 31 | 32 | Installation 33 | ============ 34 | 35 | 1. ``pip install django-fack`` 36 | 37 | 2. Add ``"fack"`` to your ``INSTALLED_APPS`` setting. 38 | 39 | 3. Wire up the FAQ views by adding a line to your URLconf:: 40 | 41 | url('^faq/', include('fack.urls')) 42 | 43 | 44 | If you'd like to load some example data then run ``python manage.py loaddata 45 | faq_test_data.json`` 46 | 47 | The app's written with quite a bit of customization in mind; `see the customization documentation`__ for details. 48 | 49 | __ http://django-fack.rtfd.org/en/latest/customization.html 50 | 51 | Example Site 52 | ============ 53 | 54 | There is a stand-alone example site distributed with the source in the 55 | `example/` directory. To try it out: 56 | 57 | 1. Install django-Fack (see above). 58 | 59 | 1. Run ``python manage.py syncdb`` 60 | 61 | This assumes that sqlite3 is available; if not you'll need to change the 62 | ``DATABASES`` setting first. 63 | 64 | 3. Load some example data by running 65 | ``python manage.py loaddata faq_test_data.json`` 66 | 67 | 4. Run ``python manage.py runserver`` and you will have the example site up and 68 | running. The home page will have links to get to the available views as well 69 | as to the admin. 70 | 71 | The capability to submit an FAQ is available and works whether or not you are a 72 | logged in user. Note that a staff member will have to use the admin and review 73 | any submitted FAQs and clean them up and set them to active before they are 74 | viewable by the end user views. 75 | 76 | Contributing 77 | ============ 78 | 79 | To run the tests, install tox__ (``pip install tox``) then run ``tox``. 80 | 81 | __ http://codespeak.net/tox/ 82 | 83 | Development `takes place on GitHub`__. Bug reports, pataches, and pull requests 84 | are always welcome! 85 | 86 | __ https://github.com/revsys/django-fack 87 | -------------------------------------------------------------------------------- /dev-requirements.txt: -------------------------------------------------------------------------------- 1 | # Dependencies required to develop/test this app. 2 | 3 | coverage 4 | mock 5 | tox 6 | -------------------------------------------------------------------------------- /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) . 14 | 15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 16 | 17 | help: 18 | @echo "Please use \`make ' where is one of" 19 | @echo " html to make standalone HTML files" 20 | @echo " dirhtml to make HTML files named index.html in directories" 21 | @echo " singlehtml to make a single large HTML file" 22 | @echo " pickle to make pickle files" 23 | @echo " json to make JSON files" 24 | @echo " htmlhelp to make HTML files and a HTML help project" 25 | @echo " qthelp to make HTML files and a qthelp project" 26 | @echo " devhelp to make HTML files and a Devhelp project" 27 | @echo " epub to make an epub" 28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 29 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 30 | @echo " text to make text files" 31 | @echo " man to make manual pages" 32 | @echo " changes to make an overview of all changed/added/deprecated items" 33 | @echo " linkcheck to check all external links for integrity" 34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 35 | 36 | clean: 37 | -rm -rf $(BUILDDIR)/* 38 | 39 | html: 40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 41 | @echo 42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 43 | 44 | dirhtml: 45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 48 | 49 | singlehtml: 50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 51 | @echo 52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 53 | 54 | pickle: 55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 56 | @echo 57 | @echo "Build finished; now you can process the pickle files." 58 | 59 | json: 60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 61 | @echo 62 | @echo "Build finished; now you can process the JSON files." 63 | 64 | htmlhelp: 65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 66 | @echo 67 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 68 | ".hhp project file in $(BUILDDIR)/htmlhelp." 69 | 70 | qthelp: 71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 72 | @echo 73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-fack.qhcp" 76 | @echo "To view the help file:" 77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-fack.qhc" 78 | 79 | devhelp: 80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 81 | @echo 82 | @echo "Build finished." 83 | @echo "To view the help file:" 84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/django-fack" 85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-fack" 86 | @echo "# devhelp" 87 | 88 | epub: 89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 90 | @echo 91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 92 | 93 | latex: 94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 95 | @echo 96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 97 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 98 | "(use \`make latexpdf' here to do that automatically)." 99 | 100 | latexpdf: 101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 102 | @echo "Running LaTeX files through pdflatex..." 103 | make -C $(BUILDDIR)/latex all-pdf 104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 105 | 106 | text: 107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 108 | @echo 109 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 110 | 111 | man: 112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 113 | @echo 114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 115 | 116 | changes: 117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 118 | @echo 119 | @echo "The overview file is in $(BUILDDIR)/changes." 120 | 121 | linkcheck: 122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 123 | @echo 124 | @echo "Link check complete; look for any errors in the above output " \ 125 | "or in $(BUILDDIR)/linkcheck/output.txt." 126 | 127 | doctest: 128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 129 | @echo "Testing of doctests in the sources finished, look at the " \ 130 | "results in $(BUILDDIR)/doctest/output.txt." 131 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # django-fack documentation build configuration file, created by 4 | # sphinx-quickstart on Wed May 11 12:25:13 2011. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = [] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'django-fack' 44 | copyright = u'2011, Kevin Fricovsky, Jacob Kaplan-Moss' 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | # The short X.Y version. 51 | version = '1.1' 52 | # The full version, including alpha/beta/rc tags. 53 | release = '1.1' 54 | 55 | # The language for content autogenerated by Sphinx. Refer to documentation 56 | # for a list of supported languages. 57 | #language = None 58 | 59 | # There are two options for replacing |today|: either, you set today to some 60 | # non-false value, then it is used: 61 | #today = '' 62 | # Else, today_fmt is used as the format for a strftime call. 63 | #today_fmt = '%B %d, %Y' 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | exclude_patterns = ['_build'] 68 | 69 | # The reST default role (used for this markup: `text`) to use for all documents. 70 | #default_role = None 71 | 72 | # If true, '()' will be appended to :func: etc. cross-reference text. 73 | #add_function_parentheses = True 74 | 75 | # If true, the current module name will be prepended to all description 76 | # unit titles (such as .. function::). 77 | #add_module_names = True 78 | 79 | # If true, sectionauthor and moduleauthor directives will be shown in the 80 | # output. They are ignored by default. 81 | #show_authors = False 82 | 83 | # The name of the Pygments (syntax highlighting) style to use. 84 | pygments_style = 'sphinx' 85 | 86 | # A list of ignored prefixes for module index sorting. 87 | #modindex_common_prefix = [] 88 | 89 | 90 | # -- Options for HTML output --------------------------------------------------- 91 | 92 | # The theme to use for HTML and HTML Help pages. See the documentation for 93 | # a list of builtin themes. 94 | html_theme = 'default' 95 | 96 | # Theme options are theme-specific and customize the look and feel of a theme 97 | # further. For a list of options available for each theme, see the 98 | # documentation. 99 | #html_theme_options = {} 100 | 101 | # Add any paths that contain custom themes here, relative to this directory. 102 | #html_theme_path = [] 103 | 104 | # The name for this set of Sphinx documents. If None, it defaults to 105 | # " v documentation". 106 | #html_title = None 107 | 108 | # A shorter title for the navigation bar. Default is the same as html_title. 109 | #html_short_title = None 110 | 111 | # The name of an image file (relative to this directory) to place at the top 112 | # of the sidebar. 113 | #html_logo = None 114 | 115 | # The name of an image file (within the static path) to use as favicon of the 116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 117 | # pixels large. 118 | #html_favicon = None 119 | 120 | # Add any paths that contain custom static files (such as style sheets) here, 121 | # relative to this directory. They are copied after the builtin static files, 122 | # so a file named "default.css" will overwrite the builtin "default.css". 123 | html_static_path = ['_static'] 124 | 125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 126 | # using the given strftime format. 127 | #html_last_updated_fmt = '%b %d, %Y' 128 | 129 | # If true, SmartyPants will be used to convert quotes and dashes to 130 | # typographically correct entities. 131 | #html_use_smartypants = True 132 | 133 | # Custom sidebar templates, maps document names to template names. 134 | #html_sidebars = {} 135 | 136 | # Additional templates that should be rendered to pages, maps page names to 137 | # template names. 138 | #html_additional_pages = {} 139 | 140 | # If false, no module index is generated. 141 | #html_domain_indices = True 142 | 143 | # If false, no index is generated. 144 | #html_use_index = True 145 | 146 | # If true, the index is split into individual pages for each letter. 147 | #html_split_index = False 148 | 149 | # If true, links to the reST sources are added to the pages. 150 | #html_show_sourcelink = True 151 | 152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 153 | #html_show_sphinx = True 154 | 155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 156 | #html_show_copyright = True 157 | 158 | # If true, an OpenSearch description file will be output, and all pages will 159 | # contain a tag referring to it. The value of this option must be the 160 | # base URL from which the finished HTML is served. 161 | #html_use_opensearch = '' 162 | 163 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 164 | #html_file_suffix = None 165 | 166 | # Output file base name for HTML help builder. 167 | htmlhelp_basename = 'django-fackdoc' 168 | 169 | 170 | # -- Options for LaTeX output -------------------------------------------------- 171 | 172 | # The paper size ('letter' or 'a4'). 173 | #latex_paper_size = 'letter' 174 | 175 | # The font size ('10pt', '11pt' or '12pt'). 176 | #latex_font_size = '10pt' 177 | 178 | # Grouping the document tree into LaTeX files. List of tuples 179 | # (source start file, target name, title, author, documentclass [howto/manual]). 180 | latex_documents = [ 181 | ('index', 'django-fack.tex', u'django-fack Documentation', 182 | u'Kevin Fricovsky, Jacob Kaplan-Moss', 'manual'), 183 | ] 184 | 185 | # The name of an image file (relative to this directory) to place at the top of 186 | # the title page. 187 | #latex_logo = None 188 | 189 | # For "manual" documents, if this is true, then toplevel headings are parts, 190 | # not chapters. 191 | #latex_use_parts = False 192 | 193 | # If true, show page references after internal links. 194 | #latex_show_pagerefs = False 195 | 196 | # If true, show URL addresses after external links. 197 | #latex_show_urls = False 198 | 199 | # Additional stuff for the LaTeX preamble. 200 | #latex_preamble = '' 201 | 202 | # Documents to append as an appendix to all manuals. 203 | #latex_appendices = [] 204 | 205 | # If false, no module index is generated. 206 | #latex_domain_indices = True 207 | 208 | 209 | # -- Options for manual page output -------------------------------------------- 210 | 211 | # One entry per manual page. List of tuples 212 | # (source start file, name, description, authors, manual section). 213 | man_pages = [ 214 | ('index', 'django-fack', u'django-fack Documentation', 215 | [u'Kevin Fricovsky, Jacob Kaplan-Moss'], 1) 216 | ] 217 | 218 | 219 | # Example configuration for intersphinx: refer to the Python standard library. 220 | intersphinx_mapping = {'http://docs.python.org/': None} 221 | -------------------------------------------------------------------------------- /docs/customization.rst: -------------------------------------------------------------------------------- 1 | Customizing Django-Fack 2 | ======================= 3 | 4 | .. _custom-templates: 5 | 6 | Customizing templates 7 | --------------------- 8 | 9 | The one thing you'll probably want to do quickly is to make some custom 10 | templates so that the FAQ app "fits" with the rest of your site. Django-Fack 11 | uses the following templates: 12 | 13 | ============================== ============================================ 14 | Template name Use 15 | ============================== ============================================ 16 | ``faq/base.html`` The base template that all the other 17 | included templates extend by default. For a 18 | quick and dirty customization you can just 19 | override this one template, making sure to 20 | provide a ``content`` block, and 21 | everything'll look OK. 22 | 23 | But to get a more custom feel you'll 24 | probably want to move on 25 | 26 | ``faq/question_detail.html`` Used by an individual "question" detail 27 | page. 28 | 29 | The context has one variable, ``question``, 30 | which is the :class:`Question` object. 31 | 32 | ``faq/submit_question.html`` Used by the view that allows users to submit 33 | a question. 34 | 35 | The context has the obligatory ``form`` 36 | variable, which is a form containing 37 | ``topic``, ``text``, and ``answer`` fields. 38 | 39 | ``faq/submit_thanks.html`` Shown after a successful FAQ submission. 40 | No context. 41 | 42 | ``faq/topic_detail.html`` Shows all the FAQs in a given topic. 43 | 44 | Context: 45 | * ``topic`` - a :class:`Topic`. 46 | * ``questions`` - list of 47 | :class:`Question` objects in the given 48 | topic. 49 | 50 | ``faq/topic_list.html`` Shows a list of all topics. Context 51 | contains a ``topic`` variable, which is 52 | a :class:`Topic` object. 53 | ============================== ============================================ 54 | 55 | Subclassing FAQ views 56 | --------------------- 57 | 58 | All of the views in Django-Fack use `class-based generic views`__ and are 59 | designed to be extended. `Consulting the source`__ is your best bet here: 60 | the code's fairly clear, and prose will only complicate things. 61 | 62 | If you do choose to subclass views, you'll most likely want to write your 63 | own URLconf (instead of ``fack.urls``). Remember that if you maintain the 64 | names given by the default URLconf all the existing links will continue 65 | to work. 66 | 67 | __ http://docs.djangoproject.com/en/dev/topics/class-based-views/ 68 | __ https://github.com/revsys/django-fack/blob/master/fack/views.py -------------------------------------------------------------------------------- /docs/getting-started.rst: -------------------------------------------------------------------------------- 1 | Getting starting with Django-Fack 2 | ================================= 3 | 4 | Installation 5 | ------------ 6 | 7 | 1. ``pip install django-fack`` 8 | 9 | 2. Add ``"fack"`` to your ``INSTALLED_APPS`` setting. 10 | 11 | 3. Wire up the FAQ views by adding a line to your URLconf:: 12 | 13 | url('^faq/', include('fack.urls')) 14 | 15 | If you'd like to load some example data then run 16 | ``python manage.py loaddata faq_test_data.json`` 17 | 18 | FAQ entries can be edited in the admin, and also via the submit view (at 19 | ``/submit``). 20 | 21 | The app's written with quite a bit of customization in mind; see 22 | :doc:`customization` for details. You'll almost certain want to :ref:`customize 23 | the templates ` to make the app "fit in" to your site. 24 | 25 | Example Site 26 | ------------ 27 | 28 | There is a stand-alone example site distributed with the source in the 29 | ``example/`` directory. To try it out: 30 | 31 | 1. Install Django-Fack (see above). 32 | 33 | 1. Run ``python manage.py syncdb`` 34 | 35 | This assumes that sqlite3 is available; if not you'll need to change the 36 | ``DATABASES`` setting first. 37 | 38 | 3. Load some example data by running 39 | ``python manage.py loaddata faq_test_data.json`` 40 | 41 | 4. Run ``python manage.py runserver`` and you will have the example site up and 42 | running. The home page will have links to get to the available views as well 43 | as to the admin. 44 | 45 | The capability to submit an FAQ is available and works whether or not you are a 46 | logged in user. Note that a staff member will have to use the admin and review 47 | any submitted FAQs and clean them up and set them to active before they are 48 | viewable by the end user views. -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | =========== 2 | Django-Fack 3 | =========== 4 | 5 | This is a simple FAQ application for a Django powered site, featuring: 6 | 7 | * The basic Q&A model you'd expect. 8 | 9 | * Question are grouped into topics. 10 | 11 | * Topics can be ordered and arranged, as can questions within topics. 12 | 13 | * Built-in views to drill down by topic and question, and individual 14 | question detail pages (for permalinks). 15 | 16 | * A view for users to submit new questions (with or without answers). These 17 | go into moderation queue and need to be marked "active" before they'll 18 | show up on the site. 19 | 20 | There's an example app (distributed with the source) to try out if you'd like 21 | to get a taste of the app. 22 | 23 | Django-Fack requires Django 1.3+ and Python 2.5+. 24 | 25 | For more details, read on: 26 | 27 | .. toctree:: 28 | :maxdepth: 2 29 | 30 | getting-started 31 | customization 32 | 33 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | if NOT "%PAPER%" == "" ( 11 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 12 | ) 13 | 14 | if "%1" == "" goto help 15 | 16 | if "%1" == "help" ( 17 | :help 18 | echo.Please use `make ^` where ^ is one of 19 | echo. html to make standalone HTML files 20 | echo. dirhtml to make HTML files named index.html in directories 21 | echo. singlehtml to make a single large HTML file 22 | echo. pickle to make pickle files 23 | echo. json to make JSON files 24 | echo. htmlhelp to make HTML files and a HTML help project 25 | echo. qthelp to make HTML files and a qthelp project 26 | echo. devhelp to make HTML files and a Devhelp project 27 | echo. epub to make an epub 28 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 29 | echo. text to make text files 30 | echo. man to make manual pages 31 | echo. changes to make an overview over all changed/added/deprecated items 32 | echo. linkcheck to check all external links for integrity 33 | echo. doctest to run all doctests embedded in the documentation if enabled 34 | goto end 35 | ) 36 | 37 | if "%1" == "clean" ( 38 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 39 | del /q /s %BUILDDIR%\* 40 | goto end 41 | ) 42 | 43 | if "%1" == "html" ( 44 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 45 | if errorlevel 1 exit /b 1 46 | echo. 47 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 48 | goto end 49 | ) 50 | 51 | if "%1" == "dirhtml" ( 52 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 53 | if errorlevel 1 exit /b 1 54 | echo. 55 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 56 | goto end 57 | ) 58 | 59 | if "%1" == "singlehtml" ( 60 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 61 | if errorlevel 1 exit /b 1 62 | echo. 63 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 64 | goto end 65 | ) 66 | 67 | if "%1" == "pickle" ( 68 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 69 | if errorlevel 1 exit /b 1 70 | echo. 71 | echo.Build finished; now you can process the pickle files. 72 | goto end 73 | ) 74 | 75 | if "%1" == "json" ( 76 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished; now you can process the JSON files. 80 | goto end 81 | ) 82 | 83 | if "%1" == "htmlhelp" ( 84 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished; now you can run HTML Help Workshop with the ^ 88 | .hhp project file in %BUILDDIR%/htmlhelp. 89 | goto end 90 | ) 91 | 92 | if "%1" == "qthelp" ( 93 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 94 | if errorlevel 1 exit /b 1 95 | echo. 96 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 97 | .qhcp project file in %BUILDDIR%/qthelp, like this: 98 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-fack.qhcp 99 | echo.To view the help file: 100 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-fack.ghc 101 | goto end 102 | ) 103 | 104 | if "%1" == "devhelp" ( 105 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 106 | if errorlevel 1 exit /b 1 107 | echo. 108 | echo.Build finished. 109 | goto end 110 | ) 111 | 112 | if "%1" == "epub" ( 113 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 117 | goto end 118 | ) 119 | 120 | if "%1" == "latex" ( 121 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 122 | if errorlevel 1 exit /b 1 123 | echo. 124 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 125 | goto end 126 | ) 127 | 128 | if "%1" == "text" ( 129 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 130 | if errorlevel 1 exit /b 1 131 | echo. 132 | echo.Build finished. The text files are in %BUILDDIR%/text. 133 | goto end 134 | ) 135 | 136 | if "%1" == "man" ( 137 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 141 | goto end 142 | ) 143 | 144 | if "%1" == "changes" ( 145 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.The overview file is in %BUILDDIR%/changes. 149 | goto end 150 | ) 151 | 152 | if "%1" == "linkcheck" ( 153 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Link check complete; look for any errors in the above output ^ 157 | or in %BUILDDIR%/linkcheck/output.txt. 158 | goto end 159 | ) 160 | 161 | if "%1" == "doctest" ( 162 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 163 | if errorlevel 1 exit /b 1 164 | echo. 165 | echo.Testing of doctests in the sources finished, look at the ^ 166 | results in %BUILDDIR%/doctest/output.txt. 167 | goto end 168 | ) 169 | 170 | :end 171 | -------------------------------------------------------------------------------- /example/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/revsys/django-fack/a4543e01809f190ccc9afdf822e4c6c9280aa821/example/__init__.py -------------------------------------------------------------------------------- /example/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | 6 | try: 7 | import faq 8 | except ImportError: 9 | sys.stderr.write("django-fack isn't installed; trying to use a source checkout in ../fack.") 10 | sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) 11 | 12 | from django.core.management import execute_manager 13 | try: 14 | import settings # Assumed to be in the same directory. 15 | except ImportError: 16 | import sys 17 | sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) 18 | sys.exit(1) 19 | 20 | if __name__ == "__main__": 21 | execute_manager(settings) 22 | -------------------------------------------------------------------------------- /example/settings.py: -------------------------------------------------------------------------------- 1 | # 2 | # A minimal settings file that ought to work out of the box for just about 3 | # anyone trying this project. It's deliberately missing most settings to keep 4 | # everything simple. 5 | # 6 | # A real app would have a lot more settings. The only important bit as far as 7 | # django-FAQ is concerned is to have `faq` in INSTALLED_APPS. 8 | # 9 | 10 | import os 11 | 12 | PROJECT_DIR = os.path.dirname(__file__) 13 | DEBUG = TEMPLATE_DEBUG = True 14 | 15 | DATABASES = { 16 | 'default': { 17 | 'ENGINE': 'django.db.backends.sqlite3', 18 | 'NAME': os.path.join(PROJECT_DIR, 'faq.db'), 19 | } 20 | } 21 | 22 | SITE_ID = 1 23 | SECRET_KEY = 'c#zi(mv^n+4te_sy$hpb*zdo7#f7ccmp9ro84yz9bmmfqj9y*c' 24 | ROOT_URLCONF = 'urls' 25 | TEMPLATE_DIRS = ( 26 | [os.path.join(PROJECT_DIR, "templates")] 27 | ) 28 | INSTALLED_APPS = ( 29 | 'django.contrib.auth', 30 | 'django.contrib.contenttypes', 31 | 'django.contrib.sessions', 32 | 'django.contrib.sites', 33 | 'django.contrib.admin', 34 | 'fack', 35 | ) -------------------------------------------------------------------------------- /example/templates/home.html: -------------------------------------------------------------------------------- 1 | {% extends "faq/base.html" %} 2 | 3 | {% block body %} 4 | {% load url from future %} 5 |

Welcome to the django-fack example project

6 |

7 | If you aren't seeing any data below, or if you're getting random 404s, make 8 | sure you've loaded the sample data by running ./manage.py loaddata 9 | faq_test_data. 10 |

11 |

Here are some options to try:

12 |
13 |
The topic list.
14 |
This view shows a list of all the FAQ topic areas.
15 | 16 |
17 | A topic detail 18 | page. 19 |
20 |
21 | This shows the list of all questions in a given topic. 22 |
23 | 24 |
25 | A question 26 | detail page. 27 |
28 |
29 | This shows an individual question. Again, it'll only work if you've loaded 30 | the sample data. 31 |
32 | 33 |
34 | The question submission page. 35 |
36 |
37 | You can submit questions here. You'll notice that submitted questions 38 | don't immediately appear: they're set to "inactive" and have to be 39 | approved via the site admin. 40 |
41 | 42 |
43 | Speaking of the admin, here's the FAQ admin. 44 |
45 |
46 | Remember that you can clean up submitted questions in the admin before the 47 | will be visible in the FAQ. 48 |
49 | 50 |
51 | Finally, below are some questions fetched into this template using a 52 | template tag - {% templatetag openblock %} faq_list 3 as faqs 53 | {% templatetag closeblock %}. 54 |
55 |
56 | Some FAQ questions include: 57 | {% load faqtags %} 58 | {% faq_list 3 as faqs %} 59 | {% for faq in faqs %} 60 | {{ faq.text }} {% if not forloop.last %}/{% endif %} 61 | {% endfor %} 62 |
63 | 64 |
65 | {% endblock %} 66 | 67 | -------------------------------------------------------------------------------- /example/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls.defaults import patterns, url, include 2 | from django.contrib import admin; admin.autodiscover() 3 | from django.conf import settings 4 | from django.views.generic import TemplateView 5 | 6 | urlpatterns = patterns('', 7 | # Just a simple example "home" page to show a bit of help/info. 8 | url(r'^$', TemplateView.as_view(template_name="home.html")), 9 | 10 | # This is the URLconf line you'd put in a real app to include the FAQ views. 11 | url(r'^faq/', include('fack.urls')), 12 | 13 | # Everybody wants an admin to wind a piece of string around. 14 | url(r'^admin/', include(admin.site.urls)), 15 | 16 | # Normally we'd do this if DEBUG only, but this is just an example app. 17 | url(regex = r'^static/(?P.*)$', 18 | view = 'django.views.static.serve', 19 | kwargs = {'document_root': settings.MEDIA_ROOT} 20 | ), 21 | ) -------------------------------------------------------------------------------- /fack/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.0' -------------------------------------------------------------------------------- /fack/_testrunner.py: -------------------------------------------------------------------------------- 1 | """ 2 | Test support harness to make setup.py test work. 3 | """ 4 | 5 | import sys 6 | 7 | import django 8 | from django.conf import settings 9 | settings.configure( 10 | DATABASES = { 11 | 'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory;'} 12 | }, 13 | INSTALLED_APPS = [ 14 | 'django.contrib.auth', 15 | 'django.contrib.contenttypes', 16 | 'django.contrib.messages', 17 | 'django.contrib.sessions', 18 | 'fack', 19 | ], 20 | MIDDLEWARE_CLASSES = [ 21 | 'django.middleware.common.CommonMiddleware', 22 | 'django.contrib.sessions.middleware.SessionMiddleware', 23 | 'django.middleware.csrf.CsrfViewMiddleware', 24 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 25 | 'django.contrib.messages.middleware.MessageMiddleware', 26 | ], 27 | ROOT_URLCONF = 'fack.urls', 28 | ) 29 | if hasattr(django, 'setup'): 30 | django.setup() 31 | 32 | def runtests(): 33 | import django.test.utils 34 | runner_class = django.test.utils.get_runner(settings) 35 | test_runner = runner_class(verbosity=1, interactive=True) 36 | failures = test_runner.run_tests(['fack']) 37 | sys.exit(failures) 38 | -------------------------------------------------------------------------------- /fack/admin.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from django.contrib import admin 4 | from .models import Question, Topic 5 | 6 | class TopicAdmin(admin.ModelAdmin): 7 | prepopulated_fields = {'slug':('name',)} 8 | 9 | class QuestionAdmin(admin.ModelAdmin): 10 | list_display = ['text', 'sort_order', 'created_by', 'created_on', 11 | 'updated_by', 'updated_on', 'status'] 12 | list_editable = ['sort_order', 'status'] 13 | 14 | def save_model(self, request, obj, form, change): 15 | ''' 16 | Update created-by / modified-by fields. 17 | 18 | The date fields are upadated at the model layer, but that's not got 19 | access to the user. 20 | ''' 21 | # If the object's new update the created_by field. 22 | if not change: 23 | obj.created_by = request.user 24 | 25 | # Either way update the updated_by field. 26 | obj.updated_by = request.user 27 | 28 | # Let the superclass do the final saving. 29 | return super(QuestionAdmin, self).save_model(request, obj, form, change) 30 | 31 | admin.site.register(Question, QuestionAdmin) 32 | admin.site.register(Topic, TopicAdmin) 33 | -------------------------------------------------------------------------------- /fack/fixtures/faq_test_data.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "pk": 1, 4 | "model": "auth.user", 5 | "fields": { 6 | "username": "frank", 7 | "first_name": "", 8 | "last_name": "", 9 | "is_active": true, 10 | "is_superuser": true, 11 | "is_staff": true, 12 | "last_login": "2012-04-21T12:03:48.783", 13 | "groups": [], 14 | "user_permissions": [], 15 | "password": "pbkdf2_sha256$10000$JfEKewjP2qt9$/AkikFcmVRSGTuwS82UCadK0k8ejGs0/rz+JEHZ+LCE=", 16 | "email": "frank@revsys.com", 17 | "date_joined": "2012-04-21T12:03:48.783" 18 | } 19 | }, 20 | { 21 | "pk": 1, 22 | "model": "fack.topic", 23 | "fields": { 24 | "sort_order": 0, 25 | "name": "Silly questions", 26 | "slug": "silly-questions" 27 | } 28 | }, 29 | { 30 | "pk": 2, 31 | "model": "fack.topic", 32 | "fields": { 33 | "sort_order": 1, 34 | "name": "Serious questions", 35 | "slug": "serious-questions" 36 | } 37 | }, 38 | { 39 | "pk": 1, 40 | "model": "fack.question", 41 | "fields": { 42 | "status": 1, 43 | "updated_by": 1, 44 | "text": "What is your favorite color?", 45 | "created_by": 1, 46 | "topic": 1, 47 | "created_on": "2011-05-09 15:38:47", 48 | "sort_order": 0, 49 | "answer": "Red... no blue.. no *AHHHHH....*", 50 | "updated_on": "2011-05-09 15:38:47", 51 | "protected": false, 52 | "slug": "favorite-color" 53 | } 54 | }, 55 | { 56 | "pk": 2, 57 | "model": "fack.question", 58 | "fields": { 59 | "status": 1, 60 | "updated_by": 1, 61 | "text": "What is your quest?", 62 | "created_by": 1, 63 | "topic": 1, 64 | "created_on": "2011-05-09 15:39:19", 65 | "sort_order": 1, 66 | "answer": "I seek the grail!", 67 | "updated_on": "2011-05-09 15:39:19", 68 | "protected": false, 69 | "slug": "your-quest" 70 | } 71 | }, 72 | { 73 | "pk": 3, 74 | "model": "fack.question", 75 | "fields": { 76 | "status": 1, 77 | "updated_by": 1, 78 | "text": "What is Django-fack?", 79 | "created_by": 1, 80 | "topic": 2, 81 | "created_on": "2011-05-09 15:40:55", 82 | "sort_order": 3, 83 | "answer": "A simple FAQ application for a Django powered site. This app follows\r\nseveral \"best practices\" for reusable apps by allowing for template overrides\r\nand extra_context arguments and such.\r\n", 84 | "updated_on": "2011-05-09 15:40:55", 85 | "protected": false, 86 | "slug": "what-is-django-fack" 87 | } 88 | } 89 | ] 90 | -------------------------------------------------------------------------------- /fack/forms.py: -------------------------------------------------------------------------------- 1 | """ 2 | Here we define a form for allowing site users to submit a potential FAQ that 3 | they would like to see added. 4 | 5 | From the user's perspective the question is not added automatically, but 6 | actually it is, only it is added as inactive. 7 | """ 8 | 9 | from __future__ import absolute_import 10 | import datetime 11 | from django import forms 12 | from .models import Question, Topic 13 | 14 | class SubmitFAQForm(forms.ModelForm): 15 | class Meta: 16 | model = Question 17 | fields = ['topic', 'text', 'answer'] -------------------------------------------------------------------------------- /fack/managers.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.db.models.query import QuerySet 3 | 4 | class QuestionQuerySet(QuerySet): 5 | def active(self): 6 | """ 7 | Return only "active" (i.e. published) questions. 8 | """ 9 | return self.filter(status__exact=self.model.ACTIVE) 10 | 11 | class QuestionManager(models.Manager): 12 | def get_query_set(self): 13 | return QuestionQuerySet(self.model) 14 | 15 | def active(self): 16 | return self.get_query_set().active() 17 | -------------------------------------------------------------------------------- /fack/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models, migrations 5 | from django.conf import settings 6 | import datetime 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | dependencies = [ 12 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='Question', 18 | fields=[ 19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 20 | ('text', models.TextField(help_text='The actual question itself.', verbose_name='question')), 21 | ('answer', models.TextField(blank=True, help_text='The answer text.', verbose_name='answer')), 22 | ('slug', models.SlugField(max_length=100, verbose_name='slug')), 23 | ('status', models.IntegerField(default=0, help_text="Only questions with their status set to 'Active' will be displayed. Questions marked as 'Group Header' are treated as such by views and templates that are set up to use them.", choices=[(1, 'Active'), (0, 'Inactive'), (2, 'Group Header')], verbose_name='status')), 24 | ('protected', models.BooleanField(default=False, help_text='Set true if this question is only visible by authenticated users.', verbose_name='is protected')), 25 | ('sort_order', models.IntegerField(default=0, help_text='The order you would like the question to be displayed.', verbose_name='sort order')), 26 | ('created_on', models.DateTimeField(default=datetime.datetime.now, verbose_name='created on')), 27 | ('updated_on', models.DateTimeField(verbose_name='updated on')), 28 | ('created_by', models.ForeignKey(to=settings.AUTH_USER_MODEL, verbose_name='created by', related_name='+', null=True)), 29 | ], 30 | options={ 31 | 'verbose_name_plural': 'Frequently asked questions', 32 | 'verbose_name': 'Frequent asked question', 33 | 'ordering': ['sort_order', 'created_on'], 34 | }, 35 | ), 36 | migrations.CreateModel( 37 | name='Topic', 38 | fields=[ 39 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 40 | ('name', models.CharField(max_length=150, verbose_name='name')), 41 | ('slug', models.SlugField(max_length=150, verbose_name='slug')), 42 | ('sort_order', models.IntegerField(default=0, help_text='The order you would like the topic to be displayed.', verbose_name='sort order')), 43 | ], 44 | options={ 45 | 'verbose_name_plural': 'Topics', 46 | 'verbose_name': 'Topic', 47 | 'ordering': ['sort_order', 'name'], 48 | }, 49 | ), 50 | migrations.AddField( 51 | model_name='question', 52 | name='topic', 53 | field=models.ForeignKey(to='fack.Topic', verbose_name='topic', related_name='questions'), 54 | ), 55 | migrations.AddField( 56 | model_name='question', 57 | name='updated_by', 58 | field=models.ForeignKey(to=settings.AUTH_USER_MODEL, verbose_name='updated by', related_name='+', null=True), 59 | ), 60 | ] 61 | -------------------------------------------------------------------------------- /fack/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/revsys/django-fack/a4543e01809f190ccc9afdf822e4c6c9280aa821/fack/migrations/__init__.py -------------------------------------------------------------------------------- /fack/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import datetime 4 | 5 | import django 6 | from django.conf import settings 7 | from django.db import models 8 | from django.utils.translation import ugettext_lazy as _ 9 | from django.template.defaultfilters import slugify 10 | from django.utils.encoding import python_2_unicode_compatible 11 | 12 | from .managers import QuestionManager, QuestionQuerySet 13 | 14 | 15 | AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') 16 | 17 | 18 | @python_2_unicode_compatible 19 | class Topic(models.Model): 20 | """ 21 | Generic Topics for FAQ question grouping 22 | """ 23 | name = models.CharField(_('name'), max_length=150) 24 | slug = models.SlugField(_('slug'), max_length=150) 25 | sort_order = models.IntegerField(_('sort order'), default=0, 26 | help_text=_('The order you would like the topic to be displayed.')) 27 | 28 | class Meta: 29 | verbose_name = _("Topic") 30 | verbose_name_plural = _("Topics") 31 | ordering = ['sort_order', 'name'] 32 | 33 | def __str__(self): 34 | return self.name 35 | 36 | @models.permalink 37 | def get_absolute_url(self): 38 | return ('faq_topic_detail', [self.slug]) 39 | 40 | 41 | @python_2_unicode_compatible 42 | class Question(models.Model): 43 | HEADER = 2 44 | ACTIVE = 1 45 | INACTIVE = 0 46 | STATUS_CHOICES = ( 47 | (ACTIVE, _('Active')), 48 | (INACTIVE, _('Inactive')), 49 | (HEADER, _('Group Header')), 50 | ) 51 | 52 | text = models.TextField(_('question'), help_text=_('The actual question itself.')) 53 | answer = models.TextField(_('answer'), blank=True, help_text=_('The answer text.')) 54 | topic = models.ForeignKey(Topic, verbose_name=_('topic'), related_name='questions') 55 | slug = models.SlugField(_('slug'), max_length=100) 56 | status = models.IntegerField(_('status'), 57 | choices=STATUS_CHOICES, default=INACTIVE, 58 | help_text=_("Only questions with their status set to 'Active' will be " 59 | "displayed. Questions marked as 'Group Header' are treated " 60 | "as such by views and templates that are set up to use them.")) 61 | 62 | protected = models.BooleanField(_('is protected'), default=False, 63 | help_text=_("Set true if this question is only visible by authenticated users.")) 64 | 65 | sort_order = models.IntegerField(_('sort order'), default=0, 66 | help_text=_('The order you would like the question to be displayed.')) 67 | 68 | created_on = models.DateTimeField(_('created on'), default=datetime.datetime.now) 69 | updated_on = models.DateTimeField(_('updated on')) 70 | created_by = models.ForeignKey(AUTH_USER_MODEL, verbose_name=_('created by'), 71 | null=True, related_name="+") 72 | updated_by = models.ForeignKey(AUTH_USER_MODEL, verbose_name=_('updated by'), 73 | null=True, related_name="+") 74 | 75 | if django.VERSION >= (1, 7): 76 | objects = QuestionQuerySet.as_manager() 77 | else: 78 | objects = QuestionManager() 79 | 80 | class Meta: 81 | verbose_name = _("Frequent asked question") 82 | verbose_name_plural = _("Frequently asked questions") 83 | ordering = ['sort_order', 'created_on'] 84 | 85 | def __str__(self): 86 | return self.text 87 | 88 | @models.permalink 89 | def get_absolute_url(self): 90 | return ('faq_question_detail', [self.topic.slug, self.slug]) 91 | 92 | def save(self, *args, **kwargs): 93 | # Set the date updated. 94 | self.updated_on = datetime.datetime.now() 95 | 96 | # Create a unique slug, if needed. 97 | if not self.slug: 98 | suffix = 0 99 | potential = base = slugify(self.text[:90]) 100 | while not self.slug: 101 | if suffix: 102 | potential = "%s-%s" % (base, suffix) 103 | if not Question.objects.filter(slug=potential).exists(): 104 | self.slug = potential 105 | # We hit a conflicting slug; increment the suffix and try again. 106 | suffix += 1 107 | 108 | super(Question, self).save(*args, **kwargs) 109 | 110 | def is_header(self): 111 | return self.status == Question.HEADER 112 | 113 | def is_active(self): 114 | return self.status == Question.ACTIVE 115 | -------------------------------------------------------------------------------- /fack/templates/faq/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {% block title %}Django Fack {% endblock %} 6 | 7 | 8 | {% for message in messages %} 9 |

{{ message }}

10 | {% endfor %} 11 | {% block body %}{% endblock %} 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /fack/templates/faq/question_detail.html: -------------------------------------------------------------------------------- 1 | {% extends "faq/base.html" %} 2 | 3 | {% block title %}{{ block.super }}: Question - {{ question.text|truncatewords:30}}{% endblock %} 4 | 5 | 6 | {% block body %} 7 | 8 | {{ question.text }} 9 | 10 |
11 | 12 | {{ question.answer }} 13 | 14 | {% endblock %} 15 | -------------------------------------------------------------------------------- /fack/templates/faq/submit_question.html: -------------------------------------------------------------------------------- 1 | {% extends "faq/base.html" %} 2 | 3 | {% block title %}{{ block.super }}: Add Question{% endblock %} 4 | 5 | {% block body %} 6 |

Submit Question

7 |

8 | Use this form to submit a question (and optionally a corresponding answer) 9 | that you would like to see added to the FAQs on this site. 10 |

11 |
12 | {% csrf_token %} 13 | 14 | {{ form.as_table }} 15 |
16 | 17 |
18 | {% endblock %} 19 | -------------------------------------------------------------------------------- /fack/templates/faq/submit_thanks.html: -------------------------------------------------------------------------------- 1 | {% extends "faq/base.html" %} 2 | 3 | {% block title %}{{ block.super }}: Thanks{% endblock %} 4 | {% block body %}

Thanks!

{% endblock %} 5 | -------------------------------------------------------------------------------- /fack/templates/faq/topic_detail.html: -------------------------------------------------------------------------------- 1 | {% extends "faq/base.html" %} 2 | 3 | {% block title %}{{ block.super }}: {{ topic }}{% endblock %} 4 | 5 | {% block body %} 6 |

{{ topic }}

7 |
8 | {% for question in questions %} 9 |
{{ question.text }}
10 |
{{ question.answer }}
11 | {% endfor %} 12 |
13 | 14 | {% endblock %} 15 | -------------------------------------------------------------------------------- /fack/templates/faq/topic_list.html: -------------------------------------------------------------------------------- 1 | {% extends "faq/base.html" %} 2 | 3 | {% block title %}{{ block.super }}: Topics{% endblock %} 4 | 5 | {% block body %} 6 |

Topics

7 |
    8 | {% for topic in topics %} 9 |
  • {{ topic }}
  • 10 | {% endfor %} 11 |
12 | {% endblock %} 13 | -------------------------------------------------------------------------------- /fack/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/revsys/django-fack/a4543e01809f190ccc9afdf822e4c6c9280aa821/fack/templatetags/__init__.py -------------------------------------------------------------------------------- /fack/templatetags/faqtags.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from django import template 4 | from ..models import Question, Topic 5 | 6 | register = template.Library() 7 | 8 | class FaqListNode(template.Node): 9 | def __init__(self, num, varname, topic=None): 10 | self.num = template.Variable(num) 11 | self.topic = template.Variable(topic) if topic else None 12 | self.varname = varname 13 | 14 | def render(self, context): 15 | try: 16 | num = self.num.resolve(context) 17 | topic = self.topic.resolve(context) if self.topic else None 18 | except template.VariableDoesNotExist: 19 | return '' 20 | 21 | if isinstance(topic, Topic): 22 | qs = Question.objects.filter(topic=topic) 23 | elif topic is not None: 24 | qs = Question.objects.filter(topic__slug=topic) 25 | else: 26 | qs = Question.objects.all() 27 | 28 | context[self.varname] = qs.filter(status=Question.ACTIVE)[:num] 29 | return '' 30 | 31 | @register.tag 32 | def faqs_for_topic(parser, token): 33 | """ 34 | Returns a list of 'count' faq's that belong to the given topic 35 | the supplied topic argument must be in the slug format 'topic-name' 36 | 37 | Example usage:: 38 | 39 | {% faqs_for_topic 5 "my-slug" as faqs %} 40 | """ 41 | 42 | args = token.split_contents() 43 | if len(args) != 5: 44 | raise template.TemplateSyntaxError("%s takes exactly four arguments" % args[0]) 45 | if args[3] != 'as': 46 | raise template.TemplateSyntaxError("third argument to the %s tag must be 'as'" % args[0]) 47 | 48 | return FaqListNode(num=args[1], topic=args[2], varname=args[4]) 49 | 50 | 51 | @register.tag 52 | def faq_list(parser, token): 53 | """ 54 | returns a generic list of 'count' faq's to display in a list 55 | ordered by the faq sort order. 56 | 57 | Example usage:: 58 | 59 | {% faq_list 15 as faqs %} 60 | """ 61 | args = token.split_contents() 62 | if len(args) != 4: 63 | raise template.TemplateSyntaxError("%s takes exactly three arguments" % args[0]) 64 | if args[2] != 'as': 65 | raise template.TemplateSyntaxError("second argument to the %s tag must be 'as'" % args[0]) 66 | 67 | return FaqListNode(num=args[1], varname=args[3]) 68 | 69 | class TopicListNode(template.Node): 70 | def __init__(self, varname): 71 | self.varname = varname 72 | 73 | def render(self, context): 74 | context[self.varname] = Topic.objects.all() 75 | return '' 76 | 77 | @register.tag 78 | def faq_topic_list(parser, token): 79 | """ 80 | Returns a list of all FAQ Topics. 81 | 82 | Example usage:: 83 | {% faq_topic_list as topic_list %} 84 | """ 85 | args = token.split_contents() 86 | if len(args) != 3: 87 | raise template.TemplateSyntaxError("%s takes exactly two arguments" % args[0]) 88 | if args[1] != 'as': 89 | raise template.TemplateSyntaxError("second argument to the %s tag must be 'as'" % args[0]) 90 | 91 | return TopicListNode(varname=args[2]) 92 | 93 | -------------------------------------------------------------------------------- /fack/tests/__init__.py: -------------------------------------------------------------------------------- 1 | from fack.tests.test_admin import * 2 | from fack.tests.test_models import * 3 | from fack.tests.test_templatetags import * 4 | from fack.tests.test_views import * 5 | -------------------------------------------------------------------------------- /fack/tests/templates/404.html: -------------------------------------------------------------------------------- 1 | 404 -------------------------------------------------------------------------------- /fack/tests/templates/500.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/revsys/django-fack/a4543e01809f190ccc9afdf822e4c6c9280aa821/fack/tests/templates/500.html -------------------------------------------------------------------------------- /fack/tests/test_admin.py: -------------------------------------------------------------------------------- 1 | """ 2 | Some basic admin tests. 3 | 4 | Rather than testing the frontend UI -- that's be a job for something like 5 | Selenium -- this does a bunch of mocking and just tests the various admin 6 | callbacks. 7 | """ 8 | 9 | from __future__ import absolute_import 10 | 11 | import mock 12 | from django.contrib import admin 13 | from django.contrib.auth.models import User 14 | try: 15 | from django.utils import unittest 16 | except ImportError: # Django >= 1.9 17 | import unittest 18 | from django.http import HttpRequest 19 | from django import forms 20 | from ..admin import QuestionAdmin 21 | from ..models import Question 22 | 23 | class FAQAdminTests(unittest.TestCase): 24 | 25 | def test_question_admin_save_model(self): 26 | user1 = mock.Mock(spec=User) 27 | user2 = mock.Mock(spec=User) 28 | req = mock.Mock(spec=HttpRequest) 29 | obj = mock.Mock(spec=Question) 30 | form = mock.Mock(spec=forms.Form) 31 | 32 | qa = QuestionAdmin(Question, admin.site) 33 | 34 | # Test saving a new model. 35 | req.user = user1 36 | qa.save_model(req, obj, form, change=False) 37 | self.assertEqual(obj.save.call_count, 1) 38 | self.assertEqual(obj.created_by, user1, "created_by wasn't set to request.user") 39 | self.assertEqual(obj.updated_by, user1, "updated_by wasn't set to request.user") 40 | 41 | # And saving an existing model. 42 | obj.save.reset_mock() 43 | req.user = user2 44 | qa.save_model(req, obj, form, change=True) 45 | self.assertEqual(obj.save.call_count, 1) 46 | self.assertEqual(obj.created_by, user1, "created_by shouldn't have been changed") 47 | self.assertEqual(obj.updated_by, user2, "updated_by wasn't set to request.user") -------------------------------------------------------------------------------- /fack/tests/test_models.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import datetime 4 | import django.test 5 | from django.core.urlresolvers import reverse 6 | from ..models import Topic, Question 7 | 8 | class FAQModelTests(django.test.TestCase): 9 | 10 | def test_model_save(self): 11 | t = Topic.objects.create(name='t', slug='t') 12 | q = Question.objects.create( 13 | text = "What is your quest?", 14 | answer = "I see the grail!", 15 | topic = t 16 | ) 17 | self.assertEqual(q.created_on.date(), datetime.date.today()) 18 | self.assertEqual(q.updated_on.date(), datetime.date.today()) 19 | self.assertEqual(q.slug, "what-is-your-quest") 20 | 21 | def test_model_save_duplicate_slugs(self): 22 | t = Topic.objects.create(name='t', slug='t') 23 | q = Question.objects.create( 24 | text = "What is your quest?", 25 | answer = "I see the grail!", 26 | topic = t 27 | ) 28 | q2 = Question.objects.create( 29 | text = "What is your quest?", 30 | answer = "I see the grail!", 31 | topic = t 32 | ) 33 | self.assertEqual(q2.slug, 'what-is-your-quest-1') 34 | 35 | def test_permalinks(self): 36 | # Perhaps a bit overkill to test, but we missed it initially 37 | t = Topic.objects.create(name='t', slug='t') 38 | q = Question.objects.create( 39 | text = "What is your quest?", 40 | answer = "I see the grail!", 41 | topic = t 42 | ) 43 | t_url = t.get_absolute_url() 44 | t_test_url = reverse('faq_topic_detail', args=[t.slug]) 45 | q_url = q.get_absolute_url() 46 | q_test_url = reverse('faq_question_detail', args=[t.slug, q.slug]) 47 | 48 | self.assertEqual(t_url, t_test_url) 49 | self.assertEqual(q_url, q_test_url) 50 | 51 | -------------------------------------------------------------------------------- /fack/tests/test_templatetags.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import django.test 4 | from django import template 5 | try: 6 | from django.utils import unittest 7 | except ImportError: # Django >= 1.9 8 | import unittest 9 | from ..templatetags import faqtags 10 | from ..models import Topic 11 | 12 | class FAQTagsSyntaxTests(unittest.TestCase): 13 | """ 14 | Tests for the syntax/compliation functions. 15 | 16 | These are broken out here so that they don't have to be 17 | django.test.TestCases, which are slower. 18 | """ 19 | 20 | def compile(self, tagfunc, token_contents): 21 | """ 22 | Mock out a call to a template compliation function. 23 | 24 | Assumes the tag doesn't use the parser, so this won't work for block tags. 25 | """ 26 | t = template.base.Token(template.base.TOKEN_BLOCK, token_contents) 27 | return tagfunc(None, t) 28 | 29 | def test_faqs_for_topic_compile(self): 30 | t = self.compile(faqtags.faqs_for_topic, "faqs_for_topic 15 'some-slug' as faqs") 31 | self.assertEqual(t.num.var, "15") 32 | self.assertEqual(t.topic.var, "'some-slug'") 33 | self.assertEqual(t.varname, "faqs") 34 | 35 | def test_faqs_for_topic_too_few_arguments(self): 36 | self.assertRaises(template.TemplateSyntaxError, 37 | self.compile, 38 | faqtags.faqs_for_topic, 39 | "faqs_for_topic 15 'some-slug' as") 40 | 41 | def test_faqs_for_topic_too_many_arguments(self): 42 | self.assertRaises(template.TemplateSyntaxError, 43 | self.compile, 44 | faqtags.faqs_for_topic, 45 | "faqs_for_topic 15 'some-slug' as varname foobar") 46 | 47 | def test_faqs_for_topic_bad_as(self): 48 | self.assertRaises(template.TemplateSyntaxError, 49 | self.compile, 50 | faqtags.faqs_for_topic, 51 | "faqs_for_topic 15 'some-slug' blahblah varname") 52 | 53 | def test_faq_list_compile(self): 54 | t = self.compile(faqtags.faq_list, "faq_list 15 as faqs") 55 | self.assertEqual(t.num.var, "15") 56 | self.assertEqual(t.varname, "faqs") 57 | 58 | def test_faq_list_too_few_arguments(self): 59 | self.assertRaises(template.TemplateSyntaxError, 60 | self.compile, 61 | faqtags.faq_list, 62 | "faq_list 15") 63 | 64 | def test_faq_list_too_many_arguments(self): 65 | self.assertRaises(template.TemplateSyntaxError, 66 | self.compile, 67 | faqtags.faq_list, 68 | "faq_list 15 as varname foobar") 69 | 70 | def test_faq_list_bad_as(self): 71 | self.assertRaises(template.TemplateSyntaxError, 72 | self.compile, 73 | faqtags.faq_list, 74 | "faq_list 15 blahblah varname") 75 | 76 | class FAQTagsNodeTests(django.test.TestCase): 77 | """ 78 | Tests for the node classes themselves, and hence the rendering functions. 79 | """ 80 | fixtures = ['faq_test_data.json'] 81 | 82 | def test_faqs_for_topic_node(self): 83 | context = template.Context() 84 | node = faqtags.FaqListNode(num='5', topic='"silly-questions"', varname="faqs") 85 | content = node.render(context) 86 | self.assertEqual(content, "") 87 | self.assertQuerysetEqual(context['faqs'], 88 | ['', 89 | '']) 90 | 91 | def test_faqs_for_topic_node_variable_arguments(self): 92 | """ 93 | Test faqs_for_topic with a variable arguments. 94 | """ 95 | context = template.Context({'topic': Topic.objects.get(pk=1), 96 | 'number': 1}) 97 | node = faqtags.FaqListNode(num='number', topic='topic', varname="faqs") 98 | content = node.render(context) 99 | self.assertEqual(content, "") 100 | self.assertQuerysetEqual(context['faqs'], [""]) 101 | 102 | def test_faqs_for_topic_node_invalid_variables(self): 103 | context = template.Context() 104 | node = faqtags.FaqListNode(num='number', topic='topic', varname="faqs") 105 | content = node.render(context) 106 | self.assertEqual(content, "") 107 | self.assert_("faqs" not in context, 108 | "faqs variable shouldn't have been added to the context.") 109 | 110 | def test_faq_list_node(self): 111 | context = template.Context() 112 | node = faqtags.FaqListNode(num='5', varname="faqs") 113 | content = node.render(context) 114 | self.assertEqual(content, "") 115 | self.assertQuerysetEqual(context['faqs'], 116 | ['', 117 | '', 118 | '']) 119 | 120 | def test_faq_list_node_variable_arguments(self): 121 | """ 122 | Test faqs_for_topic with a variable arguments. 123 | """ 124 | context = template.Context({'topic': Topic.objects.get(pk=1), 125 | 'number': 1}) 126 | node = faqtags.FaqListNode(num='number', varname="faqs") 127 | content = node.render(context) 128 | self.assertEqual(content, "") 129 | self.assertQuerysetEqual(context['faqs'], [""]) 130 | 131 | def test_faq_list_node_invalid_variables(self): 132 | context = template.Context() 133 | node = faqtags.FaqListNode(num='number', varname="faqs") 134 | content = node.render(context) 135 | self.assertEqual(content, "") 136 | self.assert_("faqs" not in context, 137 | "faqs variable shouldn't have been added to the context.") 138 | 139 | def test_faq_topic_list(self): 140 | context = template.Context() 141 | node = faqtags.TopicListNode(varname="topic_list") 142 | content = node.render(context) 143 | self.assertEqual(content, "") 144 | self.assert_("topic_list" in context, "topic_list should be in context") 145 | self.assertEqual(len(context['topic_list']), 2) 146 | 147 | -------------------------------------------------------------------------------- /fack/tests/test_views.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import datetime 4 | import django.test 5 | import mock 6 | import os 7 | from django.conf import settings 8 | from ..models import Topic, Question 9 | 10 | class FAQViewTests(django.test.TestCase): 11 | urls = 'fack.urls' 12 | fixtures = ['faq_test_data.json'] 13 | 14 | def setUp(self): 15 | # Make some test templates available. 16 | self._oldtd = settings.TEMPLATE_DIRS 17 | settings.TEMPLATE_DIRS = [os.path.join(os.path.dirname(__file__), 'templates')] 18 | 19 | def tearDown(self): 20 | settings.TEMPLATE_DIRS = self._oldtd 21 | 22 | def test_submit_faq_get(self): 23 | response = self.client.get('/submit/') 24 | self.assertEqual(response.status_code, 200) 25 | self.assertTemplateUsed(response, "faq/submit_question.html") 26 | 27 | @mock.patch('fack.views.messages') 28 | def test_submit_faq_post(self, mock_messages): 29 | data = { 30 | 'topic': '1', 31 | 'text': 'What is your favorite color?', 32 | 'answer': 'Blue. I mean red. I mean *AAAAHHHHH....*', 33 | } 34 | response = self.client.post('/submit/', data) 35 | self.assertEqual(mock_messages.success.call_count, 1) 36 | self.assertRedirects(response, "/submit/thanks/") 37 | self.assert_( 38 | Question.objects.filter(text=data['text']).exists(), 39 | "Expected question object wasn't created." 40 | ) 41 | 42 | def test_submit_thanks(self): 43 | response = self.client.get('/submit/thanks/') 44 | self.assertEqual(response.status_code, 200) 45 | self.assertTemplateUsed(response, "faq/submit_thanks.html") 46 | 47 | def test_faq_index(self): 48 | response = self.client.get('/') 49 | self.assertEqual(response.status_code, 200) 50 | self.assertTemplateUsed(response, "faq/topic_list.html") 51 | self.assertQuerysetEqual( 52 | response.context["topics"], 53 | ["", ""] 54 | ) 55 | self.assertEqual( 56 | response.context['last_updated'], 57 | Question.objects.order_by('-updated_on')[0].updated_on 58 | ) 59 | 60 | def test_topic_detail(self): 61 | response = self.client.get('/silly-questions/') 62 | self.assertEqual(response.status_code, 200) 63 | self.assertTemplateUsed(response, "faq/topic_detail.html") 64 | self.assertEqual( 65 | response.context['topic'], 66 | Topic.objects.get(slug="silly-questions") 67 | ) 68 | self.assertEqual( 69 | response.context['last_updated'], 70 | Topic.objects.get(slug='silly-questions').questions.order_by('-updated_on')[0].updated_on 71 | ) 72 | self.assertQuerysetEqual( 73 | response.context["questions"], 74 | ["", 75 | ""] 76 | ) 77 | 78 | def test_question_detail(self): 79 | response = self.client.get('/silly-questions/your-quest/') 80 | self.assertEqual(response.status_code, 200) 81 | self.assertTemplateUsed(response, "faq/question_detail.html") 82 | self.assertEqual( 83 | response.context["question"], 84 | Question.objects.get(slug="your-quest") 85 | ) 86 | -------------------------------------------------------------------------------- /fack/urls.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | try: 4 | from django.conf.urls.defaults import * 5 | except: 6 | from django.conf.urls import url, patterns 7 | from . import views 8 | 9 | urlpatterns = patterns('', 10 | url(regex = r'^$', 11 | view = views.TopicList.as_view(), 12 | name = 'faq_topic_list', 13 | ), 14 | url(regex = r'^submit/$', 15 | view = views.SubmitFAQ.as_view(), 16 | name = 'faq_submit', 17 | ), 18 | url(regex = r'^submit/thanks/$', 19 | view = views.SubmitFAQThanks.as_view(), 20 | name = 'faq_submit_thanks', 21 | ), 22 | url(regex = r'^(?P[\w-]+)/$', 23 | view = views.TopicDetail.as_view(), 24 | name = 'faq_topic_detail', 25 | ), 26 | url(regex = r'^(?P[\w-]+)/(?P[\w-]+)/$', 27 | view = views.QuestionDetail.as_view(), 28 | name = 'faq_question_detail', 29 | ), 30 | ) 31 | -------------------------------------------------------------------------------- /fack/views.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from django.db.models import Max 3 | from django.core.urlresolvers import reverse 4 | from django.contrib import messages 5 | from django.shortcuts import get_object_or_404 6 | from django.utils.translation import ugettext as _ 7 | from django.views.generic import ListView, DetailView, TemplateView, CreateView 8 | from .models import Question, Topic 9 | from .forms import SubmitFAQForm 10 | 11 | class TopicList(ListView): 12 | model = Topic 13 | template_name = "faq/topic_list.html" 14 | allow_empty = True 15 | context_object_name = "topics" 16 | 17 | def get_context_data(self, **kwargs): 18 | data = super(TopicList, self).get_context_data(**kwargs) 19 | 20 | # This slightly magical queryset grabs the latest update date for 21 | # topic's questions, then the latest date for that whole group. 22 | # In other words, it's:: 23 | # 24 | # max(max(q.updated_on for q in topic.questions) for topic in topics) 25 | # 26 | # Except performed in the DB, so quite a bit more efficiant. 27 | # 28 | # We can't just do Question.objects.all().aggregate(max('updated_on')) 29 | # because that'd prevent a subclass from changing the view's queryset 30 | # (or even model -- this view'll even work with a different model 31 | # as long as that model has a many-to-one to something called "questions" 32 | # with an "updated_on" field). So this magic is the price we pay for 33 | # being generic. 34 | last_updated = (data['object_list'] 35 | .annotate(updated=Max('questions__updated_on')) 36 | .aggregate(Max('updated'))) 37 | 38 | data.update({'last_updated': last_updated['updated__max']}) 39 | return data 40 | 41 | class TopicDetail(DetailView): 42 | model = Topic 43 | template_name = "faq/topic_detail.html" 44 | context_object_name = "topic" 45 | 46 | def get_context_data(self, **kwargs): 47 | # Include a list of questions this user has access to. If the user is 48 | # logged in, this includes protected questions. Otherwise, not. 49 | qs = self.object.questions.active() 50 | if self.request.user.is_anonymous(): 51 | qs = qs.exclude(protected=True) 52 | 53 | data = super(TopicDetail, self).get_context_data(**kwargs) 54 | data.update({ 55 | 'questions': qs, 56 | 'last_updated': qs.aggregate(updated=Max('updated_on'))['updated'], 57 | }) 58 | return data 59 | 60 | class QuestionDetail(DetailView): 61 | queryset = Question.objects.active() 62 | template_name = "faq/question_detail.html" 63 | 64 | def get_queryset(self): 65 | topic = get_object_or_404(Topic, slug=self.kwargs['topic_slug']) 66 | 67 | # Careful here not to hardcode a base queryset. This lets 68 | # subclassing users re-use this view on a subset of questions, or 69 | # even on a new model. 70 | # FIXME: similar logic as above. This should push down into managers. 71 | qs = super(QuestionDetail, self).get_queryset().filter(topic=topic) 72 | if self.request.user.is_anonymous(): 73 | qs = qs.exclude(protected=True) 74 | 75 | return qs 76 | 77 | class SubmitFAQ(CreateView): 78 | model = Question 79 | form_class = SubmitFAQForm 80 | template_name = "faq/submit_question.html" 81 | success_view_name = "faq_submit_thanks" 82 | 83 | def get_form_kwargs(self): 84 | kwargs = super(SubmitFAQ, self).get_form_kwargs() 85 | kwargs['instance'] = Question() 86 | if self.request.user.is_authenticated(): 87 | kwargs['instance'].created_by = self.request.user 88 | return kwargs 89 | 90 | def form_valid(self, form): 91 | response = super(SubmitFAQ, self).form_valid(form) 92 | messages.success(self.request, 93 | _("Your question was submitted and will be reviewed by for inclusion in the FAQ."), 94 | fail_silently=True, 95 | ) 96 | return response 97 | 98 | def get_success_url(self): 99 | # The superclass version raises ImproperlyConfigered if self.success_url 100 | # isn't set. Instead of that, we'll try to redirect to a named view. 101 | if self.success_url: 102 | return self.success_url 103 | else: 104 | return reverse(self.success_view_name) 105 | 106 | class SubmitFAQThanks(TemplateView): 107 | template_name = "faq/submit_thanks.html" -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [build_sphinx] 2 | source-dir = docs/ 3 | build-dir = docs/_build -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import setup, find_packages 3 | 4 | def read(fname): 5 | return open(os.path.join(os.path.dirname(__file__), fname)).read() 6 | 7 | setup( 8 | name = 'django-fack', 9 | version = '1.1', 10 | description = 'A simple FAQ application for Django sites.', 11 | long_description = read('README.rst'), 12 | license = "BSD", 13 | 14 | author ='Kevin Fricovsky', 15 | author_email = 'kfricovsky@gmail.com', 16 | url = 'http://django-fack.rtfd.org/', 17 | 18 | packages = find_packages(exclude=['example']), 19 | zip_safe = False, 20 | 21 | classifiers = [ 22 | 'Development Status :: 3 - Alpha', 23 | 'Environment :: Web Environment', 24 | 'Intended Audience :: Developers', 25 | 'License :: OSI Approved :: BSD License', 26 | 'Operating System :: OS Independent', 27 | 'Programming Language :: Python', 28 | 'Framework :: Django', 29 | ], 30 | 31 | install_requires = ['Django >= 1.3'], 32 | test_suite = "fack._testrunner.runtests", 33 | tests_require = ["mock"], 34 | ) 35 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | downloadcache = .tox/_download/ 3 | envlist = py27-dj{14,15,16,17,18,19}, docs 4 | 5 | [testenv] 6 | deps = 7 | mock 8 | dj14: Django>=1.4,<1.5 9 | dj15: Django>=1.5,<1.6 10 | dj16: Django>=1.6,<1.7 11 | dj17: Django>=1.7,<1.8 12 | dj18: Django>=1.8,<1.9 13 | dj19: Django>=1.9,<1.10 14 | commands = 15 | {envpython} setup.py test 16 | 17 | # There's no need to measure coverage on each different pyversion (I think!) 18 | # so only do it for 2.7 (chosen arbitrarily). 19 | [testenv:py27] 20 | deps = 21 | coverage 22 | mock 23 | commands = 24 | coverage run --branch --source=fack setup.py test 25 | coverage report --omit=fack/_testrunner.py,fack/tests/* 26 | coverage html --omit=fack/_testrunner.py,fack/tests/* -d htmlcov/ 27 | 28 | [testenv:docs] 29 | basepython = python 30 | deps = sphinx 31 | commands = 32 | {envpython} setup.py build_sphinx 33 | --------------------------------------------------------------------------------