How can I fill up form with model object data?

前端 未结 2 862
陌清茗
陌清茗 2021-01-31 15:15

I want to fill up form with data from model instance. But my form has less fields than model. If I have code like this:

class Item(models.Model)
    name = model         


        
相关标签:
2条回答
  • 2021-01-31 15:48
    def bound_form(request, id): 
        item = Item.objects.get(id=id) 
        form = ItemForm(initial={'name': item.name}) 
        return render_to_response('bounded_form.html', {'form': form}) 
    
    0 讨论(0)
  • 2021-01-31 15:49

    Generally when creating a form for a Model, you will want to use ModelForm. It keeps to the DRY principle such that you do not have to redefine field types for the form class. It also automatically handles validation. You retain full flexibility to customize the fields and widgets used. Use fields to specify the fields you want or exclude to specify fields to ignore. With your example:

    from django import forms
    from django.shortcuts import get_object_or_404
    
    class ItemForm(forms.ModelForm):
        class Meta:
            model = Item
            fields = ("name", )
    
    def bound_form(request, id):
        item = get_object_or_404(Item, id=id)
        form = ItemForm(instance=item)
        return render_to_response('bounded_form.html', {'form': form})
    

    get_object_or_404() is useful here as a form of error handling. Using Item.objects.get(id=id) on a missing ID will throw an uncaught Item.DoesNotExist exception otherwise. You could use a try/except block also of course.

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