如何从Django中的链接设置预定义的表单值? [英] How to set a predefined form value from a link in Django?
问题描述
我的项目排列如下:
1. page
has many: categories
2. category
belongs to: page
has many: items
3. item
belongs to: category
当我输入我想修改的页面(添加新类别或这些类别的新项目),到目前为止,我只能得到一个点,我可以通过一个主链接添加一个新的类别或一个项目,让我到一个表格,我必须选择该项目必须属于哪个类别。我想做的是在类别标题旁边添加一个链接添加新项目,当我点击它时,项目表单默认设置为该类别。我怎样才能做到这一点?我现在的形式看起来很原始,如下所示:
when I enter a page I'd like to modify (add new categories or new items to those categories), so far I've only gotten to the point where I can add a new category or an item through a main link that gets me to a form where I have to chose which category the item must belong to. What I'd like to do is have a link "Add new item" next to categories title and when I click on it, the item form sets to that category by default. How can I do that? My current form looks very primitive, like so:
{% extends "base.html" %}
{% block content %}
{% if page.id %}
<h1>Edit Category</h1>
{% else %}
<h1>Add Category</h1>
{% endif %}
<form action="{{ action }}" method="POST">
{% csrf_token %}
<ul>
{{ form.as_ul }}
</ul>
<input type="submit" id="save_page" value="Save" class="success button" /> <a href="javascript:window.history.back();">Cancel</a>
</form>
{% endblock %}
推荐答案
p>所以,这样做的方法是将其从表单中完全排除,并将其设置在保存视图中。
So, the way to do this is to exclude it from the form completely and set it in the view on save.
class ItemForm(forms.ModelForm):
class Meta:
model = Item
exclude = ('category',)
和视图:
def create_item(request, category_id):
if request.method == 'POST':
form = ItemForm(request.POST)
if form.is_valid():
item = form.save(commit=False)
item.category_id = category_id
item.save()
return redirect(...)
...etc...
通过网址提供:
url(r'^create_item/(?P<category_id>\d+)/$, 'create_item', name='create_item'),
你可以在哪里重新链接到您的类别列表:
and which you can therefore link to from your categories list:
{% for category in categories %}
<li>{{ category.name }} - <a href="{% url 'create_item' category.id }">Create item</a></li>
{% endfor %}
这篇关于如何从Django中的链接设置预定义的表单值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!