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.
Related
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)
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)
i would like to export to a XLS file my data in the Admin, i tried Import-Export (with admin integration) and works great, the problem here is, i'm already using a model, so i need to export a proxy model to XLS, can you help me please?, with this code the model appears, and the import, export menu appears too, but when i try to export or import i got this error:
**StopIteration
No exception message supplied**
Admin.py:
from django.contrib import admin
from models import *
from django.utils.html import format_html_join
from import_export import resources
from import_export.admin import ImportExportModelAdmin
class ExportarDatosPromo(Promo):
class Meta:
proxy = True
class PromoCountResource(resources.ModelResource):
class Meta:
model = Promo
class PromoCountAdmin(ImportExportModelAdmin):
fields = ('name', 'title_description1', 'description1', 'offer', 'coupon_code', 'count')
readonly_fields = ('name', 'title_description1', 'description1', 'offer', 'coupon_code', 'count')
admin.site.register(ExportarDatosPromo, PromoCountAdmin)
Well, because nobody answer anything, i fix my error. The problem is, if you have a Taggit (Django-Taggit) field in your model, Django Import-Export App will not work, so you have to delete the field (and there is no other app for tagging actually working), and import-export will work just fine.
If you want to continue to use django taggit as an app, just put your field in a model with a foreign key to your original model.
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 learning Python Django framework. Thanks to StackOverFlow Community, i have learned how to use open-id in django (social_auth i'm using ).
with social_auth, sign in and sign out process are pretty easy and practical. But i want to build friendship relationship between users, for this i created new model class which is extended from from django.contrib.auth.models import User and add control when new user is created in auth_table, i create new user on CustomUser Table.(It is not efficient because the parameters coming from open-id are different for each open-id connection)
My model code is here
from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import UserManager
# Create your models here.
class CustomUser(User):
gender = models.CharField(max_length=50)
location = models.CharField(max_length=50)
bio = models.CharField(max_length=50)
web_pages = models.CharField(max_length=50)
friends = models.ManyToManyField("self")
And How can i use CustomUser model and OpenID together in Django for authentication?
Any Help will be appreciated.
The way to extend the User class in Django is to provide user profile class. See here. You can then just use the User model as always and get the profile instance on demand.