Python Django Part 2 - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Python Django Part 2 - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript


Post Top Ad

Post Top Ad

Saturday, December 22, 2018

Python Django Part 2

Python Django Part 2

Building a simple home page(cont.)

Writing a simple template A template sets up the structure for a page. It's a mix of html and template code, which is like Python but not as powerful. Make a folder called templates inside the project folder. Inside the template folder make another folder with the same name as the app. This is where the template files should be saved.
<p>Learning Log</p>
<p>Learning Log helps you keep track of your learning, for any topic you're learning about.</p>
Template inheritance

Many elements of a web page are repeated on every page in this site, or every page in a section of the site. By writing one parent template for the site, and one for each section, you can easily modify the look and feel of your entire site.

The parent template
The parent template defines the elemnets common to a set of pages, and defines blocks that will be filled by individual pages.
<a href="{% url 'index'  %}">
Learning Log
{% block content %}{% endblock content %}

python  base.html

The child template
The child template uses the {% extends %} template tag to pull in the structure of the parent template. It then defines the content for any blocks defined in the parent template.
{% extends 'learning_logs/base.html' %}

{% block content %}
Learning Log helps you keep track of your learning, for any topic you're learning about.
{% endblock content %}

python child.html

Template indentation

Python code is usually indented by four spaces. In templates you'll often see two spaces used for indentation , because elements tend to be nested more deeply in templates. Another model

A new model can use an existing model. The ForeignKey attribute establishes a connection between instances of the two related models. Make sure to migrate the database after adding a new model to
your app
from django.db import models

# Create your models here.
class Topic(models.Model):
 """A topic the user is learning about."""
 text = models.CharField(max_length=200)
 date_added = models.DateTimeField(auto_now_add=True)

 def __str__(self):
  return self.text

#Defining a model with a foreign key
class Entry(models.Model):
 """Learning logentries for a topic."""
 topic = models.ForeignKey(Topic,on_delete=models.CASCADE)
 text = models.TextField()
 date_added = models.DateTimeField(auto_now_add=True)
 def __str__(self):
  return self.text[:50] + "..."

python django model

Building a page with data

Most pages in a project need to present data that's specific to the current user
#URL parameters
#A URL often needs to accept a parameter telling it which data to access from the database. The second URL pattern shown here looks for the Id of a specific topic and stores it in the parameter topic_id.
urlpatterns =[
url('r^$', views.index, name='index'),
views.topic, name='topic'),

python url
#Using data in a view
#The view uses a parameter from the URL to pull the correct data from the database. In this example the views is sending a context dictionary to the template, containing data that should be displayed on this page.

from django.shortcuts import render

def index(request):
 """The home page for Learning Log."""
 return render(request, 'learning_logs/index.html') 

def topic(request, topic_id):
 """Show a topic and all its entries."""
 topic = Topic.object.get(id=topic_id)
 entries = topic.entry_set.order_by('-date_added')
 context = {
   'topic': topic,
   'entries': entries,
 return render(request, 'learning_logs/topic.html', context)

python view

Restarting the development server

If you make a change to your project and the change doesn't seem to have any effect, try restarting the server: $ python runserver

Building a page with data (cont.)(topic.html)
#Using data in a template

#The data in the view function's context dictionary is available within the template. This data is accessed using template variables, which are indicated by doubled curly braces.
#The vertical line after a template variable indicates a filter. In this case a filter called date formats date objects, and the filter linebreaks renders paragraphs properly on a web page.

{% extends 'learning_logs/base.html' %}

{% block content %}

<p>Topic: {{ topic}}</p>

{% for entry in entries %}
{{ entry.date_added|date:'M d, Y H:i' }}
{{ entry.text|linebreaks }}
{% empty %}
<li>There are no entries yet.</li>
{% endfor %}

{% endblock content %}

python topic.html

The Django shell

You can explore the data in your project from the command line. This is helpful for developing queries and testing code snippets.
#Start a shell session
$python shell
#Access data from the project
>>> from learning_logs.models import Topic
>>> Topic.objects.all()
[<topic: chess>,<Topic: Rock Climbing>]
>>> topic = Topic.objects.get(id=1)
>>> topic.text


Insert Data in table

python insert data

Python run migration again to create entry table
python migration

Python Run Django Server

python django server

No comments:

Post a Comment

Post Top Ad