././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/README.rst0000644000000000000000000001243214701764264012731 0ustar00pylint-django ============= .. image:: https://github.com/pylint-dev/pylint-django/actions/workflows/build.yml/badge.svg :target: https://github.com/pylint-dev/pylint-django/actions/workflows/build.yml .. image:: https://coveralls.io/repos/github/pylint-dev/pylint-django/badge.svg?branch=master :target: https://coveralls.io/github/pylint-dev/pylint-django?branch=master .. image:: https://img.shields.io/pypi/v/pylint-django.svg :target: https://pypi.python.org/pypi/pylint-django About ----- ``pylint-django`` is a `Pylint `__ plugin for improving code analysis when analysing code using Django. It is also used by the `Prospector `__ tool. Installation ------------ To install:: pip install pylint-django **WARNING:** ``pylint-django`` will not install ``Django`` by default because this causes more trouble than good, `see discussion `__. If you wish to automatically install the latest version of ``Django`` then:: pip install pylint-django[with-django] otherwise sort out your testing environment and please **DO NOT** report issues about missing Django! Usage ----- Ensure ``pylint-django`` is installed and on your path. In order to access some of the internal Django features to improve pylint inspections, you should also provide a Django settings module appropriate to your project. This can be done either with an environment variable:: DJANGO_SETTINGS_MODULE=your.app.settings pylint --load-plugins pylint_django [..other options..] Alternatively, this can be passed in as a commandline flag:: pylint --load-plugins pylint_django --django-settings-module=your.app.settings [..other options..] If you do not configure Django, default settings will be used but this will not include, for example, which applications to include in `INSTALLED_APPS` and so the linting and type inference will be less accurate. It is recommended to specify a settings module. Prospector ---------- If you have ``prospector`` installed, then ``pylint-django`` will already be installed as a dependency, and will be activated automatically if Django is detected:: prospector [..other options..] Features -------- * Prevents warnings about Django-generated attributes such as ``Model.objects`` or ``Views.request``. * Prevents warnings when using ``ForeignKey`` attributes ("Instance of ForeignKey has no member"). * Fixes pylint's knowledge of the types of Model and Form field attributes * Validates ``Model.__unicode__`` methods. * ``Meta`` informational classes on forms and models do not generate errors. * Flags dangerous use of the exclude attribute in ModelForm.Meta. * Uses Django's internal machinery to try and resolve models referenced as strings in ForeignKey fields. That relies on ``django.setup()`` which needs the appropriate project settings defined! Additional plugins ------------------ ``pylint_django.checkers.migrations`` looks for migrations which: - add new model fields and these fields have a default value. According to `Django docs `_ this may have performance penalties especially on large tables. The preferred way is to add a new DB column with ``null=True`` because it will be created instantly and then possibly populate the table with the desired default values. Only the last migration from a sub-directory will be examined; - are ``migrations.RunPython()`` without a reverse callable - these will result in non reversible data migrations; This plugin is disabled by default! To enable it:: pylint --load-plugins pylint_django --load-plugins pylint_django.checkers.migrations Contributing ------------ Please feel free to add your name to the ``CONTRIBUTORS.rst`` file if you want to be credited when pull requests get merged. You can also add to the ``CHANGELOG.rst`` file if you wish, although we'll also do that when merging. Tests ----- The structure of the test package follows that from pylint itself. It is fairly simple: create a module starting with ``func_`` followed by a test name, and insert into it some code. The tests will run pylint against these modules. If the idea is that no messages now occur, then that is fine, just check to see if it works by running ``scripts/test.sh``. Any command line argument passed to ``scripts/test.sh`` will be passed to the internal invocation of ``pytest``. For example if you want to debug the tests you can execute ``scripts/test.sh --capture=no``. A specific test case can be run by filtering based on the file name of the test case ``./scripts/test.sh -k 'func_noerror_views'``. Ideally, add some pylint error suppression messages to the file to prevent spurious warnings, since these are all tiny little modules not designed to do anything so there's no need to be perfect. It is possible to make tests with expected error output, for example, if adding a new message or simply accepting that pylint is supposed to warn. A ``test_file_name.txt`` file contains a list of expected error messages in the format ``error-type:line number:class name or empty:1st line of detailed error text:confidence or empty``. License ------- ``pylint-django`` is available under the GPLv2 license. ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/LICENSE0000644000000000000000000004317414701764264015117 0ustar00GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. 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 this service 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. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. 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 convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Pylint plugin for improving code analysis for when using Django Copyright (C) 2013 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/__init__.py0000644000000000000000000000031114701764264016205 0ustar00"""pylint_django module.""" from pylint_django import plugin register = plugin.register # pylint: disable=invalid-name load_configuration = plugin.load_configuration # pylint: disable=invalid-name ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/__pkginfo__.py0000644000000000000000000000003514701764264016702 0ustar00"""pkginfo.""" BASE_ID = 51 ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/augmentations/__init__.py0000644000000000000000000007223114701764264021075 0ustar00"""Augmentations.""" # pylint: disable=invalid-name import functools import itertools from astroid import InferenceError from astroid.nodes import Attribute, ClassDef, ImportFrom from astroid.nodes.scoped_nodes import ClassDef as ScopedClass from astroid.nodes.scoped_nodes import Module from astroid.objects import Super from django import VERSION as django_version from django.utils import termcolors from django.views.generic.base import ContextMixin, RedirectView, View from django.views.generic.dates import DateMixin, DayMixin, MonthMixin, WeekMixin, YearMixin from django.views.generic.detail import SingleObjectMixin, SingleObjectTemplateResponseMixin, TemplateResponseMixin from django.views.generic.edit import DeletionMixin, FormMixin, ModelFormMixin from django.views.generic.list import MultipleObjectMixin, MultipleObjectTemplateResponseMixin from pylint.checkers.base import DocStringChecker, NameChecker from pylint.checkers.classes import ClassChecker from pylint.checkers.design_analysis import MisdesignChecker from pylint.checkers.newstyle import NewStyleConflictChecker from pylint.checkers.typecheck import TypeChecker from pylint.checkers.variables import ScopeConsumer, VariablesChecker from pylint_plugin_utils import augment_visit, suppress_message from pylint_django.utils import PY3, node_is_subclass # Note: it would have been nice to import the Manager object from Django and # get its attributes that way - and this used to be the method - but unfortunately # there's no guarantee that Django is properly configured at that stage, and importing # anything from the django.db package causes an ImproperlyConfigured exception. # Therefore, we'll fall back on a hard-coded list of attributes which won't be as accurate, # but this is not 100% accurate anyway. MANAGER_ATTRS = { "none", "all", "count", "dates", "distinct", "extra", "get", "get_or_create", "update_or_create", "get_queryset", "create", "bulk_create", "filter", "aggregate", "annotate", "complex_filter", "exclude", "in_bulk", "iterator", "latest", "order_by", "select_for_update", "select_related", "prefetch_related", "values", "values_list", "update", "reverse", "defer", "only", "using", "exists", } QS_ATTRS = { "filter", "exclude", "annotate", "order_by", "reverse", "distinct", "values", "values_list", "dates", "datetimes", "none", "all", "select_related", "prefetch_related", "extra", "defer", "only", "using", "select_for_update", "raw", "get", "create", "get_or_create", "update_or_create", "bulk_create", "count", "in_bulk", "iterator", "latest", "earliest", "first", "last", "aggregate", "exists", "update", "delete", "as_manager", "expression", "output_field", } MODELADMIN_ATTRS = { # options "actions", "actions_on_top", "actions_on_bottom", "actions_selection_counter", "date_hierarchy", "empty_value_display", "exclude", "fields", "fieldsets", "filter_horizontal", "filter_vertical", "form", "formfield_overrides", "inlines", "list_display", "list_display_links", "list_editable", "list_filter", "list_max_show_all", "list_per_page", "list_select_related", "ordering", "paginator", "prepopulated_fields", "preserve_filters", "radio_fields", "raw_id_fields", "readonly_fields", "save_as", "save_on_top", "search_fields", "show_full_result_count", "view_on_site", # template options "add_form_template", "change_form_template", "change_list_template", "delete_confirmation_template", "delete_selected_confirmation_template", "object_history_template", } MODEL_ATTRS = { "id", "DoesNotExist", "MultipleObjectsReturned", "_base_manager", "_default_manager", "_meta", "delete", "get_next_by_date", "get_previous_by_date", "objects", "save", } FIELD_ATTRS = { "null", "blank", "choices", "db_column", "db_index", "db_tablespace", "default", "editable", "error_messages", "help_text", "primary_key", "unique", "unique_for_date", "unique_for_month", "unique_for_year", "verbose_name", "validators", } CHAR_FIELD_ATTRS = { "max_length", } DATE_FIELD_ATTRS = { "auto_now", "auto_now_add", } DECIMAL_FIELD_ATTRS = { "max_digits", "decimal_places", } FILE_FIELD_ATTRS = { "upload_to", "storage", } IMAGE_FIELD_ATTRS = { "height_field", "width_field", } IP_FIELD_ATTRS = { "protocol", "unpack_ipv4", } SLUG_FIELD_ATTRS = { "allow_unicode", } FOREIGNKEY_FIELD_ATTRS = { "limit_choices_to", "related_name", "related_query_name", "to_field", "db_constraint", "swappable", } MANYTOMANY_FIELD_ATTRS = { "add", "clear", "related_name", "related_query_name", "remove", "set", "limit_choices_to", "symmetrical", "through", "through_fields", "db_table", "db_constraint", "swappable", } ONETOONE_FIELD_ATTRS = { "parent_link", } STYLE_ATTRS = set(itertools.chain.from_iterable(termcolors.PALETTES.values())) VIEW_ATTRS = { ( ( f"{cls.__module__}.{cls.__name__}", f".{cls.__name__}", ), tuple(cls.__dict__.keys()), ) for cls in ( View, RedirectView, ContextMixin, DateMixin, DayMixin, MonthMixin, WeekMixin, YearMixin, SingleObjectMixin, SingleObjectTemplateResponseMixin, TemplateResponseMixin, DeletionMixin, FormMixin, ModelFormMixin, MultipleObjectMixin, MultipleObjectTemplateResponseMixin, ) } FORM_ATTRS = { "declared_fields", } def ignore_import_warnings_for_related_fields(orig_method, self, node): """ Replaces the leave_module method on the VariablesChecker class to prevent unused-import warnings which are caused by the ForeignKey and OneToOneField transformations. By replacing the nodes in the AST with their type rather than the django field, imports of the form 'from django.db.models import OneToOneField' raise an unused-import warning """ consumer = self._to_consume[0] # pylint: disable=W0212 # we can disable this warning ('Access to a protected member _to_consume of a client class') # as it's not actually a client class, but rather, this method is being monkey patched # onto the class and so the access is valid new_things = {} iterat = consumer.to_consume.items if PY3 else consumer.to_consume.iteritems for name, stmts in iterat(): if isinstance(stmts[0], ImportFrom): if any(n[0] in ("ForeignKey", "OneToOneField") for n in stmts[0].names): continue new_things[name] = stmts # ScopeConsumer changed between pylint 2.12 and 2.13 # see https://github.com/pylint-dev/pylint/issues/5970#issuecomment-1078778393 if hasattr(consumer, "consumed_uncertain"): # this is pylint >= 2.13, and the ScopeConsumer tuple has an additional field sc_args = (new_things, consumer.consumed, consumer.consumed_uncertain, consumer.scope_type) else: # this is <2.13 and does not have the consumer_uncertain field sc_args = (new_things, consumer.consumed, consumer.scope_type) consumer._atomic = ScopeConsumer(*sc_args) # pylint: disable=W0212 self._to_consume = [consumer] # pylint: disable=W0212 return orig_method(self, node) def foreign_key_sets(chain, node): """ When a Django model has a ForeignKey to another model, the target of the foreign key gets a '_set' attribute for accessing a queryset of the model owning the foreign key - eg: class ModelA(models.Model): pass class ModelB(models.Model): a = models.ForeignKey(ModelA) Now, ModelA instances will have a modelb_set attribute. It's also possible to explicitly name the relationship using the related_name argument to the ForeignKey constructor. As it's impossible to know this without inspecting all models before processing, we'll instead do a "best guess" approach and see if the attribute being accessed goes on to be used as a queryset. This is via 'duck typing': if the method called on the attribute being accessed is something we might find in a queryset, we'll warn. """ quack = False if node.attrname in MANAGER_ATTRS or node.attrname.endswith("_set"): # if this is a X_set method, that's a pretty strong signal that this is the default # Django name, rather than one set by related_name quack = True # we will elif isinstance(node.parent, Attribute): func_name = getattr(node.parent, "attrname", None) if func_name in MANAGER_ATTRS: quack = True if quack: children = list(node.get_children()) for child in children: try: inferred_cls = child.inferred() except InferenceError: pass else: for cls in inferred_cls: if node_is_subclass( cls, "django.db.models.manager.Manager", "django.db.models.base.Model", ".Model", "django.db.models.fields.related.ForeignObject", ): # This means that we are looking at a subclass of models.Model # and something is trying to access a _set attribute. # Since this could exist, we will return so as not to raise an # error. return chain() def foreign_key_ids(chain, node): if node.attrname.endswith("_id"): return chain() def is_model_admin_subclass(node): """Checks that node is derivative of ModelAdmin class.""" if node.name[-5:] != "Admin" or isinstance(node.parent, ClassDef): return False return node_is_subclass(node, "django.contrib.admin.options.ModelAdmin") def is_model_media_subclass(node): """Checks that node is derivative of Media class.""" if node.name != "Media" or not isinstance(node.parent, ClassDef): return False parents = ( "django.contrib.admin.options.ModelAdmin", "django.forms.widgets.Media", "django.db.models.base.Model", ".Model", # for the transformed version used in this plugin "django.forms.forms.Form", ".Form", "django.forms.widgets.Widget", ".Widget", "django.forms.models.ModelForm", ".ModelForm", ) return node_is_subclass(node.parent, *parents) def is_model_meta_subclass(node): """Checks that node is derivative of Meta class.""" if node.name != "Meta" or not isinstance(node.parent, ClassDef): return False parents = ( ".Model", # for the transformed version used here "django.db.models.base.Model", ".Form", "django.forms.forms.Form", ".ModelForm", "django.forms.models.ModelForm", "rest_framework.serializers.BaseSerializer", "rest_framework.generics.GenericAPIView", "rest_framework.viewsets.ReadOnlyModelViewSet", "rest_framework.viewsets.ModelViewSet", "django_filters.filterset.FilterSet", "factory.django.DjangoModelFactory", ) return node_is_subclass(node.parent, *parents) def is_model_factory(node): """Checks that node is derivative of DjangoModelFactory or SubFactory class.""" try: parent_classes = node.expr.inferred() except: # noqa: E722, pylint: disable=bare-except return False parents = ( "factory.declarations.LazyFunction", "factory.declarations.SubFactory", "factory.django.DjangoModelFactory", ) for parent_class in parent_classes: try: if parent_class.qname() in parents: return True if node_is_subclass(parent_class, *parents): return True except AttributeError: continue return False def is_factory_post_generation_method(node): if not node.decorators: return False for decorator in node.decorators.get_children(): try: inferred = decorator.inferred() except InferenceError: continue for target in inferred: if target.qname() == "factory.helpers.post_generation": return True return False def is_model_mpttmeta_subclass(node): """Checks that node is derivative of MPTTMeta class.""" if node.name != "MPTTMeta" or not isinstance(node.parent, ClassDef): return False parents = ( "django.db.models.base.Model", ".Model", # for the transformed version used in this plugin "django.forms.forms.Form", ".Form", "django.forms.models.ModelForm", ".ModelForm", ) return node_is_subclass(node.parent, *parents) def _attribute_is_magic(node, attrs, parents): """Checks that node is an attribute used inside one of allowed parents""" if node.attrname not in attrs: return False if not node.last_child(): return False try: for cls in node.last_child().inferred(): if isinstance(cls, Super): cls = cls._self_class # pylint: disable=protected-access # noqa:PLW2901 if node_is_subclass(cls, *parents) or cls.qname() in parents: return True except InferenceError: pass return False def is_style_attribute(node): parents = ("django.core.management.color.Style",) return _attribute_is_magic(node, STYLE_ATTRS, parents) def is_manager_attribute(node): """Checks that node is attribute of Manager or QuerySet class.""" parents = ( "django.db.models.manager.Manager", ".Manager", "factory.base.BaseFactory.build", "django.db.models.query.QuerySet", ".QuerySet", ) return _attribute_is_magic(node, MANAGER_ATTRS.union(QS_ATTRS), parents) def is_admin_attribute(node): """Checks that node is attribute of BaseModelAdmin.""" parents = ("django.contrib.admin.options.BaseModelAdmin", ".BaseModelAdmin") return _attribute_is_magic(node, MODELADMIN_ATTRS, parents) def is_model_attribute(node): """Checks that node is attribute of Model.""" parents = ("django.db.models.base.Model", ".Model") return _attribute_is_magic(node, MODEL_ATTRS, parents) def is_field_attribute(node): """Checks that node is attribute of Field.""" parents = ("django.db.models.fields.Field", ".Field") return _attribute_is_magic(node, FIELD_ATTRS, parents) def is_charfield_attribute(node): """Checks that node is attribute of CharField.""" parents = ("django.db.models.fields.CharField", ".CharField") return _attribute_is_magic(node, CHAR_FIELD_ATTRS, parents) def is_datefield_attribute(node): """Checks that node is attribute of DateField.""" parents = ("django.db.models.fields.DateField", ".DateField") return _attribute_is_magic(node, DATE_FIELD_ATTRS, parents) def is_decimalfield_attribute(node): """Checks that node is attribute of DecimalField.""" parents = ("django.db.models.fields.DecimalField", ".DecimalField") return _attribute_is_magic(node, DECIMAL_FIELD_ATTRS, parents) def is_filefield_attribute(node): """Checks that node is attribute of FileField.""" parents = ("django.db.models.fields.files.FileField", ".FileField") return _attribute_is_magic(node, FILE_FIELD_ATTRS, parents) def is_imagefield_attribute(node): """Checks that node is attribute of ImageField.""" parents = ("django.db.models.fields.files.ImageField", ".ImageField") return _attribute_is_magic(node, IMAGE_FIELD_ATTRS, parents) def is_ipfield_attribute(node): """Checks that node is attribute of GenericIPAddressField.""" parents = ( "django.db.models.fields.GenericIPAddressField", ".GenericIPAddressField", ) return _attribute_is_magic(node, IP_FIELD_ATTRS, parents) def is_slugfield_attribute(node): """Checks that node is attribute of SlugField.""" parents = ("django.db.models.fields.SlugField", ".SlugField") return _attribute_is_magic(node, SLUG_FIELD_ATTRS, parents) def is_foreignkeyfield_attribute(node): """Checks that node is attribute of ForeignKey.""" parents = ("django.db.models.fields.related.ForeignKey", ".ForeignKey") return _attribute_is_magic(node, FOREIGNKEY_FIELD_ATTRS, parents) def is_manytomanyfield_attribute(node): """Checks that node is attribute of ManyToManyField.""" parents = ("django.db.models.fields.related.ManyToManyField", ".ManyToManyField") return _attribute_is_magic(node, MANYTOMANY_FIELD_ATTRS, parents) def is_onetoonefield_attribute(node): """Checks that node is attribute of OneToOneField.""" parents = ("django.db.models.fields.related.OneToOneField", ".OneToOneField") return _attribute_is_magic(node, ONETOONE_FIELD_ATTRS, parents) def is_form_attribute(node): """Checks that node is attribute of Form.""" parents = ("django.forms.forms.Form", "django.forms.models.ModelForm") return _attribute_is_magic(node, FORM_ATTRS, parents) def is_model_test_case_subclass(node): """Checks that node is derivative of TestCase class.""" if not node.name.endswith("Test") and not isinstance(node.parent, ClassDef): return False return node_is_subclass(node, "django.test.testcases.TestCase") class IsAttribute: # pylint: disable=too-few-public-methods def __init__(self, parents, attrs): self.parents = parents self.attrs = attrs def __call__(self, node): return _attribute_is_magic(node, self.attrs, self.parents) def is_model_view_subclass_method_shouldnt_be_function(node): """Checks that node is a default http method (i.e get, post, put, and more) of the View class.""" if node.name not in View.http_method_names: return False parent = node.parent while parent and not isinstance(parent, ScopedClass): parent = parent.parent subclass = ( "django.views.View", "django.views.generic.View", "django.views.generic.base.View", ) return parent is not None and node_is_subclass(parent, *subclass) def ignore_unused_argument_warnings_for_request(orig_method, self, stmt, name): """ Ignore unused-argument warnings for function arguments named "request". The signature of Django view functions require the request argument but it is okay if the request is not used. This function should be used as a wrapper for the `VariablesChecker._is_name_ignored` method. """ if name in ("request", "args", "kwargs"): return True return orig_method(self, stmt, name) def is_model_field_display_method(node): """Accept model's fields with get_*_display names.""" if not node.attrname.endswith("_display"): return False if not node.attrname.startswith("get_"): return False if node.last_child(): # TODO: could validate the names of the fields on the model rather than # blindly accepting get_*_display try: for cls in node.last_child().inferred(): if node_is_subclass(cls, "django.db.models.base.Model", ".Model"): return True except InferenceError: return False return False def is_model_media_valid_attributes(node): """Suppress warnings for valid attributes of Media class.""" if node.name not in ("js",): return False parent = node.parent while parent and not isinstance(parent, ScopedClass): parent = parent.parent if parent is None or parent.name != "Media": return False return True def is_templatetags_module_valid_constant(node): """Suppress warnings for valid constants in templatetags module.""" if node.name not in ("register",): return False parent = node.parent while not isinstance(parent, Module): parent = parent.parent if "templatetags." not in parent.name: return False return True def is_urls_module_valid_constant(node): """Suppress warnings for valid constants in urls module.""" if node.name not in ("urlpatterns", "app_name"): return False parent = node.parent while not isinstance(parent, Module): parent = parent.parent if not parent.name.endswith("urls"): return False return True def allow_meta_protected_access(node): if django_version >= (1, 8): return node.attrname == "_meta" return False class IsClass: # pylint: disable=too-few-public-methods def __init__(self, class_name): self.class_name = class_name def __call__(self, node): return node_is_subclass(node, self.class_name) def wrap(orig_method, with_method): @functools.wraps(orig_method) def wrap_func(*args, **kwargs): return with_method(orig_method, *args, **kwargs) return wrap_func def is_wsgi_application(node): frame = node.frame() return ( node.name == "application" and isinstance(frame, Module) and ( frame.name == "asgi" or frame.path[0].endswith("asgi.py") or frame.file.endswith("asgi.py") or frame.name == "wsgi" or frame.path[0].endswith("wsgi.py") or frame.file.endswith("wsgi.py") ) ) # Compat helpers def pylint_newstyle_classdef_compat(linter, warning_name, augment): if not hasattr(NewStyleConflictChecker, "visit_classdef"): return suppress_message( linter, # pylint: disable-next=no-member NewStyleConflictChecker.visit_classdef, warning_name, augment, ) def apply_wrapped_augmentations(): """ Apply augmentation and suppression rules through monkey patching of pylint. """ # NOTE: The monkey patching is done with wrap and needs to be done in a thread safe manner to support the # parallel option of pylint (-j). # This is achieved by comparing __name__ of the monkey patched object to the original value and only patch it if # these are equal. # Unused argument 'request' (get, post) current_is_name_ignored = VariablesChecker._is_name_ignored # pylint: disable=protected-access if current_is_name_ignored.__name__ == "_is_name_ignored": # pylint: disable=protected-access VariablesChecker._is_name_ignored = wrap(current_is_name_ignored, ignore_unused_argument_warnings_for_request) # ForeignKey and OneToOneField current_leave_module = VariablesChecker.leave_module if current_leave_module.__name__ == "leave_module": # current_leave_module is not wrapped # Two threads may hit the next assignment concurrently, but the result is the same VariablesChecker.leave_module = wrap(current_leave_module, ignore_import_warnings_for_related_fields) # VariablesChecker.leave_module is now wrapped # else VariablesChecker.leave_module is already wrapped # augment things def apply_augmentations(linter): """Apply augmentation and suppression rules.""" augment_visit(linter, TypeChecker.visit_attribute, foreign_key_sets) augment_visit(linter, TypeChecker.visit_attribute, foreign_key_ids) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_model_field_display_method) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_style_attribute) suppress_message( linter, NameChecker.visit_assignname, "invalid-name", is_urls_module_valid_constant, ) # suppress errors when accessing magical class attributes suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_manager_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_admin_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_model_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_field_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_charfield_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_datefield_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_decimalfield_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_filefield_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_imagefield_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_ipfield_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_slugfield_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_foreignkeyfield_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_manytomanyfield_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_onetoonefield_attribute) suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_form_attribute) for parents, attrs in VIEW_ATTRS: suppress_message( linter, TypeChecker.visit_attribute, "no-member", IsAttribute(parents, attrs), ) # formviews have too many ancestors, there's nothing the user of the library can do about that suppress_message( linter, MisdesignChecker.visit_classdef, "too-many-ancestors", IsClass("django.views.generic.edit.FormView"), ) # class-based generic views just have a longer inheritance chain suppress_message( linter, MisdesignChecker.visit_classdef, "too-many-ancestors", IsClass("django.views.generic.detail.BaseDetailView"), ) suppress_message( linter, MisdesignChecker.visit_classdef, "too-many-ancestors", IsClass("django.views.generic.edit.ProcessFormView"), ) # model forms have no __init__ method anywhere in their bases suppress_message( linter, ClassChecker.visit_classdef, "W0232", IsClass("django.forms.models.ModelForm"), ) # Meta suppress_message( linter, DocStringChecker.visit_classdef, "missing-docstring", is_model_meta_subclass, ) pylint_newstyle_classdef_compat(linter, "old-style-class", is_model_meta_subclass) suppress_message(linter, ClassChecker.visit_classdef, "no-init", is_model_meta_subclass) suppress_message( linter, MisdesignChecker.leave_classdef, "too-few-public-methods", is_model_meta_subclass, ) suppress_message( linter, ClassChecker.visit_attribute, "protected-access", allow_meta_protected_access, ) # Media suppress_message(linter, NameChecker.visit_assignname, "C0103", is_model_media_valid_attributes) suppress_message( linter, DocStringChecker.visit_classdef, "missing-docstring", is_model_media_subclass, ) pylint_newstyle_classdef_compat(linter, "old-style-class", is_model_media_subclass) suppress_message(linter, ClassChecker.visit_classdef, "no-init", is_model_media_subclass) suppress_message( linter, MisdesignChecker.leave_classdef, "too-few-public-methods", is_model_media_subclass, ) # Admin # Too many public methods (40+/20) # TODO: Count public methods of django.contrib.admin.options.ModelAdmin and increase # MisdesignChecker.config.max_public_methods to this value to count only user' methods. # nb_public_methods = 0 # for method in node.methods(): # if not method.name.startswith('_'): # nb_public_methods += 1 suppress_message(linter, MisdesignChecker.leave_classdef, "R0904", is_model_admin_subclass) # Tests suppress_message(linter, MisdesignChecker.leave_classdef, "R0904", is_model_test_case_subclass) # View # Method could be a function (get, post) suppress_message( linter, ClassChecker.leave_functiondef, "no-self-use", is_model_view_subclass_method_shouldnt_be_function, ) # django-mptt suppress_message( linter, DocStringChecker.visit_classdef, "missing-docstring", is_model_mpttmeta_subclass, ) pylint_newstyle_classdef_compat(linter, "old-style-class", is_model_mpttmeta_subclass) suppress_message(linter, ClassChecker.visit_classdef, "W0232", is_model_mpttmeta_subclass) suppress_message( linter, MisdesignChecker.leave_classdef, "too-few-public-methods", is_model_mpttmeta_subclass, ) # factory_boy's DjangoModelFactory suppress_message(linter, TypeChecker.visit_attribute, "no-member", is_model_factory) suppress_message( linter, ClassChecker.visit_functiondef, "no-self-argument", is_factory_post_generation_method, ) # wsgi.py suppress_message(linter, NameChecker.visit_assignname, "invalid-name", is_wsgi_application) apply_wrapped_augmentations() ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/checkers/__init__.py0000644000000000000000000000144314701764264020003 0ustar00"""Checkers.""" from pylint_django.checkers.auth_user import AuthUserChecker from pylint_django.checkers.django_installed import DjangoInstalledChecker from pylint_django.checkers.foreign_key_strings import ForeignKeyStringsChecker from pylint_django.checkers.forms import FormChecker from pylint_django.checkers.json_response import JsonResponseChecker from pylint_django.checkers.models import ModelChecker def register_checkers(linter): """Register checkers.""" linter.register_checker(ModelChecker(linter)) linter.register_checker(DjangoInstalledChecker(linter)) linter.register_checker(JsonResponseChecker(linter)) linter.register_checker(FormChecker(linter)) linter.register_checker(AuthUserChecker(linter)) linter.register_checker(ForeignKeyStringsChecker(linter)) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/checkers/auth_user.py0000644000000000000000000000246214701764264020245 0ustar00from pylint import checkers from pylint_django.__pkginfo__ import BASE_ID from pylint_django.compat import check_messages class AuthUserChecker(checkers.BaseChecker): name = "auth-user-checker" msgs = { f"E{BASE_ID}41": ( "Hard-coded 'auth.User'", "hard-coded-auth-user", "Don't hard-code the auth.User model. Use settings.AUTH_USER_MODEL instead!", ), f"E{BASE_ID}42": ( "User model imported from django.contrib.auth.models", "imported-auth-user", "Don't import django.contrib.auth.models.User model. Use django.contrib.auth.get_user_model() instead!", ), } @check_messages("hard-coded-auth-user") def visit_const(self, node): # for now we don't check if the parent is a ForeignKey field # because the user model should not be hard-coded anywhere if node.value == "auth.User": self.add_message("hard-coded-auth-user", node=node) @check_messages("imported-auth-user") def visit_importfrom(self, node): if node.modname == "django.contrib.auth.models": for imported_names in node.names: if imported_names[0] in ["*", "User"]: self.add_message("imported-auth-user", node=node) break ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/checkers/django_installed.py0000644000000000000000000000237614701764264021553 0ustar00from pylint.checkers import BaseChecker from pylint_django.__pkginfo__ import BASE_ID from pylint_django.compat import check_messages class DjangoInstalledChecker(BaseChecker): name = "django-installed-checker" msgs = { # pylint: disable=implicit-str-concat f"F{BASE_ID}01": ( "Django is not available on the PYTHONPATH", "django-not-available", "Django could not be imported by the pylint-django plugin, so most Django related " "improvements to pylint will fail.", ), f"W{BASE_ID}99": ( "Placeholder message to prevent disabling of checker", "django-not-available-placeholder", "PyLint does not recognise checkers as being enabled unless they have at least" " one message which is not fatal...", ), } @check_messages("django-not-available") def open(self): try: __import__("django") except ImportError: # mild hack: this error is added before any modules have been inspected # so we need to set some kind of value to prevent the linter failing to it self.linter.set_current_module("pylint_django") self.add_message("django-not-available") ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/checkers/foreign_key_strings.py0000644000000000000000000001434014701764264022316 0ustar00import astroid from pylint.checkers import BaseChecker from pylint_django.__pkginfo__ import BASE_ID from pylint_django.compat import check_messages from pylint_django.transforms import foreignkey class ForeignKeyStringsChecker(BaseChecker): """ Adds transforms to be able to do type inference for model ForeignKeyField properties which use a string to name the foreign relationship. This uses Django's model name resolution and this checker wraps the setup to ensure Django is able to configure itself before attempting to use the lookups. """ _LONG_MESSAGE = """Finding foreign-key relationships from strings in pylint-django requires configuring Django. This can be done via the DJANGO_SETTINGS_MODULE environment variable or the pylint option django-settings-module, eg: `pylint --load-plugins=pylint_django --django-settings-module=myproject.settings` . This can also be set as an option in a .pylintrc configuration file. Some basic default settings were used, however this will lead to less accurate linting. Consider passing in an explicit Django configuration file to match your project to improve accuracy.""" name = "Django foreign keys referenced by strings" options = ( ( "django-settings-module", { "default": None, "type": "string", "metavar": "", "help": "A module containing Django settings to be used while linting.", }, ), ) msgs = { # pylint: disable=implicit-str-concat f"E{BASE_ID}10": ( "Django was not configured. For more information run " "pylint --load-plugins=pylint_django --help-msg=django-not-configured", "django-not-configured", _LONG_MESSAGE, ), f"F{BASE_ID}10": ( "Provided Django settings %s could not be loaded", "django-settings-module-not-found", "The provided Django settings module %s was not found on the path", ), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._raise_warning = False def open(self): # This is a bit of a hacky workaround. pylint-django does not *require* that # Django is configured explicitly, and will use some basic defaults in that # case. However, as this is a WARNING not a FATAL, the error must be raised # with an AST node - only F and R messages are scope exempt (see # https://github.com/pylint-dev/pylint/blob/master/pylint/constants.py#L24) # However, testing to see if Django is configured happens in `open()` # before any modules are inspected, as Django needs to be configured with # defaults before the foreignkey checker can work properly. At this point, # there are no nodes. # Therefore, during the initialisation in `open()`, if django was configured # using defaults by pylint-django, it cannot raise the warning yet and # must wait until some module is inspected to be able to raise... so that # state is stashed in this property. try: from django.core.exceptions import ImproperlyConfigured # pylint: disable=import-outside-toplevel except ModuleNotFoundError: return try: import django # pylint: disable=import-outside-toplevel django.setup() # pylint: disable-next=import-outside-toplevel,unused-import from django.apps import apps # noqa: F401 except ImproperlyConfigured: # this means that Django wasn't able to configure itself using some defaults # provided (likely in a DJANGO_SETTINGS_MODULE environment variable) # so see if the user has specified a pylint option if hasattr(self, "linter"): django_settings_module = self.linter.config.django_settings_module else: # TODO: remove this no-member ignore : this is to avoid the missing `config` for pylint 3+, # and can be removed once pylint 2 # pylint: disable=no-member django_settings_module = self.linter.config.django_settings_module if django_settings_module is None: # we will warn the user that they haven't actually configured Django themselves self._raise_warning = True # but use django defaults then... from django.conf import settings # pylint: disable=import-outside-toplevel settings.configure() django.setup() else: # see if we can load the provided settings module try: from django.conf import Settings, settings # pylint: disable=import-outside-toplevel settings.configure(Settings(django_settings_module)) django.setup() except ImportError: # we could not find the provided settings module... # at least here it is a fatal error so we can just raise this immediately self.add_message( "django-settings-module-not-found", args=self.linter.config.django_settings_module, ) # however we'll trundle on with basic settings from django.conf import settings # pylint: disable=import-outside-toplevel settings.configure() django.setup() # Now we can add the transforms specific to this checker foreignkey.add_transform(astroid.MANAGER) # TODO: this is a bit messy having so many inline imports but in order to avoid # duplicating the django_installed checker, it'll do for now. In the future, merging # those two checkers together might make sense. @check_messages("django-not-configured") def visit_module(self, node): if self._raise_warning: # just add it to the first node we see... which isn't nice but not sure what else to do self.add_message("django-not-configured", node=node) self._raise_warning = False # only raise it once... ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/checkers/forms.py0000644000000000000000000000263114701764264017372 0ustar00"""Models.""" from astroid.nodes import Assign, AssignName, ClassDef from pylint.checkers import BaseChecker from pylint_django.__pkginfo__ import BASE_ID from pylint_django.compat import check_messages from pylint_django.utils import node_is_subclass def _get_child_meta(node): for child in node.get_children(): if isinstance(child, ClassDef) and child.name == "Meta": return child return None class FormChecker(BaseChecker): """Django model checker.""" name = "django-form-checker" msgs = { f"W{BASE_ID}04": ( "Use explicit fields instead of exclude in ModelForm", "modelform-uses-exclude", "Prevents accidentally allowing users to set fields, especially when adding new fields to a Model", ) } @check_messages("modelform-uses-exclude") def visit_classdef(self, node): """Class visitor.""" if not node_is_subclass(node, "django.forms.models.ModelForm", ".ModelForm"): # we only care about forms return meta = _get_child_meta(node) if not meta: return for child in meta.get_children(): if not isinstance(child, Assign) or not isinstance(child.targets[0], AssignName): continue if child.targets[0].name == "exclude": self.add_message(f"W{BASE_ID}04", node=child) break ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/checkers/json_response.py0000644000000000000000000000513214701764264021132 0ustar00# Copyright (c) 2018 Alexander Todorov # Licensed under the GPL 2.0: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/pylint-dev/pylint-django/blob/master/LICENSE """ Various suggestions about JSON http responses """ import astroid from pylint import checkers from pylint_django.__pkginfo__ import BASE_ID from pylint_django.compat import check_messages class JsonResponseChecker(checkers.BaseChecker): """ Looks for some common patterns when returning http responses containing JSON data! """ # configuration section name name = "json-response-checker" msgs = { f"R{BASE_ID}01": ( "Instead of HttpResponse(json.dumps(data)) use JsonResponse(data)", "http-response-with-json-dumps", "Used when json.dumps() is used as an argument to HttpResponse().", ), f"R{BASE_ID}02": ( "Instead of HttpResponse(content_type='application/json') use JsonResponse()", "http-response-with-content-type-json", "Used when HttpResponse() is returning application/json.", ), f"R{BASE_ID}03": ( "Redundant content_type parameter for JsonResponse()", "redundant-content-type-for-json-response", "Used when JsonResponse() contains content_type parameter. " "This is either redundant or the content_type is not JSON " "which is probably an error.", ), } @check_messages( "http-response-with-json-dumps", "http-response-with-content-type-json", "redundant-content-type-for-json-response", ) def visit_call(self, node): if ( node.func.as_string().endswith("HttpResponse") and node.args and isinstance(node.args[0], astroid.Call) and node.args[0].func.as_string() == "json.dumps" ): self.add_message("http-response-with-json-dumps", node=node) if node.func.as_string().endswith("HttpResponse") and node.keywords: for keyword in node.keywords: if keyword.arg == "content_type" and keyword.value.as_string().lower().find("application/json") > -1: self.add_message("http-response-with-content-type-json", node=node) break if node.func.as_string().endswith("JsonResponse") and node.keywords: for keyword in node.keywords: if keyword.arg == "content_type": self.add_message("redundant-content-type-for-json-response", node=node) break ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/checkers/migrations.py0000644000000000000000000001425714701764264020427 0ustar00# Copyright (c) 2018, 2020 Alexander Todorov # Copyright (c) 2020 Bryan Mutai # Licensed under the GPL 2.0: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/pylint-dev/pylint-django/blob/master/LICENSE """ Various suggestions around migrations. Disabled by default! Enable with pylint --load-plugins=pylint_django.checkers.migrations """ import astroid from pylint import checkers from pylint_plugin_utils import suppress_message from pylint_django import compat from pylint_django.__pkginfo__ import BASE_ID from pylint_django.compat import check_messages from pylint_django.utils import is_migrations_module def _is_addfield_with_default(call): if not isinstance(call.func, astroid.Attribute): return False if not call.func.attrname == "AddField": return False for keyword in call.keywords: # looking for AddField(..., field=XXX(..., default=Y, ...), ...) if keyword.arg == "field" and isinstance(keyword.value, astroid.Call): # loop over XXX's keywords # NOTE: not checking if XXX is an actual field type because there could # be many types we're not aware of. Also the migration will probably break # if XXX doesn't instantiate a field object! for field_keyword in keyword.value.keywords: if field_keyword.arg == "default": return True return False class NewDbFieldWithDefaultChecker(checkers.BaseChecker): """ Looks for migrations which add new model fields and these fields have a default value. According to Django docs this may have performance penalties especially on large tables: https://docs.djangoproject.com/en/2.0/topics/migrations/#postgresql The preferred way is to add a new DB column with null=True because it will be created instantly and then possibly populate the table with the desired default values. """ # configuration section name name = "new-db-field-with-default" msgs = { f"W{BASE_ID}98": ( "%s AddField with default value", "new-db-field-with-default", "Used when Pylint detects migrations adding new fields with a default value.", ) } _migration_modules = [] _possible_offences = {} def visit_module(self, node): if is_migrations_module(node): self._migration_modules.append(node) def visit_call(self, node): try: module = node.frame().parent except: # noqa: E722, pylint: disable=bare-except return if not is_migrations_module(module): return if _is_addfield_with_default(node): if module not in self._possible_offences: self._possible_offences[module] = [] if node not in self._possible_offences[module]: self._possible_offences[module].append(node) @check_messages("new-db-field-with-default") def close(self): def _path(node): return node.path # sort all migrations by name in reverse order b/c # we need only the latest ones self._migration_modules.sort(key=_path, reverse=True) # filter out the last migration modules under each distinct # migrations directory, iow leave only the latest migrations # for each application last_name_space = "" latest_migrations = [] for module in self._migration_modules: name_space = module.path[0].split("migrations")[0] if name_space != last_name_space: last_name_space = name_space latest_migrations.append(module) for module, nodes in self._possible_offences.items(): if module in latest_migrations: for node in nodes: self.add_message("new-db-field-with-default", args=module.name, node=node) class MissingBackwardsMigrationChecker(checkers.BaseChecker): name = "missing-backwards-migration-callable" msgs = { f"W{BASE_ID}97": ( "Always include backwards migration callable", "missing-backwards-migration-callable", "Always include a backwards/reverse callable counterpart so that the migration is not irreversible.", ) } @check_messages("missing-backwards-migration-callable") def visit_call(self, node): try: module = node.frame().parent except: # noqa: E722, pylint: disable=bare-except return if not is_migrations_module(module): return if node.func.as_string().endswith("RunPython") and len(node.args) < 2: if node.keywords: for keyword in node.keywords: if keyword.arg == "reverse_code": return self.add_message("missing-backwards-migration-callable", node=node) else: self.add_message("missing-backwards-migration-callable", node=node) def is_in_migrations(node): """ RunPython() migrations receive forward/backwards functions with signature: def func(apps, schema_editor): which could be unused. This augmentation will suppress all 'unused-argument' messages coming from functions in migration modules. """ return is_migrations_module(node.parent) def load_configuration(linter): # TODO this is redundant and can be removed # don't blacklist migrations for this checker new_black_list = list(linter.config.black_list) if "migrations" in new_black_list: new_black_list.remove("migrations") linter.config.black_list = new_black_list def register(linter): """Required method to auto register this checker.""" linter.register_checker(NewDbFieldWithDefaultChecker(linter)) linter.register_checker(MissingBackwardsMigrationChecker(linter)) if not compat.LOAD_CONFIGURATION_SUPPORTED: load_configuration(linter) # apply augmentations for migration checkers # Unused arguments for migrations suppress_message( linter, checkers.variables.VariablesChecker.leave_functiondef, "unused-argument", is_in_migrations, ) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/checkers/models.py0000644000000000000000000001070314701764264017526 0ustar00"""Models.""" from astroid import Const from astroid.nodes import Assign, AssignName, ClassDef, FunctionDef from pylint.checkers import BaseChecker from pylint_django.__pkginfo__ import BASE_ID from pylint_django.compat import check_messages from pylint_django.utils import PY3, node_is_subclass MESSAGES = { f"E{BASE_ID}01": ( "__unicode__ on a model must be callable (%s)", "model-unicode-not-callable", "Django models require a callable __unicode__ method", ), f"W{BASE_ID}01": ( "No __unicode__ method on model (%s)", "model-missing-unicode", "Django models should implement a __unicode__ method for string representation", ), f"W{BASE_ID}02": ( "Found __unicode__ method on model (%s). Python3 uses __str__.", "model-has-unicode", "Django models should not implement a __unicode__ method for string representation when using Python3", ), f"W{BASE_ID}03": ( "Model does not explicitly define __unicode__ (%s)", "model-no-explicit-unicode", "Django models should implement a __unicode__ method for string representation. " "A parent class of this model does, but ideally all models should be explicit.", ), } def _is_meta_with_abstract(node): if isinstance(node, ClassDef) and node.name == "Meta": for meta_child in node.get_children(): if not isinstance(meta_child, Assign): continue if not meta_child.targets[0].name == "abstract": continue if not isinstance(meta_child.value, Const): continue # TODO: handle tuple assignment? # eg: # abstract, something_else = True, 1 if meta_child.value.value: # this class is abstract return True return False def _has_python_2_unicode_compatible_decorator(node): if node.decorators is None: return False for decorator in node.decorators.nodes: if getattr(decorator, "name", None) == "python_2_unicode_compatible": return True return False def _is_unicode_or_str_in_python_2_compatibility(method): if method.name == "__unicode__": return True if method.name == "__str__" and _has_python_2_unicode_compatible_decorator(method.parent): return True return False class ModelChecker(BaseChecker): """Django model checker.""" name = "django-model-checker" msgs = MESSAGES @check_messages("model-missing-unicode") def visit_classdef(self, node): # noqa: PLR0911 """Class visitor.""" if not node_is_subclass(node, "django.db.models.base.Model", ".Model"): # we only care about models return for child in node.get_children(): if _is_meta_with_abstract(child): return if isinstance(child, Assign): grandchildren = list(child.get_children()) if not isinstance(grandchildren[0], AssignName): continue name = grandchildren[0].name if name != "__unicode__": continue grandchild = grandchildren[1] assigned = grandchild.inferred()[0] if assigned.callable(): return self.add_message(f"E{BASE_ID}01", args=node.name, node=node) return if isinstance(child, FunctionDef) and child.name == "__unicode__": if PY3: self.add_message(f"W{BASE_ID}02", args=node.name, node=node) return # if we get here, then we have no __unicode__ method directly on the class itself # a different warning is emitted if a parent declares __unicode__ for method in node.methods(): if method.parent != node and _is_unicode_or_str_in_python_2_compatibility(method): # this happens if a parent declares the unicode method but # this node does not self.add_message(f"W{BASE_ID}03", args=node.name, node=node) return # if the Django compatibility decorator is used then we don't emit a warning # see https://github.com/pylint-dev/pylint-django/issues/10 if _has_python_2_unicode_compatible_decorator(node): return if PY3: return self.add_message(f"W{BASE_ID}01", args=node.name, node=node) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/compat.py0000644000000000000000000000257414701764264015746 0ustar00# flake8: noqa # pylint: skip-file # no sane linter can figure out the hackiness in this compatibility layer... import sys try: from astroid.nodes import AssignName, Attribute, ClassDef, FunctionDef, ImportFrom except ImportError: from astroid.nodes import AssName as AssignName from astroid.nodes import Class as ClassDef from astroid.nodes import From as ImportFrom from astroid.nodes import Function as FunctionDef from astroid.nodes import Getattr as Attribute # pylint 2.04->2.2 : YES was renamed to Uninferable, then YES became deprecated, then was removed try: from astroid.bases import YES as Uninferable except ImportError: try: from astroid.util import YES as Uninferable except ImportError: from astroid.util import Uninferable try: from pylint.checkers.utils import only_required_for_messages as check_messages except (ImportError, ModuleNotFoundError): from pylint.checkers.utils import check_messages import pylint # pylint before version 2.3 does not support load_configuration() hook. LOAD_CONFIGURATION_SUPPORTED = False try: LOAD_CONFIGURATION_SUPPORTED = tuple(pylint.__version__.split(".")) >= ("2", "3") except AttributeError: LOAD_CONFIGURATION_SUPPORTED = pylint.__pkginfo__.numversion >= (2, 3) # datetime module is compiled and moved to _pydatetime COMPILED_DATETIME_CLASSES = sys.version_info >= (3, 12) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.477103 pylint-django-2.6.1/pylint_django/plugin.py0000644000000000000000000000243014701764264015750 0ustar00"""Common Django module.""" # we want to import the transforms to make sure they get added to the astroid manager, # however we don't actually access them directly, so we'll disable the warning from pylint_django import compat from pylint_django.checkers import register_checkers def load_configuration(linter): """ Amend existing checker config. """ linter.config.good_names += ( "pk", "qs", "urlpatterns", "register", "app_name", "handler400", "handler403", "handler404", "handler500", ) # we don't care about South migrations linter.config.black_list += ("migrations", "south_migrations") def register(linter): """ Registering additional checkers. """ # add all of the checkers register_checkers(linter) # register any checking fiddlers try: # pylint: disable=import-outside-toplevel from pylint_django.augmentations import apply_augmentations apply_augmentations(linter) except ImportError: # probably trying to execute pylint_django when Django isn't installed # in this case the django-not-installed checker will kick-in pass if not compat.LOAD_CONFIGURATION_SUPPORTED: load_configuration(linter) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.481103 pylint-django-2.6.1/pylint_django/transforms/__init__.py0000644000000000000000000000320414701764264020407 0ustar00""" These transforms replace the Django types with adapted versions to provide additional typing and method inference to pylint. All of these transforms are considered "global" to pylint-django, in that all checks and improvements require them to be loaded. Additional transforms specific to checkers are loaded by the checker rather than here. For example, the ForeignKeyStringsChecker loads the foreignkey.py transforms itself as it may be disabled independently of the rest of pylint-django """ import os import re import astroid from pylint_django.transforms import fields fields.add_transforms(astroid.MANAGER) def _add_transform(package_name): def fake_module_builder(): """ Build a fake module to use within transformations. @package_name is a parameter from the outer scope b/c according to the docs this can't receive any parameters. https://pylint.readthedocs.io/projects/astroid/en/latest/extending.html#module-extender-transforms """ transforms_dir = os.path.join(os.path.dirname(__file__), "transforms") transformed_name = re.sub(r"\.", "_", package_name) fake_module_path = os.path.join(transforms_dir, f"{transformed_name}.py") with open(fake_module_path, encoding="utf-8") as modulefile: fake_module = modulefile.read() return astroid.builder.AstroidBuilder(astroid.MANAGER).string_build(fake_module) astroid.register_module_extender(astroid.MANAGER, package_name, fake_module_builder) _add_transform("django.utils.translation") # register transform for FileField/ImageField, see #60 _add_transform("django.db.models.fields.files") ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.481103 pylint-django-2.6.1/pylint_django/transforms/fields.py0000644000000000000000000001126314701764264020122 0ustar00from astroid import MANAGER, AstroidImportError, inference_tip, nodes from astroid.nodes import scoped_nodes from pylint_django import compat, utils _STR_FIELDS = ( "CharField", "SlugField", "URLField", "TextField", "EmailField", "CommaSeparatedIntegerField", "FilePathField", "GenericIPAddressField", "IPAddressField", "RegexField", "SlugField", ) _INT_FIELDS = ( "IntegerField", "SmallIntegerField", "BigIntegerField", "PositiveIntegerField", "PositiveSmallIntegerField", ) _BOOL_FIELDS = ("BooleanField", "NullBooleanField") _RANGE_FIELDS = ( "RangeField", "IntegerRangeField", "BigIntegerRangeField", "FloatRangeField", "DateTimeRangeField", "DateRangeField", ) def is_model_field(cls): return cls.qname().startswith("django.db.models.fields") or cls.qname().startswith("django.contrib.postgres.fields") def is_form_field(cls): return cls.qname().startswith("django.forms.fields") def is_model_or_form_field(cls): return is_model_field(cls) or is_form_field(cls) def apply_type_shim(cls, _context=None): # pylint: disable=too-many-statements if cls.name in _STR_FIELDS: base_nodes = scoped_nodes.builtin_lookup("str") elif cls.name in _INT_FIELDS: base_nodes = scoped_nodes.builtin_lookup("int") elif cls.name in _BOOL_FIELDS: base_nodes = scoped_nodes.builtin_lookup("bool") elif cls.name == "FloatField": base_nodes = scoped_nodes.builtin_lookup("float") elif cls.name == "DecimalField": try: base_nodes = MANAGER.ast_from_module_name("_decimal").lookup("Decimal") except AstroidImportError: base_nodes = MANAGER.ast_from_module_name("_pydecimal").lookup("Decimal") elif cls.name in ("SplitDateTimeField", "DateTimeField"): if compat.COMPILED_DATETIME_CLASSES: base_nodes = MANAGER.ast_from_module_name("_pydatetime").lookup("datetime") else: base_nodes = MANAGER.ast_from_module_name("datetime").lookup("datetime") elif cls.name == "TimeField": if compat.COMPILED_DATETIME_CLASSES: base_nodes = MANAGER.ast_from_module_name("_pydatetime").lookup("time") else: base_nodes = MANAGER.ast_from_module_name("datetime").lookup("time") elif cls.name == "DateField": if compat.COMPILED_DATETIME_CLASSES: base_nodes = MANAGER.ast_from_module_name("_pydatetime").lookup("date") else: base_nodes = MANAGER.ast_from_module_name("datetime").lookup("date") elif cls.name == "DurationField": if compat.COMPILED_DATETIME_CLASSES: base_nodes = MANAGER.ast_from_module_name("_pydatetime").lookup("timedelta") else: base_nodes = MANAGER.ast_from_module_name("datetime").lookup("timedelta") elif cls.name == "UUIDField": base_nodes = MANAGER.ast_from_module_name("uuid").lookup("UUID") elif cls.name == "ManyToManyField": base_nodes = MANAGER.ast_from_module_name("django.db.models.query").lookup("QuerySet") elif cls.name in ("ImageField", "FileField"): base_nodes = MANAGER.ast_from_module_name("django.core.files.base").lookup("File") elif cls.name == "ArrayField": base_nodes = scoped_nodes.builtin_lookup("list") elif cls.name in ("HStoreField", "JSONField"): base_nodes = scoped_nodes.builtin_lookup("dict") elif cls.name in _RANGE_FIELDS: try: base_nodes = MANAGER.ast_from_module_name("django.db.backends.postgresql.psycopg_any").lookup("Range") except AstroidImportError: base_nodes = MANAGER.ast_from_module_name("psycopg2._range").lookup("Range") else: return iter([cls]) # XXX: for some reason, with python3, this particular line triggers a # check in the StdlibChecker for deprecated methods; one of these nodes # is an ImportFrom which has no qname() method, causing the checker # to die... if utils.PY3: base_nodes = [_valid_base_node(n, _context) for n in base_nodes[1]] base_nodes = [n for n in base_nodes if n] else: base_nodes = list(base_nodes[1]) return iter([cls, *base_nodes]) def _valid_base_node(node, context): """Attempts to convert `node` to a valid base node, returns None if it cannot.""" if isinstance(node, nodes.AssignAttr): inferred = next(node.parent.value.infer(context), None) if inferred and isinstance(node, nodes.ClassDef): return inferred return None if isinstance(node, nodes.ImportFrom): return None return node def add_transforms(manager): manager.register_transform(nodes.ClassDef, inference_tip(apply_type_shim), is_model_or_form_field) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.481103 pylint-django-2.6.1/pylint_django/transforms/foreignkey.py0000644000000000000000000001336514701764264021023 0ustar00from itertools import chain from astroid import MANAGER, InferenceError, UseInferenceDefault, inference_tip, nodes from astroid.nodes import Attribute, ClassDef from pylint_django.utils import node_is_subclass def is_foreignkey_in_class(node): # is this of the form field = models.ForeignKey if not isinstance(node.parent, nodes.Assign): return False if not isinstance(node.parent.parent, ClassDef): return False # Make sure the outfit class is the subclass of django.db.models.Model is_in_django_model_class = node_is_subclass(node.parent.parent, "django.db.models.base.Model", ".Model") if not is_in_django_model_class: return False if isinstance(node.func, Attribute): attr = node.func.attrname elif isinstance(node.func, nodes.Name): attr = node.func.name else: return False return attr in ("OneToOneField", "ForeignKey") def _get_model_class_defs_from_module(module, model_name, module_name): class_defs = [] for module_node in module.lookup(model_name)[1]: if isinstance(module_node, nodes.ClassDef) and node_is_subclass(module_node, "django.db.models.base.Model"): class_defs.append(module_node) elif isinstance(module_node, nodes.ImportFrom): imported_module = module_node.do_import_module() class_defs.extend(_get_model_class_defs_from_module(imported_module, model_name, module_name)) return class_defs def _module_name_from_django_model_resolution(model_name, module_name): import django # pylint: disable=import-outside-toplevel django.setup() from django.apps import apps # pylint: disable=import-outside-toplevel app = apps.get_app_config(module_name) model = app.get_model(model_name) return model.__module__ def infer_key_classes(node, context=None): from django.core.exceptions import ImproperlyConfigured # pylint: disable=import-outside-toplevel keyword_args = [] if node.keywords: keyword_args = [kw.value for kw in node.keywords if kw.arg == "to"] all_args = chain(node.args, keyword_args) for arg in all_args: # typically the class of the foreign key will # be the first argument, so we'll go from left to right if isinstance(arg, (nodes.Name, nodes.Attribute)): try: key_cls = None for inferred in arg.infer(context=context): key_cls = inferred break except InferenceError: continue else: if key_cls is not None: break elif isinstance(arg, nodes.Const): try: # can be 'self' , 'Model' or 'app.Model' if arg.value == "self": module_name = "" # for relations with `to` first parent be Keyword(arg='to') # and we need to go deeper in parent tree to get model name if isinstance(arg.parent, nodes.Keyword) and arg.parent.arg == "to": model_name = arg.parent.parent.parent.parent.name else: model_name = arg.parent.parent.parent.name else: module_name, _, model_name = arg.value.rpartition(".") except AttributeError: break # when ForeignKey is specified only by class name we assume that # this class must be found in the current module if not module_name: current_module = node.frame() while not isinstance(current_module, nodes.Module): current_module = current_module.parent.frame() module_name = current_module.name elif not module_name.endswith("models"): # otherwise Django allows specifying an app name first, e.g. # ForeignKey('auth.User') try: module_name = _module_name_from_django_model_resolution(model_name, module_name) except LookupError: # If Django's model resolution fails we try to convert that to # 'auth.models', 'User' which works nicely with the `endswith()` # comparison below module_name += ".models" except ImproperlyConfigured as exep: raise RuntimeError( "DJANGO_SETTINGS_MODULE required for resolving ForeignKey " "string references, see Usage section in README at " "https://pypi.org/project/pylint-django/!" ) from exep # ensure that module is loaded in astroid_cache, for cases when models is a package if module_name not in MANAGER.astroid_cache: MANAGER.ast_from_module_name(module_name) # create list from dict_values, because it may be modified in a loop for module in list(MANAGER.astroid_cache.values()): # only load model classes from modules which match the module in # which *we think* they are defined. This will prevent inferring # other models of the same name which are found elsewhere! if model_name in module.locals and module.name.endswith(module_name): class_defs = _get_model_class_defs_from_module(module, model_name, module_name) if class_defs: return iter([class_defs[0].instantiate_class()]) else: raise UseInferenceDefault return iter([key_cls.instantiate_class()]) def add_transform(manager): manager.register_transform(nodes.Call, inference_tip(infer_key_classes), is_foreignkey_in_class) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.481103 pylint-django-2.6.1/pylint_django/transforms/transforms/__init__.py0000644000000000000000000000000014701764264022574 0ustar00././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.481103 pylint-django-2.6.1/pylint_django/transforms/transforms/django_db_models_fields_files.py0000644000000000000000000000116314701764264027032 0ustar00# pylint: disable=super-init-not-called from django.db.models.fields import files as django_fields class FileField(django_fields.FieldFile, django_fields.FileField): def __init__(self, verbose_name=None, name=None, upload_to="", storage=None, **kwargs): django_fields.FileField.__init__(verbose_name, name, upload_to, storage, **kwargs) class ImageField(django_fields.ImageFieldFile, django_fields.ImageField): def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): django_fields.ImageField.__init__(verbose_name, name, width_field, height_field, **kwargs) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.481103 pylint-django-2.6.1/pylint_django/transforms/transforms/django_utils_translation.py0000644000000000000000000000014114701764264026143 0ustar00def gettext_lazy(_): return "" ugettext_lazy = gettext_lazy # pylint:disable=invalid-name ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.481103 pylint-django-2.6.1/pylint_django/utils.py0000644000000000000000000000223214701764264015612 0ustar00"""Utils.""" import sys import astroid from astroid.bases import Instance from astroid.exceptions import InferenceError from astroid.nodes import ClassDef from pylint_django.compat import Uninferable PY3 = sys.version_info >= (3, 0) # TODO: pylint_django doesn't support Py2 any more def node_is_subclass(cls, *subclass_names): """Checks if cls node has parent with subclass_name.""" if not isinstance(cls, (ClassDef, Instance)): return False if cls.bases == Uninferable: return False for base_cls in cls.bases: try: for inf in base_cls.inferred(): if inf.qname() in subclass_names: return True if inf != cls and node_is_subclass(inf, *subclass_names): # check up the hierarchy in case we are a subclass of # a subclass of a subclass ... return True except InferenceError: continue return False def is_migrations_module(node): if not isinstance(node, astroid.Module): return False return "migrations" in node.path[0] and not node.path[0].endswith("__init__.py") ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728571572.481103 pylint-django-2.6.1/pyproject.toml0000644000000000000000000000603014701764264014153 0ustar00[build-system] build-backend = "poetry.core.masonry.api" requires = [ "poetry-core>=1" ] [tool.poetry] name = "pylint-django" version = "2.6.1" readme = "README.rst" description = "A Pylint plugin to help Pylint understand the Django web framework" repository = "https://github.com/pylint-dev/pylint-django" authors = [ "Carl Crowder " ] classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Operating System :: Unix", "Topic :: Software Development :: Quality Assurance", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Framework :: Django :: 2.2", "Framework :: Django :: 3", "Framework :: Django :: 3.0", "Framework :: Django :: 3.1", "Framework :: Django :: 3.2", "Framework :: Django :: 4", "Framework :: Django :: 4.0", "Framework :: Django :: 4.1", "Framework :: Django :: 4.2", "Framework :: Django :: 5.0", "Framework :: Django :: 5.1", "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)", ] keywords = [ "pylint", "django", "plugin" ] packages = [ { include = "pylint_django/" }, ] include = [ "pylint_django/LICENSE" ] exclude = [ "**/tests/**", "**/testutils.py", "**/tests.py" ] [tool.poetry.dependencies] python = ">=3.9,<4.0" pylint-plugin-utils = ">=0.8" pylint = ">=3.0,<4" Django = { version = ">=2.2", optional = true } [tool.poetry.group.dev.dependencies] tox = ">=4.9" pytest = "^7.3.1" ruff = ">=0.6.9" wheel = "^0.40" pytest-cov = "^4" django-tables2 = "^2.6" factory-boy = "^3.3" django-tastypie = "^0.14" pre-commit = ">=1" [tool.poetry.extras] with_django = [ "Django" ] [tool.black] line-length = 120 [tool.ruff] line-length = 120 lint.select = [ "B", # bugbear "E", # pycodestyle "F", # pyflakes "FA100", # add future annotations "I", # isort "PGH004", # pygrep-hooks - Use specific rule codes when using noqa "PIE", # flake8-pie "PLC", # pylint convention "PLE", # pylint error "PLR", # pylint refactor "PLR1714", # Consider merging multiple comparisons "PLW", # pylint warning "PYI", # flake8-pyi "RUF", # ruff "T100", # flake8-debugger "UP", # pyupgrade "W", # pycodestyle ] lint.ignore = [ "PLR0912", # Too many branches, worse than C901 "PLR0915", # Too many statements, worse than C901 "PLR2004", # Magic value used in comparison, opinionated "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` ] [tool.isort] multi_line_output = 3 include_trailing_comma = true force_grid_wrap = 0 use_parentheses = true line_length = 120 [tool.pylint.main] disable = [ "missing-docstring", "too-many-branches", "too-many-return-statements", "too-many-ancestors", "too-few-public-methods", "fixme", ] ignore = "tests" max-line-length = 120 [tool.codespell] ignore-words = [ "custom_dict.txt" ] pylint-django-2.6.1/setup.py0000644000000000000000000001453700000000000012712 0ustar00# -*- coding: utf-8 -*- from setuptools import setup packages = \ ['pylint_django', 'pylint_django.augmentations', 'pylint_django.checkers', 'pylint_django.transforms', 'pylint_django.transforms.transforms'] package_data = \ {'': ['*']} install_requires = \ ['pylint-plugin-utils>=0.8', 'pylint>=3.0,<4'] extras_require = \ {'with_django': ['Django>=2.2']} setup_kwargs = { 'name': 'pylint-django', 'version': '2.6.1', 'description': 'A Pylint plugin to help Pylint understand the Django web framework', 'long_description': 'pylint-django\n=============\n\n.. image:: https://github.com/pylint-dev/pylint-django/actions/workflows/build.yml/badge.svg\n :target: https://github.com/pylint-dev/pylint-django/actions/workflows/build.yml\n\n.. image:: https://coveralls.io/repos/github/pylint-dev/pylint-django/badge.svg?branch=master\n :target: https://coveralls.io/github/pylint-dev/pylint-django?branch=master\n\n.. image:: https://img.shields.io/pypi/v/pylint-django.svg\n :target: https://pypi.python.org/pypi/pylint-django\n\n\nAbout\n-----\n\n``pylint-django`` is a `Pylint `__ plugin for improving code\nanalysis when analysing code using Django. It is also used by the\n`Prospector `__ tool.\n\n\nInstallation\n------------\n\nTo install::\n\n pip install pylint-django\n\n\n**WARNING:** ``pylint-django`` will not install ``Django`` by default because\nthis causes more trouble than good,\n`see discussion `__. If you wish\nto automatically install the latest version of ``Django`` then::\n\n pip install pylint-django[with-django]\n\notherwise sort out your testing environment and please **DO NOT** report issues\nabout missing Django!\n\n\nUsage\n-----\n\n\nEnsure ``pylint-django`` is installed and on your path. In order to access some\nof the internal Django features to improve pylint inspections, you should also\nprovide a Django settings module appropriate to your project. This can be done\neither with an environment variable::\n\n DJANGO_SETTINGS_MODULE=your.app.settings pylint --load-plugins pylint_django [..other options..] \n\nAlternatively, this can be passed in as a commandline flag::\n\n pylint --load-plugins pylint_django --django-settings-module=your.app.settings [..other options..] \n\nIf you do not configure Django, default settings will be used but this will not include, for\nexample, which applications to include in `INSTALLED_APPS` and so the linting and type inference\nwill be less accurate. It is recommended to specify a settings module.\n\nProspector\n----------\n\nIf you have ``prospector`` installed, then ``pylint-django`` will already be\ninstalled as a dependency, and will be activated automatically if Django is\ndetected::\n\n prospector [..other options..]\n\n\nFeatures\n--------\n\n* Prevents warnings about Django-generated attributes such as\n ``Model.objects`` or ``Views.request``.\n* Prevents warnings when using ``ForeignKey`` attributes ("Instance of\n ForeignKey has no member").\n* Fixes pylint\'s knowledge of the types of Model and Form field attributes\n* Validates ``Model.__unicode__`` methods.\n* ``Meta`` informational classes on forms and models do not generate errors.\n* Flags dangerous use of the exclude attribute in ModelForm.Meta.\n* Uses Django\'s internal machinery to try and resolve models referenced as\n strings in ForeignKey fields. That relies on ``django.setup()`` which needs\n the appropriate project settings defined!\n\n\nAdditional plugins\n------------------\n\n``pylint_django.checkers.migrations`` looks for migrations which:\n\n- add new model fields and these fields have a default value. According to\n `Django docs `_\n this may have performance penalties especially on large tables. The preferred way\n is to add a new DB column with ``null=True`` because it will be created instantly\n and then possibly populate the table with the desired default values.\n Only the last migration from a sub-directory will be examined;\n- are ``migrations.RunPython()`` without a reverse callable - these will result in\n non reversible data migrations;\n\n\nThis plugin is disabled by default! To enable it::\n\n pylint --load-plugins pylint_django --load-plugins pylint_django.checkers.migrations\n\n\nContributing\n------------\n\nPlease feel free to add your name to the ``CONTRIBUTORS.rst`` file if you want to\nbe credited when pull requests get merged. You can also add to the\n``CHANGELOG.rst`` file if you wish, although we\'ll also do that when merging.\n\n\nTests\n-----\n\nThe structure of the test package follows that from pylint itself.\n\nIt is fairly simple: create a module starting with ``func_`` followed by\na test name, and insert into it some code. The tests will run pylint\nagainst these modules. If the idea is that no messages now occur, then\nthat is fine, just check to see if it works by running ``scripts/test.sh``.\n\nAny command line argument passed to ``scripts/test.sh`` will be passed to the internal invocation of ``pytest``.\nFor example if you want to debug the tests you can execute ``scripts/test.sh --capture=no``.\nA specific test case can be run by filtering based on the file name of the test case ``./scripts/test.sh -k \'func_noerror_views\'``.\n\nIdeally, add some pylint error suppression messages to the file to prevent\nspurious warnings, since these are all tiny little modules not designed to\ndo anything so there\'s no need to be perfect.\n\nIt is possible to make tests with expected error output, for example, if\nadding a new message or simply accepting that pylint is supposed to warn.\nA ``test_file_name.txt`` file contains a list of expected error messages in the\nformat\n``error-type:line number:class name or empty:1st line of detailed error text:confidence or empty``.\n\n\nLicense\n-------\n\n``pylint-django`` is available under the GPLv2 license.\n', 'author': 'Carl Crowder', 'author_email': 'git@carlcrowder.com', 'maintainer': 'None', 'maintainer_email': 'None', 'url': 'https://github.com/pylint-dev/pylint-django', 'packages': packages, 'package_data': package_data, 'install_requires': install_requires, 'extras_require': extras_require, 'python_requires': '>=3.9,<4.0', } setup(**setup_kwargs) pylint-django-2.6.1/PKG-INFO0000644000000000000000000001571500000000000012274 0ustar00Metadata-Version: 2.1 Name: pylint-django Version: 2.6.1 Summary: A Pylint plugin to help Pylint understand the Django web framework Home-page: https://github.com/pylint-dev/pylint-django Keywords: pylint,django,plugin Author: Carl Crowder Author-email: git@carlcrowder.com Requires-Python: >=3.9,<4.0 Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Framework :: Django :: 2.2 Classifier: Framework :: Django :: 3 Classifier: Framework :: Django :: 3.0 Classifier: Framework :: Django :: 3.1 Classifier: Framework :: Django :: 3.2 Classifier: Framework :: Django :: 4 Classifier: Framework :: Django :: 4.0 Classifier: Framework :: Django :: 4.1 Classifier: Framework :: Django :: 4.2 Classifier: Framework :: Django :: 5.0 Classifier: Framework :: Django :: 5.1 Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+) Classifier: Operating System :: Unix Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.9 Classifier: Topic :: Software Development :: Quality Assurance Provides-Extra: with_django Requires-Dist: Django (>=2.2); extra == "with_django" Requires-Dist: pylint (>=3.0,<4) Requires-Dist: pylint-plugin-utils (>=0.8) Project-URL: Repository, https://github.com/pylint-dev/pylint-django Description-Content-Type: text/x-rst pylint-django ============= .. image:: https://github.com/pylint-dev/pylint-django/actions/workflows/build.yml/badge.svg :target: https://github.com/pylint-dev/pylint-django/actions/workflows/build.yml .. image:: https://coveralls.io/repos/github/pylint-dev/pylint-django/badge.svg?branch=master :target: https://coveralls.io/github/pylint-dev/pylint-django?branch=master .. image:: https://img.shields.io/pypi/v/pylint-django.svg :target: https://pypi.python.org/pypi/pylint-django About ----- ``pylint-django`` is a `Pylint `__ plugin for improving code analysis when analysing code using Django. It is also used by the `Prospector `__ tool. Installation ------------ To install:: pip install pylint-django **WARNING:** ``pylint-django`` will not install ``Django`` by default because this causes more trouble than good, `see discussion `__. If you wish to automatically install the latest version of ``Django`` then:: pip install pylint-django[with-django] otherwise sort out your testing environment and please **DO NOT** report issues about missing Django! Usage ----- Ensure ``pylint-django`` is installed and on your path. In order to access some of the internal Django features to improve pylint inspections, you should also provide a Django settings module appropriate to your project. This can be done either with an environment variable:: DJANGO_SETTINGS_MODULE=your.app.settings pylint --load-plugins pylint_django [..other options..] Alternatively, this can be passed in as a commandline flag:: pylint --load-plugins pylint_django --django-settings-module=your.app.settings [..other options..] If you do not configure Django, default settings will be used but this will not include, for example, which applications to include in `INSTALLED_APPS` and so the linting and type inference will be less accurate. It is recommended to specify a settings module. Prospector ---------- If you have ``prospector`` installed, then ``pylint-django`` will already be installed as a dependency, and will be activated automatically if Django is detected:: prospector [..other options..] Features -------- * Prevents warnings about Django-generated attributes such as ``Model.objects`` or ``Views.request``. * Prevents warnings when using ``ForeignKey`` attributes ("Instance of ForeignKey has no member"). * Fixes pylint's knowledge of the types of Model and Form field attributes * Validates ``Model.__unicode__`` methods. * ``Meta`` informational classes on forms and models do not generate errors. * Flags dangerous use of the exclude attribute in ModelForm.Meta. * Uses Django's internal machinery to try and resolve models referenced as strings in ForeignKey fields. That relies on ``django.setup()`` which needs the appropriate project settings defined! Additional plugins ------------------ ``pylint_django.checkers.migrations`` looks for migrations which: - add new model fields and these fields have a default value. According to `Django docs `_ this may have performance penalties especially on large tables. The preferred way is to add a new DB column with ``null=True`` because it will be created instantly and then possibly populate the table with the desired default values. Only the last migration from a sub-directory will be examined; - are ``migrations.RunPython()`` without a reverse callable - these will result in non reversible data migrations; This plugin is disabled by default! To enable it:: pylint --load-plugins pylint_django --load-plugins pylint_django.checkers.migrations Contributing ------------ Please feel free to add your name to the ``CONTRIBUTORS.rst`` file if you want to be credited when pull requests get merged. You can also add to the ``CHANGELOG.rst`` file if you wish, although we'll also do that when merging. Tests ----- The structure of the test package follows that from pylint itself. It is fairly simple: create a module starting with ``func_`` followed by a test name, and insert into it some code. The tests will run pylint against these modules. If the idea is that no messages now occur, then that is fine, just check to see if it works by running ``scripts/test.sh``. Any command line argument passed to ``scripts/test.sh`` will be passed to the internal invocation of ``pytest``. For example if you want to debug the tests you can execute ``scripts/test.sh --capture=no``. A specific test case can be run by filtering based on the file name of the test case ``./scripts/test.sh -k 'func_noerror_views'``. Ideally, add some pylint error suppression messages to the file to prevent spurious warnings, since these are all tiny little modules not designed to do anything so there's no need to be perfect. It is possible to make tests with expected error output, for example, if adding a new message or simply accepting that pylint is supposed to warn. A ``test_file_name.txt`` file contains a list of expected error messages in the format ``error-type:line number:class name or empty:1st line of detailed error text:confidence or empty``. License ------- ``pylint-django`` is available under the GPLv2 license.