Django 之 modelForm (edit.html页面的编写)
models.py文件
from django.db import models # Create your models here. from django.db import models # Create your models here. class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() # 与AuthorDetail建立一对一的关系 authorDetail = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE) def __str__(self): return self.name class AuthorDetail(models.Model): nid = models.AutoField(primary_key=True) birthday = models.DateField() telephone = models.BigIntegerField() addr = models.CharField(max_length=64) def __str__(self): return str(self.telephone) class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True, verbose_name="ID") title = models.CharField(max_length=32, verbose_name="书名") publishDate = models.DateField() price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="价格") # 与Publish建立一对多的关系,外键字段建立在多的一方 publish = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE) # 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表 authors = models.ManyToManyField(to='Author', ) def __str__(self): return self.title
在view的 edit 方法里:
class ModelStark: # 获取modelform类 @property def modelform_class(self): if self.modelfoem_class: return self.modelfoem_class else: class ModelFormClass(forms.ModelForm): class Meta: model = self.model fields = '__all__' return ModelFormClass # 改 def edit(self, request, id): model_obj = self.model.objects.get(pk=id) if request.method == 'GET': # 生成一个带有model对象内容的modelform对象 form = self.modelform_class(instance=model_obj) return render(request, 'stark/edit.html', {'form': form}) else: form = self.modelform_class(request.POST, instance=model_obj) if form.is_valid(): form.save() _url = self.get_url('list') return redirect(_url) else: return render(request, 'stark/edit.html', {'form': form})
在html页面里:
<form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="">{{ field.label }}</label> {{ field }} {% if field.is_pop %} <a class="pull-right addfield-type" onclick="add_page('{{ field.url }}')">
<span class="glyphicon glyphicon-plus"></span>
</a> {% endif %} <span class="erorr ">{{ field.errors.0 }}</span> </div> {% endfor %} <button type="submit" name="submit" value="提交">提交</button> </form>