zoukankan      html  css  js  c++  java
  • Django使用的一点心得

        1.form模块

      Django的form模块使前端的操作更加简单直观,一些数据项的校验都是模块自带的不用重写,前端页面对后端表的操作更快捷,继承ModelForm建一个类,如下:

    class AddForm(forms.ModelForm):
        class Meta:
            model = models.Course
            # fields = ('name','price')
            exclude=()
    View Code

     通过此类可以实现表的增删改查

    增加

    1     CourseModelForm = form.AddForm()
    2     if request.method == 'POST':
    3         forms = form.AddForm(request.POST)
    4         if forms.is_valid():
    5             forms_data = forms.cleaned_data
    6             forms.save()
    View Code

    更新

    1     Course=get_object_or_404(models.Course,pk=int(id))
    2     if request.method=="POST":
    3         forms=form.AddForm(request.POST,instance=Course)
    4         if forms.is_valid():
    5             forms.save()
    View Code

    删除

    1   Course=get_object_or_404(models.Course,pk=int(id))
    2   Course.delete()
    View Code

        前端的查询展示页面仍是用老的从后端传对象到前端,前端操作对象属性,如:

     1      {%for item in object%}<div style="border-bottom:1px dotted #ccc;">
     2           <table border="1">
     3             <tr>
     4                 <td><input type="checkbox" onclick="selected(this)"/>{{ a }}</td>
     5                 <td style=" 100px">{{ item.name }}</td>
     6                 <td style=" 100px">{{ item.price }}</td>
     7                 <td style=" 100px">{{ item.online_price }}</td>
     8                 <td style=" 100px">{{ item.brief }}</td>
     9                 <td>
    10                      <a href="{%url "Course_update" item.id %}">修改</a>   
    11                      <a href="{%url "Course_delete" item.id %}" onclick="return confirm('你确认要删除吗?')">删除</a>
    12                 </td>
    13             </tr>
    14         </table>
    15          </div>
    16      {%endfor%}
    View Code

       前端的修改提交页面可以用form模块,省去了前端再单独对数据项一个一个渲染,如:

    1     <form method="post" action="" >
    2         <table> {{form.as_table}} </table>
    3         <input type="submit"/>返回列表</a>
    4     </form>
    View Code

        2.页面重定向及url传值

        重定向导入HttpResponseRedirect模块:

     from django.http import HttpResponseRedirect
     from django.core.urlresolvers import reverse
     return HttpResponseRedirect(reverse("Course_update"))

    url别名:
     url(r'^update/(?P<id>d+)/$', views.update,name="Course_update")


    url传数字参数
    1 url(r'^update/(?P<id>d+)/$', views.update,name="Course_update"),
    2 
    3 def update(request,id):
    4     Course=get_object_or_404(models.Course,pk=int(id))
    View Code
     
  • 相关阅读:
    岳麓山岳麓书院
    花洲书院
    《诫子书》诸葛亮
    AI ML DL
    台湾大学林轩田机器学习基石
    LeNet
    VGGNet
    AlexNet 2012
    AS 中 Plugin for Gradle 和 Gradle 之间的版本对应关系
    AndroidStudio、gradle、buildToolsVersion关系
  • 原文地址:https://www.cnblogs.com/lizheng19822003/p/5569275.html
Copyright © 2011-2022 走看看