Django如何将外键传递给ModelForm字段

Posted

技术标签:

【中文标题】Django如何将外键传递给ModelForm字段【英文标题】:Django how to pass foreign key into ModelForm field 【发布时间】:2014-09-02 07:54:35 【问题描述】:

我是 Django 新手,作为一个学习项目,我正在构建一个待办事项列表应用程序。 主页 (lists.html) 显示 List 对象和 Item 对象(通过外键关联)。

Lists.html 显示所有列表和这些列表中的任何项目。列表标题旁边是一个“新建”链接。单击此链接将转到 create.html,您可以在其中创建新项目并将它们添加到列表中。我想要发生的是,当您单击“新建”时,它会带您创建.html 但它已经预先填充了 todo_list 外键字段,具体取决于您单击旁边的“新建”哪个列表。

我最初的策略是尝试将列表 ID 传递到 URL,但后来我很难将其输入 todo_list 外键字段。这是正确的方法吗?还有什么其他方法可以实现?

代码如下,在此先感谢。

models.py:

from django.db import models
from django.forms import ModelForm
import datetime

PRIORITY_CHOICES = (
    (1,'Low'),
    (2,'Normal'),
    (3,'High'),
)
# Create your models here.
class List(models.Model):
    title = models.CharField(max_length=250,unique=True)

    def __str__(self):
        return self.title
    class Meta:
        ordering = ['title']
    class Admin:
        pass

class Item(models.Model):
    title = models.CharField(max_length=250)
    created_date = models.DateTimeField(default=datetime.datetime.now)
    priority = models.IntegerField(choices=PRIORITY_CHOICES,default=2)
    completed = models.BooleanField(default=False)
    todo_list = models.ForeignKey(List)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-priority','title']

    class Admin:
        pass

class NewItem(ModelForm):
   class Meta:
       model = Item
       fields = ['title','priority','completed','todo_list']

views.py:

from django.shortcuts import render_to_response
from django.shortcuts import render
from todo.models import List
from todo.models import Item
from todo.models import NewItem
from django.http import HttpResponseRedirect
# Create your views here.
def status_report(request):
    todo_listing = []
    for todo_list in List.objects.all():
        todo_dict = 
        todo_dict['id'] = id
        todo_dict['list_object'] = todo_list
        todo_dict['item_count'] = todo_list.item_set.count()
        todo_dict['items_complete'] = todo_list.item_set.filter(completed=True).count()
        todo_dict['percent_complete'] =int(float(todo_dict['items_complete'])/todo_dict['item_count']*100)
        todo_listing.append(todo_dict)
    return render_to_response('status_report.html', 'todo_listing': todo_listing)

def lists(request):
    todo_listing = []
    for todo_list in List.objects.all():
        todo_dict = 
        todo_dict['list_object'] = todo_list
        todo_dict['items'] = todo_list.item_set.all()
        todo_listing.append(todo_dict)
    return render_to_response('lists.html','todo_listing': todo_listing)

def create(request):
    if request.method == 'POST':
        form = NewItem(request.POST or None)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/lists/')
    else:
        form = NewItem()

    return render(request, 'create.html', 'form': form)

lists.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>To-do List Status Report</title>

  </head>

  <body>

    <h1>To-do lists</h1>

% for list_dict in todo_listing %

    <h2> list_dict.list_object.title  <a href='/create/'>New</a></h2>
    <table>
    % for item in list_dict.items %


    <tr><td> item </td><td><a href='/delete/item.id/'>Del</a></td></tr>

    % endfor %
    </table>



    </ul>

% endfor %

  </body>

</html>

创建.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Create Task</title> 
</head>

  <body>
        <form action="/create/" method="post">
            % csrf_token %
            % for field in form %<p>field</p>% endfor %
            <input type="submit" value="Submit" />
        </form>

  </body>

</html>

【问题讨论】:

【参考方案1】:

也许这会有所帮助:https://***.com/a/5470037/2002580

您希望通过请求传递一些数据。我认为 URL 方案之类的东西可能很有用,因为它不会太复杂。

# urls.py
urlpatterns += patterns('myview.views',
    url(r'^(?P<user>\w+)/', 'myview', name='myurl'), # I can't think of a better name
)

# template.html
<form name="form" method="post" action="% url myurl username %">

# above code is from the linked answer

【讨论】:

以上是关于Django如何将外键传递给ModelForm字段的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Django 中向 ModelForm 添加外键字段?

ajax调用时如何将外键传递给json数据?

如何在编辑内容并将javascript变量传递给它的新输入字段后将Django“forms.ModelForm”保存在数据库中

将外键放入表单

Django将外键限制为满足特定条件的记录

将外键传递给 Rails 中的部分渲染