Python Django uses forms to implement comments and django comments

Source: Internet
Author: User

Python Django uses forms to implement comments and django comments

It seems that Django has abandoned the use of its own comments since version 1.6. The specific reason is not found. However, the comment function can be implemented by using the internal modules of Django, that is, using the forms module, below is a small example of mine.

Environment preparation
• Operating System: windows 7 64-bit flagship Edition
• IDE: PyCharm 2016.1
• Python: 2.7.11
• Django: 1.9.6

Design

The so-called Design refers to the underlying model that will be involved in the comments function we will implement. My simple design here is as follows. You can set it as needed. For my settings here, see the models. py file:

 from __future__ import unicode_literalsfrom django.contrib import adminfrom django.db import modelsfrom django import forms# Create your models here.TOPIC_CHOICES = (  ('level1','Bad'),  ('level2','SoSo'),  ('level3','Good'),)class RemarkForm(forms.Form):  subject = forms.CharField(max_length=100,label='Mark Board')  mail = forms.EmailField(label='email')  topic = forms.ChoiceField(choices=TOPIC_CHOICES,label='choose one topic')  message = forms.CharField(label='content for mark',widget=forms.Textarea)  cc_myself = forms.BooleanField(required=False,label='watch this tie')class Remark(models.Model):  subject = models.CharField(max_length=100)  mail = models.EmailField()  topic = models.CharField(max_length=100)  message = models.CharField(max_length=300)  cc_myself = models.BooleanField()  def __unicode__(self):    return self.subject  class Meta:    ordering = ['subject']admin.site.register([Remark,])

As you can see, models. the py file contains a subclass of forms. This time, because our operations involve webpage forms, it is best to create a Form class for each model class, it is convenient to obtain cleaned_data from the form.

Url ing file urls. py

This file is relatively simple, as follows:

"""FormRelative URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:  https://docs.djangoproject.com/en/1.9/topics/http/urls/Examples:Function views  1. Add an import: from my_app import views  2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')Class-based views  1. Add an import: from other_app.views import Home  2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')Including another URLconf  1. Import the include() function: from django.conf.urls import url, include  2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))"""from django.conf.urls import urlfrom django.contrib import adminfrom app.views import *urlpatterns = [  url(r'^admin/', admin.site.urls),  url(r'^remark/$',reamark),]

View layer views. py

This file determines the display view corresponding to the ing file, so it is more important.

from django.shortcuts import renderfrom app.models import *from django.http import *# Create your views here.# subject = models.CharField(max_length=100)#   mail = models.EmailField()#   topic = models.CharField(max_length=100)#   message = models.CharField(max_length=300)#   cc_myself = models.BooleanField()def reamark(request):  if request.method =="POST":    form = RemarkForm(request.POST)    if form.is_valid():      myremark = Remark()      myremark.subject=form.cleaned_data['subject']      myremark.mail = form.cleaned_data['mail']      myremark.topic = form.cleaned_data['topic']      myremark.message = form.cleaned_data['message']      myremark.cc_myself = form.cleaned_data['cc_myself']      myremark.save()      # return HttpResponse("Publish Success!")  else:    form = RemarkForm()  ctx = {    'form':form,    'ties':Remark.objects.all()  }  return render(request,'message.html',ctx)

Template templates/message.html

The use of templates greatly reduces the amount of data and achieves data separation at the presentation layer more flexibly, reducing the coupling between modules.

<!DOCTYPE html>

Note that the makeup tag and template variables are declared in the remark method of views. py, so you can directly use them.

Initialize Database

The sqlite database is used here. The configuration in the settings. py file is as follows;

# Database# https://docs.djangoproject.com/en/1.9/ref/settings/#databasesDATABASES = {  'default': {    'ENGINE': 'django.db.backends.sqlite3',    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),  }}

Then, in the terminal environment, enter the following commands:

// Create a database table structure python manage. py makemigrationspython manage. py migrate // follow the prompts to create a super administrator python createsuperuser // run the python manage project on the built-in development server. py runserver

Debugging Verification

Enter
127.0.0.1: 8000/admin
You can see the following

Enter 127.0.0.1: 8000/remark

Database:

In this way, except for the absence of beautifying the interface, the rest are complete.

Summary

Although this is a very simple small example, I also found some of my own conceptual problems, such as unreasonable model design, because there is no comment time, this is embarrassing.

Then

if request.method =="POST":    form = RemarkForm(request.POST)    if form.is_valid():      myremark = Remark()      myremark.subject=form.cleaned_data['subject']      myremark.mail = form.cleaned_data['mail']      myremark.topic = form.cleaned_data['topic']      myremark.message = form.cleaned_data['message']      myremark.cc_myself = form.cleaned_data['cc_myself']      myremark.save()      # return HttpResponse("Publish Success!")  else:    form = RemarkForm()  ctx = {    'form':form,    'ties':Remark.objects.all()  }  return render(request,'message.html',ctx)

In this Code, the corresponding action in the form is. This indicates that when the form is submitted to this page, the comment of the form data is realized, which is very clever. In addition, this feature of Django also has the advantage that the asynchronous loading of comments can still be realized without manual page refreshing.

Finally, the Remark model and RemarkForm form attributes in the model are consistent. Pay special attention to this!

Now, let's talk about it here today. You are welcome to criticize and correct it because of your ability and code or logic errors!

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.