我目前只为 models.py 中的某些字段创建条目。现在我想将Delete
和Update
函数添加到我的应用程序中。我们以模型为例:
class todoList(models.Model):
trainee = models.ForeignKey(trainee, verbose_name = "Azubi", blank = True)
todoLearningObjective = models.ManyToManyField(learningObjective, verbose_name = "Lernziel", blank = True, null = True)
tasks = models.TextField(verbose_name = 'Aufgaben')
levyDate = models.DateField(verbose_name = 'Abgabedatum', blank = True, null = True)
priority = models.IntegerField(verbose_name = 'Prioritaet', blank = True, null = True)
class Meta:
verbose_name = "To-Do Liste"
verbose_name_plural = "To-Do Listen"
匹配表单:
class todoListForm(forms.Form):
formtrainee = forms.IntegerField(required = False)
formtodoLearningObjective = forms.CharField(required = False)
formtasks = forms.CharField(required = True)
formlevyDate = forms.DateField(required = False)
formpriority = forms.IntegerField(required = False)
查看:
def todo(request):
trainee_objects = trainee.objects.all()
usernameID = 1
for traineeUser in trainee_objects:
if traineeUser.username == request.user.username:
usernameID = traineeUser.id
if request.method == 'POST':
forms = todoListForm(request.POST)
if forms.is_valid():
formtasks = forms.cleaned_data['formtasks']
formtodoLearningObjective = forms.cleaned_data['formtodoLearningObjective']
formlevyDate = forms.cleaned_data['formlevyDate']
formpriority = forms.cleaned_data['formpriority']
neueTodo=todoList(tasks=formtasks, levyDate=formlevyDate, priority=formpriority, trainee_id = usernameID)
neueTodo.save()
for todo in learningObjective.objects.filter(learningObjectives=formtodoLearningObjective):
neueTodo.todoLearningObjective.add(todo)
else:
forms = todoList()
return render(request, 'todo.html', {'todo': todoList.objects.all(), 'Lernziel': learningObjective.objects.all()})
如您所见,我有M to M
个关系,我只是创建新条目。我现在的问题是:我是否必须为每个模型创建一个新的更新和删除方法?或者有更简单的方法吗?我想保持我的项目DRY,尽管我可能已经失败了。如果你能给我一些关于如何在Django中进行删除和更新的示例或文档,那将是非常棒的。
答案 0 :(得分:2)
您已为此构建了基于类的视图。
from django.views.generic import CreateView,UpdateView,DeleteView
class Todo(CreateView):
formClass = todoListForm
template_name = 'your_template_name.html'