Django-提交表单后分配外键

时间:2019-03-20 07:41:33

标签: python html django

您好,我本周刚刚开始学习Django,正在创建一个待办事项列表应用程序,用户可以在其中创建多个待办事项列表,每个列表都可以容纳多个项目。

Models.py

class Todolist(models.Model):
    listname = models.CharField(max_length=200)
    date = models.DateTimeField(default=datetime.now)
    user = models.ForeignKey(User, default=None, on_delete=models.CASCADE)

class Todo(models.Model):
    todoname = models.CharField(max_length=200)
    date = models.DateTimeField(default=datetime.now)
    user = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    whichlist = models.ForeignKey(Todolist, on_delete=models.CASCADE, null=True)

Views.py

def dolist(request, list_id):
    tdlist = Todolist.objects.get(id=list_id)
    current_user = request.user
    user_todo = Todo.objects.filter(user=current_user, whichlist=tdlist)
    return render(request, 'todolist/tdlists.html', {'tdlist': tdlist, 'todos': user_todo,'list_id':list_id})

def addtodo(request):
    if request.method == 'POST':
        user = request.user
        list_id = request.POST.get('list_id')
        Todo.objects.create(todoname = request.POST['todoname'], user=user, whichlist=list_id)
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    else:
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

.HTML模板表格

<form action="/index/todolist/addtodo" method="POST">
    {% csrf_token %}
    <input type="hidden" name="list_id" value={{list_id}}>
    <input type="text" name="todoname"/>
    <input type="submit" value="Add to-do item"/>
</form>

现在,如果我在Todo.objects.create()中删除了whichlist参数,则可以在提交表单时创建待办事项,但未分配外键,因此它不会显示在待办事项上列表页面。我可以转到Django管理站点并手动为Todo项目分配哪个列表,然后它将显示在该列表页面上。

如何做到这一点,以便自动分配待办事项的外键?即分配给马里奥待办事项列表的马里奥待办事项

感谢您的帮助!

0 个答案:

没有答案