rspec/rules/S6554/python/rule.adoc
Fred Tingaud d3cfe19d7e
Fix broken or dangerous backquotes
Co-authored-by: Marco Borgeaud <89914223+marco-antognini-sonarsource@users.noreply.github.com>
2023-10-30 10:33:56 +01:00

53 lines
1.5 KiB
Plaintext

This rule ensures that Django models have a ``++__str__++`` method defined.
== Why is this an issue?
The ``++__str__++`` method in Django models is used to represent the model instance as a string. For example, the return value of this method will be inserted in a template when displaying an object in the Django admin site. Without this method, the model instance will be represented by its object identifier, which is not meaningful to end-users. This can result in confusion and make debugging more difficult.
== How to fix it
To fix this issue, the Django model must define a ``++__str__++`` method that returns a string representation of the instance. This string should be meaningful to end-users and provide information about the model instance.
=== Code examples
==== Noncompliant code example
[source,python]
----
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
----
==== Compliant solution
[source,python]
----
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
----
== Resources
=== Documentation
https://docs.djangoproject.com/en/4.1/ref/models/instances/#django.db.models.Model.__str__[Django Model.__str__()]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Define a "__str__" method for this Django model.
'''
endif::env-github,rspecator-view[]