Best VPN Service (English Banners)

GeekBuying.com

Using Django to Build a Website (Mac) 4

Alibaba Cloud
Autonomous Standing Desk

System Mechanic® Ultimate Defense™
Save up to 50% on ANSI Standards Packages

Render Data from Database with a Model

 

(project1_env) SS-MacBook:src liveuk$ ls

IK Multimedia's T-RackS 5

db.sqlite3 pages templates

manage.py products trydjango

(project1_env) SS-MacBook:src liveuk$ python manage.py shell

Autonomous Standing Desk

Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37)

[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin

Type “help”, “copyright”, “credits” or “license” for more information.

(InteractiveConsole)

>>> from products.models import Product

>>> Product.objects.get(id=1)

<Product: Product object (1)>

>>> obj = <Product: Product object (1)>

  File “<console>”, line 1

    obj = <Product: Product object (1)>

          ^

SyntaxError: invalid syntax

>>> obj = Product.objects.get(id=1)

>>> dir(obj)

[‘DoesNotExist’, ‘MultipleObjectsReturned’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getstate__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__setstate__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘_check_column_name_clashes’, ‘_check_field_name_clashes’, ‘_check_fields’, ‘_check_id_field’, ‘_check_index_together’, ‘_check_local_fields’, ‘_check_long_column_names’, ‘_check_m2m_through_same_relationship’, ‘_check_managers’, ‘_check_model’, ‘_check_model_name_db_lookup_clashes’, ‘_check_ordering’, ‘_check_swappable’, ‘_check_unique_together’, ‘_do_insert’, ‘_do_update’, ‘_get_FIELD_display’, ‘_get_next_or_previous_by_FIELD’, ‘_get_next_or_previous_in_order’, ‘_get_pk_val’, ‘_get_unique_checks’, ‘_meta’, ‘_perform_date_checks’, ‘_perform_unique_checks’, ‘_save_parents’, ‘_save_table’, ‘_set_pk_val’, ‘_state’, ‘check’, ‘clean’, ‘clean_fields’, ‘date_error_message’, ‘delete’, ‘description’, ‘featured’, ‘from_db’, ‘full_clean’, ‘get_deferred_fields’, ‘id’, ‘objects’, ‘pk’, ‘prepare_database_save’, ‘price’, ‘refresh_from_db’, ‘save’, ‘save_base’, ‘serializable_value’, ‘summary’, ‘title’, ‘unique_error_message’, ‘validate_unique’]

>>> obj.title

‘abc’

>>> obj.price

Decimal(‘2.12’)

>>> obj.description

‘dfjiewjfow’

>>>

ADD FOLDER product UNDER template AND CREATE detail.html AND REFLECT IT IN views.py (under product not pages anymore)

from django.shortcuts import render
# Create your views here.
def product_detail_view(request):
obj = Product.objects.get(id=1)
context = {
‘title’: obj.title,
‘description’: obj.description

}
#return render(request, “product/detail.html”, {})
return render(request, “product/detail.html”, context)

IN detail.html (with some CONDITIONS) – render out an object

{% extends ‘base.html’ %}

{% block content %}
<h1> {{ title }} </h1>
<p>{% if description != “” and description != None %}{{ description }}{% else %}Contact for more Details{% endif %}</p>

{% endblock %}

OR ADDING object IN context, so step 1 IN views.py:

from django.shortcuts import render

from .models import Product
# Create your views here.
def product_detail_view(request):
obj = Product.objects.get(id=1)
# context = {
# ‘title’: obj.title,
# ‘description’: obj.description
#
# }
context = {
‘object’: obj
}
return render(request, “product/detail.html”, context)

STEP 2 IN detail.html

{% extends ‘base.html’ %}

{% block content %}
<h1> {{ object.title }} </h1>
<p>{% if object.description != “” and object.description != None %}
{{ object.description }}{% else %}Contact for more Details{% endif %}</p>

{{ object.price }}
{% endblock %}

 

STEP 3? urls.py ADD PATH FOR product:

from django.contrib import admin
from django.urls import path

#from pages import views
from pages.views import home_view
from pages.views import contact_view
from pages.views import about_view
from pages.views import social_view
from products.views import product_detail_view

urlpatterns = [
#path(”, views.home_view, name=’home’),
path(”, home_view, name=’home’),
path(‘contact/’, contact_view),
path(‘about/’, about_view),
path(‘social/’, social_view),
path(‘product/’, product_detail_view),
path(‘admin/’, admin.site.urls),
]

HOW DJANGO TEMPLATES LOAD WITH APPS (2:00:00 – 2sec)

ADD FOLDER templates UNDER THE APP products AND COPY AND PASTE THE detail.html in to product_detail.html WITH SMALL CHANGES SO THAT WE CAN TEST IT ON THE PAGE:

{% extends ‘base.html’ %}

{% block content %}
<h1>In App template: {{ object.title }} </h1>
<p>{% if object.description != “” and object.description != None %}
{{ object.description }}{% else %}Contact for more Details{% endif %}</p>

{{ object.price }}
{% endblock %}

BEFORE MAKING A CHANGE IN views.py IN FOLDER products WE SEE THE PAGE:

Template-loader postmortem

Django tried loading these templates, in this order:

Using engine django:

  • django.template.loaders.filesystem.Loader: /Users/liveuk/Env1/project1_env/src/templates/products/produc_detail.html (Source does not exist)
  • django.template.loaders.app_directories.Loader: /Users/liveuk/Env1/project1_env/lib/python3.6/site-packages/django/contrib/admin/templates/products/produc_detail.html (Source does not exist)
  • django.template.loaders.app_directories.Loader: /Users/liveuk/Env1/project1_env/lib/python3.6/site-packages/django/contrib/auth/templates/products/produc_detail.html (Source does not exist)
  • django.template.loaders.app_directories.Loader: /Users/liveuk/Env1/project1_env/src/products/templates/products/produc_detail.html (Source does not exist)

SO THAT WE HAVE TO CHANGE FROM products/detail to products/product_detail.html BUT WE DON’T NEED TO SPECIFY THE NEW (TEMPLATES) PATH AS DJANGO WILL GO THROUGH ALL POSSIBLE FOLDERS WHEN LOADING:

from django.shortcuts import render

from .models import Product
# Create your views here.
def product_detail_view(request):
obj = Product.objects.get(id=1)
# context = {
# ‘title’: obj.title,
# ‘description’: obj.description
#
# }
context = {
‘object’: obj
}
#return render(request, “product/detail.html”, {})
return render(request, “products/product_detail.html“, context)

KEEP THE templates/products FOLDER WITHIN THE APP FOLDER (THAT WE JUST SET UP) AND DELETE THE templates/product THAT COULD OVERWRITE THE product_detail.html IF WE CHANGE THE FOLDER NAME TO MATCH THE WHAT IS IN views.py (SEE ABOVE) I.E. CHANGING FROM templates/product/details.html TO templates/products/product_details.html

Django Model Forms

SETP 1 UNDER products APP (FOLDER) CREATE form.py

from django import forms

from .models import Product

class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = [
‘title’,
‘description’,
‘price’,
‘summary’
]

STEP 2 GO TO views.py TO DEFINE product_create_view

from django.shortcuts import render

from .forms import ProductForm

from .models import Product
# Create your views here.
def product_create_view(request):
form = ProductForm(request.POST or None)
if form.is_valid():
form.save()
context = {
‘form’: form
}
return render(request, “products/product_create.html”, context)

def product_detail_view(request):
obj = Product.objects.get(id=1)
# context = {
# ‘title’: obj.title,
# ‘description’: obj.description
#
# }
context = {
‘object’: obj
}
#return render(request, “product/detail.html”, {})
return render(request, “products/product_detail.html”, context)

STEP 3 CREATE product_create.html IN THE NEW templates FOLDER

{% extends ‘base.html’ %}

{% block content %}
<form>
{{ form.as_p}}
<input type=’submit’ value=’Save’ />
</form>
{% endblock %}

STEP 4 IMPORT THE NEW VIEW AND CREATE A NEW PATH IN urls.py

from products.views import product_detail_view, product_create_view

path(‘product/’, product_detail_view),
path(‘create/’, product_create_view),

THEN GO TO http://127.0.0.1:8000/create/ THE FORM IS THERE!

TO GET A NEW EMPTY FORM AFTER SUBMIT ONE ENTRY: ADD form = ProductForm() TO RENDER A NEW FORM IN views.py

from django.shortcuts import render

from .forms import ProductForm

from .models import Product
# Create your views here.
def product_create_view(request):
form = ProductForm(request.POST or None)
if form.is_valid():
form.save()
form = ProductForm()
context = {
‘form’: form
}
return render(request, “products/product_create.html”, context)

def product_detail_view(request):
obj = Product.objects.get(id=1)
# context = {
# ‘title’: obj.title,
# ‘description’: obj.description
#
# }
context = {
‘object’: obj
}
#return render(request, “product/detail.html”, {})
return render(request, “products/product_detail.html”, context)

Raw HTML Form

RAW EXAMPLE 2:14:20 – 2:26:00 (2:18:00 SEARCH IN GOOGLE DOESNT WORK FOR ME IE. NOT SHOWING http://127.0.0.1:8000/create/?title=abc OR A GOOGLE SEARCH RESULT)

STEP 1 product_create.html

{% extends ‘base.html’ %}

{% block content %}
<!– <form method=’POST’> {% csrf_token %}
{{ form.as_p}}
<input type=’submit’ value=’Save’ />
</form> –>

<form method=’POST’> {% csrf_token %}
<input type=’text’ mame=’my_title’ placeholder=’Your Title’
<input type=’submit’ value=’Save’ />
{% endblock %}

OR method=’GET’

OR <form action=’http://www.google.com/search/’ method=’GET’>
<input type=’text’ mame=’q’ placeholder=’产品名’/>

<QueryDict: {‘title’: [‘fewofjojwef’]}>

<QueryDict: {}>

[19/Nov/2019 16:09:03] “GET /create/?title=fewofjojwef HTTP/1.1” 200 574


CHANGE IN view.py

def product_create_view(request):
print(request.GET[‘title’])
print(request.POST)
context = {}
return render(request, “products/product_create.html”, context)

12193913831

<QueryDict: {}>

[19/Nov/2019 16:10:05] “GET /create/?title=12193913831 HTTP/1.1” 200 574

GET RID OF []

def product_create_view(request):
print(request.GET)
print(request.POST)
context = {}
return render(request, “products/product_create.html”, context)

AND IN product_create.html

<form method=’POST’> {% csrf_token %}

<QueryDict: {}>

<QueryDict: {‘csrfmiddlewaretoken’: [‘CltrdkeB761BVtdG9CMBlcUJxbCwpgUbooGQI5U2s5QQvvHvABpFGX6rjFZFJGBG’]}>

[19/Nov/2019 16:15:27] “POST /create/ HTTP/1.1” 200 699

SOMEHOW

Pure Django Form

EXAMPLES IN views.py AND product_create.html UNTIL 2:35:40

IN forms.py ADD (PLAYED WITH FORM WIDGETS)

class RawProductForm(forms.Form):
title = forms.CharField(label=’产品’,
widget=forms.TextInput(
attrs={
“placeholder”: “您的产品名”
}
)
)
description = forms.CharField(required=False,
label=’产品描述’,
widget=forms.Textarea(
attrs={
“placeholder”: “您的描述”,
“class”: “new-class-name two”,
“id”: “my-id-for-textarea”,
“rows”: 20,
“cols”: 120
}
)
)
price = forms.DecimalField(label=’价格’,
initial=199.99)

IN views.py ADD RawProductForm TO RENDER IT OUT

from django.shortcuts import render

from .forms import ProductForm, RawProductForm

from .models import Product

def product_create_view(request):
my_form = RawProductForm(request.POST)
context = {
“form”: my_form
}
return render(request, “products/product_create.html”, context)

AND YOU SEE REQUIRED – BUILT IN DJANGO

Screenshot 2019-11-19 at 17.16.29

IN views.py

def product_create_view(request):
my_form = RawProductForm()
if request.method == “POST”:
my_form = RawProductForm(request.POST)
if my_form.is_valid():
#now the data is good
print(my_form.cleaned_data)
Product.objects.create(**my_form.cleaned_data)
else:
print(my_form.errors)
context = {
‘form’: my_form
}
return render(request, “products/product_create.html”, context)

DJANGO VALIDATION AND SECURITY WILL VALIDATE THE DATA ENTERED AND EVEN IF YOU CHANGE THE HTML ON THE WEBSITE IT WILL NOT ALLOW A TEXT TO BE ENTERED FOR price:

[19/Nov/2019 17:26:55] “GET /admin/jsi18n/ HTTP/1.1” 200 3185

{‘title’: ‘dw’, ‘description’: ”, ‘price’: Decimal(‘1’)}

[19/Nov/2019 17:27:15] “POST /create/ HTTP/1.1” 200 1854

<ul class=”errorlist”><li>price<ul class=”errorlist”><li>Enter a number.</li></ul></li></ul>

[19/Nov/2019 17:30:01] “POST /create/ HTTP/1.1” 200 1966

FORM WIDGETS (SEE PREV)

Form Validation Methods

(OVERWRITE CHARFIELD AND VALIDATIONS) COPY AND PASTE WHAT SET UP IN DJANGO FORM TO MODEL FORM IN forms.py :

class ProductForm(forms.ModelForm):
title = forms.CharField(label=’产品’,
widget=forms.TextInput(
attrs={
“placeholder”: “您的产品名”
}
)
)
email = forms.EmailField()
description = forms.CharField(required=False,
label=”,
widget=forms.Textarea(
attrs={
“placeholder”: “您的描述”,
“class”: “new-class-name two”,
“id”: “my-id-for-textarea”,
“rows”: 20,
“cols”: 60
}
)
)
price = forms.DecimalField(label=’价格’,
initial=199.99)

class Meta:
model = Product
fields = [
‘title’,
‘description’,
‘price’,
‘summary’,
‘featured’
]
def clean_title(self, *args, **kwargs):
title = self.cleaned_data.get(“title”)
# if not “CFA” in title:
# raise forms.ValidationError(“产品名不符合格式”)
# if not “AAA” in title:
# raise forms.ValidationError(“产品名不符合格式”)
return title

def clean_email(self, *args, **kwargs):
email = self.cleaned_data.get(“email”)
if not email.endswith(“edu”):
raise forms.ValidationError(“邮箱地址不符合格式”)
return email

Initial Value for Form (2:49:00) IN view.py

##Initial Value for Form (2:49:00)-NEED TO CHANGE urls.py
def render_initial_data(request):
initial_data = {
‘title’: “My awsome title”
}
obj = Product.objects.get(id=1)
form = ProductForm(request.POST or None, instance=obj)
if form.is_valid():
form.save()
context = {
‘form’: form
}
return render(request, “products/product_create.html”,context)

IN urls.py ADD:

from products.views import product_detail_view, product_create_view, render_initial_data

path(‘initial/’, render_initial_data),

 

nordvpn