一.
model的知识点
1 class UserInfo(AbstractUser): 2 tel=models.CharField(max_length=32) 3 gender=models.IntegerField(choices=((1,"男"),(2,"女")),default=1) 4 5 yuan=UserInfo.objects.get(pk=1) 6 yuan.get_gender_display()
modelform
modefform使用
model.py:
1 class Book(models.Model): 2 nid=models.AutoField(primary_key=True) 3 title=models.CharField(max_length=32) 4 price=models.DecimalField(max_digits=8,decimal_places=2) # 999999.99 5 pub_date=models.DateTimeField() # "2012-12-12" 6 7 # comment_count=models.IntegerField(default=100) 8 # poll_count=models.IntegerField(default=100) 9 10 publish=models.ForeignKey(to="Publish",on_delete=models.CASCADE) # 级联删除 11 authors=models.ManyToManyField(to="Author") 12 def __str__(self): 13 return self.title
复杂版
form.py:
1 form.py: 2 # 构建modelform 3 class BookModelForm(forms.ModelForm): 4 class Meta: 5 model=Book 6 fields="__all__" 7 8 ‘‘‘ 9 BookModelForm等同于: 10 class BookForm(forms.Form): 11 title=forms.CharField(max_length=32) 12 price=forms.IntegerField() 13 pub_date=forms.DateField(widget=widgets.TextInput(attrs={"type":"date"})) 14 #publish=forms.ChoiceField(choices=[(1,"AAA"),(2,"BBB")])写死的 15 publish=forms.ModelChoiceField(queryset=Publish.objects.all()) 16 authors=forms.ModelMultipleChoiceField(queryset=Author.objects.all()) 17 18 ‘‘‘
完美版
逻辑:
添加书籍
def add(request):
if GET:
form=BookModelForm()
return render(reqeust,{"form":form})渲染页面
1 ‘‘‘ 2 渲染页面 3 <form action="" method="post" novalidate> 4 {% csrf_token %} 5 {% for field in form %} 6 <div class="form-group"> 7 <label for="title">{{ field.label }}</label> 8 {{ field }} 9 <span>{{ field.errors.0 }}</span> 10 </div> 11 {% endfor %} 12 <input type="submit" value="提交" class="btn btn-default pull-right"> 13 </form> 14 ‘‘‘
add.html
esle : POST 请求
form=BookModelForm(request.POST)
if form.is_valid():
form.save()
return redirect("")
else:
return render(reqeust,{"form":form})
编辑书籍: def edit(request,id): edit_obj=Book.objects.get(pk=id) if GET请求: form=BookModelForm(instance=edit_obj) return render(reqeust,{"form":form}) ‘‘‘ 渲染页面同添加页面 ‘‘‘ else POST请求: form=BookModelForm(request.POST,instance=edit_obj)#加入instance等同于 if form.is_valid(): form.save() # edit_obj.update(clean_data) return redirect("/") else: return render(reqeust,{"form":form})
原文地址:https://www.cnblogs.com/zhangqing979797/p/9919020.html
时间: 2024-11-01 20:53:30