任务添加(一)
首先为该页面创建一个表
编辑myproject/app01/models.py
class Task(models.Model): """任务""" level_choices = ( (1, "紧急"), (2, "重要"), (3, "临时"), ) level = models.SmallIntegerField(verbose_name="级别", choices=level_choices, default=1) title = models.CharField(verbose_name="标题", max_length=64) detail = models.TextField(verbose_name="详细信息") user = models.ForeignKey(verbose_name="负责人", to=Admin, on_delete=models.CASCADE)
更新
makemigrations migrate
编辑myproject/app01/views/task.py
import json from django.shortcuts import render,HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from app01 import models from app01.utils.bootstrap import BootStrapModelForm class TaskModelForm(BootStrapModelForm): class Meta: model = models.Task fields = "__all__" def task_list(request): """任务列表""" form = TaskModelForm() return render(request, "task_list.html", {"form": form}) @csrf_exempt def task_ajax(request): #GET请求 print(request.GET) #POST请求 print(request.POST) data_dict = {"status": True, 'data': [11,22,33,44]} return HttpResponse(json.dumps(data_dict)) # json_string = json.dumps(data_dict) # return HttpResponse(json_string) # return JsonResponse(data_dict)
编辑myproject/app01/templates/task_list.html
<div class="panel panel-default"> <div class="panel-heading">表单</div> <div class="panel-body"> <form method="post" novalidate> {% for field in form %} <div class="form-group"> <label>{{ field.label }}</label> {{ field }} </div> {% endfor %} <button type="submit" class="btn btn-primary">提 交</button> </form> </div> </div>
浏览器看下效果吧
detail详细信息默认是Textarea框,如果想修改为TextInput框,编辑myproject/app01/views/task.py
class TaskModelForm(BootStrapModelForm): class Meta: model = models.Task fields = "__all__" widgets = { "detail":forms.TextInput }
问题出现了,负责人应该是一个用户
解决办法:编辑myproject/app01/models.py
class Admin(models.Model): """管理员表""" username = models.CharField(verbose_name="用户名", max_length=32) password = models.CharField(verbose_name="密码", max_length=64) def __str__(self): return self.username
接下来实现将添加的数据发送到后台
标签:__,name,models,任务,案例,Ajax,app01,import,verbose From: https://www.cnblogs.com/kekeeleven/p/17791964.html