Building Registration Page in Django using MySQL

First : I will extend my registration form fields other than what is ready made available in Django in-built forms.

So if you were looking for such forms you are at right place.

Here is the coding –

This is my directory structure at the end.

First uploading code of these files –

settings.py file

Not many things to change – Insert these lines at the end…

in Databases variable delete all the content and insert this –

dj3

In Templates variable look for ‘DIRS’ key and write this –

dj4

Inside ‘INSTALLED APPS ‘ variable add your app. In my case its ‘homepage’. Like this –

dj5

URLS.PY





Now coming inside main mysite folder

admin.py

FORMS.PY


# dappx/forms.py
from django import forms
from django.contrib.auth.models import User
# from django.contrib.auth import get_user_model
from homepage.models import UserProfileInfo

class UserProfileInfoForm(forms.ModelForm):
    class Meta():
        model   = UserProfileInfo
        fields  = ('fullname', 'address', 'city','mobile_no','alt_mob_no','other_ref_names')

class UserForm(forms.ModelForm):
    password    = forms.CharField(widget=forms.PasswordInput())
    class Meta():
        model   = User
        fields  = ('username','password','email')

MODELS.PY

# from django.db import models

# Create your models here.

# dappx/models.py
from django.db import models
from django.contrib.auth.models import User
# from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
# from django.contrib.auth import get_user_model

class UserProfileInfo(models.Model):
   fullname             = models.CharField(max_length=30)
  #  password             = models.CharField(blank=False, max_length=25)
   address              = models.TextField(blank=False, max_length=50)
   city                 = models.TextField(blank=False, max_length=20)
  #  email                = models.EmailField(max_length=60, verbose_name='email', unique=True)
   state                = models.TextField(default="Uttar Pradesh")
   mobile_no            = models.IntegerField()
   alt_mob_no           = models.IntegerField()
   profile_pic          = models.ImageField(upload_to='profile_pics',blank=True)
   user                 = models.OneToOneField(User,on_delete=models.CASCADE)
   date_joined          = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
   other_ref_names      = models.TextField(max_length=100)

   

   def __str__(self):
     return self.user.username
  
 

urls.py

dj9

VIEWS.PY



from django.shortcuts import render
from homepage.forms import UserProfileInfoForm, UserForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required

def index(request):
    return render(request,'indexn.html')

@login_required
def special(request):
    return HttpResponse("You are logged in !")

@login_required
def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('index'))

def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            if 'profile_pic' in request.FILES:
                print('found it')
                profile.profile_pic = request.FILES['profile_pic']
            profile.save()
            registered = True
        else:
            print(user_form.errors,profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()
    return render(request,'registeration.html',
                          {'user_form':user_form,
                           'profile_form':profile_form,
                           'registered':registered})

def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('index'))
            else:
                return HttpResponse("Your account was inactive.")
        else:
            print("Someone tried to login and failed.")
            print("They used username: {} and password: {}".format(username,password))
            return HttpResponse("Invalid login details given")
    else:
        return render(request, 'login.html', {})

Inside templates folder

basen.html

Well, in below code I have used CSS along with HTML. This is not the developer’s way to do. They actually do so in separate folder named ‘static’ but due to my interest and convenience I have used the same HTML page. But its not an issue. All is good. Do as you are convenient.


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Base</title>
    <style>
      body{
        margin: 0px;
      }
      .emptyhead{
        height: 30px;
        background-color: #ff6f61;
      }
      .navbar{
        
        overflow: hidden;
        overflow: hidden;
        background-color:  black;
        position: fixed; /* Set the navbar to fixed position */
         /* Position the navbar at the top of the page */
        width: 100%; /* Full width */
      }
      
      /* Links inside the navbar */
      .navbar a {
        float: left;
        display: block;
        color: #f2f2f2;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
        margin-left: 6px;
        font-size: 22px;
      }
      
      /* Change background on mouse-over */
      .navbar a:hover {
        background: #ddd;
        color: red;
      }
      
      /* Main content */
      .main {
        margin-top: 80px; /* Add a top margin to avoid content overlay */;
      }
      .head{
        margin-top: 50px;
        background-color:  #ff6f61;
        color: white;
        height: 100px;
        font-size: 50px;
        font-family: monospace;
        font-weight: bold;
        text-align: center;
        padding: 35px;
      }
    </style>
</head>
  <body >
{# Django Home Link / Admin Link / Register Link#}
    <div class="emptyhead">

    </div>
    <div class="navbar">
          <a href="{% url 'index' %}">About Us</a>
          <a href="{% url 'admin:index' %}">Admin</a>
          <a href="{% url 'homepage:register' %}">Register</a>     
          {# Some logic on what to display for last item#}
          {% if user.is_authenticated %}
            <li><a href="{% url 'logout' %}">Logout</a></li>
          {% else %}
            <li><a href="{% url 'homepage:user_login' %}">Login</a></li>
          {% endif %}
    </div>
    <div class="head">
      PROVISION STORE MANAGEMENT SYSTEM
    </div>
    <div class="main">
    {% block body_block %}
    {% endblock %}
    </div>
  </body>
</html>

INDEXN.HTML

dj11

login.html

dj12

REGISTERATION.HTML

OVER!

Yes, over only thing you have to do is to download WAMP and through phpmyadmin create a database ‘provisionstore’. If you want to name something different then change the name in dj3 pic posted above too.

Happy Coding !

Please, Please, do ask your confusion. If any. Thanks 🙂

Event Handling 2

Previously, we coded in PHP to check if the user is verified or not and we did this by matching his user name and password with our pre-declared user name and password.

Now we will expand this verification to three users. Yes, if any of those three users logins with their respective name and password, they will be successfully logged in. So, our HTML login page will be same that we created earlier –


<html>

<head>
	<title>Untitled 1</title>
</head>
<body text="maroon">
  <form action="firstand lastname.php" method="post" name="myform">

    <table border="5" bordercolor="darkslategray" align="center" width="400px" >
      <tr><td>UserID</td><td><input type="text" name="uid"></td>
      <tr><td>PASSWORD</td><td><input type="password" name="pwd"></td>
      <tr><td align="center" colspan="2"><input type="submit"
       value="LOGIN" name="submit"></td></tr>
   </table>
 </form>

</body>
</html>

Now we have to think a logic to display the message. I have derived the following logic yours might be different.

<?php
 $user = array("Randy Orton", "Lesnar", "Roman Reigns");
 $passwd = array("randy", "lesnar", "reigns");

 $count= 0 ;
 $nm = " ";
 extract($_POST);
 if (isset($submit))
 {
   for($i=0 ; $i<3 ; $i++)
   {
     if (strcmp($user[$i],$uid)==0 && strcmp($passwd[$i],$pwd)==0)
     {
       $count=1;
       $nm = $uid ;
       break;
     }
   }
  if($count==1)
    echo "Welcome $nm, You are successfully logged in.";
  else
    echo "Invalid Username or Password";
 }
?>

Remember that it is not compulsory to make two different files. We can embed both the codes in one single PHP file store it in www and run it. But it is better to keep your designing part and logic part separate in HTML and PHP files respectively.

That’s it.

Have ERROR FREE coding!

Event Handling

Let’s create a simple web page where a user will give his first and last name and we’ll display his full name (by concatenating first and last name) in some other web page.

So we’ll make two files – one HTML file and one PHP file. HTML file will be for designing the layout where user will enter his first and last name and PHP file will be for generating logic to display his full name at once.

The HTML file I have designed is something like below –

<html>
  <head>
    <title>FIRST AND LAST</title>
  </head>
  <body text="darkgreen">
    <br><br><br>

    <form name="myform" action="firstand lastname.php" method="post">
    <fieldset>
      <legend>USER INFO</legend>
      <table>
        <tr>   <td>First Name</td><td><input type="text" name="first"></td>     </tr>
        <tr>   <td>Last Name</td><td><input type="text" name="last"></td>      </tr>
        <tr>   <td><input type="submit" name="submit" value="SUBMIT"></td>    </tr>
      </table>
    </fieldset>
    </form>
  </body>
</html>

Please take note of this that whenever we place any submit button in form, it is compulsory to use <form> tag. So in above code inside <form> tag I have used action=” “ . In action I have given the name of my php file which contains logic to display full name. You may give name of your PHP file inside action. So the PHP code I wrote in my PHP file is-

In PHP code, I have first extracted the keys into variables. (Actually the keys are the name which we give inside <input> tag in HTML file. You may check this using var_dump($_POST)) .

So converting keys into variables allows us to handle them as normal variables in PHP. Using isset($submit) tells us whether SUBMIT button is pressed or not. (submit is the name of my SUBMIT button in my HTML code, if you have given some other name use that name) . If SUBMIT is pressed then the first and last name will be concatenated with a space in between. And we will simply echo this. ($first and $last are my name which I have given to first and last name respectively in my html code, yours might be different so use that)

Save both your PHP and HTML file in Documents Tool Folder (www) and run your HTML file (not PHP).

That’s it.

Have ERROR FREE coding!

How to read values from HTML file in PHP file

Remember we created a form in HTML, we entered our details and those details were clearly visible in URL. But if we use method="post"inside <form> tag in our HTML file, our details will not be visible. And recall how we used action attribute to send/post the details to some other page, and this page could be any HTML or PHP file. Also remember that whenever you want the user to submit his/her details by pressing a submit button, it is necessary to use form tag.

So here we’ll read those details in PHP file. When we coded that form in HTML file, we used <input> tag and inside it we used attributes/property like type and name. Type was used to specify the type of value the applicant should enter – text, email, password, file, image, color, date, etc. And the name given to name property is used as a key to access the details entered by the applicant in respective fields. So with the help of this KEY only we are going to read the values. This is known as EVENT HANDLING.

So first we’ll make a new PHP file. In that file we have, actually, two ways to read values.

First way

Open PHP file, and type following code and save the file-

<?php
    var_dump($_POST);
    
?>

$_POST and $_GET are known as Super Global Variables.

But, but, but…first, open your form which we designed in HTML and make some changes there in coding. Look there you must have opened <form> tag and inside that you must have written name= ” ” , method=” ” and action=” “. Right.

  • In name you can give any value that doesn’t matters, in method you should write either method=”post” or “get” .I am considering that you are aware of meaning of both of these. In action, we write the name of that file where we want to post the information submitted by applicant.
  • So, the above PHP code which I have written, you type it save it with extension .php.
  • The name which you are giving to this PHP file is important. Why important? Because we want the data to be displayed in this PHP file only, so quickly go back to your HTML code (code where we designed the complete form), inside the <form> tag, in action= ” “ , between the double quotes type the name of your PHP file, which you just saved. Done!
  • And before running your this HTML file, note that if you have written method=”post” inside <form> tag, then above PHP code which I have written is valid but if you have written method=”get”, then you need to make just a small change in above PHP code, write var_dump($_GET). That’s it !
  • You can now safely run your HTML file (not PHP file because you created PHP file just to get the information filled by user in the form and that form is designed in HTML file).
  • Fill the details and click on submit button.
  • You will get an output displaying all the information. You need to look carefully and understand the format of output, it will help in displaying individual values in PHP. Got it!

Now you must have got that the output we are getting is in the form of Associative Arrays. Why Associative Arrays? Because, look carefully, the names which we assigned in our HTML file inside the <input> tag are now acting like keys…Yes ! Now it will be quite easy to access the values associated with those keys.

So again quickly jump to your PHP code and add some lines-

<?php
    var_dump($_POST);

    echo $_POST['mob']."<br>";
    echo $_POST['fname']."<br>";
    echo $_POST['mname']."<br>";
    
?>

I have printed just three values, you may print all your values through the value of name which you gave in your HTML file. But printing individual values in this way is tiring.

So, let’s understand the second way to print values.


Second WAY

This is easy. Believe me. As we saw that the output we get after submitting our form is stored in associative array (key-value pair). We have an excellent in-built function extract(). It does all the job for us. Look at following code first –

<?php
    extract($_POST);

    echo $mob."<br>";
    echo $fname."<br>";
    echo $mname;

?>

We know, that $_POST or $_GET is an associative array name which has key-value pairs. So what extract() function does is- it converts keys into variables. And when keys are converted into variables we can simply print them through echo. This is simpler than previous method.



While displaying values you may face problem in printing the values of radio buttons and checkboxes. So let’s solve that. Open your ‘form’ code which, of course, you must have saved in some HTML file. There in gender you must have used two input tags (one for male other for female) with type=”radio”. Inside both input tags use two more properties- name property and value property. Carefully, give same name in name property in both input tags. While in value property, write value=”Male” in male input tag and value=”female” in female input tag. Now, run the output fill the form click on submit and you will surely get the right gender. And if you are not getting, then please share your problem here in comments so that I may help.

In case of checkboxes, the name which we give in the name property inside <input> tag should be an array and you should write some value in value property also. Let me explain with one example below-

<input type= "checkbox" name="chk[]" value="Reading blogs">Reading Blogs
<input type= "checkbox" name="chk[]" value="Net Surfing">Net surfing
<input type= "checkbox" name="chk[]" value="Programming">Programming
<input type= "checkbox" name="chk[]" value="Travelling">Travelling

I expect you must have got some idea how to do it. I haven’t taken any row or column, I have just given an idea of “hobbies” how you should write inside input tag. You must write this inside some row. I randomly picked some line.


I am telling to run HTML file and not PHP file and I have, above, given a valid reason also why to do so. But what if you run your PHP file without running your HTML file, of course errors will come. But if you make sure that PHP file should run only if user presses SUBMIT button in his/her form, then no error will be displayed. We’ll just do a little coding in our PHP file for this.

We have learnt that we first convert all the keys into variables through extract(). Right. To check if an applicant has pressed the SUBMIT button, we use isset($var_name).

So when an applicant presses SUBMIT in the form, the name in name property inside <input> tag is SET or ON. Coming back to our PHP code, after extracting values if the user would have pressed SUBMIT, then the name which i have taken “subBtn” would be ON or SET. Now, if I pass the name of name inside if (isset($subBtn)) then the condition will be true. Why True? Because $subBtn has now become a variable after being extracted through extract(). And when I am saying that an applicant has pressed SUBMIT button that means subBtn is ON or SET or TRUE. And so the block inside if(isset($subBtn)) will surely run. You can print all your values inside if block. And if an applicant would not have pressed SUBMIT then subBtn will be UNSET or OFF or FALSE, so the block inside if you will not run and so you will not get any error.

I have tried to explain this in most plain words, but if there is some problem please ask…That’s your HUMAN RIGHT 🙂


Doing just this much is not at all enough. We’ll do 2 more things for practice in event handling-

1- We’ll go to our calculator, and print the result there itself in result box. Click here.

2- we’ll create a login page and check if user is valid or not. Click here.

THAT’S ALL ! Please follow this blog so that you may get updates of the latest posts.

Have ERROR FREE coding.

Internal Linking in HTML file…

Getting goosebumps? or Excited ? 🙂

Have patience because today we’ll design the same page. And what is shown above is not the complete design, there is a lot to scroll down. But believe me, this is going to be really fantastic and you will enjoy designing this page. Imagine, how will you feel after you have designed your page fully.

What is needed is your complete attention and focus. I will upload whole code here (it is a little big because I have embedded whole speech so as to show internal linking). But but but… watching that code will not make you learn new things, rather you should code yourself and if you are facing any problem then you can refer to my code just for hint. So honesty need to be applied here… 🙂

Internal Linking is very much useful in web pages containing large documents where there are some links at starting of the page and on clicking those links we reach to our desired content in the same page. Usually, the links are at beginning of page but they can be anywhere. It could be on bottom of page to reach top of the page.

For internal linking <a></a> anchor tag is used. If I have designed a web page with three big stories in it. Then what I’ll do is I will add three links at the starting of my page which will straightly direct the reader to the required story. And this same thing I have implemented in my self-designed web page.

In above screenshot, I have added five links in my page if you’ll click first one you’ll reach first story in one go without scrolling and this applies to all the remaining four links.

I am now uploading my code so that you can see how anchor tags are used-

<html>
  <head>
    <title>About Us</title>
  </head>
  <body text="darkcyan" bgcolor="azure" align="center">

      <br><br>
    <hr color="darkcyan" size="15" width="600px">
    <a name="top">  <h1 size="6">Speech at Stanford</h1>  </a>
    <hr color="darkcyan" size="15" width="600px">

    <br><br>
    <img src="stevejobs.jpg" alt="Commencement Address" border="10">

    <br><br>
    <a href="#first">Click here to reach First story</a>            <br><br>
    <a href="#second">Click here to read Second story</a>           <br><br>
    <a href="#third">Click here to read Third story</a>             <br><br>
    <a href="#video">Click here to watch video</a>                    <br><br>
    <a href="#end">Click here to get to the END of the Speech</a>   <br><br>


    <pre>
    <font size="5">
    <p>I am honored to be with you today at your commencement from one of the finest
      universities in the world. I never graduated from college. Truth be told, this
      is the closest I’ve ever gotten to a college graduation. Today I want to tell
      you three stories from my life. That’s it. No big deal. Just three stories.

      <b><u><a name="first">The first story is about connecting the dots.</a></u></b>

      I dropped out of Reed College after the first 6 months, but then stayed around
      as a drop-in for another 18 months or so before I really quit. So why did I drop out?

      It started before I was born. My biological mother was a young, unwed college
      graduate student, and she decided to put me up for adoption. She felt very
      strongly that I should be adopted by college graduates, so everything was all
      set for me to be adopted at birth by a lawyer and his wife. Except that when
      I popped out they decided at the last minute that they really wanted a girl.
      So my parents, who were on a waiting list, got a call in the middle of the
      night asking: “We have an unexpected baby boy; do you want him?” They said:
      “Of course.” My biological mother later found out that my mother had never
      graduated from college and that my father had never graduated from high school.
      She refused to sign the final adoption papers. She only relented a few months
      later when my parents promised that I would someday go to college.

      And 17 years later I did go to college. But I naively chose a college that was almost
      as expensive as Stanford, and all of my working-class parents’ savings were being spent
      on my college tuition. After six months, I couldn’t see the value in it. I had no idea
      what I wanted to do with my life and no idea how college was going to help me figure
      it out. And here I was spending all of the money my parents had saved their entire life.
      So I decided to drop out and trust that it would all work out OK. It was pretty scary
      at the time, but looking back it was one of the best decisions I ever made. The minute I
      dropped out I could stop taking the required classes that didn’t interest me, and begin
      dropping in on the ones that looked interesting.

      It wasn’t all romantic. I didn’t have a dorm room, so I slept on the floor in friends’
      rooms, I returned Coke bottles for the 5¢ deposits to buy food with, and I would walk the
      7 miles across town every Sunday night to get one good meal a week at the Hare Krishna
      temple. I loved it. And much of what I stumbled into by following my curiosity and intuition
      turned out to be priceless later on. Let me give you one example:

      Reed College at that time offered perhaps the best calligraphy instruction in the country.
      Throughout the campus every poster, every label on every drawer, was beautifully hand
      calligraphed. Because I had dropped out and didn’t have to take the normal classes,
      I decided to take a calligraphy class to learn how to do this. I learned about serif
      and sans serif typefaces, about varying the amount of space between different letter
      combinations, about what makes great typography great. It was beautiful, historical,
      artistically subtle in a way that science can’t capture, and I found it fascinating.

      None of this had even a hope of any practical application in my life. But 10 years later,
      when we were designing the first Macintosh computer, it all came back to me. And we
      designed it all into the Mac. It was the first computer with beautiful typography.
      If I had never dropped in on that single course in college, the Mac would have never
      had multiple typefaces or proportionally spaced fonts. And since Windows just copied
      the Mac, it’s likely that no personal computer would have them. If I had never
      dropped out, I would have never dropped in on this calligraphy class, and personal
      computers might not have the wonderful typography that they do. Of course it was
      impossible to connect the dots looking forward when I was in college. But it was
      very, very clear looking backward 10 years later.

      Again, you can’t connect the dots looking forward; you can only connect them looking
      backward. So you have to trust that the dots will somehow connect in your future.
      You have to trust in something — your gut, destiny, life, karma, whatever. This
      approach has never let me down, and it has made all the difference in my life.

      <u><b><a name="second">My second story is about love and loss.</a></b></u>

      I was lucky — I found what I loved to do early in life. Woz and I started Apple in
      my parents’ garage when I was 20. We worked hard, and in 10 years Apple had grown
      from just the two of us in a garage into a $2 billion company with over 4,000
      employees. We had just released our finest creation — the Macintosh — a year earlier,
      and I had just turned 30. And then I got fired. How can you get fired from a company
      you started? Well, as Apple grew we hired someone who I thought was very talented
      to run the company with me, and for the first year or so things went well. But
      then our visions of the future began to diverge and eventually we had a falling out.
      When we did, our Board of Directors sided with him. So at 30 I was out.
      And very publicly out. What had been the focus of my entire adult life was gone, and
      it was devastating.

      I really didn’t know what to do for a few months. I felt that I had let the previous
      generation of entrepreneurs down — that I had dropped the baton as it was being passed
      to me. I met with David Packard and Bob Noyce and tried to apologize for screwing up
      so badly. I was a very public failure, and I even thought about running away from the
      valley. But something slowly began to dawn on me — I still loved what I did. The turn
      of events at Apple had not changed that one bit. I had been rejected, but I was still
      in love. And so I decided to start over.

      <a name="video">
         <video controls="true" autoplay poster="stevejobs.jpg">
          <source src="SPEECHjobs.webm" type="video/mp4"> 
         </video></a>

      I didn’t see it then, but it turned out that getting fired from Apple was the best thing
      that could have ever happened to me. The heaviness of being successful was replaced by
      the lightness of being a beginner again, less sure about everything. It freed me to
      enter one of the most creative periods of my life.

      During the next five years, I started a company named NeXT, another company named
      Pixar, and fell in love with an amazing woman who would become my wife. Pixar went
      on to create the world’s first computer animated feature film, Toy Story, and is
      now the most successful animation studio in the world. In a remarkable turn of events,
      Apple bought NeXT, I returned to Apple, and the technology we developed at NeXT is
      at the heart of Apple’s current renaissance. And Laurene and I have a wonderful family
      together.

      I’m pretty sure none of this would have happened if I hadn’t been fired from Apple.
      It was awful tasting medicine, but I guess the patient needed it. Sometimes life hits
      you in the head with a brick. Don’t lose faith. I’m convinced that the only thing that
      kept me going was that I loved what I did. You’ve got to find what you love. And that
      is as true for your work as it is for your lovers. Your work is going to fill a large
      part of your life, and the only way to be truly satisfied is to do what you believe is
      great work. And the only way to do great work is to love what you do. If you haven’t
      found it yet, keep looking. Don’t settle. As with all matters of the heart, you’ll know
      when you find it. And, like any great relationship, it just gets better and better as
      the years roll on. So keep looking until you find it. Don’t settle.

      <b><u><a name="third">My third story is about death.</a></u></b>

      When I was 17, I read a quote that went something like: “If you live each day as if it
      was your last, someday you’ll most certainly be right.” It made an impression on me,
      and since then, for the past 33 years, I have looked in the mirror every morning and
      asked myself: “If today were the last day of my life, would I want to do what I am
      about to do today?” And whenever the answer has been “No” for too many days in a row,
      I know I need to change something.

      Remembering that I’ll be dead soon is the most important tool I’ve ever encountered
      to help me make the big choices in life. Because almost everything — all external
      expectations, all pride, all fear of embarrassment or failure — these things just fall
      away in the face of death, leaving only what is truly important. Remembering that you
      are going to die is the best way I know to avoid the trap of thinking you have something
      to lose. You are already naked. There is no reason not to follow your heart.

      About a year ago I was diagnosed with cancer. I had a scan at 7:30 in the morning,
      and it clearly showed a tumor on my pancreas. I didn’t even know what a pancreas was.
      The doctors told me this was almost certainly a type of cancer that is incurable, and
      that I should expect to live no longer than three to six months. My doctor advised me
      to go home and get my affairs in order, which is doctor’s code for prepare to die. It
      means to try to tell your kids everything you thought you’d have the next 10 years to
      tell them in just a few months. It means to make sure everything is buttoned up so
      that it will be as easy as possible for your family. It means to say your goodbyes.

      I lived with that diagnosis all day. Later that evening I had a biopsy, where they
      stuck an endoscope down my throat, through my stomach and into my intestines, put a
      needle into my pancreas and got a few cells from the tumor. I was sedated, but my wife,
      who was there, told me that when they viewed the cells under a microscope the doctors
      started crying because it turned out to be a very rare form of pancreatic cancer that is
      curable with surgery. I had the surgery and I’m fine now.

      This was the closest I’ve been to facing death, and I hope it’s the closest I get for
      a few more decades. Having lived through it, I can now say this to you with a bit
      more certainty than when death was a useful but purely intellectual concept:

      No one wants to die. Even people who want to go to heaven don’t want to die to get
      there. And yet death is the destination we all share. No one has ever escaped it.
      And that is as it should be, because Death is very likely the single best invention
      of Life. It is Life’s change agent. It clears out the old to make way for the new.
      Right now the new is you, but someday not too long from now, you will gradually
      become the old and be cleared away. Sorry to be so dramatic, but it is quite true.

      Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped
      by dogma — which is living with the results of other people’s thinking. Don’t let the
      noise of others’ opinions drown out your own inner voice. And most important, have the
      courage to follow your heart and intuition. They somehow already know what you truly
      want to become. Everything else is secondary.

      When I was young, there was an amazing publication called The Whole Earth Catalog,
      which was one of the bibles of my generation. It was created by a fellow named
      Stewart Brand not far from here in Menlo Park, and he brought it to life with his
      poetic touch. This was in the late 1960s, before personal computers and desktop
      publishing, so it was all made with typewriters, scissors and Polaroid cameras.
      It was sort of like Google in paperback form, 35 years before Google came along:
      It was idealistic, and overflowing with neat tools and great notions.

      Stewart and his team put out several issues of The Whole Earth Catalog, and then
      when it had run its course, they put out a final issue. It was the mid-1970s,
      and I was your age. On the back cover of their final issue was a photograph of an
      early morning country road, the kind you might find yourself hitchhiking on if
      you were so adventurous. Beneath it were the words: “Stay Hungry. Stay Foolish.”
      It was their farewell message as they signed off. Stay Hungry. Stay Foolish. And I
      have always wished that for myself. And now, as you graduate to begin anew, I wish
      that for you.

      <a name="end"> Stay Hungry. Stay Foolish.</a>

      Thank you all very much.

      <a href="#top"><img src="arrow.png" width="45px" height = "45px"></a>
    </pre>

    </p>
    </font>
  </body>
</html>

This code is lengthy just because I have included his whole speech. Believe me it’s super easy.

In above code, look in lines- 16,17,18,19,20. I have used <a></a>. And inside anchor tag, I have given some name to href and that name begins with #. And between anchor opening <a> and closing </a> tags, I have placed the string which I want user to read. In line 16, I have typed – ‘Click here to reach First story’, this means i want the reader to go to the first story in case he clicks in that line. The location where I want to send the reader is line 30. So concentrate in line 30, there too I have used <a></a> but this time the the name of href is not preceded by #. So this is the basic difference between the use of anchor tags- in the link where the reader actually clicks and the location where the reader should reach upon clicking that link. Note the difference carefully.

Now let’s look at line 17. Here I have placed the string “Click here to read second story”, that means I want the reader to reach to the second story, which is at line 87, after clicking this link. So, in line 87, I have used anchor tag and href property, but note that the name of href is not starting with #, whereas the link which we want the user to press to reach second story(in line 17) contains #.

So with the help of above examples, you must be clear how to perform internal linking. And yes you can give any name to href, but the name should be same in both places (in link and at location where the reader should reach upon clicking the link). Instead of text/string which I have used in line 16, 17, 18,19, 20, we can also use any image to allow user to click on that image to reach the desired location. Nothing extra needs to be done. You just need to put your <img> tag (to insert image) between <a> and </a>. Look at line 208 for hint. I have inserted an image so as to reach to top. So, I have given #top name to href inside anchor opening tag and at top of the page look at heading line 9, there I have used the same name top. This clearly means that if reader clicks that image on the bottom of the page, he will quickly reach to the top, no matter what is the length of the page.I hope this is quite clear now. 🙂

I know, you guys must be wondering what I have done to line 19? Where it is linking? Okay so look at line 109. Don’t get confused, it is simple. I have just embedded a video there with the help of <video> tag and have smartly placed this video tag inside anchor tag so that when user clicks on line 19 at the top,(which is a string- Click here to watch video), he is likely to reach the place where I have embedded an inspirational video. Yes, it’s truly inspirational.

You may proudly watch that video after having completed your this project.

I have used one more tag <pre></pre> and I have never used this before. This actually preserves the text. If you want to copy-paste some matter from a site to your web page and you want that it should look exactly as it was looking in that site. Then you can safely use <pre> tag. Do it yourself without and with the use of <pre> tag, you will surely get it. Try it yourself, you will be better understood.

That’s all. Hope you like this. And I think solving errors and issues and doubts make the topics more clear. So please, if you have any issue, share it here in comments and you will get back the reply. Suggestions are also welcomed… 🙂

Have ERROR FREE coding !

Media files in HTML


<html>
  <head>
    <title>AUDIO and VIDEO</title>
  </head>
  <body align="center">

    <br><br>
    <embed src="alarm.png" width="600px" height="300">

    <br><br>
    <audio controls="True" >
      <source src="song.mp3" type="audio/mp3">
    </audio>

    <br><br>
    <video controls="true" autoplay poster="posterimage.jpg">
      <source src="RT.mp4" type="video/mp4">
    </video>

  </body>
</html>

To insert audio in our web page, we use <audio></audio> tag. Inside this tag, put controls=”true” (please see above code for hint) in order to play audio file. Remember that the audio file which you are going to insert should be placed inside the same folder in which your current html file is placed. Usually, audio files have ‘.mp3’ extension but it can be .wav or .ogg so you should be careful for extension. Inside the <source> tag, place name of audio file with extension and type=”audio/mp3″ will remain same for all extension.

The same rules apply for <video></video> too. Look above code for help.(Pay attention to extension of video file).

<embed> tag allows to insert either audio or video or image file. (Look above code to get a hint.)

That’s it for media files.

Have ERROR FREE coding !

Please share your doubts here, if any.

Forms in HTML continued…

In the previous post we designed a good-looking form. Yes we did that (you should proudly smile for that). And now we’ll move a step further.

But before making any changes in the coding of our previous form, let me introduce you with my next post which will be a fantastic layout of a Home Page . So don’t miss it, it will be a whole FUN, I guarantee.

We can limit the user/applicant to enter only valid details in a form. For this we need to add some attributes inside <input> just like we have learnt to add type and name attribute. In the same manner we’ll add the following attributes-

required=”true” . In whichever field (by field i mean whether name or qualification or address or any field of your form) you use this property, that field will become mandatory to be filled in order to submit the form.

<tr><th>Name</th><th><input type="text" name="name" required="true"></th></tr>

I have implemented in only one field, you may apply to all (I am making changes in same form we designed in previous post).


placeholder=”Enter your name” . You may use this as-

<tr><th>E-mail</th> <th><input type="email" name="mail" required="true" placeholder="Enter your email"></th></tr>

I have used this placeholder in my email field, you may use in any field and can give any name in placeholder.


maxlength=” “ with this you may restrict the applicant to limit the text upto a certain length. This text could be his name or introduction or anything text-based.

Just like maxlength, max and min are used to limit numbers. These are also attributes inside <input>, so you can put nthem there and run the code. You may use this max and min even in date. Remember the pattern yyyy-mm-dd

<tr><th>DOB</th> <th><input type="date" name="dob" required="true" max=2020-10-19 min="2008-04-19"></th></tr>

QUERY STRING

Query String is the means to send information from one page to other through Uniform Resource Locator. In previous post we have seen how the information given by an applicant is shown in the url. Even the password is clearly visible. It means we cannot give sensitive information through this. But there is a way out. With the use of method = “post ” attribute inside <form>, we can hide the information. Please do it yourself and check the url after submitting the form.

Till now the information was loaded in the same page in which the form was displayed but if we want to send that information to some other page( this could be a html or php or any file which could be opened on browser), we can do so. This is done using action attribute inside <form> tag. We can give some name of other html file in the action and run the code. And be sure that the file whose name you are going to put in action is in the same folder. This time as soon as you will submit the form , you will be directed to that page whose name you have given in action. Let me quickly show you that line of code-

<form method="post" action="syntax.html">

By default method is get.

That’s it for this post. I have tried to keep this short and simple. But if you have any doubt share your problems here in comments. And follow this blog so that you may know about new posts.



Have ERROR FREE coding !

Designing Forms in HTML

Forms provide a formal way to get information from client/user.

With HTML, we can create forms too. The basic idea is to create a table and add various fields using the <input/> tag. Note that input tag is a singular tag.

Let me show you a basic structure first-

Above code looks complex, but believe me its super easy. I have first done some formatting inside the <body> just to make the page look good. You can ignore doing this.

Then, I have created a table using <table> tag. I have done some formatting here also, just to make the table look good. And I believe you are aware of all the tags and their properties used till here (till table tag).

Now, inside table tag I need to create several rows with two columns each. One column for field name other for user input.

Since I need several rows, I will use <tr> for each row and in order to store some data in it we will use <th> . Remember it is a table heading tag which makes the content inside a cell as bold and aligned at center. <input> tag is used to take input from the user.

Inside <input>, we have to specify what type of input we want from user- text( used to take input in the form of text from the user so that’s why in above code I have used it while taking the name, father’s name, mother’s name from the user) or number (used to take number from user) or email (takes email from user) or password (a secret code from user as password) or date (takes date from user) or radio button (used to allow user to choose any one option among many) or checkbox (used to allow user to choose many options or even user can select all options).

Please note that, in case of radio buttons if you select all the all the radio buttons, then all will be selected. And this is something we do not want. We want only one radio button to be selected. For this, we add one property ‘name‘ in all the radio buttons and the name for the name should be same for all. You could write something like this…

<tr><th>Gender</th> <th><input type="radio" name="gen1">Male
                              <input type="radio" name="gen1">Female</th></tr>

You can give name any name of your wish. And if you want to know the use of this name, then after completing your coding part fully run your code in browser ( run your code after reading the whole post), fill all the details and then click on SUBMIT button (adding SUBMIT button and its proper working is shown at last). After you SUBMIT, look at your web page’s URL before and after filling the form. I hope you got the thing.


To give a address field, we use <textarea></textarea> tag . It has some properties like rows, columns. You can give values as per our needs. You can very easily add this field in your form using following code-

<tr><th>Address</th> <th><textarea rows="7" cols="30"></textarea></th> </tr>

To add a qualification field in our form, we can give a drop down list to user to select any one option from that list. This dropdown list is useful than giving radio buttons because it will take much lesser space than radio buttons. So, to allow user to select any one item from the list we use <select></select> tag. After <select> , we need to give options to be displayed in the drop down list. These options are placed inside <option></option> We can add this ‘qualification’ field using following code-

To give a color field in our form, we can use input type as color. To allow user to upload his/her image we will have to use input type as file. The code for both these field will be-

<tr><th>Color</th> <th><input type="color"></th> </tr>
<tr><th>Image</th> <th><input type="file"></th> </tr>

Almost everything is added in our form, feeling Happy… Wait ! Wait ! . We have forgotten to add ‘submit’ , ‘reset’ button. We can even give an image which will act like submit button. Seeeee… the code below-

After adding your submit button, if you run your code in browser, fill details and click SUBMIT, you’ll experience no changes, nothing will take place. To make the SUBMIT work add <form> just below <body> and close </form> just before </body>.

Your final code would be like this clean code (it is really a good habit to write a clean and readable code) –

<html>
  <head>
    <title>Forms in HTML</title>
  </head>
  <body text="black" bgcolor="lightblue">
    <form >

    <table bordercolor="black" bgcolor="lightgray" cellspacing="0" cellpadding= "8px"
            border="10" align="center" width="500px" >

      <tr><th>Name</th><th><input type="text" name="name"></th></tr>
      <tr><th>Father's Name</th> <th><input type="text" name="fname"></th></tr>
      <tr><th>Mother's Name</th> <th><input type="text" name="mname"></th></tr>
      <tr><th>Mobile no.</th> <th><input type="number" name="mob"></th></tr>
      <tr><th>Password</th> <th><input type="password" name="pwd"></th></tr>
      <tr><th>E-mail</th> <th><input type="email" name="mail"></th></tr>
      <tr><th>Gender</th> <th><input type="radio" name="gen1">Male
                              <input type="radio" name="gen1">Female</th></tr>
      <tr><th>DOB</th> <th><input type="date" name="dob"></th></tr>
      <tr><th>Address</th><th><textarea rows="5" cols="30" name="add"></textarea></th></tr>

      <tr><th>Qualification</th><th><select name="qul">
                                    <option>**Select</option>
                                    <option>Phd</option>
                                    <option>Mphil</option>
                                    <option>MBA</option>
                                    <option>GateRanker</option>
                                    <option>Mtech</option>
                                  </select></th></tr>

    <tr><th>Color</th><th><input type="color" name="color"> </th></tr>
    <tr><th>Image</th><th><input type="file" name="img"> </th></tr>

    <tr><th colspan="2"><input type="submit">
                        <input type="reset">
                        <input type="image" src="wallpaper.jpg" width="50px" height="40px">
        </th></tr>

    </table>
  </form>
  </body>
</html>

Now, our form is complete… You can save the code and run it… You will get a wonderful output. Look what I am getting in my browser…

We will see some more features in our next continued post



Have a ERROR FREE coding !

Table in HTML

Tables are a great way to integrate your content in lesser space. Now, the question is how to make them in HTML. Well, HTML provides a <table></table> tag to insert your table in HTML page. Suppose, I want to create a table to record a top player from each cricket team (World class) .Let me first show you a basic structure-

So, a table is created inside <table></table> tag. Then, to insert a row (remember rows are horizontal, columns are vertical), we use <tr></tr> (table row) tag . Inside <tr>, we use <td></td> (tabular data) . Within <td></td>, we write our content of table. So, where are columns?

The content which you will insert inside <td></td> will make a separate column. For eg. in above code, I have used two <td></td> tags inside each row. It means, I have designed 4X2 table (4 rows, 2 columns).

The output of above code will be something like-

This border may differ in other browsers. I am using advanced version of Opera, so its something different from other browsers. For practical, try running the code after removing border property inside <table> tag and see the effect.

Like this border property, we have many more properties which we can use inside table tag, I will share some common ones-

width – sets the width of table ; align – positions the table in the web page ; bgcolor – sets the background color of the table ; background – we can set image as the background of the table, but remember that image should be in the same folder.

cellspacing – cells are the boxes which contains our content. In above code, I have created 8 cells look carefully. So the space between these cells is cell spacing and we can use this property to increase/decrease the space between cells.

cellpadding – the space between cell and the content in that cell is cell padding.

Let’s implement the above properties in one code. You can create your own table simply by playing with the values in each property.

original table

And it will result the following output-

We can set the content of each row in center by inserting align property – <tr align="center"> or if we wish to align the content of particular cell use- <th align="center">.

We can add heading for each column using <th> tag. We need to replace <td> with <th>. That’s it ! . Content inside ‘th’ tag is always in bold, as well as, is aligned at center. . It works as follows-

We only need to look at the first line. Look, I have used <th> in first row to make ‘Country’ and ‘Player’ as heading of their columns. Now look at its output-


Now, if we want to merge two rows, we use rowspan and if we want to merge two columns, we use colspan.

Suppose, if we want to merge ‘Root and Rohit’ into one and name it as ‘Root’, then this is called rowspan. It’s code will be-

And this will output –

Similarly, if we want to merge columns then –

Run above code and analyse the result. For better understanding of rowspan and colspan, compare both the above codes with original code.


<caption></caption> tag is used to set a small 2-3 word title for the table. Remember it is a paired tag, since it has both opening and closing tags. Caption tag is used after all the rows are done, but before the end of </table> table tag.

So just before this tag </table>, we can write –

<caption align="bottom">Table 8.1</caption>

This will insert a caption at the bottom of the table. We can use align as “top” also, as per our preference. And can insert any piece of content, I have written ‘Table 8.1’, you can write anything.



If you face any issue in above post,share here in comments.

Have ERROR FREE coding.

HTML continued… (2)

We have discussed many basic tags of HTML in our previous post.

Here, we will see 2 important topics-

MARQUEE tag

Marquee is such an amazing tag, you can play with it using some of its fascinating properties. You might have seen in some sites there is some image or a text which moves either from left to right or right to left or top to bottom or bottom to top. This movement is due to the use of <marquee>. Look below-

<marquee> tag has three basic properties – scrollamount (decides the speed of movement), behavior (this includes scroll, alternate or slide) and direction (it includes the direction of motion right, left, top, bottom). Try changing the result of these properties and analyze the result by yourself.

Instead of text, we can add any image or even a link to other page and it will also move in the page as per the properties which you will set. Let me now, quickly show you a code with image, as well as a link as a moving item-

In above code I have inserted two <marquee> tags. First <marquee> tag makes a image move while second one is the movement of link. And I have given that link a name ‘Be better at coding’. So you will see this line- ‘Be better at coding’ move and if you click on this line you will jump to some other web page. Remember that to insert any link in a web page, we use <a></a> anchor tag. And inside anchor tag we give the address of page, in which we want to jump, to href. And so, I have done the same thing.

If you run the code as it is, you will see some wonderful result. But again remember that the image should be in the same folder in which your HTML file is located. I have saved my image with “images” and so I have used that name in my HTML file. You should write your image’s name.



Now, while the link or image or text moves in the page, we have no control to stop that. But HTML provides some events using which, if you bring/hover your mouse pointer over that moving image/ text it will stop. And as soon as you remove your mouse pointer, the image/text will resume its movement. So, the two events are- onmouseover and onmouseout. We want that if we bring the mouse pointer over the image or even in its path of movement, it should stop moving and if we remove the mouse pointer over that image, it should start moving. These two actions – stop and start are performed using stop() and start() function. These will be implemented as follows-

I have tried to make this post simple. So, iof you have any confusion or doubt, share it in comments below so that it can be resolved.

Have ERROR-FREE coding…