Chris Harty
Chris Harty

Reputation: 73

How to add a Model (not an app) to django?

I am using django 1.3 and just trying to add a simple model(not an app) to the admin site. so i have tried:

from django.db import models

class UserProfile(models.Model):
    notes = models.TextField(db_name="Notes", max_length=15)

    def _str_(self):
        return self.notes

    class Admin:
        pass

and have also tried creating the admin.py file in the site root and in the /static/admin/ directory and have attempted two standard entries for it as follows:

from django.contrib import admin
from mock.models import UserProfile                                       

admin.site.register(UserProfile)

and

from django.contrib import admin
from mock.models import UserProfile

class UserProfileAdmin(admin.ModelAdmin):                                               
    pass                                                                                

admin.site.register(UserProfile, UserProfileAdmin)

any help would be much appreciated. Thank you very much.

Upvotes: 0

Views: 872

Answers (1)

Alasdair
Alasdair

Reputation: 308939

Don't define your Admin class in the model itself like below. That's the really old way to do it, from before Django 1.0. I'm not sure what tutorial or documentation you are using, but it's very out of date.

class UserProfile(models.Model):
    notes = models.TextField(db_name="Notes", max_length=15)
    # don't do this!
    class Admin:
        pass

Defining a UserProfileAdmin is the correct approach. The admin.py file should not go in the /static/admin/. The static directory is for static files like CSS stylesheets and javascript files, not for Django code.

As for your question of whether you can define a model without defining an app, it's not a really good idea. Lots of parts of django assume that each model belongs to an app. For example the database table name is appname_modelname.

Creating an app doesn't take too long. Run the startapp command and it will create the base directory and files.

./manage.py startapp <appname>

All you then need to do is add the new app to INSTALLED_APPS, and create your admin.py file.

As your project gets bigger, keeping models in apps will keep it more organized. Many Django users create an app named utils (or similar) for the odd model.

Upvotes: 2

Related Questions