Using URL Parameters in Views

A base view normally looks like:

class PostPage(View):
    def get(self, request):
        return render(request, 'post.html')

And so we'd update the urls.py to have:

from instaclone.views import HomePage, PostPage

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', HomePage.as_view()),
    url(r'^post/(?P<postID>[a-zA-Z0-9_.-]+)', PostPage.as_view())
]

But we need to get postID somehow. We get it as an argument into the get method, has to have the same variable name:

class PostPage(View):
    def get(self, request, postID):
        print(postID)
        return render(request, 'post.html')

Let's see if this works by going to the URL and seeing what gets printed out. Go to:

http://127.0.0.1:8000/post/thisworkedwoohooo

We expect postID = "thisworkedwoohooo"

You may have noticed that it crashed after because template not found. This makes sense because we havent made a post.html yet. Let's do that now. Make post.html in your templates folder. I have initialized it with the following repeat code from the index.html:

{% load staticfiles %}
<html>
    <head>
        <title>instaclone</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    </head>

    <body>

    <nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Brand</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>
      </ul>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

This is a post page!


    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


    </body>
</html>

All that is here is the Bootstrap + jQuery imports and our navbar. You might be wondering if there is a way to not have to copy the repeat html each time. The answer is yet and we will cover that later in the book :) Let's see what the page looks like:

Now let's get the specific post by the id that is passed in (for instance 1 or 2) and load the page's context with the neccesary info. Query for the post by id:

post = Post.objects.get(id=postID)

Passed the data into the front end:

class PostPage(View):
    def get(self, request, postID):
        context = {}
        post = Post.objects.get(id=postID)
        context["post"] = post
        return render(request, 'post.html', context)

Now let's make the post page HTML item:

<div class="container">
    <div class="row post-area">
        <div class="col-md-4">
            <div class="image-area">
                <img class="image" src="{{ post.imgURL }}">
            </div>
        </div>
        <div class="col-md-8">
            <div class="image-info">
                <div class="caption-text">
                    {{ post.caption }}
                </div>
                <div class="postedby-text">
                    Posted by {{ post.postedBy }}
                </div>
            </div>
        </div>
    </div>
</div>

Let's go to the post with an ID of 1 to see what this looks like:

It looks pretty bad so let's add some style. Recall that first we have to make a new css file for this page and then we have to link it. Let's make a post.css file and link it to our post.html by putting the following in the head:

<link rel="stylesheet" type="text/css" href="{% static 'css/post.css' %}">

and add the following styles:

.post-area {
    height: 400px;
}

.image {
    width: 100%;
    height: 100%;
}

.image-info {
    background-color: #d3d3d3;
    height: 100%;
    padding: 30px;
}

.caption-text {
    font-size: 200%;
}

.postedby-text {
    font-size: 150%;
    margin-top: 30px;
    font-weight: 100;
}

I also updated the header navbar to be much simpler and just this:

<nav class="navbar navbar-default">
  <div class="container-fluid">
      <a class="navbar-brand" href="/">Instaclone</a>
    </div>
  </div><!-- /.container-fluid -->
</nav>

Note that I set the href of the Instaclone link to be "/" which is our home page. Be sure to update the navbar in the index.html as well. It Looks like:

Now that we have a specific URL page, we have to link to this page from the posts on the home page! We'll do that next :)

results matching ""

    No results matching ""