field choices() as queryset?

前端 未结 4 1876
难免孤独
难免孤独 2020-12-09 10:46

I need to make a form, which have 1 select and 1 text input. Select must be taken from database. model looks like this:

class Province(models.Model):
    nam         


        
4条回答
  •  忘掉有多难
    2020-12-09 11:41

    Read Maersu's answer for the method that just "works".

    If you want to customize, know that choices takes a list of tuples, ie (('val','display_val'), (...), ...)

    Choices doc:

    An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.

    from django.forms.widgets import Select
    
    
    class ProvinceForm(ModelForm):
        class Meta:
            CHOICES = Province.objects.all()
    
            model = Province
            fields = ('name',)
            widgets = {
                'name': Select(choices=( (x.id, x.name) for x in CHOICES )),
            }
    

提交回复
热议问题