I'm working on a simple DRF API and I can't seem to access one of my many models from the admin site, although I can access some models from the same Application, please help!
project/app/models.py looks something like this:
class ImportantModel(models.Model):
name = # character field
relation1 = # foreign key
relation2 = # foreign key
...
class Contact(models.Model):
information = # character field
...
The problem is I can see the Contact model(and multiple other models) from the admin site(http://localhost:8000/admin/) but ImportantModel is not showing. Thank you in advance.
You need to register your model in admin.py file.
Well I was in same problem because the problem is I registered my models in admin.py file but in a wrong way
wrong way:
from django.contrib import admin
from .models import Article
from .models import User
# Register your models here.
admin.register(Article)
admin.register(User)
And the right way is
right way:
from django.contrib import admin
from .models import Article
from .models import User
# Register your models here.
admin.site.register(Article)
admin.site.register(User)
Related
Embrassing question.
I cannot seem to be able to add new models.
I have list of models in my models.py file which appear in admin panel.
However, the new model I am trying to add does not appear.
What makes it embarrassing is that it was showing earlier this afternoon.
I made some changes to the code and clearly something went wrong. I deleted the code, hoping this might resolve the problem, but no.
Just in case it would be related to the actual model I was creating, I completly change the code to something simple (see below) but again no change.
I am not too sure what I clicked, deleted to make this happen.
Any clues?
(PS: I did do the migrations.)
(PS2: there is post about user permission. Where the user didnt have the right level of permissions to see the models which is why the model couldnt be seen. In my case, Im logged in as the superuser so this problem shouldnt be relevant for me)
from django.db import models
from django.contrib.auth.models import User
from decimal import Decimal
import locale
import logging
...
class Event(models.Model):
name = models.CharField('Venue Name', max_length=120)
def __str__(self):
return self.name
##EDIT##
admin.py
from .models import Event
from django.urls import path
from django.shortcuts import render
from import_export.admin import ImportExportModelAdmin
# Register your models here.
admin.site.register(Event)
I've followed the documentation at https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#substituting-a-custom-user-model, but for some reason things still aren't working for me. I can create and login to User accounts, but for some reason I can't view them with the admin. This leads me to believe they're not being registered correctly, but as said before, I've followed the documentation on how to do that:
sign_up/models.py
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
pass
sign_up/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
# Register your models here.
admin.register(User, UserAdmin)
site/settings.py
# define custom user model
AUTH_USER_MODEL = 'sign_up.User'
I've also tried deleting my database and migrations and reapplying them, but this still isn't helping.
not this
admin.register(User, UserAdmin)
but this
admin.site.register(User, UserAdmin)
I need to get to the search_fields property defined on the admin options for a model. A long time ago it was really simple and direct (but undocumented), i.e. model._meta.admin.search_fields.
Getting to the admin is the hard part, and the closest I could get was:
def admin_options(model):
from django.contrib import admin
return admin.site._registry.get(model)
I couldn't find the ._registry member documented (and the underscore seems to imply that it isn't public). This also doesn't work for sites that haven't run admin.autodiscover(). The fallback-code does this:
try:
appname = model.__module__.split('.models')[0]
admin_module = appname + '.admin'
__import__(admin_module) # registers admin option classes with AdminSite
except:
return None
else:
return admin.site._registry.get(model)
Is there an official (or simpler) way to get the admin options for a model?
first create model
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
class LocationCode(models.Model):
"""
A web service that will allow user to create there price rule based on conditions
"""
name = models.CharField(max_length=255)
code = models.CharField(max_length=255)
def __unicode__(self):
return self.name
in admin.py you need to add code
from django.contrib import admin
from dx_man.models import LocationCode
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class LocationAdmin(admin.ModelAdmin):
list_display=[]
for x in LocationCode._meta.get_all_field_names():
list_display.append(str(x))
admin.site.register(LocationCode, LocationAdmin)
in url.py add these line
from django.contrib import admin
admin.autodiscover()
You need to ensure the registration code has been run or the site will not contain the (model, modeladmin) in the _registry.
code.py
from django.contrib.admin.sites import site
# run admin registration code before we get here
for model, model_admin in site._registry.items():
if model == whatevermodel:
print(model_admin.search_fields)
Any suggestion on this please?
Initially I had class Customer(): in models.py
This is how the code in admin.py looked
from django.contrib import admin
from booknowapp.models import Customer
# Register your models here.
admin.site.register(Customer)
Now that I have added two new classes to models how do I register in admin for other new two classes to appear in the app? I am not sure of the syntax to be used.
If your added two new classes of models are ModelClass1 and ModelClass2 then you can register multiple models in admin.py like :
from django.contrib import admin
from booknowapp.models import Customer, ModelClass1, ModelClass2
myModels = [Customer, ModelClass1, ModelClass2] # iterable list
admin.site.register(myModels)
OR
You can repeat admin.site.register for other two new classes just like your Customer .
If you extend the syntax that you have already used, it would simply be:
from django.contrib import admin
# wrap the line if it's too long
from booknowapp.models import (
Customer,
SecondModel,
ThirdModel
)
# Register your models here.
admin.site.register(Customer)
admin.site.register(SecondModel)
admin.site.register(ThirdModel)
However, this will only give you the default admin model list views - which you will probably want to extend.
class CustomerAdmin(admin.ModelAdmin):
"""Specialised admin view for the Customer model."""
# set the fields to display
list_display = ('name', 'address', 'registered')
# register your Customer model, using the CustomerAdmin view
admin.site.register(Customer, CustomerAdmin)
The ModelAdmin has lots more functionality that you can leverage - search fields, filtering, custom fields, custom actions ('Activate customer'), which you can read about here - http://www.djangobook.com/en/2.0/chapter06.html#custom-modeladmin-classes
I'm trying to extend default Django's model with a new field.
In localsite/models.py I have the following code:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from satchmo_store.contact.models import Organization
class OrganizationExtra(models.Model):
organization = models.OneToOneField(Organization,
verbose_name=_('Organization'), primary_key=True )
vat_number = models.CharField(_('VAT'), max_length=12)
Followed with run of ./manage.py syncdb which did created a new table for above model. So far so good.
Now I'm trying to add this new field in related Organization view in the admin interface.
The following code registers the new menu, however the new vat_number field is not displayed in view of the related Organization model.
from django.contrib import admin
from localsite.models import ProductResource, OrganizationExtra
admin.site.register(OrganizationExtra)
The original Organization model is registered with
from satchmo_store.contact.models import Organization
from django.contrib import admin
class OrganizationOptions(admin.ModelAdmin):
list_filter = ['type', 'role']
list_display = ['name', 'type', 'role']
admin.site.register(Organization, OrganizationOptions)
Any idea how to insert my new field without touching original Satchmo sources ?
See the docs as usual.
One possible way is to create new MyOrganization derived from Organization and register it in place of satchmo one
Your models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from satchmo_store.contact.models import Organization
class MyOrganization(Organization):
vat_number = models.CharField(_('VAT'), max_length=12)
Your admin.py
from django.contrib import admin
from localsite.models import MyOrganization
from satchmo_store.contact.models import Organization
from satchmo_store.contact.admin import OrganizationOptions
admin.site.unregister(Organization)
admin.site.register(MyOrganization, OrganizationOptions)
Another possible solution (if you wish to stick with OrganizationExtra) is to create custom form for Organization for admin interface and again reregister model. By it seems to me as more boilerplate and result will be the same.
NB: in both cases DB structure would be the same, i.e. extra table would be created.