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

后端 未结 1 654
执念已碎
执念已碎 2021-01-26 08:49

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
1条回答
  •  孤独总比滥情好
    2021-01-26 09:32

    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\d+)/$, 'create_item', name='create_item'),
    

    and which you can therefore link to from your categories list:

    {% for category in categories %}
        
  • {{ category.name }} - Create item
  • {% endfor %}

    0 讨论(0)
提交回复
热议问题