Creating Items in the Database

As we saw earlier, our database models are simply classes with attributes. Thus, it makes sense that to add something to our database, all that we have to do is instantiate an instance of the table's class and pass in our data. Our POST view for creating a post currently looks like:

class CreatePost(View):
    def post(self, request):
        name = request.POST.get("name")
        url = request.POST.get("imgURL")
        caption = request.POST.get("caption")

We now have to use the name, url, and caption to make a new Post instance. We can do that as follows:

post = Post(imgURL=url, caption=caption, postedBy=name)

We finally have to save it and so our method looks like:

class CreatePost(View):
    def post(self, request):
        name = request.POST.get("name")
        url = request.POST.get("imgURL")
        caption = request.POST.get("caption")
        post = Post(imgURL=url, caption=caption, postedBy=name)
        post.save()

The last step is that the post request has to return a link telling the client what page to go to. We can do that with a Django HTTPResponseredirect:

from django.http import HttpResponseRedirect

...

class CreatePost(View):
    def post(self, request):
        name = request.POST.get("name")
        url = request.POST.get("imgURL")
        caption = request.POST.get("caption")
        post = Post(imgURL=url, caption=caption, postedBy=name)
        post.save()
        return HttpResponseRedirect("/")

Now, if we submit the form with a new post, watch as it appears on the screen!


Woot woot! One thing you might notice is that when we do this, the posts make up more than 12 columns and so the 4th post is overflowed to the next row:

The issue is that there is no space between the top posts and the bottom post. We can easily add this in by pushing away things below a post with a margin in the index.css styles:

.image-post {
    background-color: #d3d3d3;
    margin-bottom: 30px;
}

results matching ""

    No results matching ""