Django Quick Build Blog Section nineth (comment function Implementation)

Source: Internet
Author: User
Tags button type
The distance from the previous section has been almost a week did not write, our blog is almost finished, but more is a number of advanced learning, this section, we learn to build an article comment function

The realization of the function of article comment

1 for the article comment function, we can see that the finished product is like this

Django officially suggests a feature for an app, so we can create another app, where we call it comments.

1 we create the app at the manage.py sibling directory:

Python manage.py Startapp comments

Then open the Blogproject project under the settings, add comments, do not understand the period to see the creation of blog app Tutorial

2 Here we will create model based on the comment content

From model, we can see that we need to create

Name Email URL text Created_time Post
where Created_time for automatic creation, post for foreign keys, linked to the blog's specific article

3 Next, we do the database migration operation
We use the command:

4 Now we're done with the data model, and then we're going to submit the data to the server from the HTML tag, and of course, Django has done that for us now, and then we'll create a forms.py in the model.py sibling directory to store the form's code.
/comments/forms.py

From Django import forms from
. Models import Comment

class Commentform (forms. Modelform):
    #Meta Specify some form-related
    class Meta:
        #表明这个表单对应的数据库模型是 Comment class
        model = Comment
        fields = [' Name ', ' url ', ' email ', ' text '

5 Here the code has been explained, next we need to deal with the submitted form data processing, we write a view.py view function
/comments/views.py

From django.shortcuts import Render,get_object_or_404,redirect to blog.models import Post from. Models Import Comment F

Rom. Forms Import Commentform # Create your views here. def post_comment (REQUEST,POST_PK): # Here Gets the content of the article, no words return 404 page post = get_object_or_404 (POST,PK=POST_PK) if reques T.method = = ' POST ': # construct Commentform form = commentform (Request. POST) # Forms available If Form.is_valid (): # Check to see that the data is valid, call the form's Save method to save the data to the database, # commit=f
            The role of alse is to generate only instances of the Comment model class using the form's data, but not to save the comment data to the database.
            Comment = Form.save (commit=false) #将评论和被评论的文章关联起来 comment.post = post # finally saved to database Comment.save () # Redirects to the details page of the post, and in fact, when the redirect function receives an instance of a model, # It calls the Get_absolute_u of the model instance
            RL method, # and then redirect to the URL returned by the Get_absolute_url method.
            Return Redirect (post) Else: # checks to see if the data is illegal, renders the detail page, and renders the form error. # so we passed three template variables to detail.html,
            # One is the article (POST), one is the comment list, the other is form form # Note Here we use the Post.comment_set.all () method, # This usage is somewhat similar to P Ost.objects.all () # The effect is to get all the comments under this post, # because Post and Comment are foreignkey associated, # so that
            Use Post.comment_set.all () to reverse query for all comments.
            Comment_list = Post.comment_set.all () # Passes the comments list of articles, forms, and articles as template variables to the detail.html template to render the corresponding data.
            Context = {' Post ':p ost, ' form ': Form, ' comment_list ': comment_list
    return render (Request, ' blog/detail.html ', Context=context) # is not a POST request, stating that the user did not submit data and redirected to the article detail page.
 return render (POST)

6 binding URL, here we need to create a new urls.py
/comments/urls.py

From Django.conf.urls import URLs from
. Import views

app_name= ' comments '
urlpatterns = [
    url (r ' ^ comment/post/(? p<post_pk>[0-9]+)/$ ', views.post_comment,name= ' post_comment '),
]

Note Here must add app_name= ' comments ', otherwise will appear when debugging the bug, or simply cannot run up

7 This is the time to add comments URLs to blogproejct urls.py files.
URL (r ', include (' Comments.urls '), there is a little understanding of the place, you can forward a few articles to see

But we do not run this list of comments details, here we need to update the blog under the Detail function, where we need to import commentform

8 Finally, we in front of the page rendering, there need to change two places, one is the name, mailbox, URL, comments and other changes; one is the revision of the comment content
Open our detail.html template, find the contents of the above two places, and make the following changes

        <form action= "{% url ' comments:post_comment ' post.pk%}" method= "Post" class= "Comment-form" > {% Csrf_token%} <div class= "row" > <div class= "col-md-4" > <lab El for= ' {Form.name.id_for_label}} ' > name:</label> {{Form.name}} {Form . name.errors}} </div> <div class= "col-md-4" > <label fo R= ' {Form.email.id_for_label}} ' > Mailbox:</label> {{Form.email}} {{Form.em Ail.errors}} </div> <div class= "col-md-4" > <label for= ' {{Form.url.id_for_label}} ' > URL:</label> {form.url}} {{Form.url.erro RS} </div> <div class= "col-md-12" > <label for= "{for M.comment.id_for_label}} ' > Comment:</label> {{Form.text}} {{form.text.errors}}}    <button type= "Submit" class= "COMMENT-BTN" > Release </button> </div> </div> <!--row--> </form> <div class= "Comment-list-panel" >  

! [Fill in the comment content. png] (http://upload-images.jianshu.io/upload_images/2577413-e03c8adc85040154.png?)
imagemogr2/auto-orient/strip%7cimageview2/2/w/1240)

Comments on the contents of the display:

Here, we will write the comments, of course, this is just a simple comment, comments and comments back to reply, and so on ....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.