1

I'm very new to Django and I'm trying to make it so that I could select several choices for a field, but I seem to be having problems with that

Here is simplified version of my model for a site

class Zone(models.Model): 
    zone = (
        ('NE','Northeast'),
        ('SE','Southeast'),
        ('SW','Southwest'),
        ('MW','Midwest'),
        ('CN','Canada'),
    )

class Site(models.Model):

    region = models.ManyToManyField(Zone)
    state = models.CharField(max_length = 30)
    ...


class SiteForm(ModelForm): 
    class Meta: 
        model = Site

Now, there are more zones than I'm showing here and potentially this means that a site may have several zone simultaneously.

Simple view function:

def add_site(request): 
    if request.method == 'POST':
        form = SiteForm(request.POST)
        if form.is_valid():
            profile = form.save(commit=False) 
            profile.user = request.user 
            profile.save()
        else:
            form = SiteForm()

    return render(request, 'index.html', {'form': form,})

It is my understanding that once the form is on the webpage, I should be presented with a box with he choices I specified in the Zone class, but the box is completely empty. How do I populate it with the choices such as Northwest, Southeast, Southwest, etc?

Rufat M
  • 33
  • 2

1 Answers1

1

This isn't quite how it works. Check out this definition in the django documentation. The example is pretty clear, but to you are also trying to do something really strange.

I suspect you were trying to create a separate model for your choices - to do that you would use a modelchoicefield or a modelmultiplechoicefield - for this you would just define your Zone model as an actual model; what you have isn't a Django model at all.

In addition "Site" is a django-provided model - you should be okay, but you can run into some hard-to-diagnose problems if you're also using the django contributed auth.

tsalaroth
  • 112
  • 9