Repository: sebst/pythonic-news Branch: master Commit: 3a6d03985f40 Files: 110 Total size: 187.4 KB Directory structure: gitextract__e9vnpwr/ ├── .gitignore ├── LICENSE ├── README.md ├── accounts/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations/ │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20190914_1247.py │ │ ├── 0003_auto_20190914_2031.py │ │ ├── 0004_auto_20190915_1105.py │ │ ├── 0005_emailverification_verification_code.py │ │ ├── 0006_auto_20190915_1321.py │ │ ├── 0007_auto_20190923_1323.py │ │ └── __init__.py │ ├── models.py │ ├── receivers.py │ ├── templates/ │ │ └── accounts/ │ │ ├── __base.html │ │ ├── create_invite.html │ │ ├── invite.html │ │ ├── login.html │ │ ├── logout.html │ │ ├── my_profile.html │ │ ├── password_change_done.html │ │ ├── password_change_form.html │ │ ├── password_forgotten_form.html │ │ ├── profile.html │ │ ├── register.html │ │ ├── register_closed.html │ │ ├── resend_verification.html │ │ └── user_tree.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── emaildigest/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── mailing.py │ ├── migrations/ │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20190923_2028.py │ │ ├── 0003_auto_20190923_2120.py │ │ ├── 0004_auto_20190926_2118.py │ │ └── __init__.py │ ├── models.py │ ├── receivers.py │ ├── templates/ │ │ └── emaildigest/ │ │ ├── __base.html │ │ ├── _subscription_form_tag.html │ │ ├── my_subscriptions.html │ │ ├── subscribe.html │ │ ├── subscribe_thankyou_a.html │ │ ├── subscribe_thankyou_u.html │ │ ├── subscribe_verification_done.html │ │ ├── unsubscribe.html │ │ ├── unsubscribe_confirm.html │ │ └── unsubscribe_done.html │ ├── templatetags/ │ │ ├── __init__.py │ │ └── emaildigest_extra.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── hnclone/ │ ├── __init__.py │ ├── context_processors.py │ ├── middleware.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── news/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── feeds.py │ ├── forms.py │ ├── migrations/ │ │ ├── 0001_initial.py │ │ ├── 0002_story_title.py │ │ ├── 0003_auto_20190908_1642.py │ │ ├── 0004_auto_20190908_2249.py │ │ ├── 0005_auto_20190908_2250.py │ │ ├── 0006_auto_20190908_2251.py │ │ ├── 0007_auto_20190908_2256.py │ │ ├── 0008_story_duplicate_of.py │ │ ├── 0009_story_domain.py │ │ ├── 0010_auto_20190930_1620.py │ │ ├── 0011_auto_20190930_1623.py │ │ ├── 0012_auto_20190930_1625.py │ │ └── __init__.py │ ├── models.py │ ├── receivers.py │ ├── templates/ │ │ └── news/ │ │ ├── __base.html │ │ ├── _item_content_tag.html │ │ ├── _item_control_tag.html │ │ ├── _item_tag.html │ │ ├── _link_user_tag.html │ │ ├── _more_link_tag.html │ │ ├── bookmarklet.html │ │ ├── formatting_help.html │ │ ├── index.html │ │ ├── item.html │ │ ├── item_delete.html │ │ ├── item_edit.html │ │ ├── submit.html │ │ └── zen.html │ ├── templatetags/ │ │ ├── __init__.py │ │ └── news_extra.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── requirements.txt └── static/ ├── news.css └── news.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Created by https://www.gitignore.io/api/code,macos,python,django,visualstudiocode # Edit at https://www.gitignore.io/?templates=code,macos,python,django,visualstudiocode ### Code ### .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json ### Django ### *.log *.pot *.pyc __pycache__/ local_settings.py db.sqlite3 media # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ # in your Git repository. Update and uncomment the following line accordingly. # /staticfiles/ ### Django.Python Stack ### # Byte-compiled / optimized / DLL files *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo # Django stuff: db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ ### macOS ### # General .DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk ### Python ### # Byte-compiled / optimized / DLL files # C extensions # Distribution / packaging # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. # Installer logs # Unit test / coverage reports # Translations # Django stuff: # Flask stuff: # Scrapy stuff: # Sphinx documentation # PyBuilder # Jupyter Notebook # IPython # pyenv # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. # celery beat schedule file # SageMath parsed files # Environments # Spyder project settings # Rope project settings # mkdocs documentation # mypy # Pyre type checker ### VisualStudioCode ### ### VisualStudioCode Patch ### # Ignore all local history of files .history # End of https://www.gitignore.io/api/code,macos,python,django,visualstudiocode ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: README.md ================================================ # pythonic-news A Hacker News lookalike written in Python/Django, powering [https://news.python.sc](https://news.python.sc) [![screenshot](http://cdn.sebastiansteins.com/screenshot-news-python-sc.png "Screenshot")](https://news.python.sc) ## Setup for local development ### Set up virtual environment ```shell script python -m venv venv/ source venv/bin/activate ``` ### Install Dependencies ```shell script pip install -r requirements.txt ``` ### Migrate Database ```shell script python manage.py migrate ``` ### Extra setup work * Set ```DEBUG=True``` if necessary * Add ```127.0.0.1``` to ```ALLOWED_HOSTS``` ### Run Django Server ```shell script python manage.py runserver ``` Now you can access the website at ```127.0.0.1:8000```. ================================================ FILE: accounts/__init__.py ================================================ default_app_config = 'accounts.apps.AccountsConfig' ================================================ FILE: accounts/admin.py ================================================ from django.contrib import admin # Register your models here. ================================================ FILE: accounts/apps.py ================================================ from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'accounts' def ready(self): from . import receivers ================================================ FILE: accounts/forms.py ================================================ from django import forms from .models import CustomUser, Invitation class ProfileForm(forms.ModelForm): class Meta: model = CustomUser fields = ['about', 'email'] def clean_email(self): data = self.cleaned_data['email'] if data: data = data.lower() return data class RegisterForm(forms.ModelForm): MIN_LENGTH = 8 class Meta: model = CustomUser fields = ['username', 'password', 'email'] widgets = { 'password': forms.PasswordInput(), } def clean_password(self): password = self.cleaned_data.get('password') if len(password) < self.MIN_LENGTH: raise forms.ValidationError("Your password must be at least %d characters long." % self.MIN_LENGTH) return password class CreateInviteForm(forms.ModelForm): class Meta: model = Invitation fields = ['invited_email_address'] def clean_invited_email_address(self): invited_email_address = self.cleaned_data['invited_email_address'] if invited_email_address: invited_email_address = invited_email_address.lower() return invited_email_address class PasswordForgottenForm(forms.Form): username = forms.CharField() class PasswortResetForm(forms.Form): password = forms.CharField() ================================================ FILE: accounts/migrations/0001_initial.py ================================================ # Generated by Django 2.2.5 on 2019-09-07 12:14 import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='CustomUser', fields=[ ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('karma', models.IntegerField(default=1)), ('about', models.TextField(default='')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name': 'user', 'verbose_name_plural': 'users', 'abstract': False, }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), ] ================================================ FILE: accounts/migrations/0002_auto_20190914_1247.py ================================================ # Generated by Django 2.2.5 on 2019-09-14 12:47 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='customuser', name='karma', field=models.IntegerField(default=0), ), migrations.CreateModel( name='EmailVerification', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('created_at', models.DateTimeField(auto_now_add=True)), ('changed_at', models.DateTimeField(auto_now=True)), ('verified', models.BooleanField(default=False)), ('verified_at', models.DateTimeField(null=True)), ('email', models.EmailField(max_length=254)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] ================================================ FILE: accounts/migrations/0003_auto_20190914_2031.py ================================================ # Generated by Django 2.2.5 on 2019-09-14 20:31 from django.conf import settings import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion import django.db.models.manager import mptt.fields class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_auto_20190914_1247'), ] operations = [ migrations.AlterModelManagers( name='customuser', managers=[ ('_tree_manager', django.db.models.manager.Manager()), ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.AddField( model_name='customuser', name='level', field=models.PositiveIntegerField(default=1, editable=False), preserve_default=False, ), migrations.AddField( model_name='customuser', name='lft', field=models.PositiveIntegerField(default=1, editable=False), preserve_default=False, ), migrations.AddField( model_name='customuser', name='parent', field=mptt.fields.TreeForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='invitees', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='customuser', name='rght', field=models.PositiveIntegerField(default=2, editable=False), preserve_default=False, ), migrations.AddField( model_name='customuser', name='tree_id', field=models.PositiveIntegerField(db_index=True, default=1, editable=False), preserve_default=False, ), ] ================================================ FILE: accounts/migrations/0004_auto_20190915_1105.py ================================================ # Generated by Django 2.2.5 on 2019-09-15 11:05 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('accounts', '0003_auto_20190914_2031'), ] operations = [ migrations.CreateModel( name='Invitation', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('created_at', models.DateTimeField(auto_now_add=True)), ('changed_at', models.DateTimeField(auto_now=True)), ('num_signups', models.PositiveIntegerField(default=1, null=True)), ('invited_email_address', models.EmailField(default=None, max_length=254, null=True)), ('invite_code', models.UUIDField(default=uuid.uuid4, editable=False)), ('inviting_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='customuser', name='used_invitation', field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='accounts.Invitation'), ), ] ================================================ FILE: accounts/migrations/0005_emailverification_verification_code.py ================================================ # Generated by Django 2.2.5 on 2019-09-15 13:16 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('accounts', '0004_auto_20190915_1105'), ] operations = [ migrations.AddField( model_name='emailverification', name='verification_code', field=models.UUIDField(default=uuid.uuid4, editable=False), ), ] ================================================ FILE: accounts/migrations/0006_auto_20190915_1321.py ================================================ # Generated by Django 2.2.5 on 2019-09-15 13:21 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0005_emailverification_verification_code'), ] operations = [ migrations.AlterModelOptions( name='customuser', options={}, ), migrations.AlterModelManagers( name='customuser', managers=[ ], ), ] ================================================ FILE: accounts/migrations/0007_auto_20190923_1323.py ================================================ # Generated by Django 2.2.5 on 2019-09-23 13:23 from django.conf import settings import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_auto_20190915_1321'), ] operations = [ migrations.AlterModelOptions( name='customuser', options={'default_manager_name': 'objects'}, ), migrations.AlterModelManagers( name='customuser', managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='PasswordResetRequest', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('created_at', models.DateTimeField(auto_now_add=True)), ('changed_at', models.DateTimeField(auto_now=True)), ('verification_code', models.UUIDField(default=uuid.uuid4, editable=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] ================================================ FILE: accounts/migrations/__init__.py ================================================ ================================================ FILE: accounts/models.py ================================================ import uuid from django.contrib.auth.models import AbstractUser from django.urls import reverse from django.db import models from django.utils import timezone import datetime import hashlib from urllib.parse import urlencode from mptt.models import MPTTModel, TreeForeignKey #class CustomUser(MPTTModel, AbstractUser): class CustomUser(AbstractUser, MPTTModel): class Meta: default_manager_name = 'objects' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) karma = models.IntegerField(default=0) about = models.TextField(default='') # api_key = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='invitees', editable=False) used_invitation = models.ForeignKey('Invitation', null=True, default=None, on_delete=models.CASCADE) def get_absolute_url(self): return reverse("accounts_profile", kwargs={"username": self.username}) @property def is_green(self): return timezone.now() - self.date_joined < datetime.timedelta(days=30) def gravatar_url(self, size=80): if self.email: default = "https://www.example.com/default.jpg" url = "https://www.gravatar.com/avatar/" + hashlib.md5(self.email.lower()).hexdigest() + "?" url += urlencode({'d':default, 's':str(size)}) return url @property def latest_verified_email(self): verifications = EmailVerification.objects.filter(user=self, verified=True).order_by('-verified_at') if verifications.count(): return verifications[0].email class Invitation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) inviting_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) num_signups = models.PositiveIntegerField(null=True, default=1) invited_email_address = models.EmailField(null=True, default=None) invite_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) def get_absolute_url(self): return reverse("accounts_invite", kwargs={"pk": self.pk}) def get_register_url(self): return reverse("accounts_register") + '?invite=' + str(self.invite_code) @property def active(self): return True pass # TODO class EmailVerification(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) verified = models.BooleanField(default=False) verified_at = models.DateTimeField(null=True) email = models.EmailField() user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) verification_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) def get_verify_url(self): return reverse("accounts_verify", kwargs={"verification_code": self.verification_code}) class PasswordResetRequest(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) verification_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) def get_verify_url(self): return reverse("password_forgotten", kwargs={"verification_code": self.verification_code}) ================================================ FILE: accounts/receivers.py ================================================ #from django.core.signals import request_finished from django.db.models.signals import pre_save, post_save, post_delete from django.dispatch import receiver from django.core.mail import send_mail from django.core.mail import EmailMultiAlternatives from django.conf import settings from .models import CustomUser, Invitation, EmailVerification, PasswordResetRequest @receiver(pre_save) def lower_email_addresses(sender, instance, **kwargs): if isinstance(instance, CustomUser): email = getattr(instance, 'email', None) if email: instance.email = email.lower() @receiver(post_save) def send_invitation_email(sender, instance, created, **kwargs): if created and isinstance(instance, Invitation): subject, from_email, to = 'You have been invited to %s'%(settings.SITE_DOMAIN), 'bot@python.sc', instance.invited_email_address text_content = """ You have been invited to news.python.sc. Would you like to accept {inviting_user}'s invite? Please sign up here: https://news.python.sc{url} -- news.python.sc - A social news aggregator for the Python community. """.format(inviting_user=instance.inviting_user.username, url=instance.get_register_url()) #html_content = '

This is an important message.

' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) #msg.attach_alternative(html_content, "text/html") msg.send() @receiver(post_save) def create_verification(sender, instance, created, **kwargs): if isinstance(instance, CustomUser): if instance.email: verifications = EmailVerification.objects.filter(user=instance, email=instance.email) if not verifications.count(): create_v = True else: verified = any([i.verified for i in verifications]) # create_v = not verified create_v = False if create_v: verification = EmailVerification(user=instance, email=instance.email) verification.save() @receiver(post_save) def send_verification_email(sender, instance, created, **kwargs): if created and isinstance(instance, EmailVerification): subject, from_email, to = 'Please confirm your account on news.python.sc', 'bot@python.sc', instance.email text_content = """ Please confirm your email address here: https://news.python.sc{url} -- news.python.sc - A social news aggregator for the Python community. """.format(url=instance.get_verify_url()) #html_content = '

This is an important message.

' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) #msg.attach_alternative(html_content, "text/html") msg.send() @receiver(post_save) def send_password_reset_email(sender, instance, created, **kwargs): if created and isinstance(instance, PasswordResetRequest): subject, from_email, to = 'Reset password for your account on news.python.sc', 'bot@python.sc', instance.email text_content = """ Please confirm your email address here: https://news.python.sc{url} -- news.python.sc - A social news aggregator for the Python community. """.format(url=instance.get_verify_url()) #html_content = '

This is an important message.

' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) #msg.attach_alternative(html_content, "text/html") msg.send() ================================================ FILE: accounts/templates/accounts/__base.html ================================================ {% extends 'news/__base.html' %} ================================================ FILE: accounts/templates/accounts/create_invite.html ================================================ {% extends 'accounts/__base.html' %} {% block content %}
{% csrf_token %} {{form}}
{% endblock content %} ================================================ FILE: accounts/templates/accounts/invite.html ================================================ {% extends 'accounts/__base.html' %} {% block content %} You have created an invite for {{invitation.invited_email_address}}. Create anotther? {% endblock content %} ================================================ FILE: accounts/templates/accounts/login.html ================================================ {% extends 'accounts/__base.html' %} {% block content %} {% if user.is_authenticated %} Signed in. {% else %}

Login

{% csrf_token %} {{ form.as_p }}
password forgotten? {% endif %} {% endblock content %} ================================================ FILE: accounts/templates/accounts/logout.html ================================================ {% extends 'accounts/__base.html' %} {% block content %}

Logout

{% csrf_token %}
{% endblock content %} ================================================ FILE: accounts/templates/accounts/my_profile.html ================================================ {% extends 'accounts/__base.html' %} {% block content %} {% endblock content %} ================================================ FILE: accounts/templates/accounts/password_change_done.html ================================================ {% extends 'accounts/__base.html' %} {% block content %} Password changed successfully. {% endblock content %} ================================================ FILE: accounts/templates/accounts/password_change_form.html ================================================ {% extends 'accounts/__base.html' %} {% block content %}

Change Password

{% csrf_token %} {{ form.as_p }}
{% endblock content %} ================================================ FILE: accounts/templates/accounts/password_forgotten_form.html ================================================ {% extends 'accounts/__base.html' %} {% block content %}

Password forgotten?

{% csrf_token %} {{ form.as_p }}
{% endblock content %} ================================================ FILE: accounts/templates/accounts/profile.html ================================================ {% extends 'accounts/__base.html' %} {% block content %}
user: {{profile}}
created: {{profile.date_joined}}
karma: {{profile.karma}}
about: {{profile.about}}
submissions
comments
{% endblock content %} ================================================ FILE: accounts/templates/accounts/register.html ================================================ {% extends 'accounts/__base.html' %} {% block content %}

Create Account

While you don't need to supply an email address, it is strongly recommended to do so. Without an email address, we won't be able to restore your account if you've lost your password.

{% csrf_token %} {{ form.as_table }}

By signing up, you agree to the Zen of {{SITE_NAME}}.

{% endblock content %} ================================================ FILE: accounts/templates/accounts/register_closed.html ================================================ {% extends 'accounts/__base.html' %} {% block content %} Closed.

You want an invite? Please leave your email address here: Request an invite

{% endblock content %} ================================================ FILE: accounts/templates/accounts/resend_verification.html ================================================ {% extends 'accounts/__base.html' %} {% block content %} A new email has been sent. {% endblock content %} ================================================ FILE: accounts/templates/accounts/user_tree.html ================================================ {% extends 'accounts/__base.html' %} {% block content %} {% load mptt_tags %}
    {% recursetree users %}
  • {{ node.username }} {% if not node.is_leaf_node %}
      {{ invitees }}
    {% endif %}
  • {% endrecursetree %}
{% endblock content %} ================================================ FILE: accounts/tests.py ================================================ from django.contrib.auth.models import AnonymousUser from accounts.models import CustomUser from django.test import RequestFactory, TestCase from .views import * from .models import * class BasicAccountsTest(TestCase): """Tests the basic functionality of the accounts app.""" def setUp(self): # Every test needs access to the request factory. self.factory = RequestFactory() self.user = CustomUser.objects.create_user( username='sebst', email='hi@seb.st', password='top_secret') self.other_user = CustomUser.objects.create_user( username='bla1', email='two@seb.st', password='top_secret') class ReceiversAccountsTest(TestCase): """Tests the basic functionality of the accounts app.""" def setUp(self): # Every test needs access to the request factory. self.factory = RequestFactory() self.user = CustomUser.objects.create_user( username='sebst', email='hi@seb.st', password='top_secret') self.other_user = CustomUser.objects.create_user( username='bla1', email='two@seb.st', password='top_secret') def test_lower_email_addresses(self): user = CustomUser.objects.create_user( username='johndoe', email='J.Doe@exAmple.org', password='top_secret') user = CustomUser.objects.get(pk=user.pk) self.assertEqual(user.email, 'j.doe@example.org') def test_send_invitation_email(self): self.skipTest() self.assertTrue(False) def test_create_verification(self): user = CustomUser.objects.create_user( username='johndoe', email='J.Doe@exAmple.org', password='top_secret') verification = EmailVerification.objects.get(user=user, email=user.email) self.assertEqual(verification.email, user.email) self.assertEqual(verification.email, 'j.doe@example.org') def test_send_verification_email(self): self.skipTest() self.assertTrue(False) def test_send_password_reset_email(self): self.skipTest() self.assertTrue(False) ================================================ FILE: accounts/urls.py ================================================ from django.urls import path, include from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('profile', views.profile, name="accounts_my_profile"), path('profile/', views.profile, name="accounts_profile"), path('user-tree', views.user_tree, name="accounts_user_tree"), path('create-invite', views.create_invite, name="accounts_create_invite"), path('invite/', views.invite, name="accounts_invite"), path('verify/', views.verify, name="accounts_verify"), path('resend-verification', views.resend_verification, name="accounts_resend_verification"), path('register', views.register, name="accounts_register"), # path('accounts/', include('django.contrib.auth.urls')), # new path('accounts/login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name="login"), #path('accounts/logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name="logout"), path('accounts/logout/', views.logout, name="logout"), path('accounts/password-change/', auth_views.PasswordChangeView.as_view(template_name='accounts/password_change_form.html'), name="password_change"), path('accounts/password-change-done/', auth_views.PasswordChangeDoneView.as_view(template_name='accounts/password_change_done.html'), name="password_change_done"), path('accounts/password-forgotten/', views.password_forgotten, name="password_forgotten"), path('accounts/password-forgotten/', views.password_forgotten, name="password_forgotten"), ] ================================================ FILE: accounts/views.py ================================================ from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login from django.contrib.auth import logout as do_logout from django.urls import reverse from django.conf import settings from django.utils import timezone from .models import CustomUser, Invitation, EmailVerification from .forms import ProfileForm, RegisterForm, CreateInviteForm, PasswordForgottenForm, PasswortResetForm def profile(request, username=None): if username is None: return my_profile(request) profile = get_object_or_404(CustomUser, username=username) if profile == request.user: return my_profile(request) return render(request, 'accounts/profile.html', {'profile': profile}) @login_required def my_profile(request): instance = request.user form = ProfileForm(request.POST or None, instance=instance) if request.user.email: verifications = EmailVerification.objects.filter(user=request.user, email=request.user.email) verified = any([i.verified for i in verifications]) else: verified = False if request.method == 'POST': if form.is_valid(): instance = form.save() return HttpResponseRedirect(instance.get_absolute_url()) return render(request, 'accounts/my_profile.html', {'form': form, 'verified': verified}) @login_required def create_invite(request): instance = Invitation(inviting_user = request.user) form = CreateInviteForm(request.POST or None, instance=instance) if request.method=="POST": if form.is_valid(): instance = form.save() return HttpResponseRedirect(instance.get_absolute_url()) return render(request, 'accounts/create_invite.html', {'form': form}) @login_required def invite(request, pk): invitation = get_object_or_404(Invitation, pk=pk) return render(request, 'accounts/invite.html', {'invitation': invitation}) def register(request): invite_code = request.GET.get('invite') try: invitation = Invitation.objects.get(invite_code=invite_code) except: invitation = None instance = CustomUser(used_invitation=invitation, parent=getattr(invitation, 'inviting_user', None), email=getattr(invitation, 'invited_email_address', None)) if not settings.ACCEPT_UNINVITED_REGISTRATIONS and (invitation is None or not getattr(invitation, 'active', False)): return render(request, 'accounts/register_closed.html') form = RegisterForm(request.POST or None, instance=instance) if request.method == 'POST': if form.is_valid(): instance = form.save() instance.set_password(form.cleaned_data['password']) instance.is_active = True instance.save() login(request, instance) return HttpResponseRedirect(instance.get_absolute_url()) return render(request, 'accounts/register.html', {'form': form}) def verify(request, verification_code): verification = get_object_or_404(EmailVerification, verification_code=verification_code) assert verification.user.email == verification.email verification.verified = True verification.verified_at = timezone.now() verification.save() return render(request, 'accounts/verify.html') @login_required def resend_verification(request): if request.method=="POST": assert request.user.email verification = EmailVerification(user=request.user, email=request.user.email) verification.save() return render(request, 'accounts/resend_verification.html') def user_tree(request): users = CustomUser.objects.all() return render(request, 'accounts/user_tree.html', {'users': users}) def password_forgotten(request, verification_code=None): assert not request.user.is_authenticated error = None if verification_code is None: if 'sent' in request.GET.keys(): return render(request, 'accounts/password_forgotten_sent.html', {}) form = PasswordForgottenForm(request.POST or None) if form.is_valid(): user = None try: username = form.cleaned_data['username'] user = CustomUser.objects.get_by_natural_key(username) except: pass if user: if user.email == user.latest_verified_email: reset_request = PasswordResetRequest(user=user) reset_request.save() return HttpResponseRedirect(reverse('password_forgotten')+'?sent') else: error = 'This user does not have a verified email. Please contact support.' else: error = 'User not found.' return render(request, 'accounts/password_forgotten_form.html', {'form': form, 'error': error}) else: reset_request = get_object_or_404(PasswordResetRequest, verification_code=verification_code) form = PasswortResetForm(request.POST or None) if request.method=="POST": if form.is_valid(): reset_request.user.set_password(form.cleaned_data['password']) # TODO: confirm password, password rules reset_request.user.save() return HttpResponseRedirect(reverse('/login')) return render(request, 'accounts/password_forgotten_form.html', {'form': form}) @login_required def logout(request): if request.method=="POST": do_logout(request) redirect_url = settings.LOGOUT_REDIRECT_URL or '/' return HttpResponseRedirect(redirect_url) else: return render(request, 'accounts/logout.html') ================================================ FILE: emaildigest/__init__.py ================================================ default_app_config = 'emaildigest.apps.EmaildigestConfig' ================================================ FILE: emaildigest/admin.py ================================================ from django.contrib import admin # Register your models here. ================================================ FILE: emaildigest/apps.py ================================================ from django.apps import AppConfig class EmaildigestConfig(AppConfig): name = 'emaildigest' def ready(self): from . import receivers ================================================ FILE: emaildigest/forms.py ================================================ from django import forms from .models import UserSubscription, AnonymousSubscription, Subscription class UserSubscriptionForm(forms.ModelForm): thankyou = 'u' class Meta: model = UserSubscription fields = [] class AnonymousSubscriptionForm(forms.ModelForm): thankyou = 'a' class Meta: model = AnonymousSubscription fields = ['email'] def clean_email(self): data = self.cleaned_data['email'] if data: data = data.lower() return data def validate_active_email(email): qs = Subscription.objects.filter(verfied_email=email, is_active=True) if not qs.count(): raise forms.ValidationError( ('No subscription found for email %(email)s'), code='invalid', params={'email': email},) class UnsunscribeForm(forms.Form): email = forms.EmailField(validators=[validate_active_email]) def clean_email(self): data = self.cleaned_data['email'] if data: data = data.lower() return data def get_subscription_form(user, *args, **kwargs): return AnonymousSubscriptionForm(*args, **kwargs) if user.is_authenticated: return UserSubscriptionForm(*args, **kwargs) else: return AnonymousSubscriptionForm(*args, **kwargs) ================================================ FILE: emaildigest/mailing.py ================================================ from django.conf import settings from .models import Subscription, EmailDigest def create_and_send_digest(frequency): pass # Get list of objects stories = [] # TODO: Find from _font_page # make templates and trigger sending subscriptions = Subscription.objects.filter(is_active=True, frequency=frequency) for subscription in subscriptions: tpl = 'TODO: Here is your list' # TODO subject = settings.SITE_NAME + " " + frequency + " Digest" send_mail(subscription, tpl, subject) def send_mail(subscription, template, subject): pass ================================================ FILE: emaildigest/migrations/0001_initial.py ================================================ # Generated by Django 2.2.5 on 2019-09-23 13:23 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('news', '0008_story_duplicate_of'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Subscription', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('created_at', models.DateTimeField(auto_now_add=True)), ('changed_at', models.DateTimeField(auto_now=True)), ], ), migrations.CreateModel( name='AnonymousSubscription', fields=[ ('subscription_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='emaildigest.Subscription')), ('email', models.EmailField(blank=True, max_length=254, null=True)), ('verified', models.BooleanField(default=False)), ('verified_at', models.DateTimeField(null=True)), ('verification_code', models.UUIDField(default=uuid.uuid4, editable=False)), ], bases=('emaildigest.subscription',), ), migrations.CreateModel( name='EmailDigest', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('created_at', models.DateTimeField(auto_now_add=True)), ('changed_at', models.DateTimeField(auto_now=True)), ('frequency', models.CharField(choices=[('weekly', 'weekly'), ('daily', 'daily')], max_length=16)), ('weekly_weekday', models.CharField(blank=True, choices=[('Sun', 'Sun'), ('Mon', 'Mon'), ('Tue', 'Tue'), ('Wed', 'Wed'), ('Thu', 'Thu'), ('Fri', 'Fri'), ('Sat', 'Sat')], max_length=16, null=True)), ('stories', models.ManyToManyField(to='news.Story')), ], ), migrations.CreateModel( name='UserSubscription', fields=[ ('subscription_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='emaildigest.Subscription')), ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], bases=('emaildigest.subscription',), ), ] ================================================ FILE: emaildigest/migrations/0002_auto_20190923_2028.py ================================================ # Generated by Django 2.2.5 on 2019-09-23 20:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('emaildigest', '0001_initial'), ] operations = [ migrations.AddField( model_name='subscription', name='frequency', field=models.CharField(choices=[('weekly', 'weekly'), ('daily', 'daily')], default='daily', max_length=16), preserve_default=False, ), migrations.AddField( model_name='subscription', name='weekly_weekday', field=models.CharField(blank=True, choices=[('Sun', 'Sun'), ('Mon', 'Mon'), ('Tue', 'Tue'), ('Wed', 'Wed'), ('Thu', 'Thu'), ('Fri', 'Fri'), ('Sat', 'Sat')], max_length=16, null=True), ), ] ================================================ FILE: emaildigest/migrations/0003_auto_20190923_2120.py ================================================ # Generated by Django 2.2.5 on 2019-09-23 21:20 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('emaildigest', '0002_auto_20190923_2028'), ] operations = [ migrations.AddField( model_name='anonymoussubscription', name='logged_in_user', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='subscription', name='verfied_email', field=models.EmailField(blank=True, max_length=254, null=True), ), ] ================================================ FILE: emaildigest/migrations/0004_auto_20190926_2118.py ================================================ # Generated by Django 2.2.5 on 2019-09-26 21:18 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('emaildigest', '0003_auto_20190923_2120'), ] operations = [ migrations.AddField( model_name='subscription', name='is_active', field=models.BooleanField(default=False), ), migrations.CreateModel( name='UnSubscription', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('created_at', models.DateTimeField(auto_now_add=True)), ('changed_at', models.DateTimeField(auto_now=True)), ('from_digest', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='emaildigest.EmailDigest')), ('subscription', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='emaildigest.Subscription')), ], ), ] ================================================ FILE: emaildigest/migrations/__init__.py ================================================ ================================================ FILE: emaildigest/models.py ================================================ import uuid from django.db import models class EmailDigest(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) frequency = models.CharField(max_length=16, choices=(('weekly', 'weekly'), ('daily', 'daily'))) weekly_weekday = models.CharField(max_length=16, null=True, blank=True, choices=(('Sun', 'Sun'), ('Mon', 'Mon'), ('Tue', 'Tue'), ('Wed', 'Wed'), ('Thu', 'Thu'), ('Fri', 'Fri'), ('Sat', 'Sat'))) stories = models.ManyToManyField('news.Story') class Subscription(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) frequency = models.CharField(max_length=16, choices=(('weekly', 'weekly'), ('daily', 'daily'))) weekly_weekday = models.CharField(max_length=16, null=True, blank=True, choices=(('Sun', 'Sun'), ('Mon', 'Mon'), ('Tue', 'Tue'), ('Wed', 'Wed'), ('Thu', 'Thu'), ('Fri', 'Fri'), ('Sat', 'Sat'))) verfied_email = models.EmailField(null=True, blank=True) is_active = models.BooleanField(default=False) class UserSubscription(Subscription): user = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE, null=True) class AnonymousSubscription(Subscription): email = models.EmailField(null=True, blank=True) verified = models.BooleanField(default=False) verified_at = models.DateTimeField(null=True) verification_code = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) logged_in_user = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE, null=True) class UnSubscription(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE) from_digest = models.ForeignKey(EmailDigest, on_delete=models.CASCADE, null=True) ================================================ FILE: emaildigest/receivers.py ================================================ #from django.core.signals import request_finished from django.db.models.signals import pre_save, post_save, post_delete from django.dispatch import receiver from django.core.mail import send_mail from django.core.mail import EmailMultiAlternatives from .models import UserSubscription, AnonymousSubscription, Subscription, UnSubscription @receiver(pre_save) def lower_email_addresses(sender, instance, **kwargs): if isinstance(instance, (UserSubscription, AnonymousSubscription)): if isinstance(instance, AnonymousSubscription): instance.email = instance.email.lower() if isinstance(instance, Subscription): if instance.verfied_email: instance.verfied_email = instance.verfied_email.lower() @receiver(post_save) def activate_subscription_on_verification(sender, instance, created, **kwargs): if isinstance(instance, AnonymousSubscription): if instance.verified: subscription = instance.subscription_ptr subscription.is_active = True subscription.verfied_email = instance.email subscription.save() @receiver(post_save) def on_subscription_created(sender, instance, created, **kwargs): if created and isinstance(instance, (UserSubscription, AnonymousSubscription)): subscription = instance @receiver(post_save) def on_unsubscription_created(sender, instance, created, **kwargs): if created and isinstance(instance, (UnSubscription)): unsubscription = instance unsubscription.subscription.is_active = False unsubscription.subscription.save() ================================================ FILE: emaildigest/templates/emaildigest/__base.html ================================================ {% extends 'news/__base.html' %} ================================================ FILE: emaildigest/templates/emaildigest/_subscription_form_tag.html ================================================ {% if False and subscription_form %}

Don't miss interesting Python stories by subscribing to our digest

{% csrf_token %} {{subscription_form}}
{% endif %} ================================================ FILE: emaildigest/templates/emaildigest/my_subscriptions.html ================================================ {% extends 'emaildigest/__base.html' %} {% block content %}
my_subscriptions.html
{% endblock content %} ================================================ FILE: emaildigest/templates/emaildigest/subscribe.html ================================================ ================================================ FILE: emaildigest/templates/emaildigest/subscribe_thankyou_a.html ================================================ {% extends 'emaildigest/__base.html' %} {% block content %}
Thank you!
You will receive a confirmation email soon
{% endblock content %} ================================================ FILE: emaildigest/templates/emaildigest/subscribe_thankyou_u.html ================================================ {% extends 'emaildigest/__base.html' %} {% block content %}
Thank you!
You are now subscribed.
{% endblock content %} ================================================ FILE: emaildigest/templates/emaildigest/subscribe_verification_done.html ================================================ {% extends 'emaildigest/__base.html' %} {% block content %}
Thank you!
You are now subscribed.
{% endblock content %} ================================================ FILE: emaildigest/templates/emaildigest/unsubscribe.html ================================================ {% extends 'news/__base.html' %} {% load humanize %} {% load mptt_tags %} {% block content %}
{% csrf_token %} {{form}}
{% endblock content %} ================================================ FILE: emaildigest/templates/emaildigest/unsubscribe_confirm.html ================================================ {% extends 'news/__base.html' %} {% load humanize %} {% load mptt_tags %} {% block content %}
{% csrf_token %} Do yo really want to unsubscribe?
{% endblock content %} ================================================ FILE: emaildigest/templates/emaildigest/unsubscribe_done.html ================================================ {% extends 'news/__base.html' %} {% load humanize %} {% load mptt_tags %} {% block content %}
You are unsubscribed.
{% endblock content %} ================================================ FILE: emaildigest/templatetags/__init__.py ================================================ ================================================ FILE: emaildigest/templatetags/emaildigest_extra.py ================================================ from django import template register = template.Library() from emaildigest.forms import get_subscription_form @register.inclusion_tag('emaildigest/_subscription_form_tag.html') def digest_subscription_form(user, **kwargs): form = get_subscription_form(user) return {'subscription_form': form} ================================================ FILE: emaildigest/tests.py ================================================ from django.contrib.auth.models import AnonymousUser from accounts.models import CustomUser from django.test import RequestFactory, TestCase from .views import * from .models import * from .forms import * class BasicEmailDigestTest(TestCase): """Tests the basic functionality of the emaildigest app.""" def setUp(self): # Every test needs access to the request factory. self.factory = RequestFactory() self.user = CustomUser.objects.create_user( username='sebst', email='hi@seb.st', password='top_secret') self.other_user = CustomUser.objects.create_user( username='bla1', email='two@seb.st', password='top_secret') def _subscribe(self, i=0): self.assertEqual(Subscription.objects.all().count(), 0+i) request = self.factory.post('/digest/subscribe', {'email': 'test@example.org'}) request.user = self.user response = subscribe(request) #self.assertContains(response.url, 'thankyou') self.assertRegex(response.url, r'.*thankyou.*') self.assertEqual(Subscription.objects.all().count(), 1+i) subscription = Subscription.objects.all().order_by('-created_at')[0] self.assertFalse(subscription.is_active) verification_code = subscription.anonymoussubscription.verification_code return subscription def _confirm(self, subscription): subscription = Subscription.objects.get(pk=subscription.pk) self.assertFalse(subscription.anonymoussubscription.verified) self.assertFalse(subscription.is_active) verification_code = subscription.anonymoussubscription.verification_code url = '/digest/subscribe?v=' + str(verification_code) request = self.factory.get(url) request.user = self.user response = subscribe(request) subscription = Subscription.objects.get(pk=subscription.pk) anonymoussubscription = AnonymousSubscription.objects.get(pk=subscription.pk) self.assertTrue(anonymoussubscription.verified) def _unsubscribe_via_mail(self, subscription, assert_form_error=False): subscription = Subscription.objects.get(pk=subscription.pk) self.assertEqual(UnSubscription.objects.all().count(), 0) url = '/digest/unsubscribe' request = self.factory.post(url, {'email': subscription.anonymoussubscription.email}) request.user = self.user response = unsubscribe(request) if assert_form_error: # self.assertFormError(response, UnsunscribeForm, 'email', 'No subscription found for email ' + subscription.anonymoussubscription.email) self.assertContains(response, 'No subscription found for email') return None self.assertEqual(response.status_code, 302) self.assertRegex(response.url, r'.*done.*') self.assertEqual(UnSubscription.objects.all().count(), 1) unsubscription = UnSubscription.objects.get() return unsubscription def test_subscribe(self): subscription = self._subscribe() self.assertFalse(subscription.is_active) def test_subscribe_confirm(self): subscription = self._subscribe() self._confirm(subscription) subscription = Subscription.objects.get(pk=subscription.pk) self.assertTrue(subscription.is_active) def test_subscribe_unsubscribe(self): subscription = self._subscribe() unsubscription = self._unsubscribe_via_mail(subscription, assert_form_error=True) subscription = Subscription.objects.get(pk=subscription.pk) self.assertFalse(subscription.is_active) def test_subscribe_confirm_unsubscribe(self): subscription = self._subscribe() self._confirm(subscription) unsubscription = self._unsubscribe_via_mail(subscription) subscription = Subscription.objects.get(pk=subscription.pk) self.assertFalse(subscription.is_active) def test_subscribe_unsubscribe_confirm(self): subscription = self._subscribe() unsubscription = self._unsubscribe_via_mail(subscription, assert_form_error=True) subscription = Subscription.objects.get(pk=subscription.pk) self.assertFalse(subscription.is_active) subscription = Subscription.objects.get(pk=subscription.pk) self.assertFalse(subscription.is_active) self._confirm(subscription) subscription = Subscription.objects.get(pk=subscription.pk) self.assertTrue(subscription.is_active) def test_subscribe_confirm_unsubscribe_subscribe(self): subscription = self._subscribe() self._confirm(subscription) unsubscription = self._unsubscribe_via_mail(subscription) subscription2 = self._subscribe(i=1) subscription2 = Subscription.objects.get(pk=subscription2.pk) self.assertFalse(subscription.is_active) def test_subscribe_confirm_unsubscribe_subscribe_confirm(self): subscription = self._subscribe() self._confirm(subscription) unsubscription = self._unsubscribe_via_mail(subscription) subscription = Subscription.objects.get(pk=subscription.pk) self.assertFalse(subscription.is_active) re_subscription = self._subscribe(i=1) self._confirm(re_subscription) re_subscription = Subscription.objects.get(pk=re_subscription.pk) subscription = Subscription.objects.get(pk=subscription.pk) self.assertTrue(re_subscription.is_active) self.assertFalse(subscription.is_active) # class ReceiversEmailDigestTest(TestCase): # """Tests the basic receivers functionality of the emaildigest app.""" # def setUp(self): # # Every test needs access to the request factory. # self.factory = RequestFactory() # self.user = CustomUser.objects.create_user( # username='sebst', email='hi@seb.st', password='top_secret') # self.other_user = CustomUser.objects.create_user( # username='bla1', email='two@seb.st', password='top_secret') # def test_lower_email_addresses(self): # self.fail() # def activate_subscription_on_verification(self): # self.fail() # def test_on_subscription_created(self): # self.fail() # def test_on_unsubscription_created(self): # self.fail() ================================================ FILE: emaildigest/urls.py ================================================ from django.urls import path, include from . import views urlpatterns = [ #path('profile', views.profile, name="accounts_my_profile"), path('subscribe', views.subscribe, name="emaildigest_subscribe"), path('subscriptions', views.my_subscriptions, name="emaildigest_subscriptions"), path('unsubscribe', views.unsubscribe, name='emaildigest_unsubscribe'), path('unsubscribe//', views.unsubscribe, name='emaildigest_unsubscribe'), ] ================================================ FILE: emaildigest/views.py ================================================ from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect from django.utils import timezone from .forms import get_subscription_form, UnsunscribeForm from .models import AnonymousSubscription, UnSubscription, Subscription, EmailDigest def subscribe(request): form = get_subscription_form(request.user, request.POST or None) thankyou = request.GET.get('thankyou', None) if thankyou: return render(request, 'emaildigest/subscribe_thankyou_%s.html'%(thankyou), {'prevent_footer_subscription_form': True}) verification_code = request.GET.get('v', None) if verification_code: subscription = get_object_or_404(AnonymousSubscription, verification_code=verification_code) if not subscription.verified: subscription.verified = True subscription.verified_at = timezone.now() subscription.save() # TODO: Verify User account if needed # TODO: Activate usage of get_subsciption_form return render(request, 'emaildigest/subscribe_verification_done.html', {'prevent_footer_subscription_form': True}) if request.method=="POST": if form.is_valid(): subscription = form.save() if request.user.is_authenticated: subscription.logged_in_user = request.user subscription.save() return HttpResponseRedirect(reverse('emaildigest_subscribe') + '?thankyou=' + form.thankyou) return render(request, 'emaildigest/subscribe.html', {'subscription_form': form, 'prevent_footer_subscription_form': True}) def unsubscribe(request, subscription_id=None, digest_id=None): if 'done' in request.GET.keys(): email = request.GET.get('email', None) suscription = request.GET.get('subscription', None) return render(request, 'emaildigest/unsubscribe_done.html', {'email': email, 'subscription': subscription, 'prevent_footer_subscription_form': True}) if subscription_id is None and digest_id is None: form = UnsunscribeForm(request.POST or None) if request.method=="POST": if form.is_valid(): email = form.cleaned_data['email'] subscriptions = Subscription.objects.filter(verfied_email=email, is_active=True) for subscription in subscriptions: unsubscription = UnSubscription(subscription=subscription) unsubscription.save() return HttpResponseRedirect(reverse('emaildigest_unsubscribe') + "?done&email="+email) return render(request, 'emaildigest/unsubscribe.html', {'form': form, 'prevent_footer_subscription_form': True}) elif subscription_id is not None and digest_id is not None: subscription = get_object_or_404(Subscription, pk=subscription_id) digest = get_object_or_404(EmailDigest, pk=digest_id) if request.method=="GET": return render(request, 'emaildigest/unsubscribe_confirm.html', {}) elif request.method=="POST": unsubscription = UnSubscription(subscription=subscription, from_digest=digest) unsubscription.save() return HttpResponseRedirect(reverse('emaildigest_unsubscribe') + "?done&subscription="+subscription_id) else: return HttpResponseRedirect(reverse('emaildigest_unsubscribe')) else: return HttpResponseRedirect(reverse('emaildigest_unsubscribe')) pass def my_subscriptions(request): return render(request, 'emaildigest/my_subscriptions.html') ================================================ FILE: hnclone/__init__.py ================================================ ================================================ FILE: hnclone/context_processors.py ================================================ from django.conf import settings def settings_context_processor(request): return { 'SITE_NAME': settings.SITE_NAME, 'SITE_DOMAIN': settings.SITE_DOMAIN, 'SITE_URL': settings.SITE_URL } ================================================ FILE: hnclone/middleware.py ================================================ ================================================ FILE: hnclone/settings.py ================================================ """ Django settings for hnclone project. Generated by 'django-admin startproject' using Django 2.2.5. Modified by me 2019-09-30 15.50 CEST For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'TODO' # TODO # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False USE_X_FORWARDED_HOST = True ALLOWED_HOSTS = [ 'news.python.sc', 'localhost', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'mptt', 'debug_toolbar', 'accounts', 'news', 'emaildigest', ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'django.middleware.gzip.GZipMiddleware', #'htmlmin.middleware.HtmlMinifyMiddleware', # TODO: When activated, Django Debug Toolbar has JS issues 'htmlmin.middleware.MarkRequestMiddleware', ] ROOT_URLCONF = 'hnclone.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'hnclone.context_processors.settings_context_processor', ], }, }, ] WSGI_APPLICATION = 'hnclone.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] AUTH_USER_MODEL = 'accounts.CustomUser' INTERNAL_IPS = [ '127.0.0.1', ] PAGING_SIZE = 30 HTML_MINIFY = True LOGOUT_REDIRECT_URL = '/' LOGIN_REDIRECT_URL = '/' ACCEPT_UNINVITED_REGISTRATIONS = False SITE_NAME = 'Pythonic News' SITE_URL = 'https://news.python.sc' SITE_DOMAIN = 'news.python.sc' ================================================ FILE: hnclone/urls.py ================================================ """hnclone URL Configuration """ from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.http import HttpResponse urlpatterns = [ path('', include('news.urls')), path('', include('accounts.urls')), path('digest/', include('emaildigest.urls')), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns from ratelimit.exceptions import Ratelimited def handler403(request, exception=None): if isinstance(exception, Ratelimited): return HttpResponse("
Sorry, we're not able to serve your requests this quickly.", status=429) return HttpResponseForbidden('Forbidden') ================================================ FILE: hnclone/wsgi.py ================================================ """ WSGI config for hnclone project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os, sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR ) sys.path.append(BASE_DIR + '/../') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hnclone.settings') application = get_wsgi_application() ================================================ FILE: manage.py ================================================ #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hnclone.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() ================================================ FILE: news/__init__.py ================================================ default_app_config = 'news.apps.NewsConfig' ================================================ FILE: news/admin.py ================================================ from django.contrib import admin from .models import Story, Comment admin.site.register(Story) admin.site.register(Comment) ================================================ FILE: news/apps.py ================================================ from django.apps import AppConfig class NewsConfig(AppConfig): name = 'news' def ready(self): from . import receivers ================================================ FILE: news/feeds.py ================================================ from django.contrib.syndication.views import Feed from .models import Story from .views import _newest, _front_page from django.conf import settings class NewestFeed(Feed): title = "%s: Latest"%(settings.SITE_NAME) link = "/newest/" description = "Latest stories" def items(self): return _newest(30, 0) def item_title(self, item): return item.title def item_pubdate(self, item): return item.created_at def item_updateddate(self, item): return item.changed_at def item_author_name(self, item): return str(item.user) def item_author_link(self, item): return settings.SITE_URL + item.user.get_absolute_url() def item_description(self, item): return "TODO" # TODO return item.url class FrontPageFeed(NewestFeed): title = "%s: Front Page" % (settings.SITE_NAME) link = "/feed" description = "Front Page stories" def items(self): return _front_page(30, 0) ================================================ FILE: news/forms.py ================================================ from django import forms from .models import Comment, Story class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['text'] class AddStoryForm(forms.ModelForm): class Meta: model = Story fields = ['title', 'url', 'text'] def clean(self): cleaned_data = super().clean() title = self.cleaned_data.get('title') text = self.cleaned_data.get('text') url = self.cleaned_data.get('url') if not title: raise forms.ValidationError("Please provide a title.") if (not text) and (not url): raise forms.ValidationError("Please provide either a text or a URL.") class StoryForm(forms.ModelForm): class Meta: model = Story fields = ['title', 'text'] ================================================ FILE: news/migrations/0001_initial.py ================================================ # Generated by Django 2.2.5 on 2019-09-07 12:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import mptt.fields import uuid class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Item', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('created_at', models.DateTimeField(auto_now_add=True)), ('changed_at', models.DateTimeField(auto_now=True)), ('upvotes', models.PositiveIntegerField(default=0)), ('downvotes', models.PositiveIntegerField(default=0)), ('points', models.IntegerField(default=0)), ('num_comments', models.PositiveIntegerField(default=0)), ('lft', models.PositiveIntegerField(editable=False)), ('rght', models.PositiveIntegerField(editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='news.Item')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Story', fields=[ ('item_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='news.Item')), ('url', models.URLField(null=True)), ('text', models.TextField(null=True)), ], options={ 'abstract': False, }, bases=('news.item',), ), migrations.CreateModel( name='Vote', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('created_at', models.DateTimeField(auto_now_add=True)), ('changed_at', models.DateTimeField(auto_now=True)), ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news.Item')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Comment', fields=[ ('item_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='news.Item')), ('text', models.TextField()), ('to_story', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='news.Story')), ], options={ 'abstract': False, }, bases=('news.item',), ), ] ================================================ FILE: news/migrations/0002_story_title.py ================================================ # Generated by Django 2.2.5 on 2019-09-07 13:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0001_initial'), ] operations = [ migrations.AddField( model_name='story', name='title', field=models.CharField(default='-', max_length=255), preserve_default=False, ), ] ================================================ FILE: news/migrations/0003_auto_20190908_1642.py ================================================ # Generated by Django 2.2.5 on 2019-09-08 16:42 from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('news', '0002_story_title'), ] operations = [ migrations.AddField( model_name='vote', name='vote', field=models.SmallIntegerField(default=1), ), migrations.AlterField( model_name='comment', name='to_story', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='news.Story'), ), migrations.AlterField( model_name='item', name='downvotes', field=models.PositiveIntegerField(default=0, editable=False), ), migrations.AlterField( model_name='item', name='num_comments', field=models.PositiveIntegerField(default=0, editable=False), ), migrations.AlterField( model_name='item', name='parent', field=mptt.fields.TreeForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='news.Item'), ), migrations.AlterField( model_name='item', name='points', field=models.IntegerField(default=0, editable=False), ), migrations.AlterField( model_name='item', name='upvotes', field=models.PositiveIntegerField(default=0, editable=False), ), migrations.AlterField( model_name='story', name='text', field=models.TextField(blank=True, null=True), ), migrations.AlterField( model_name='story', name='title', field=models.CharField(blank=True, max_length=255), ), migrations.AlterField( model_name='story', name='url', field=models.URLField(blank=True, null=True), ), ] ================================================ FILE: news/migrations/0004_auto_20190908_2249.py ================================================ # Generated by Django 2.2.5 on 2019-09-08 22:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0003_auto_20190908_1642'), ] operations = [ migrations.AddIndex( model_name='item', index=models.Index(fields=['points', 'created_at'], name='news_item_points_d03885_idx'), ), migrations.AddIndex( model_name='item', index=models.Index(fields=['created_at', 'points'], name='news_item_created_f2b812_idx'), ), ] ================================================ FILE: news/migrations/0005_auto_20190908_2250.py ================================================ # Generated by Django 2.2.5 on 2019-09-08 22:50 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('news', '0004_auto_20190908_2249'), ] operations = [ migrations.RemoveIndex( model_name='item', name='news_item_points_d03885_idx', ), ] ================================================ FILE: news/migrations/0006_auto_20190908_2251.py ================================================ # Generated by Django 2.2.5 on 2019-09-08 22:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0005_auto_20190908_2250'), ] operations = [ migrations.RemoveIndex( model_name='item', name='news_item_created_f2b812_idx', ), migrations.AddIndex( model_name='item', index=models.Index(fields=['points', 'created_at'], name='news_item_points_d03885_idx'), ), ] ================================================ FILE: news/migrations/0007_auto_20190908_2256.py ================================================ # Generated by Django 2.2.5 on 2019-09-08 22:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0006_auto_20190908_2251'), ] operations = [ migrations.RemoveIndex( model_name='item', name='news_item_points_d03885_idx', ), migrations.AddField( model_name='item', name='is_ask', field=models.BooleanField(default=False), ), migrations.AddField( model_name='item', name='is_show', field=models.BooleanField(default=False), ), migrations.AddIndex( model_name='item', index=models.Index(fields=['created_at', 'points'], name='news_item_created_f2b812_idx'), ), ] ================================================ FILE: news/migrations/0008_story_duplicate_of.py ================================================ # Generated by Django 2.2.5 on 2019-09-23 13:23 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('news', '0007_auto_20190908_2256'), ] operations = [ migrations.AddField( model_name='story', name='duplicate_of', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='news.Story'), ), ] ================================================ FILE: news/migrations/0009_story_domain.py ================================================ # Generated by Django 2.2.5 on 2019-09-30 16:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0008_story_duplicate_of'), ] operations = [ migrations.AddField( model_name='story', name='domain', field=models.CharField(blank=True, max_length=255, null=True), ), ] ================================================ FILE: news/migrations/0010_auto_20190930_1620.py ================================================ # Generated by Django 2.2.5 on 2019-09-30 16:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0009_story_domain'), ] operations = [ migrations.AlterField( model_name='story', name='domain', field=models.CharField(blank=True, db_index=True, max_length=255, null=True), ), ] ================================================ FILE: news/migrations/0011_auto_20190930_1623.py ================================================ # Generated by Django 2.2.5 on 2019-09-30 16:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0010_auto_20190930_1620'), ] operations = [ migrations.AddIndex( model_name='story', index=models.Index(fields=['domain', 'duplicate_of'], name='news_story_domain_07db78_idx'), ), ] ================================================ FILE: news/migrations/0012_auto_20190930_1625.py ================================================ # Generated by Django 2.2.5 on 2019-09-30 16:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0011_auto_20190930_1623'), ] operations = [ migrations.AddIndex( model_name='item', index=models.Index(fields=['created_at', 'id'], name='news_item_created_10dd57_idx'), ), migrations.AddIndex( model_name='item', index=models.Index(fields=['id', 'created_at'], name='news_item_id_b557ce_idx'), ), ] ================================================ FILE: news/migrations/__init__.py ================================================ ================================================ FILE: news/models.py ================================================ import uuid from accounts.models import CustomUser from django.db import models from mptt.models import MPTTModel, TreeForeignKey from django.urls import reverse from urllib.parse import urlparse class Item(MPTTModel): class Meta: indexes = [ #models.Index(fields=['points', 'created_at']), models.Index(fields=['created_at', 'points']), models.Index(fields=['created_at', 'id']), models.Index(fields=['id', 'created_at']), ] # ordering = ['-created_at'] id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) upvotes = models.PositiveIntegerField(default=0, editable=False) downvotes = models.PositiveIntegerField(default=0, editable=False) points = models.IntegerField(default=0, editable=False) num_comments = models.PositiveIntegerField(default=0, editable=False) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', editable=False) user = models.ForeignKey(to=CustomUser, on_delete=models.CASCADE) is_ask = models.BooleanField(default=False) is_show = models.BooleanField(default=False) def get_absolute_url(self): return reverse("item", kwargs={"pk": self.pk}) def can_be_upvoted_by(self, user): if not user.is_authenticated: return False if user == self.user: return False if Vote.objects.filter(user=user, item=self).count(): return False return True def can_be_downvoted_by(self, user): if not user.is_authenticated: return False if user == self.user: return False else: if user.karma > 1: if not Vote.objects.filter(user=user, item=self).count(): return True return False def can_be_edited_by(self, user): return self.user == user and self.num_comments == 0 def can_be_deleted_by(self, user): return self.can_be_edited_by(user) class Story(Item): class Meta: indexes = [ models.Index(fields=['domain', 'duplicate_of']), ] is_story = True # class Meta: # ordering = ['-pk'] title = models.CharField(max_length=255, blank=True) url = models.URLField(null=True, blank=True) text = models.TextField(null=True, blank=True) duplicate_of = models.ForeignKey('Story', on_delete=models.CASCADE, null=True) domain = models.CharField(max_length=255, null=True, blank=True, db_index=True) def __str__(self): return self.title # @property # def domain(self): # o = urlparse(self.url) # return o.hostname def can_be_downvoted_by(self, user): return False # def Kcomments(self): # return self.comments # return { # 'all': self.get_descendants() # lambda: [i.comment for i in self.get_descendants().select_related('comment')] # } # return self.comments class Comment(Item): is_comment = True text = models.TextField() to_story = models.ForeignKey(Story, on_delete=models.CASCADE, related_name="comments") def __str__(self): return self.text[:255] def comments(self): return { #'all': lambda: [i.comment for i in self.get_descendants().select_related('comment')] 'all': lambda: [i.comment for i in self.get_descendants()] } class Vote(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) item = models.ForeignKey(Item, on_delete=models.CASCADE) # vote = None # -1 | 0 | 1 --> BooleanField(default=None, null=True)?? vote = models.SmallIntegerField(default=1) user = models.ForeignKey(to=CustomUser, on_delete=models.CASCADE) ================================================ FILE: news/receivers.py ================================================ #from django.core.signals import request_finished from django.db.models.signals import pre_save, post_save, post_delete from django.dispatch import receiver from urllib.parse import urlparse from .models import Item, Vote, Comment, Story @receiver(pre_save) def mark_show_and_ask(sender, instance, **kwargs): if isinstance(instance, Story): if instance.title.lower().startswith('ask'): instance.is_ask = True if instance.title.lower().startswith('show'): instance.is_show = True @receiver(post_save) def create_self_upvote_for_submission(sender, instance, created, **kwargs): if created and isinstance(instance, Item): vote = Vote(item=instance, user=instance.user) vote.save() @receiver(post_save) def check_for_duplicates(sender, instance, created, **kwargs): if created and isinstance(instance, Story): story = instance if story.url and story.duplicate_of is None: other_stories = Story.objects.filter(url=story.url).exclude(pk=story.pk).order_by('-changed_at') c = other_stories.count() if c > 0: new_vote = Vote(item=other_stories[0], vote=1, user=story.user) new_vote.save() story.duplicate_of = other_stories[0] story.save() @receiver(post_save) def update_votes_count_on_submission(sender, instance, created, **kwargs): if created and isinstance(instance, Vote): vote = instance item = instance.item other_votes = Vote.objects.filter(item=vote.item, user=vote.user, vote=vote.vote).exclude(pk=vote.pk) if other_votes.count(): return if instance.vote > 0: item.upvotes += instance.vote else: item.downvotes += (-1)*instance.vote item.points += instance.vote item.save() @receiver(post_save) def update_user_karma_on_vote(sender, instance, created, **kwargs): if created and isinstance(instance, Vote): vote = instance other_votes = Vote.objects.filter(item=vote.item, user=vote.user, vote=vote.vote).exclude(pk=vote.pk) if other_votes.count(): return item = instance.item if item.user != instance.user: item.user.karma += instance.vote item.user.save() def _recount_comments(instance, val=1): assert isinstance(instance, Comment) instance.to_story.num_comments += val instance.to_story.save() parent = instance.parent while parent is not None: parent.num_comments += val parent.save() parent = parent.parent @receiver(post_save) def update_comments_count_on_submission(sender, instance, created, **kwargs): if created and isinstance(instance, Comment): _recount_comments(instance, 1) @receiver(post_delete) def update_comments_count_on_deletion(sender, instance, **kwargs): if isinstance(instance, Comment): _recount_comments(instance, -1) @receiver(post_delete) def update_item_votes_on_unvote(sender, instance, **kwargs): if isinstance(instance, Vote): vote = instance item = vote.item if vote.user == item.user: return item.points -= vote.vote if vote.vote > 0: item.upvotes -= abs(vote.vote) else: item.downvotes -= abs(vote.vote) item.save() @receiver(post_delete) def update_user_karma_on_unvote(sender, instance, **kwargs): if isinstance(instance, Vote): vote = instance item = vote.item if vote.user == item.user: return item.user.karma -= vote.vote item.user.save() @receiver(pre_save) def add_domain_to_link_stories(sender, instance, **kwargs): if isinstance(instance, Story): if instance.url: o = urlparse(instance.url) instance.domain = o.hostname.lower() ================================================ FILE: news/templates/news/__base.html ================================================ {% load static %}{% load humanize %}{% load emaildigest_extra %} {% block title %}{% endblock title %}{{SITE_NAME}}
{% block content %}{% endblock content %}
================================================ FILE: news/templates/news/_item_content_tag.html ================================================ {% load news_extra %}
{% if item.title %} {% if item.url %} {{item.title}} {% if item.domain %}({{item.domain}}){% endif %} {% else %} {{item.title}} {% endif %} {% endif %} {% if item.text and not hide_text %} {{ item.text | comment_markdown }} {% endif %}
================================================ FILE: news/templates/news/_item_control_tag.html ================================================ {% load humanize %} {% load news_extra %} {{item.points}} point{{item.points|pluralize}} by {%link_user item.user%} {{item.created_at|naturaltime}} | flag | hide | {{item.num_comments}} comments {% if item.num_comments == 0 and item.user == request_user %}| edit{% endif %} {% if item.num_comments == 0 and item.user == request_user %}| delete{% endif %} ================================================ FILE: news/templates/news/_item_tag.html ================================================ {% load humanize %} {% load static %} {% load news_extra %} {%if rank %}{{rank}}.{% endif %}
{% user_arrows user=user item=item as assignment_options %} {% if 'star' in assignment_options %} * {% endif %} {% if 'up' in assignment_options %}
{% csrf_token %}
{% endif %} {% if 'down' in assignment_options %}
{% csrf_token %}
{% endif %} {% if not assignment_options %}   {% endif %}
{% if item.is_comment %}{% item_control item=item request_user=request_user %} {% else%} {% item_content item=item hide_text=hide_text %} {% endif %} {% if item.is_comment %}{% item_content item=item hide_text=hide_text %} {% else %}{% item_control item=item request_user=request_user %}{% endif %} ================================================ FILE: news/templates/news/_link_user_tag.html ================================================ {{user}} ================================================ FILE: news/templates/news/_more_link_tag.html ================================================ More ================================================ FILE: news/templates/news/bookmarklet.html ================================================ {% extends "news/__base.html" %} {% load humanize %} {% load static %} {% load mptt_tags %} {% load news_extra %} {% block content %}

When you click on the bookmarklet, it will submit the page you're on. To install, drag this link to your browser toolbar:

post to 🐍
{% endblock content %} ================================================ FILE: news/templates/news/formatting_help.html ================================================
Markdown Output
# Heading level 1

Heading level 1

## Heading level 2

Heading level 2

### Heading level 3
Heading level 3
#### Heading level 4
Heading level 4
* unordered item 1
* unordered item 2
* unordered item 3
                
  • unordered item 1
  • unordered item 2
  • unordered item 3
1. ordered item 1
2. ordered item 2
3. ordered item 3
                
  1. ordered item 1
  2. ordered item 2
  3. ordered item 3
[title](https://www.google.com/)
                
title
================================================ FILE: news/templates/news/index.html ================================================ {% extends "news/__base.html" %} {% load humanize %} {% load static %} {% load mptt_tags %} {% load news_extra %} {% block content %}
{% for story in stories %} {% news_item item=story show_text=False hide_text=hide_text rank=forloop.counter|add:rank_start user=user %} {% if show_children %} {% endif %} {% endfor %}
{% recursetree story.comments.all %} {% news_item item=node show_text=True hide_text=hide_text rank=None user=user %} {% if not node.is_leaf_node %} {% endif %}
{{ children }}
{% endrecursetree %}
{% more_link %}
{% endblock content %} ================================================ FILE: news/templates/news/item.html ================================================ {% extends 'news/__base.html' %} {% load humanize %} {% load mptt_tags %} {% load news_extra %} {% block content %}
{% news_item item=item rank=None hide_text=False user=user %}
{% if comment_form %}
{% csrf_token %} {{ comment_form.text }}

{% include "news/formatting_help.html" %} {% endif %}

{% recursetree item.comments.all %} {% news_item item=node rank=None show_text=True hide_text=False user=user %} {% if not node.is_leaf_node %} {% endif %} {% endrecursetree %}
{{ children }}
{% endblock content %} ================================================ FILE: news/templates/news/item_delete.html ================================================ {% extends 'news/__base.html' %} {% load humanize %} {% load mptt_tags %} {% load news_extra %} {% block content %}
Are you sure, you want to delete this:
{% news_item item=item rank=None hide_text=False user=user %}
{% csrf_token %}
{% endblock content %} ================================================ FILE: news/templates/news/item_edit.html ================================================ {% extends 'news/__base.html' %} {% load humanize %} {% load mptt_tags %} {% load news_extra %} {% block content %}
{% news_item item=item rank=None hide_text=False user=user %}
{% if edit_form %}
{% csrf_token %} {{ edit_form.text }}guidelines
{% endif %}
{% endblock content %} ================================================ FILE: news/templates/news/submit.html ================================================ {% extends 'news/__base.html' %} {% block content %}
{% csrf_token %} {{ form.as_table }}

Leave url blank to submit a question for discussion. If there is no url, the text (if any) will appear at the top of the thread.

You can also submit via bookmarklet.

{% endblock content %} ================================================ FILE: news/templates/news/zen.html ================================================ {% extends 'news/__base.html' %} {% load humanize %} {% load mptt_tags %} {% block content %}

The Zen of {{SITE_NAME}} (aka Guidelines)

Based on The Zen of Python

{{SITE_NAME}} is a platform for friends of Python (the programming language).
It shall enable people to discover, share and discuss interesting thoughts, publications or web pieces about Python and its related fields.
On the platform, anybody shall feel welcomed.

Beautiful is better than ugly.

Be beautiful to each other. Always remember, {{SITE_NAME}} is a community built around Python stuff, which is mostly technical. When discussing this kind of stuff, there is no need to offend someone personally.

Explicit is better than implicit.

Be on-topic. We are here to discuss the Python programming language, its ecosystem, its applications and its community. For off-topic discussions there are plenty of forums out there on the net.
This community regards political discussions as off-topic, unless discussion the walrus operator (just kidding).

In the face of ambiguity, refuse the temptation to guess.

Please think of a contribution of another member of this community as well-intended. We should all assume that people here behave nicely and respectful.

Errors should never pass silently.

We value transparency. If there is any action taken by moderators on submissions, comments or user accounts, we try to be as clear about what happened as possible. For now, there is no moderation system in place. This means that we might be forced to delete contributions silently when we notice off-topic, disrespectful or otherwise abusive content without further notice. However, a moderation audit trail is on the roadmap to be implemented soon

Code of Conduct

This is a news aggregator and we all want to be nice to each other. Rude behaviour in form of continiously spamming, posting off-topic content, offending people ad-hominem, will result in a ban.

{% endblock content %} ================================================ FILE: news/templatetags/__init__.py ================================================ ================================================ FILE: news/templatetags/news_extra.py ================================================ from django import template from django.utils.safestring import mark_safe import mistune register = template.Library() @register.inclusion_tag('news/_item_tag.html', takes_context=True) def news_item(context, item, **kwargs): kwargs['item'] = item kwargs['request_user'] = context['user'] return kwargs @register.inclusion_tag('news/_link_user_tag.html') def link_user(user): return { 'user': user } @register.simple_tag def user_arrows(user, item): if user == item.user: return ['star'] else: res = [] if item.can_be_upvoted_by(user=user): res.append('up') if item.can_be_downvoted_by(user=user): res.append('down') return res @register.inclusion_tag('news/_more_link_tag.html', takes_context=True) def more_link(context): request = context.request page = int(request.GET.get('p', 0)) query_dict = request.GET.copy() query_dict['p'] = page + 1 _more_link=request.path_info + '?' + query_dict.urlencode() return {'more_link': _more_link} @register.inclusion_tag('news/_item_content_tag.html') def item_content(**kwargs): return kwargs @register.inclusion_tag('news/_item_control_tag.html') def item_control(**kwargs): return kwargs class MarkdownRenderer(mistune.Renderer): @classmethod def setup(cls): renderer = cls(escape=True, hard_wrap=True) return mistune.Markdown(renderer=renderer) def header(self, text, level, raw=None): level = min(level + 2, 6) return super().header(text, level, raw) markdown = MarkdownRenderer.setup() @register.filter def comment_markdown(value): return mark_safe(markdown(value)) ================================================ FILE: news/tests.py ================================================ from django.contrib.auth.models import AnonymousUser from accounts.models import CustomUser from django.test import RequestFactory, TestCase from .views import * from .models import * class BasicNewsTest(TestCase): """Tests the basic functionality of the news app.""" def setUp(self): # Every test needs access to the request factory. self.factory = RequestFactory() self.user = CustomUser.objects.create_user( username='sebst', email='hi@seb.st', password='top_secret') self.other_user = CustomUser.objects.create_user( username='bla1', email='two@seb.st', password='top_secret') def test_submit_get(self): """The submit form is displayed.""" request = self.factory.get('/submit') request.user = self.user response = submit(request) self.assertEqual(response.status_code, 200) self.assertContains(response, '', views.item, name="item"), path('item//upvote', views.upvote, name="upvote"), # TODO path('item//downvote', views.downvote, name="downvote"), # TODO path('item//edit', views.item_edit, name="edit"), path('item//delete', views.item_delete, name="delete"), path('submit', views.submit, name="submit"), path('newest/feed/', NewestFeed()), path('feed/', FrontPageFeed()), path('robots.txt', views.robots_txt, name="robots_txt"), path('humans.txt', views.humans_txt, name="humans_txt"), path('bookmarklet', views.bookmarklet, name="bookmarklet"), ] ================================================ FILE: news/views.py ================================================ from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse, Http404, HttpResponseForbidden from django.conf import settings from django.contrib.auth.decorators import login_required from django.urls import reverse from .models import Item, Story, Comment, Vote from accounts.models import CustomUser from .forms import CommentForm, AddStoryForm, StoryForm from ratelimit.decorators import ratelimit # create_story # add_comment # upvote / downvote / unvote # flag / hide # Tags? # suggest changes # save DEFAULT_GET_RATE = "2/s" DEFAULT_VOTES_RATE = "10/m" DEFAULT_POST_RATE = "5/m" TIMEOUT_MEDIUM = 0# 1*60 # one minute TIMEOUT_SHORT = 0# 1*2 # two seconds from django.db.models.functions import Power, Now, Cast, Extract #, Min from django.db.models import Value, F, Func, ExpressionWrapper, fields, Q, Min from django.db.models import OuterRef, Subquery from django.db import models from django.utils import timezone import datetime from django.core.cache import cache from django.views.decorators.vary import vary_on_cookie from django.views.decorators.cache import cache_page from django.db import connection def _one_page_back(request): page = int(request.GET.get('p', 0)) query_dict = request.GET.copy() page = page - 1 if page >= 0: query_dict['p'] = page else: return None _more_link=request.path_info + '?' + query_dict.urlencode() return HttpResponseRedirect(_more_link) def _front_page(paging_size=settings.PAGING_SIZE, page=0, add_filter={}, add_q=[], as_of=None, days_back=50): # TODO: weighting https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d # (P-1) / (T+2)^G if as_of is None: now = timezone.now() else: now = as_of if connection.vendor == 'postgresql': now_value = Value(now, output_field=fields.DateTimeField()) submission_age_float = ExpressionWrapper( ( now_value - F('created_at')), output_field=fields.DurationField()) submission_age_hours = ExpressionWrapper(Extract(F('tf'), 'epoch') / 60 / 60 + 2.1 , output_field=fields.FloatField()) real_p = ExpressionWrapper(F('points') - 1, output_field=fields.FloatField()) formula = ExpressionWrapper( F('p') / ( Power(F('tfh'), F('g')) +0.001) , output_field=fields.FloatField()) return Story.objects.select_related('user')\ .filter(duplicate_of__isnull=True)\ .filter(points__gte=1) \ .filter(created_at__gte=now - datetime.timedelta(days=days_back)) \ .filter(created_at__lte=now) \ .filter(**add_filter) \ .annotate(tf=submission_age_float) \ .annotate(tfh=submission_age_hours) \ .annotate(p=real_p) \ .annotate(g=Value(1.8, output_field=fields.FloatField())) \ .annotate(formula=formula) \ .order_by('-formula')[(page*paging_size):(page+1)*(paging_size)] elif connection.vendor == 'sqlite': now_value = Value(now, output_field=fields.DateTimeField()) submission_age_float = ExpressionWrapper( ( now_value - F('created_at')), output_field=fields.FloatField()) submission_age_hours = ExpressionWrapper(F('tf') / 60 / 60 / 1000000 + 2.1 , output_field=fields.FloatField()) real_p = ExpressionWrapper(F('points') - 1, output_field=fields.FloatField()) formula = ExpressionWrapper( F('p') / ( Power(F('tfh'), F('g')) +0.001) , output_field=fields.FloatField()) return Story.objects.select_related('user')\ .filter(duplicate_of__isnull=True)\ .filter(points__gte=1) \ .filter(created_at__gte=now - datetime.timedelta(days=days_back)) \ .filter(created_at__lte=now) \ .filter(**add_filter) \ .annotate(tf=submission_age_float) \ .annotate(tfh=submission_age_hours) \ .annotate(p=real_p) \ .annotate(g=Value(1.8, output_field=fields.FloatField())) \ .annotate(formula=formula) \ .order_by('-formula')[(page*paging_size):(page+1)*(paging_size)] else: raise NotImplementedError("No frontpage magic for database engine %s implemented"%(connection.vendor)) def _newest(paging_size=settings.PAGING_SIZE, page=0, add_filter={}, add_q=[]): return Story.objects \ .select_related('user') \ .filter(duplicate_of__isnull=True) \ .filter(**add_filter) \ .filter(*add_q) \ .order_by('-created_at')[(page*paging_size):(page+1)*(paging_size)] @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True) def index(request): page = int(request.GET.get('p', 0)) stories = cache.get_or_set("news-index-%s"%(page), lambda: list(_front_page(page=page)), timeout=TIMEOUT_MEDIUM) # one minute if len(stories) < 1 and page != 0: back = _one_page_back(request) if back: return back return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE}) @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True) def show(request): page = int(request.GET.get('p', 0)) stories = cache.get_or_set("news-show-%s"%(page), lambda: list(_front_page(page=page, add_filter={'is_show': True})), timeout=TIMEOUT_MEDIUM) # one minute if len(stories) < 1 and page != 0: back = _one_page_back(request) if back: return back return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE}) @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True) def ask(request): page = int(request.GET.get('p', 0)) stories = lambda: list(_front_page(page=page, add_filter={'is_ask': True})) stories = cache.get_or_set("news-ask-%s"%(page), stories, timeout=TIMEOUT_MEDIUM) # one minute if len(stories) < 1 and page != 0: back = _one_page_back(request) if back: return back return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE}) @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True) def newest(request): # Done page = int(request.GET.get('p', 0)) add_filter = {} add_q = [] if 'submitted_by' in request.GET.keys(): try: submitted_by = CustomUser.objects.get_by_natural_key(request.GET['submitted_by']) add_filter['user'] = submitted_by except CustomUser.DoesNotExist: raise Http404() if 'upvoted_by' in request.GET.keys(): try: assert request.user.is_authenticated assert request.user.username == request.GET['upvoted_by'] except AssertionError: return HttpResponseForbidden() add_filter['pk__in'] = Vote.objects.filter(vote=1, user=request.user).values('item') add_q.append(~Q(user=request.user)) if 'site' in request.GET.keys(): add_filter['domain'] = request.GET['site'] stories = lambda: list(_newest(page=page, add_filter=add_filter, add_q=add_q)) stories = cache.get_or_set("news-newest-%s"%(page), stories, timeout=TIMEOUT_SHORT) # two seconds if len(stories) < 1 and page != 0: back = _one_page_back(request) if back: return back return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE}) @login_required @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True) @cache_page(TIMEOUT_SHORT) @vary_on_cookie def threads(request): page = int(request.GET.get('p', 0)) paging_size = settings.PAGING_SIZE tree = Comment.objects.filter( tree_id=OuterRef('tree_id'), user=OuterRef('user')).values('tree_id', 'user__pk').annotate(min_level=Min('level')).order_by() stories = Comment.objects.filter( user=request.user ).filter( Q(level__in=Subquery(tree.values('min_level'), output_field=models.IntegerField())) # TODO: level= or level__in= ??? ).select_related( 'user', 'parent', 'to_story' ).order_by( '-created_at' )[(page*paging_size):(page+1)*(paging_size)] if len(stories) < 1 and page != 0: back = _one_page_back(request) if back: return back return render(request, 'news/index.html', {'stories': stories, 'hide_text':False, 'page': page, 'rank_start': None, 'show_children': True}) @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True) @cache_page(TIMEOUT_SHORT) @vary_on_cookie def comments(request): # TODO page = int(request.GET.get('p', 0)) paging_size = settings.PAGING_SIZE add_filter = {} if 'submitted_by' in request.GET.keys(): try: submitted_by = CustomUser.objects.get_by_natural_key(request.GET['submitted_by']) add_filter['user'] = submitted_by except CustomUser.DoesNotExist: raise Http404() if 'upvoted_by' in request.GET.keys(): try: assert request.user.is_authenticated assert request.user.username == request.GET['upvoted_by'] except AssertionError: return HttpResponseForbidden() add_filter['pk__in'] = Vote.objects.filter(vote=1, user=request.user).values('item') stories = Comment.objects.filter( parent=None ).filter( **add_filter ).select_related( 'user', 'parent', 'to_story' ).order_by( 'created_at' )[(page*paging_size):(page+1)*(paging_size)] if len(stories) < 1 and page != 0: back = _one_page_back(request) if back: return back return render(request, 'news/index.html', {'stories': stories, 'hide_text':False, 'page': page, 'rank_start': page*paging_size}) @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, block=True) def zen(request): return render(request, 'news/zen.html') def _vote(request, pk, vote=None, unvote=False): assert not unvote and vote is not None or unvote and vote is None item = get_object_or_404(Item, pk=pk) if (not unvote) and (vote is not None): votes = Vote.objects.filter(item=item, user=request.user) if request.method=="POST": if vote > 0: if not item.can_be_upvoted_by(request.user): return HttpResponseForbidden() else: if not item.can_be_downvoted_by(request.user): return HttpResponseForbidden() vote = Vote(vote=vote, item=item, user=request.user) vote.save() return HttpResponse("OK %s"%(vote.pk)) if unvote: if request.method=="POST": Vote.objects.filter(item=item, user=request.user).delete() return HttpResponse("OK") @login_required @ratelimit(key="user_or_ip", group="news-votes", rate=DEFAULT_VOTES_RATE, block=True) def upvote(request, pk): return _vote(request, pk, vote=1) @login_required @ratelimit(key="user_or_ip", group="news-votes", rate=DEFAULT_VOTES_RATE, block=True) def downvote(request, pk): return _vote(request, pk, vote=-1) @login_required @ratelimit(key="user_or_ip", group="news-votes", rate=DEFAULT_VOTES_RATE, block=True) def unvote(request, pk): return _vote(request, pk, vote=None, unvote=True) def flag(request): pass def save(request): pass def _item_story_comment(pk): try: # .prefetch_related('children', 'parent') item = Item.objects.select_related('story', 'comment', 'user', 'parent').prefetch_related('children').get(pk=pk) except Exception as e: raise e try: story = item.story comment = None item = story except Item.story.RelatedObjectDoesNotExist: story = None comment = None try: comment = item.comment story = comment.to_story item = comment except Item.comment.RelatedObjectDoesNotExist: pass assert story is not None return item, story, comment @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, method=['GET'], block=True) @ratelimit(key="user_or_ip", group="news-post", rate=DEFAULT_POST_RATE, method=['POST'], block=True) def item(request, pk): # DONE item, story, comment = _item_story_comment(pk) if story == item: if story.duplicate_of is not None: return HttpResponseRedirect(story.duplicate_of.get_absolute_url()) if request.user.is_authenticated: parent = None if story==item else item comment_instance = Comment(user=request.user, to_story=story, parent=parent) comment_form = CommentForm(request.POST or None, instance=comment_instance) if request.method == 'POST': if comment_form.is_valid(): comment = comment_form.save() return HttpResponseRedirect(story.get_absolute_url() + '#' + str(comment.pk)) else: comment_form = None return render(request, 'news/item.html', {'item': item, 'comment_form': comment_form}) @login_required @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, method=['GET'], block=True) @ratelimit(key="user_or_ip", group="news-post", rate=DEFAULT_POST_RATE, method=['POST'], block=True) def item_edit(request, pk): item, story, comment = _item_story_comment(pk) if not item.can_be_edited_by(request.user): return HttpResponseForbidden() if story == item: if story.duplicate_of is not None: return HttpResponseRedirect(story.duplicate_of.get_absolute_url()) if comment is not None: form = CommentForm(request.POST or None, instance=item) else: assert story is not None form = StoryForm(request.POST or None, instance=item) assert form is not None if request.method=="POST": if form.is_valid(): item = form.save() return HttpResponseRedirect(story.get_absolute_url() + '#' + str(item.pk)) return render(request, 'news/item_edit.html', {'item': item, 'edit_form': form}) @login_required @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, method=['GET'], block=True) @ratelimit(key="user_or_ip", group="news-post", rate=DEFAULT_POST_RATE, method=['POST'], block=True) def item_delete(request, pk): item, story, comment = _item_story_comment(pk) if not item.can_be_deleted_by(request.user): return HttpResponseForbidden() if request.method == "POST": redirect_url = '/' if comment is not None: redirect_url = item.to_story.get_absolute_url() item.delete() return HttpResponseRedirect(redirect_url) return render(request, 'news/item_delete.html', {'item': item}) @login_required @ratelimit(key="user_or_ip", group="news-get", rate=DEFAULT_GET_RATE, method=['GET'], block=True) @ratelimit(key="user_or_ip", group="news-post", rate=DEFAULT_POST_RATE, method=['POST'], block=True) def submit(request): # DONE instance = Story(user=request.user) form = AddStoryForm(request.POST or None, initial={ 'title': request.GET.get('t'), 'url': request.GET.get('u'), 'text': request.GET.get('x'), }, instance=instance) if request.method=="POST": if form.is_valid(): instance = form.save() return HttpResponseRedirect(instance.get_absolute_url()) return render(request, 'news/submit.html', {'form': form}) def robots_txt(request): return HttpResponse(""" User-agent: * Disallow: """, content_type='text/plain') def humans_txt(request): return HttpResponse(""" 🐍 """, content_type='text/plain', charset='utf-8') def bookmarklet(request): return render(request, 'news/bookmarklet.html') ================================================ FILE: requirements.txt ================================================ appnope==0.1.0 aws-psycopg2==1.1.1 awsebcli==3.15.3 backcall==0.1.0 beautifulsoup4==4.8.0 blessed==1.15.0 botocore==1.12.238 cached-property==1.5.1 cement==2.8.2 certifi==2019.9.11 chardet==3.0.4 colorama==0.3.9 coverage==4.5.4 decorator==4.4.0 Django==2.2.5 django-debug-toolbar==2.0 django-htmlmin==0.11.0 django-js-asset==1.2.2 django-mptt==0.10.0 django-ratelimit==2.0.0 docker==3.7.3 docker-compose==1.23.2 docker-pycreds==0.4.0 dockerpty==0.4.1 docopt==0.6.2 docutils==0.15.2 future==0.16.0 html5lib==1.0.1 idna==2.7 ipython==7.8.0 ipython-genutils==0.2.0 jedi==0.15.1 jmespath==0.9.4 jsonschema==2.6.0 Markdown==3.1.1 mistune==0.8.4 parso==0.5.1 pathspec==0.5.9 pexpect==4.7.0 pickleshare==0.7.5 prompt-toolkit==2.0.9 ptyprocess==0.6.0 Pygments==2.4.2 python-dateutil==2.8.0 pytz==2019.2 PyYAML==3.13 requests==2.20.1 semantic-version==2.5.0 six==1.11.0 soupsieve==1.9.3 sqlparse==0.3.0 termcolor==1.1.0 texttable==0.9.1 traitlets==4.3.2 urllib3==1.24.3 wcwidth==0.1.7 webencodings==0.5.1 websocket-client==0.56.0 ================================================ FILE: static/news.css ================================================ /* https://www.schemecolor.com/python-logo-colors.php Cyan-Blue Azure #4B8BBE Lapis Lazuli #306998 Shandy #FFE873 Sunglow #FFD43B Granite Gray #646464 */ /* https://encycolorpedia.com/646464 */ /* General formatting */ body { font-family:Verdana, Geneva, sans-serif; font-size:10pt; color:#646464; } td { font-family:Verdana, Geneva, sans-serif; font-size:10pt; color:#646464; } .smaller { font-size:7pt; } input { font-family:monospace; font-size:10pt; } input[type=\"submit\"] { font-family:Verdana, Geneva, sans-serif; } textarea { font-family:monospace; font-size:10pt; } .clearfix { overflow: hidden; clear: both } p.small { margin: 5px 0; } ul.horizontal-list { list-style: none; margin: 0; padding: 0; } ul.horizontal-list li { display: inline-block; } button { padding: 0.25em; } a { color: inherit; } .green { color:green; } nav#top-bar { background-color:#306998; } nav#footer-bar { background-color:#FFD43B; } main { background-color: #EDF3F9; } nav#top-bar * { color:#FFE873; } .site-content { margin: 3%; } .site-content-dense { margin: 1%; } td {padding-right:8px; vertical-align: text-top;} #top-bar td {vertical-align: middle;} tr.spacer {height:1em;} .highlight {background-color:#FFE873;} .self-item {color: #4B8BBE;} .title > a { text-decoration: none; } .title > a:visited { color: #999; } /* td {border:1px solid red;} */ /* Site layout */ nav#top-bar *.active { color: #FFD43B; font-weight: bold; } #pnmain { width: 85%; margin: auto; } nav#pre-footer-bar > hr { border-top: 2px solid #306998; width: 95%; } /* Item Layout */ /* Forms */ form.logout-form { border: 0; margin:0; padding:0; display:inline; } .logout-button { margin:0; border:0; padding:0; background: transparent; text-decoration: underline; font-family:Verdana, Geneva, sans-serif; font-size:10pt; cursor: pointer; } form.comment-form { padding: 20px; } form.comment-form textarea { width: 50%; resize: vertical; } form.comment-form button { float: left; margin-right: 10px; } form.comment-form ul { float: left; } .vote-form { border: 0; margin:0; padding:0; } .vote-button { background:transparent; display:block; padding:0; padding-top:4px; /* border: 1px solid red; */ border:0; } /* http://apps.eky.hk/css-triangle-generator/ */ div.arrow-up { position:relative; top:-2px; width: 0; height: 0; border-style: solid; border-width: 0 0.3em 0.7em 0.3em; border-color: transparent transparent #646464 transparent; } div.arrow-down { width: 0; height: 0; border-style: solid; border-width: 0.7em 0.3em 0 0.3em; border-color: #646464 transparent transparent transparent; } .controls { line-height:6pt; vertical-align: text-top; } .formatting-help { border: 2px solid #ddd; padding: 0.25em; margin: 0 20px; box-sizing: border-box; } .formatting-help.closed { display: none; } .formatting-help h3 { display: block; margin: 0; padding: 0.5em 0 0.25em 0; font-size: 13px; font-weight: 600; } .formatting-help h3:first-child { padding-top: 0; } /* mobile device */ @media only screen and (min-width : 300px) and (max-width : 750px) { #pnmain { width: 100%; margin:0; } body { padding: 0; margin: 0; width: 100%; -webkit-text-size-adjust: none; } td { height: inherit !important; } .title, .comment { font-size: inherit; } span.pagetop { display: block; margin: 3px 5px; font-size: 12px; } span.pagetop b { display: block; font-size: 15px; } .vote-form { padding:0.2em; transform: scale(1.8); } body { font-family:Verdana, Geneva, sans-serif; font-size:12pt; color:#646464; } td { font-family:Verdana, Geneva, sans-serif; font-size:12pt; color:#646464; } .smaller { font-size:10pt; } button { background-color: #e3e3e3; border: #646464; color: #535353; text-align: center; text-decoration: none; display: inline-block; } form.comment-form textarea { width: 100%; } div.arrow-up { position:relative; top:-2px; width: 0; height: 0; border-style: solid; border-width: 0 0.2em 0.6em 0.2em; border-color: transparent transparent #646464 transparent; } div.arrow-down { width: 0; height: 0; border-style: solid; border-width: 0.6em 0.2em 0 0.2em; border-color: #646464 transparent transparent transparent; } } ================================================ FILE: static/news.js ================================================ document.addEventListener("DOMContentLoaded", function() { // Highlight the posted comment, if comment-id is in url hash if(e = document.getElementById(window.location.hash.substring(1))) e.classList.add('highlight'); function getFormData(form) { var data = {}; for (var i = 0, ii = form.length; i < ii; ++i) { var input = form[i]; if (input.name) { data[input.name] = input.value; } } return data; } // AJAX-ify the upvote button document.querySelectorAll(".vote-form").forEach(function (elem_form) { elem_form.addEventListener("submit", function(e){ e.preventDefault(); var form = e.srcElement; var data = getFormData(form); var xhr = new XMLHttpRequest(); xhr.open(form.method, form.action, true); var form_data = new FormData(); for ( var key in data ) { form_data.append(key, data[key]); } xhr.send(form_data); // form.parentNode.removeChild(form); var parent = form.parentNode; parent.parentNode.removeChild(parent); }); }); });