0
# String Type Handling
1
2
Type aliases for Django's Promise-based string handling system, providing proper type safety for lazy string evaluation, internationalization, and template rendering. These types handle Django's deferred string evaluation system used throughout the framework.
3
4
## Capabilities
5
6
### Promise String Type
7
8
Type alias for Django's Promise-based lazy string evaluation system, commonly used for internationalization and template rendering.
9
10
```python { .api }
11
StrPromise = Promise
12
"""
13
Django Promise string type for lazy string evaluation.
14
15
In TYPE_CHECKING mode: Resolves to _StrPromise from django-stubs
16
At runtime: Django's Promise class for lazy string evaluation
17
"""
18
```
19
20
### String or Promise Union
21
22
Union type that handles both regular strings and Django Promise objects, providing flexibility for functions that accept either immediate or lazy string values.
23
24
```python { .api }
25
StrOrPromise = Union[str, StrPromise]
26
"""
27
Union type for string or Promise types.
28
29
Accepts both:
30
- Regular Python strings (str)
31
- Django Promise objects for lazy evaluation
32
"""
33
```
34
35
### Usage Examples
36
37
Internationalization with lazy strings:
38
39
```python
40
from django_stubs_ext import StrOrPromise, StrPromise
41
from django.utils.translation import gettext_lazy as _
42
from django.db import models
43
44
class Category(models.Model):
45
name = models.CharField(max_length=100)
46
47
def get_display_name(self) -> StrOrPromise:
48
"""Return localized category name."""
49
name_mapping = {
50
'electronics': _('Electronics'),
51
'clothing': _('Clothing & Fashion'),
52
'books': _('Books & Media')
53
}
54
return name_mapping.get(self.name, self.name)
55
56
# Usage with lazy strings
57
category = Category.objects.get(name='electronics')
58
display_name: StrOrPromise = category.get_display_name()
59
60
# Can be used in contexts expecting strings
61
print(f"Category: {display_name}") # Evaluates Promise at print time
62
```
63
64
Template context and form handling:
65
66
```python
67
from django_stubs_ext import StrOrPromise
68
from django import forms
69
from django.utils.translation import gettext_lazy as _
70
71
class ContactForm(forms.Form):
72
name = forms.CharField(
73
label=_('Full Name'),
74
help_text=_('Enter your complete name')
75
)
76
email = forms.EmailField(
77
label=_('Email Address'),
78
help_text=_('We will not share your email')
79
)
80
81
def get_field_label(self, field_name: str) -> StrOrPromise:
82
"""Get the label for a form field."""
83
field = self.fields.get(field_name)
84
if field and field.label:
85
return field.label
86
return field_name.replace('_', ' ').title()
87
88
# Type-safe field label access
89
form = ContactForm()
90
name_label: StrOrPromise = form.get_field_label('name')
91
```
92
93
Model verbose names and metadata:
94
95
```python
96
from django_stubs_ext import StrOrPromise
97
from django.db import models
98
from django.utils.translation import gettext_lazy as _
99
100
class Article(models.Model):
101
title = models.CharField(max_length=200)
102
content = models.TextField()
103
104
class Meta:
105
verbose_name: StrOrPromise = _('Article')
106
verbose_name_plural: StrOrPromise = _('Articles')
107
108
def get_status_display(self) -> StrOrPromise:
109
"""Get human-readable status."""
110
status_choices = {
111
'draft': _('Draft'),
112
'published': _('Published'),
113
'archived': _('Archived')
114
}
115
return status_choices.get(self.status, _('Unknown'))
116
117
# Type-safe metadata access
118
article = Article()
119
verbose_name: StrOrPromise = article._meta.verbose_name
120
status_display: StrOrPromise = article.get_status_display()
121
```
122
123
### Type Checking Behavior
124
125
The string type aliases adapt their behavior based on the execution context:
126
127
```python
128
import typing
129
from django.utils.functional import Promise
130
131
if typing.TYPE_CHECKING:
132
# Static type checking mode - use django-stubs definitions
133
from django.utils.functional import _StrPromise as StrPromise
134
from django.utils.functional import _StrOrPromise as StrOrPromise
135
else:
136
# Runtime mode - use actual Django classes
137
StrPromise = Promise
138
StrOrPromise = typing.Union[str, StrPromise]
139
```
140
141
### Function Parameter Typing
142
143
Use these types to properly annotate functions that work with Django's string system:
144
145
```python
146
from django_stubs_ext import StrOrPromise
147
from django.utils.html import format_html
148
from django.utils.safestring import SafeString
149
150
def create_notification(
151
title: StrOrPromise,
152
message: StrOrPromise,
153
level: str = 'info'
154
) -> SafeString:
155
"""Create a formatted notification message."""
156
return format_html(
157
'<div class="alert alert-{level}"><h4>{title}</h4><p>{message}</p></div>',
158
level=level,
159
title=title,
160
message=message
161
)
162
163
# Works with both regular strings and lazy strings
164
from django.utils.translation import gettext_lazy as _
165
166
# Regular strings
167
notification1 = create_notification("Success", "Operation completed")
168
169
# Lazy strings for internationalization
170
notification2 = create_notification(
171
_("Error"),
172
_("An error occurred while processing your request")
173
)
174
```
175
176
## Types
177
178
```python { .api }
179
import typing
180
from typing import Union
181
from django.utils.functional import Promise
182
183
if typing.TYPE_CHECKING:
184
from django.utils.functional import _StrPromise as StrPromise
185
from django.utils.functional import _StrOrPromise as StrOrPromise
186
else:
187
StrPromise = Promise
188
StrOrPromise = Union[str, StrPromise]
189
```