This is a text field

Creating Homepage

Goal to all this ⬇️

In this chapter we will do following sections:-

  ● Adding Topics 
● Defining the entry
Model.
● Registering Entry
with the Admin Site
● The Django Shell
● Adding Topics 

In this section we will workout the page which we have created previously.

Click on Topics, you will see empty box , because you have not included any topic. We will click Add you will see the new topic page. Write which topic name you want, we will write Chess on first box ,then click on Save. You’ll be sent back to the Topics admin page, and you’ll see the topic you just created.

Let’s create a second topic so we’ll have more data to work with. Click Add again, and create a second topic, Rock Climbing. When you click Save, you’ll be sent back to the main Topics page again, and you’ll see both Chess and Rock Climbing listed.

● Defining the Entry      
Model

Here we create a class Entry and feed it with variables.

models.py
    from django.db import models

    class Topic(models.Model):
        –snip–

➊ class Entry(models.Model):
       “””Something specific learned about a topic”””
➋     topic = models.ForeignKey(Topic)
➌     text = models.TextField()
       date_added = models.DateTimeField(auto_now_add=True)

➍   class Meta:
           verbose_name_plural = ‘entries’

def str(self):
           “””Return a string representation of the model.”””
➎        return self.text[:50] + “…”

● Migrating the Entry    
Model

We need to make database for the model which we have registered to Entry.

>>>python manage.py makemigrations learning_logs

The output will show like this :

Migrations for ‘learning_logs’:
➊   0002_entry.py:
       – Create model Entry

>>>python manage.py migrate

Operations to perform:
     –snip–
➋   Applying learning_logs.0002_entry… OK

At ➊  0002_entry.py tells django to how to create database for model Entry.

When we issue the migrate command, we see that Django applied this migration, and everything was okay ➋.

● Registering Entry  with the Admin Site

We also need to register the Entry model.

admin.py
from django.contrib import admin

from learning_logs.models import Topic, Entry

admin.site.register(Topic)
admin.site.register(Entry)

➡️ Go back to http://localhost/admin/, and you should see Entries listed under learning_logs.

🔘 Click the Add link for Entries, or click Entries, and then choose Add entry. You should see a drop-down list to select the topic you’re creating an entry for and a text box for adding an entry. Select Chess from the drop-down list, and add an entry. Here’s the first entry I made:

The opening is the first part of the game, roughly the first ten moves or so.

When you click Save, you’ll be brought back to the main admin page for entries. Here you’ll see the benefit of using text[:50] as the string representation for each entry; it’s much easier to work with multiple entries in the admin interface if you see only the first part of an entry rather than the entire text of each entry.

Make a second entry for Chess and one entry for Rock Climbing so we have some initial data.

● The Django Shell

In shell we have to check the data is correctly arranged or not. So we will use Django Shell to check . Open Shell using command:

>>>python manage.py shell

➊>>> from learning_logs.models import Topic
   >>> Topic.objects.all()
   

[<Topic:Chess>,<Topic:Rock Climbing>]

Here we import the model Topic from the learning_logs.models module ➊

We can loop over a queryset just as we’d loop over a list. Here’s how you can see the ID that’s been assigned to each topic object:

topics = Topic.objects.all()
for topic in topics:

…    print(topic.id, topic)


1 Chess
2 Rock Climbing

Chess has an ID of 1, and Rock Climbing has an ID of 2.

If you know the ID of a particular object, you can get that object and examine any attribute the object has. Let’s look at the text and date_added values for Chess:

>>>t = Topic.objects.get(id=1)
t.text
‘Chess’
>>>t.date_added
datetime.datetime(2015, 5, 28, 4, 39, 11, 989446, tzinfo=)

Django can use this connection to get every entry related to a certain topic, like this:
>>> t.entry_set.all()
   [, <Entry: In
   the opening phase of the game, it’s important t…>]

To get data through a foreign key relationship, you use the lowercase name of the related model followed by an underscore and the word set ➊.

___________________________________

NOTE:
Each time you modify your models, you’ll need to restart the shell to see the effects of those changes. To exit a shell session, enter CTRL-D; on Windows enter CTRL-Z and then press ENTER.

___________________________________

● Making Pages: The Learning Log Home Page

Usually, making web pages with Django consists of three stages: defining URLs, writing views, and writing templates.

url matches pattern with requested url.

view process the data and send this to template page.

template create a page that browser can read .

——-———————————————

■Mapping a URL

Users request pages by entering URLs into a browser and clicking links, so we’ll need to decide what URLs are needed in our project.

At the moment, the base URL, http://localhost:8000/, returns the default Django site that lets us know the project was set up correctly. We’ll change this by mapping the base URL to Learning Log’s home page.

In learning_log ➡️ urls.py

➊ from django.urls import include, url
from django.contrib import admin

➋ urlpatterns = [
➌     path(‘admin/’, include(admin.site.urls)),
   ]

The first two lines import the functions and modules that manage URLs for the project and admin site ➊.

The body of the file defines the urlpatterns variable ➋

The code at ➌ includes the module admin.site.urls, which defines all the URLs that can be requested from the admin site.

We need to include the URLs for learning_logs:

from django.urls import include, url
from django.contrib import admin

urlpatterns = [
     path(‘admin/’, include(admin.site.urls)),
➊  path(”, include(‘learning_logs.urls’, namespace=’learning_logs’)),
    ]

The code at ➊ include the learning_logs url to admin site.

This line includes a namespace argument, which allows us to distinguish learning_logs’s URLs from other URLs that might appear in the project, which can be very helpful as your project starts to grow.

The default urls.py is in the learning_log folder; now we need to make a second urls.py file in the learning_logs folder:

urls.py
➊ “””Defines URL patterns for learning_logs.”””

➋ from django.urls import path

➌ from . import views

➍ urlpatterns = [
       # Home page
➎     path(‘ ‘, views.index, name=’index’),

]

To make it clear which urls.py we’re working in, we add a docstring at the beginning of the file at ➊.

We then import the url function, which is needed when mapping URLs to views ➋.

We also import the views module ➌; the dot tells Python to import views from the same directory as the current urls.py module.

The variable urlpatterns in this module is a list of individual pages that can be requested from the learning_logs app ➍.

The actual URL pattern is a call to the url() function, which takes three arguments ➎. The first is a regular expression.

➡️ The second argument in url() at ➎ specifies which view function to call. When a requested URL matches the regular expression, Django will call views.index (we’ll write this view function in the next section).

➡️ The third argument provides the name index for this URL pattern so we can refer to it in other sections of the code. Whenever we want to provide a link to the home page, we’ll use this name instead of writing out a URL.

—————————————————-

■ Writing a View

A view function takes in information from a request, prepares the data needed to generate a page, and then sends the data back to the browser, often by using a template that defines what the page will look like.

from django.shortcuts import render

def index(request):
    “””The home page for Learning Log”””
    return render(request, ‘learning_logs/index.html’)

When a URL request matches the pattern we just defined, Django will look for a function called index() in the views.py file. Django then passes the request object to this view function. In this case, we don’t need to process any data for the page, so the only code in the function is a call to render(). The render() function here uses two arguments—the original request object and a template it can use to build the page. Let’s write this template.

‐‐‐————————————–

Writing a Template

A template sets up the structure for a web page. The template defines what the page should look like, and Django fills in the relevant data each time the page is requested.

Inside the learning_logs folder, make a new folder called templates. Inside the templates folder, make another folder called learning_logs.

learning_logs ⬇️ templates ⬇️ learning_logs.

Inside the inner learning_logs folder, make a new file called index.html .

index.html

<p>Learning Log</p>

<p>Learning Log helps you keep track of your learning, for any topic you’re learning about.</p>

➡️ <p> tags signify paragraphs. The <p> tag opens a paragraph, and the </p> tag closes a paragraph.

We have two paragraphs: the first acts as a title, and the second describes what users can do with Learning Log.

Now when we request the project’s base URL, http://localhost:8000/, we’ll see the page we just built instead of the default Django page.

It allows you to think about each aspect of a project separately, and in larger projects it allows individuals to focus on the areas in which they’re strongest. For example, a database specialist can focus on the models, a programmer can focus on the view code, and a web designer can focus on the templates.

We’ll we see some amazing things. Please,Check out https://vipulkunwar503.code.blog.

Avatar for Vipul kunwar
Follow me

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Back to top