How to Return JSON Encoded Response for a non-dict object
In DJango, an HttpResponse sub-class helps to create a JSON-encoded response. It was called Serialized-Object response in Django < 1.7. Its default Content-Type header is set to application/JSON. The first parameter (data set), should be a dict instance. If non-dict object is passed in as the first parameter, a TypeError will be raised. To fix this error, we just need to add a parameter called “safe” to False in the method call JsonResponse.
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False
This is the fix:
return JsonResponse(["a", "b", 1, 2], safe=False)
The safe boolean parameter defaults is True. If it’s set to False, any object can be passed for serialization (otherwise only dict instances are allowed).
Example non-dict object:
some_object = [{‘pk’: 86, “model”: “machine_models.machinemodel”, “notes”: “This is warehouse imported machine.”}]
return JsonResponse(some_object,safe=False)
A complete sample:
from django.http import JsonResponse
def home_details(req):
response = {
'id': 1,
'address': '123 Main St., San Jose, CA 95111',
'beds': 3,
'baths': 2,
'status': Sold
}
return JsonResponse(response)
Django errors while working with components
1) OperationalError at /admin/csv_app/invoicefile/add/
no such table: csv_app_invoicefile
==>solve this error by cmd
makemigrations csv_app
migrate
2)System check identified no issues (0 silenced).
You have 6 unapplied migration(s). Your project may not work properly until you
apply the migrations for app(s): csv_app.
Run ‘python manage.py migrate’ to apply them.
July 13, 2021 – 14:55:01
Django version 3.2.5, using settings ‘proj3.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
==>to fix this error, go to cmd enter:
$python manage.py makemigrations csv_app
$python manage.py migrate
$py manage.py runserver
3)os.path.join(BASE_DIR, ‘static’),
NameError: name ‘os’ is not defined
==>add this line in settings.py
import os
Inner class Meta
In Django this class works like post_meta in WordPress. In Django, it acts as a configuration class and keeps the configuration data in one place. Class Meta is the place in your code logic where your model.fields MEET With your form.widgets. So under Class Meta() you create the link between your model’ fields and the different widgets you want to have in your form.
Model metadata is “anything that’s not a field”, such as ordering options (ordering), database table name (db_table), or human-readable singular and plural names (verbose_name and verbose_name_plural). None are required, and adding class Meta to a model is completely optional.
A complete list of all possible Meta options are in this document (https://docs.djangoproject.com/en/dev/ref/models/options/):
To override the database table name, use the db_table parameter in class Meta.
db_table
db_table = ‘”name_left_in_lowercase”‘
app_label
app_label = ‘myapp’
base_manager_name
db_tablespace
default_manager_name
default_related_name
get_latest_by
managed
order_with_respect_to
ordering
permissions (Defaults to (‘add’, ‘change’, ‘delete’, ‘view’)
proxy
required_db_features
required_db_vendor
indexes
unique_together
index_together
constraints
verbose_name
verbose_name_plural
label
label_lower
OperationalError, no such column.
OperationalError at /orders/
no such column: orders.customer_id
Request Method: GET
Request URL: http://localhost:9000/orders/
Django Version: 3.1.2
Exception Type: OperationalError
Exception Value:
no such column: orders.customer_id
Exception Location: /Users/xxx/django/db/backends/sqlite3/base.py in execute, line 355
Python Executable: /Users/xxx/Programs/Python/Python38-32
Python Version: 3.8.1
You are trying to add a non-nullable field ‘customer_id’ to snippet without a default;
we can’t do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
In Django 1.7, the functionality of an app was integrated directly into Django. When working with migrations, the process is a bit different.
Make changes to models.py as usual.
Create a migration. This generates code to go from the current state to the next state of your model. This is done with the “makemigrations my-app-name” command. This command is smart enough to detect what has changed and will create a script to effect that change to your database.
Next, you apply that migration with “manage.py migrate” command. This command applies all migrations in order.
Step 1: Delete all the migration records from your app’s migration directory. These are files named 0001_,0002_,0003_ etc. Be careful as to not delete the _init__.py file.
Step 2 : Delete the db.sqlite3 file. It will be regenerated later.
Then run the following commands:
$python manage.py makemigrations your-app-name
$python manage.py migrate (new db.sqlite3 will be generated automatically)
Be sure to write the name of your app after makemigrations. You might have to create a superuser to access your database again. Do so by the following:
$python manage.py createsuperuser
Query that returns two character records from MySQL table
Today I will show you how to get records of 2 characters that are mixed in with multiple character records. This particular example I experienced from my work. All 52 states in US each has 2 names: full name and abbreviation name. For example: California is a full name and CA is its abbreviation. However in Canada a state has only full name. For example: Manitoba.
The issue here is that when you have a state table in your database that contains the states of USA and Canada. I will show what query you should use to filter the list of only US States.
Your state table will look like this picture:
The query you will have to use to get only the US states is:
- $sql_statement = “Select * from mydb.state_table where CHAR_LENGTH(state_abbr) = 2”;
And here is the list of states returned by the query above.