|
| 1 | +title: django.db.models TextField Example Code |
| 2 | +category: page |
| 3 | +slug: django-db-models-textfield-examples |
| 4 | +sortorder: 50102 |
| 5 | +toc: False |
| 6 | +sidebartitle: django.db.models TextField |
| 7 | +meta: Python code examples for the Django ORM's TextField class, found within the django.db.models module of the Django project. |
| 8 | + |
| 9 | + |
| 10 | +[TextField](https://github.com/django/django/blob/master/django/db/models/fields/__init__.py) |
| 11 | +is a field used to create an arbitrary amount of text characters in a |
| 12 | +[database](/databases.html) column defined by the |
| 13 | +[Django ORM](/django-orm.html). |
| 14 | + |
| 15 | +The [Django](/django.html) project has wonderful documentation for |
| 16 | +[TextField](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.TextField) |
| 17 | +and all of the other column fields. |
| 18 | + |
| 19 | +Note that `TextField` is defined within the |
| 20 | +[django.db.models.fields](https://github.com/django/django/blob/master/django/db/models/fields/__init__.py) |
| 21 | +module but is typically referenced from |
| 22 | +[django.db.models](https://github.com/django/django/tree/master/django/db/models) |
| 23 | +rather than including the `fields` module reference. |
| 24 | + |
| 25 | + |
| 26 | +## Example 1 from django-smithy |
| 27 | +[django-smithy](https://github.com/jamiecounsell/django-smithy) is |
| 28 | +a code library for [Django](/django.html) that makes it easy for users |
| 29 | +to send HTTP requests from the Django admin user interface. The code for |
| 30 | +the project is open source under the |
| 31 | +[MIT license](https://github.com/jamiecounsell/django-smithy/blob/master/LICENSE). |
| 32 | + |
| 33 | +[**django-smithy / smithy / models.py**](https://github.com/jamiecounsell/django-smithy/blob/master/smithy/models.py) |
| 34 | + |
| 35 | +```python |
| 36 | +# -*- coding: utf-8 -*- |
| 37 | + |
| 38 | +~~from django.db import models |
| 39 | +from django.db.models.signals import post_save |
| 40 | +from django.dispatch import receiver |
| 41 | +from requests import Request as HTTPRequest, Session |
| 42 | +from requests.cookies import create_cookie, RequestsCookieJar |
| 43 | +from urllib.parse import parse_qs, urlparse, urlencode |
| 44 | +from requests_toolbelt.utils import dump |
| 45 | + |
| 46 | +from model_utils.models import TimeStampedModel |
| 47 | + |
| 48 | +from smithy.helpers import render_with_context, parse_dump_result |
| 49 | + |
| 50 | + |
| 51 | +class NameValueModel(TimeStampedModel): |
| 52 | + name = models.CharField(max_length = 200) |
| 53 | +~~ value = models.TextField(blank = True) |
| 54 | + |
| 55 | + def __str__(self): |
| 56 | + return self.name |
| 57 | + |
| 58 | + class Meta: |
| 59 | + abstract = True |
| 60 | + |
| 61 | + |
| 62 | +class Request(TimeStampedModel): |
| 63 | + """ |
| 64 | + A base model shared by RequestBlueprint and |
| 65 | + RequestRecord. Used solely to reduce |
| 66 | + """ |
| 67 | + METHODS = ( |
| 68 | + ('GET', 'GET'), |
| 69 | + ('POST', 'POST'), |
| 70 | + ('PUT', 'PUT'), |
| 71 | + ('DELETE', 'DELETE'), |
| 72 | + ('OPTIONS', 'OPTIONS'), |
| 73 | + ('HEAD', 'HEAD'), |
| 74 | + ) |
| 75 | + BODY_TYPES = ( |
| 76 | + ('', 'Other'), |
| 77 | + ('application/x-www-form-urlencoded', 'x-www-form-urlencoded'), |
| 78 | + ('application/json', 'JSON'), |
| 79 | + ('text/plain', 'Text'), |
| 80 | + ('application/javascript', 'JavaScript'), |
| 81 | + ('application/xml', 'XML (application/xml)'), |
| 82 | + ('text/xml', 'XML (text/xml)'), |
| 83 | + ('text/html', 'HTML'), |
| 84 | + ) |
| 85 | + method = models.CharField( |
| 86 | + max_length = 7, choices = METHODS, |
| 87 | + blank = False, null = False) |
| 88 | + name = models.CharField(max_length = 500, blank = False) |
| 89 | + url = models.CharField(max_length = 2083) |
| 90 | +~~ body = models.TextField(blank = True) |
| 91 | + content_type = models.CharField( |
| 92 | + default = BODY_TYPES[0][0], |
| 93 | + blank = True, null = True, |
| 94 | + max_length = 100, choices = BODY_TYPES) |
| 95 | + |
| 96 | + def __str__(self): |
| 97 | + if self.name: |
| 98 | + return self.name |
| 99 | + return "{} {}".format( |
| 100 | + self.method, |
| 101 | + self.url, |
| 102 | + ) |
| 103 | + |
| 104 | + |
| 105 | +class RequestBlueprint(Request): |
| 106 | + """ |
| 107 | + A blueprint for HTTP requests. This model will be |
| 108 | + used to generate and send HTTP requests. Once sent, |
| 109 | + a RequestRecord will be created for that request. |
| 110 | + """ |
| 111 | + follow_redirects = models.BooleanField( |
| 112 | + default = False, blank = False, null = False) |
| 113 | + |
| 114 | + @property |
| 115 | + def name_value_related(self): |
| 116 | + return [ |
| 117 | + self.headers, |
| 118 | + self.query_parameters, |
| 119 | + self.cookies |
| 120 | + ] |
| 121 | + |
| 122 | + def send(self, context = None): |
| 123 | + |
| 124 | + context = context or {} |
| 125 | + for variable in self.variables.all(): |
| 126 | + context[variable.name] = variable.value |
| 127 | + |
| 128 | + request = HTTPRequest( |
| 129 | + url = render_with_context(self.url, context), |
| 130 | + method = self.method) |
| 131 | + |
| 132 | + session = Session() |
| 133 | + record = RequestRecord.objects.create(blueprint = self) |
| 134 | + |
| 135 | + # Copy RequestBlueprint values to RequestRecord |
| 136 | + for qs in self.name_value_related: |
| 137 | + for obj in qs.all(): |
| 138 | + obj.pk = 0 |
| 139 | + obj.name = render_with_context(obj.name, context) |
| 140 | + obj.value = render_with_context(obj.value, context) |
| 141 | + obj.add_to(request) |
| 142 | + obj.request = record |
| 143 | + obj.save() |
| 144 | + |
| 145 | + if self.content_type == self.BODY_TYPES[0][0]: |
| 146 | + data = render_with_context(self.body, context) |
| 147 | + else: |
| 148 | + data = {} |
| 149 | + for param in self.body_parameters.all(): |
| 150 | + param.add_to(data, context) |
| 151 | + |
| 152 | + request.data = data |
| 153 | + prepared_request = request.prepare() |
| 154 | + |
| 155 | + response = session.send(prepared_request, stream = True) |
| 156 | + # TODO: follow redirects |
| 157 | + |
| 158 | + RequestRecord.objects.filter(pk = record.pk).update( |
| 159 | + raw_request = parse_dump_result(dump._dump_request_data, prepared_request), |
| 160 | + raw_response = parse_dump_result(dump._dump_response_data, response), |
| 161 | + status = response.status_code, |
| 162 | + **RequestRecord.get_clone_args(self, context) |
| 163 | + ) |
| 164 | + |
| 165 | + # Return fresh copy after update |
| 166 | + return RequestRecord.objects.get(pk = record.pk) |
| 167 | + |
| 168 | + |
| 169 | +class RequestRecord(Request): |
| 170 | + """ |
| 171 | + A record of a Request that has been sent. |
| 172 | + Contains response and diagnostic information |
| 173 | + about the request. |
| 174 | + """ |
| 175 | +~~ raw_request = models.TextField() |
| 176 | +~~ raw_response = models.TextField() |
| 177 | + status = models.PositiveIntegerField(null = True) |
| 178 | + blueprint = models.ForeignKey( |
| 179 | + 'smithy.RequestBlueprint', |
| 180 | + on_delete = models.SET_NULL, |
| 181 | + null = True) |
| 182 | + |
| 183 | + @property |
| 184 | + def is_success(self): |
| 185 | + return self.status and self.status < 400 |
| 186 | + |
| 187 | + @staticmethod |
| 188 | + def of_blueprint(blueprint): |
| 189 | + return RequestRecord.objects.filter( |
| 190 | + blueprint = blueprint) |
| 191 | + |
| 192 | + @classmethod |
| 193 | + def get_clone_args(cls, obj, context : dict): |
| 194 | + return dict([ |
| 195 | + ( |
| 196 | + render_with_context(fld.name, context), |
| 197 | + render_with_context(getattr(obj, fld.name), context) |
| 198 | + ) |
| 199 | + for fld \ |
| 200 | + in cls._meta.fields \ |
| 201 | + if fld.name != obj._meta.pk \ |
| 202 | + and fld in obj._meta.fields \ |
| 203 | + and fld.name not in [ |
| 204 | + 'request', 'id', 'created', 'updated' |
| 205 | + ]]) |
| 206 | + |
| 207 | + |
| 208 | +## source file continues from here without further TextField examples |
| 209 | +``` |
0 commit comments