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

时间:2014-07-11 16:03:41

标签: python django django-forms

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

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

我最初的策略是尝试将列表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>

create.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 个答案:

答案 0 :(得分:0)

也许这可以提供帮助:https://stackoverflow.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