views:

600

answers:

1

Greetings, I have these 2 models:

from django.db import models

class Office(models.Model):
    name = models.CharField(max_length=30)
    person = models.CharField(max_length=30)
    phone = models.CharField(max_length=20)
    fax = models.CharField(max_length=20)
    address = models.CharField(max_length=100)
    def __unicode__(self):
            return self.name



class Province(models.Model):
    numberPlate = models.IntegerField(primary_key=True)
        name = models.CharField(max_length=20)
    content = models.TextField()
    office = models.ForeignKey(Office)
    def __unicode__(self):
            return self.name

I want to be able to select several Offices for Provinces, which is a one to many model. Here is my admin.py:

from harita.haritaapp.models import Province, Office
from django.contrib import admin


class ProvinceCreator(admin.ModelAdmin):
        list_display = ['name', 'numberPlate','content','office']

class OfficeCreator(admin.ModelAdmin):
        list_display = ['name','person','phone','fax','address']


admin.site.register(Province, ProvinceCreator)
admin.site.register(Office, OfficeCreator)

Right now, I am able to select one Office per Province at the admin panel while creating a new Province but I want to be able to select more than one. How can I achieve this?

Regards

A: 

I'm not sure if I'm misunderstanding you, but your models currently say "an office can be associated with many provinces, but each province may only have one office". This contradicts what you want. Use a ManyToMany field instead:

class Province(models.Model):
    numberPlate = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=20)
    content = models.TextField()
    office = models.ManyToManyField(Office)
    def __unicode__(self):
        return self.name
Cide
thanks, now working like a charm! I guess I misunderstood the meaning of one to many at django.Just a quick note for future viewers, I also had to change the ProvinceCreator as list_display doesn't allow ManyToManyFields:class ProvinceCreator(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('name', 'numberPlate', 'content', 'office') }), )Cheers!
Cide