简体   繁体   中英

Form fields | Django | ModelChoiceField

i can't find answer for my problem, so i ask you guys here. I'm trying make form with ModelChoiceField, all works (no error given) but still don't get any fields/options (blank Choice) and can't choose something. Here is my code

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())

Any ideas?

Try this:

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

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

make sure that you have data in your Search table. To test try this view:

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 template:

{{ form }}

<br/>

search ids:

{{ ids }}

in html output you should see search ids:

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

Ok, i think i've got this. I found this in documentation:

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)

And it's working (display) and a form is valid :) I hope this will be working at the next steps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM