简体   繁体   中英

How to set a predefined form value from a link in Django?

My project is laid out like so:

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 %}

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',)

and the view:

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...

which is served via a url:

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM