Django如何将外键传递给ModelForm字段
我刚开始学习Django,作为一个学习项目,我正在制作一个待办事项列表应用。主页面(lists.html)展示了列表对象和项目对象(通过外键关联)。
lists.html会显示所有的列表以及这些列表上的任何项目。在列表标题旁边,有一个“新建”链接。点击这个链接会带你到create.html,在那里你可以创建新的项目并将它们添加到列表中。我希望的效果是,当你点击“新建”时,它能带你到create.html,并且自动填充待办事项列表的外键字段,这个字段的值取决于你点击“新建”时旁边的哪个列表。
我最开始的想法是尝试把列表的ID放进URL里,但我在把这个ID放入待办事项列表的外键字段时遇到了困难。这是正确的方法吗?还有什么其他方法可以实现这个功能呢?
下面是代码,提前谢谢大家。
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
也许这能帮到你: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