Python Django如何将外键传递到ModelForm字段
我是Django的新手,作为一个学习项目,我正在构建一个待办事项列表应用程序。 主页(lists.html)显示列表对象和项目对象(通过外键关联) html显示所有列表和这些列表上的任何项目。列表标题旁边是一个“新”链接。单击此链接将进入create.html,您可以在其中创建新项目并将其添加到列表中。我想发生的是,当您单击“新建”时,您需要创建.html,但它已预先填充todo_列表外键字段,具体取决于您单击旁边的“新建”列表 我最初的策略是尝试将列表ID传递到URL中,但后来我很难将其传递到todo_列表外键字段中。这是正确的方法吗?还有什么其他方法可以做到这一点 代码如下,提前谢谢 models.py:Python Django如何将外键传递到ModelForm字段,python,django,django-forms,Python,Django,Django Forms,我是Django的新手,作为一个学习项目,我正在构建一个待办事项列表应用程序。 主页(lists.html)显示列表对象和项目对象(通过外键关联) html显示所有列表和这些列表上的任何项目。列表标题旁边是一个“新”链接。单击此链接将进入create.html,您可以在其中创建新项目并将其添加到列表中。我想发生的是,当您单击“新建”时,您需要创建.html,但它已预先填充todo_列表外键字段,具体取决于您单击旁边的“新建”列表 我最初的策略是尝试将列表ID传递到URL中,但后来我很难将其传递到
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>
待办事项列表状态报告
待办事项清单
{todo\ U清单%中的清单\目录的百分比}
{{list_dict.list_object.title}
{列表中项目的百分比\ dict.items%}
{{item}}
{%endfor%}
{%endfor%}
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>
创建任务
{%csrf_令牌%}
{%for格式为%}{{field}{%endfor%}
也许这会有帮助:
您希望获得一些随请求一起传递的数据。我认为类似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
#url.py
urlpatterns+=模式('myview.views',
url(r'^(?P\w+/),'myview',name='myurl'),#我想不出更好的名字了
)
#template.html
#以上代码来自链接答案