0

This is a very simple question, how can I create dropdown field in Django with only specific categories(something similar to the countries dropdown, but not with countries).

Antoni4040
  • 2,297
  • 11
  • 44
  • 56

2 Answers2

2

With the choice attribute of a Field if it is for fixed values. Or with a ForeignKey field if the Categories should be created dynamicly.

For the ForeignKey field you would do the following:

from django.db import models

class Category(models.Model):
    name = models.Charfield(max_length=255)
    # ...

    def __str__(self):
        return self.name

class Item(models.Model):
    category = models.ForeignKey(Category)
    # ...
NEOatNHNG
  • 904
  • 6
  • 9
1

Django's most powerful feature is to offer you direct forms. It's a broad question but you want to define a model that can be paired with a form that you can put in a template. Take a look here: https://docs.djangoproject.com/en/1.8/topics/forms/ and here: Django options field with categories and here Creating a dynamic choice field

Community
  • 1
  • 1
zom-pro
  • 1,571
  • 2
  • 16
  • 32
  • I'm sorry, I wasn't very clear. I mean a categories field for the database. The dropdown menu will be in the admin page. – Antoni4040 Aug 08 '15 at 21:28
  • I'm not sure if I fully understand what you want to achieve. Do you want a limited number of categories or a field in the database where you can define as many categories as you like? Are you looking something like this? https://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield – zom-pro Aug 08 '15 at 21:32
  • You could call it a textfield but with a limited amount of possible values, and I want to be able to add more options in the future. I'm sorry, I don't know how else to describe it... – Antoni4040 Aug 08 '15 at 21:34
  • You can use ChoiceField with choices. Take a look here: http://stackoverflow.com/questions/3419997/creating-a-dynamic-choice-field – zom-pro Aug 08 '15 at 21:35