views:

715

answers:

2

Hello, I am trying to make a many to one relationship and want to be able to control it (add -remove etc) via the admin panel. So this is my model.py:

from django.db import models

class Office(models.Model):
    name = models.CharField(max_length=30)


class Province(models.Model):
    numberPlate = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=20)
    office = models.ForeignKey(Office)

I want my model allow a province to have several Office.

So inside my admin.py:

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

class OfficeCreator(admin.ModelAdmin):
        list_display = ['name']

This seems correct to me, however when I try to add a new province with the admin panel, I get this:

TemplateSyntaxError at /admin/haritaapp/province/

Caught an exception while rendering: no such column: haritaapp_province.office_id

Thanks

A: 

Have you looked at the docs for doing Inlines?

In your admin.py

class Office(admin.TabularInline):
    model = Office

class ProvinceAdmin(admin.ModelAdmin):
    inlines = [
        Office,
    ]
+3  A: 

It seams that you have your models setup backwards. If you want province to have many offices, then province should be a foreign key in the Office model.

from django.db import models

class Province(models.Model):
    numberPlate = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=20)


class Office(models.Model):
    name = models.CharField(max_length=30)
    province = models.ForeignKey(Province)

This would be straightforward and very intuitive way to implement one-to-many relationsship

As for the error that you are getting "no such column: haritaapp_province.office_id", when you add a new attribute (in your case office) to the model, you should either manually add column to the table. Or drop the table and re-run the syncdb:

 python manage.py syncdb

Django will not automatically add new columns to the table when you add new fields to the model.

finally I could get it working, even " python manage.py syncdb" wouldn't enough so I had to delete the sqlite3 db and regen it :) One small question tho, foreign items show as Province_object while selecting/adding. How to fix it so it displays the name instead ?Regards
oh self edit: def __unicode__(self): return self.namedid the job for me :p