1

我没有使用 admin.py 有什么方法可以让我使用外键字段而不是下拉选择框,一个动态搜索框(对用户建议),就像我们在 admin.py 中有 raw_id_fields 一样。

模型.py

class model2(models.Model)
     reg = models.ForeignKey(model1, db_column='reg')
     class Meta:
         db_table = u'table2'

表格.py

class model2Form(ModelFOrm)
    def __init__(self, *args, **kwargs):
        super(model2Form, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.id:
            self.fields['reg'].required = False
            self.fields['reg'].widget.attrs['disabled'] = 'disabled'
    def clean_regid(self):
        if self.instance and self.instance.pk:
            return self.instance.reg
        else:
            return self.cleaned_data['reg']
    class Meta:
        model = model2
        exclude = ('id')

视图.py

def add(request):
    if request.method == 'POST': # If the form has been submitted...
        form = model2Form(request.POST)
        if form.is_valid():
           form.save()
           return list(request) 
        else :
            raise RuntimeError('Form is invalid')
    else :
        action = model2().get_add_url()
        form = model2Form()
        c = {'form': form, 'action' : action}
        c.update(csrf(request))
        return render_to_response('add.html', c, context_instance=RequestContext(request))
4

1 回答 1

1

您可以轻松拥有自动完成功能

于 2012-10-21T09:57:20.937 回答