2015-10-15 101 views
0

我无法找到我的问题的答案,所以我问你们在这里。 我试图用ModelChoiceField使所有的作品(没有错误给出),但仍然没有得到任何领域/选项(空白选择),并且不能选择一些东西。 这里是我的代码表单字段| Django | ModelChoiceField

models.py

class Search(models.Model): 
    name = models.CharField(max_length=30) 
    email = models.EmailField(max_length=30) 

    def __str__(self): 
     return self.name 

forms.py

class MyModelChoiceField(ModelChoiceField): 
    def label_from_instance(self, obj): 
    return "My Object #%i" % obj.id 

class SearchForm(forms.Form): 
    search_text = forms.CharField(max_length=50) 
    wybor = MyModelChoiceField(queryset= Search.objects.all()) 

任何想法?

回答

0

试试这个:

def label_from_instance(obj): 
    return "My Object #%i" % obj.id 

self.fields['wybor'].label_from_instance = label_from_instance 
+0

我得到这个:NameError:name'self'没有被定义 – Damian

0

确保你在你的搜索表中的数据。为了测试尝试这样的观点:

from django.shortcuts import render 
from django.forms import ModelChoiceField 
from django import forms 
from models import Search 


class MyModelChoiceField(ModelChoiceField): 
    def label_from_instance(self, obj): 
     return "My Object #%i" % obj.id 

class SearchForm(forms.Form): 
    search_text = forms.CharField(max_length=50) 
    wybor = MyModelChoiceField(queryset=Search.objects.all()) 


def test_view(request): 

    f = SearchForm() 

    ids = Search.objects.values_list('id', flat=True) 

    return render(request, 'yourapp/test.html', 
         { 
          'form': f, 
          'ids': ids 
         }) 

test.html的模板:

{{ form }} 

<br/> 

search ids: 

{{ ids }} 
在HTML输出,你应该可以看到检索ID

search ids: [1, 2, ...] 
+0

嘿,只有我得到的是:search ids:[] – Damian

+0

所以这意味着你的表是空的...尝试添加一些数据:) – Sergey

+0

像我回答18小时前,我发现其他解决方案在文档:) – Damian

0

好吧,我想我已经得到了这个。 我发现这个在文档:

from django.db import models 

class Person(models.Model): 
SHIRT_SIZES = (
    ('S', 'Small'), 
    ('M', 'Medium'), 
    ('L', 'Large'), 
) 
name = models.CharField(max_length=60) 
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES) 

,它的工作(显示)和形式是有效的:)我希望这将在接下来的步骤中工作。