PythonDjango uses forms to implement the comment function

Source: Internet
Author: User
This article mainly introduces PythonDjango's use of forms to implement comment functions, which has some reference value, if you are interested, you can refer to the reference. it seems that Django has abandoned the use of its own comments since version 1.6. the specific reason is not found, however, the internal modules of Django can also implement the comment function, that is, 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 Configuration The '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.

  
   Title{% for tie in ties %}  

  • {{ tie.subject }}
  • {{ tie.mail}}
  • {{ tie.topic}}
  • {{ tie.message }}
  • {{ tie.cc_myself }}

{% endfor%}

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/#databases DATABASES = {  '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 makemigrations python 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

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 help you learn and support PHP.

For more articles about using forms to implement the comment function of Python Django, refer to PHP Chinese network!

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.