开发者

Django multiple choice of foreign key returning objects

Say I want to have an input form where one of the inputs is a multiple selection based on another table. So I have the following code:

# forms.py
class AddItemForm(ModelForm):
    class Meta:
        model = mpItem
        exclude = ('date_created',
                   'created_by_user',
                   )

and the following view:

def add_item_view(request, template_name='data/add_item.html', current_app=None):
    if request.method == 'POST':
        form = AddItemForm(request.POST, request.FILES)
        if form.is_valid(): 
            item = form.save(False)
            item.created_by_user = request.user
            item.save()
            return HttpResponseRedirect('../item/'+str(item.id)) 
    else:
        form = AddItemForm() 
        form.fields["mptype"].queryset = mpType.objects.all()

    return render_to_response(template_name,context_instance=RequestContext(request,{'form':form})
)

and the template:

  <form enctype="multipart/form-data" method="post" action=".">
  {{ form.non_field_errors }}
  <div class="fieldWrapper">
    {{ form.title.errors }}
    <label for="id_title" class="second">Title</lab开发者_运维技巧el>
    {{ form.title }}    
  </div>
  <div class="fieldWrapper">
    {{ form.mptype.errors }}
    <label for="id_mptype" class="second">Type</label>
    {{ form.mptype }}
    <p>
      <span> Your item does not fit in any collection? Create a <a href="{% url addcollection %}">new one</a>.</span>
    </p>
  </div>
  <div class="fieldWrapper">
    {{ form.image.errors }}
    <label for="id_image" class="second">Image</label>
    {{ form.image }}    
  </div>
  <div class="fieldWrapper">
    {{ form.description.errors }}
    <label for="id_description" class="second">Description</label>
    {{ form.description }}    
  </div>

However when the template is rendered I got a list of objects which I don't know how to unpack (object mpType1, object mpType2). Ideally I would like the selection fields to be the 'title' field of these objects and their values to be their id's. What am I missing here?


If I understand what you're asking correctly (you want to customize how the objects appear in the select box), all you need to do is add a __unicode__ method to the mpType model, like:

def __unicode__(self):
    return self.title 

so that Django knows how you'd like those items to be displayed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜