国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

使用Django Form解決表單數據無法動態刷新的兩種方法

2019-11-25 16:01:15
字體:
來源:轉載
供稿:網友

一、無法動態更新數據的實例

1. 如下,數據庫中創建了班級表和教師表,兩張表的對應關系為“多對多”

from django.db import modelsclass Classes(models.Model):  title = models.CharField(max_length=32)class Teacher(models.Model):  name = models.CharField(max_length=32)  t2c = models.ManyToManyField(Classes)

2. views的功能有查看、添加、編輯班級或教師表

from django.shortcuts import render, redirectfrom school import modelsfrom django.forms import Form, fields, widgets#班級表單驗證規則class ClsForm(Form):  title = fields.RegexField('老男孩', error_messages={'invalid': '請以 老男孩 開頭'})#教師表單驗證規則class TchForm(Form):  name = fields.CharField(max_length=16, min_length=2, widget=widgets.TextInput(attrs={'class': 'form-control'}))  t2c = fields.MultipleChoiceField(    choices=models.Classes.objects.values_list('id', 'title'),    widget=widgets.SelectMultiple(attrs={'class': 'form-control'})  )#查看班級列表def classes(request):  cls_list = models.Classes.objects.all()  return render(request, 'classes.html', {'cls_list': cls_list})#查看教師列表def teachers(request):  tch_list = models.Teacher.objects.all()  return render(request, 'teachers.html', {'tch_list': tch_list})#添加班級def add_cls(request):  if request.method == 'GET':    obj = ClsForm()    return render(request, 'add_classes.html', {'obj': obj})  else:    obj = ClsForm(request.POST)    if obj.is_valid():      models.Classes.objects.create(**obj.cleaned_data)      return redirect('/school/classes/')    return render(request, 'add_classes.html', {'obj': obj})#添加教師def add_tch(request):  if request.method == 'GET':    obj = TchForm()    return render(request, 'add_teacher.html', {'obj': obj})  else:    obj = TchForm(request.POST)    if obj.is_valid():      tc = obj.cleaned_data.pop('t2c')  # 獲取教師任課班級id      tch_obj = models.Teacher.objects.create(name=obj.cleaned_data['name']) # 添加新教師姓名      tch_obj.t2c.add(*tc)  # 添加新教師任課班級      return redirect('/school/teachers/')    return render(request, 'add_teacher.html', {'obj': obj})#編輯班級def edit_cls(request, nid):  if request.method == 'GET':    cls = models.Classes.objects.filter(id=nid).first()    obj = ClsForm(initial={'title': cls.title})    return render(request, 'edit_classes.html', {'nid': nid, 'obj': obj})  else:    obj = ClsForm(request.POST)    if obj.is_valid():      models.Classes.objects.filter(id=nid).update(**obj.cleaned_data)      return redirect('/school/classes/')    return render(request, 'edit_classes.html', {'nid': nid, 'obj': obj})#編輯教師def edit_tch(request, nid):  if request.method == 'GET':    tch = models.Teacher.objects.filter(id=nid).first()    v = tch.t2c.values_list('id')  # 獲取該教師任課班級的id    cls_ids = list(zip(*v))[0] if list(zip(*v)) else []   # 格式化為列表類型    obj = TchForm(initial={'name': tch.name, 't2c': cls_ids})    return render(request, 'edit_teacher.html', {'nid': nid, 'obj': obj})  else:    obj = TchForm(request.POST)    if obj.is_valid():      tc = obj.cleaned_data.pop('t2c')  # 獲取修改后的任課班級id      # models.Teacher.objects.filter(id=nid).update(name=obj.cleaned_data['name'])   # 更新教師姓名方法1      tch_obj = models.Teacher.objects.filter(id=nid).first()      tch_obj.name = obj.cleaned_data['name']   # 更新教師姓名方法2      tch_obj.save()      tch_obj.t2c.set(tc)      return redirect('/school/teachers/')    return render(request, 'edit_teacher.html', {'nid': nid, 'obj': obj})

3. html文件

classe:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>班級列表</title>  <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></head><body><div style="width: 700px; margin: 30px auto">  <a class="btn btn-default" href="/school/add_cls/" rel="external nofollow" style="margin-bottom: 10px">添加班級</a>    <table class="table table-hover" border="1" cellspacing="0">      <thead>      <tr>        <th>ID</th>        <th>班級</th>        <th>操作</th>      </tr>      </thead>      <tbody>        {% for item in cls_list %}          <tr>            <td>{{ item.id }}</td>            <td>{{ item.title }}</td>            <td><a href="/school/edit_cls/{{ item.id }}" rel="external nofollow" >編輯</a></td>          </tr>        {% endfor %}      </tbody>    </table></div></body></html>

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>添加班級</title></head><body><h1>添加班級</h1><form action="/school/add_cls/" method="post">  {% csrf_token %}  <p>    {{ obj.title }} {{ obj.errors.title.0 }}  </p>  <input type="submit" value="提交"></form></body></html>
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>編輯班級</title></head><body><h1>編輯班級</h1><form action="/school/edit_cls/{{ nid }}" method="post">  {% csrf_token %}  <p>    {{ obj.title }} {{ obj.errors.title.0 }}  </p>  <input type="submit" value="提交"></form></body></html>

 teachers:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>教師列表</title>  <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></head><body><div style="width: 700px; margin: 30px auto">  <a class="btn btn-default" href="/school/add_tch/" rel="external nofollow" style="margin-bottom: 10px">添加教師</a>    <table class="table table-hover" border="1" cellspacing="0">      <thead>      <tr>        <th>ID</th>        <th>姓名</th>        <th>任教班級</th>        <th>操作</th>      </tr>      </thead>      <tbody>        {% for item in tch_list %}          <tr>            <td>{{ item.id }}</td>            <td>{{ item.name }}</td>            <td>              {% for row in item.t2c.all %}                <span style="border: solid gray 1px">{{ row.title }}</span>              {% endfor %}            </td>            <td><a href="/school/edit_tch/{{ item.id }}" rel="external nofollow" >編輯</a></td>          </tr>        {% endfor %}      </tbody>    </table></div></body></html>
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>添加教師</title>  <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></head><body><div style="width: 500px; margin: 20px auto"><h3 style="width: 100px; margin: 10px auto">添加教師</h3>  <form class="form-horizontal" action="/school/add_tch/" method="post">    {% csrf_token %} <div class="form-group">  <label class="col-sm-2 control-label">姓名</label>  <div class="col-sm-10">   {{ obj.name }} {{ obj.errors.name.0 }}  </div> </div> <div class="form-group">  <label class="col-sm-2 control-label">班級</label>  <div class="col-sm-10">      {{ obj.t2c }} {{ obj.errors.t2c.0 }}  </div> </div> <div class="form-group">  <div class="col-sm-offset-2 col-sm-10">   <input type="submit" class="btn btn-default" value="提交"></input>  </div> </div></form></div></body></html>
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>編輯教師</title>  <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></head><body><div style="width: 500px; margin: 20px auto"><h3 style="width: 100px; margin: 10px auto">編輯教師</h3>  <form class="form-horizontal" action="/school/edit_tch/{{ nid }}" method="post">    {% csrf_token %} <div class="form-group">  <label class="col-sm-2 control-label">姓名</label>  <div class="col-sm-10">   {{ obj.name }} {{ obj.errors.name.0 }}  </div> </div> <div class="form-group">  <label class="col-sm-2 control-label">班級</label>  <div class="col-sm-10">      {{ obj.t2c }} {{ obj.errors.t2c.0 }}  </div> </div> <div class="form-group">  <div class="col-sm-offset-2 col-sm-10">   <input type="submit" class="btn btn-default" value="提交"></input>  </div> </div></form></div></body></html>

4. 數據不能同步

在班級表中新增一條記錄

在教師表中新添加一名教師,發現無法獲取上一步新增記錄

5. 原因分析

在添加教師時,請求方式為GET,html標簽由Form組件自動生成,其中的數據也是由Form組件提供

而TchForm作為一個類,在project運行起來后,其中的name和t2c字段都是類的變量,其只執行一次,就將數據保存在內存中,無論之后生成多少個TchForm對象,其中的字段的值都不變。

所以會出現教師表中的班級多選列表無法動態更新。

二、解決上述bug的方法

每次更新數據庫后重啟project,讓Form類重新初始化,能夠讓數據更新,但這顯然是不切實際的。

知道了bug的根源,我們可以嘗試讓每次生成TchForm對象時就更新數據:

方法一

1. 利用 __init__將數據庫操作放入對象變量中

 修改TchForm類

#教師表單驗證規則class TchForm(Form):  name = fields.CharField(max_length=16, min_length=2, widget=widgets.TextInput(attrs={'class': 'form-control'}))  t2c = fields.MultipleChoiceField(    # choices=models.Classes.objects.values_list('id', 'title'),    widget=widgets.SelectMultiple(attrs={'class': 'form-control'})  )  def __init__(self, *args, **kwargs):  # 自定義__init__    super(TchForm, self).__init__(*args, **kwargs) # 調用父類的__init__    self.fields['t2c'].choices = models.Classes.objects.values_list('id', 'title')  # 為字段t2c的choices賦值

2. 驗證

 在班級表中新增一條記錄

 再在教師表中添加

方法二

1. 利用django.forms.models模塊中的queryset連接數據庫

 修改TchForm類

#教師表單驗證規則from django.forms import models as form_models # 導入django.forms.modelsclass TchForm(Form):  name = fields.CharField(max_length=16, min_length=2, widget=widgets.TextInput(attrs={'class': 'form-control'}))  #重新定義字段  t2c = form_models.ModelMultipleChoiceField(    # choices=models.Classes.objects.values_list('id', 'title'),    queryset=models.Classes.objects.all(), # 利用queryset連接數據庫,只能連接object類型    widget=widgets.SelectMultiple(attrs={'class': 'form-control'})  )

2. 驗證

由于TchForm類中,queryset只能連接object類型,所以,需要設置models.py中的Classes類的返回值。

 設置models.py中的Classes類的返回值

class Classes(models.Model):  title = models.CharField(max_length=32)   def __str__(self):     return self.title

在班級表中新增一條記錄

再在教師表中添加

以上所述是小編給大家介紹的使用Django Form解決表單數據無法動態刷新的兩種方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 台州市| 华宁县| 女性| 汽车| 金坛市| 黄冈市| 涞源县| 宜丰县| 阿克| 斗六市| 古浪县| 米脂县| 榆中县| 蒲江县| 连城县| 大宁县| 安乡县| 珲春市| 唐山市| 若尔盖县| 正宁县| 文化| 体育| 泸定县| 吉隆县| 昭通市| 澄江县| 唐河县| 嘉黎县| 镇远县| 广河县| 保靖县| 深水埗区| 德惠市| 绿春县| 两当县| 枣阳市| 建始县| 丹东市| 中宁县| 于都县|