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)
Related
Actually i have created my own custom-user (MyUser) in models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class MyUser(AbstractUser):
country=models.CharField(max_length=20)
settings.py
AUTH_USER_MODEL = 'new_user.MyUser'
I created a simple function in views.py to create new users.
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth import get_user_model
from django.conf import settings
def save_account(request):
MyUser=get_user_model()
if request.method == "POST":
name=request.POST.get("name")
email=request.POST.get("email")
password1=request.POST.get("password1")
password2=request.POST.get("confirm-password")
country=request.POST.get("country")
new_user=MyUser.objects.create_user(username=name,email=email,password=password1,country=country)
new_user.save()
return redirect('/')
else:
return HttpResponse("404 Not Found")
1. Here i use get_user_model() function to get my currently custom-user.
2. I have second option to get my custom user just by importing MyUser model from models.py and then use it.
from .models import MyUser
3. I have third option to get custom-user just by importing AUTH_USER_MODEL directly from settings.py and use it like in this way.
from django.conf import settings
MyUser=settings.AUTH_USER_MODEL
but third option returning a string instead of returning my custom-user.but why?
I just want to know that which option is best to import custom-user in views.py and why?
Your first two options are both ok. Using get_user_model makes it easier to reuse the app without changing the import. However many Django projects are not meant to be re-used, in which case the explicit import makes it clearer where the user model is imported from.
settings.AUTH_USER_MODEL is meant to be a string. You set it to a string when you did AUTH_USER_MODEL = 'new_user.MyUser', and Django doesn't automatically change it to the model instance when you access it. It's useful in foreign keys because it means you don't need to import the model. For example:
class MyModel(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
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'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.
in django by default when syncdb is run with django.contrib.auth installed, it creates default permissions on each model... like foo.can_change , foo.can_delete and foo.can_add. To add custom permissions to models one can add class Meta: under the model and define permissions there, as explained here https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#custom-permissions
My question is that what should I do if I want to add a custom permission to the User model? like foo.can_view. I could do this with the following snippet,
ct = ContentType.objects.get(app_label='auth', model='user')
perm = Permission.objects.create(codename='can_view', name='Can View Users',
content_type=ct)
perm.save()
But I want something that plays nicely with syncdb, for example the class Meta under my custom models. Should I just have these in class Meta: under UserProfile since that is the way to extend the user model. but is that the RIGHT way to do it? Wouldn't that tie it to UserProfile model?
You could do something like this:
in the __init__.py of your Django app add:
from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import Permission
# custom user related permissions
def add_user_permissions(sender, **kwargs):
ct = ContentType.objects.get(app_label='auth', model='user')
perm, created = Permission.objects.get_or_create(codename='can_view', name='Can View Users', content_type=ct)
post_syncdb.connect(add_user_permissions, sender=auth_models)
I don't think there is a "right" answer here, but i used the exact same code as you except i changed Permission.objects.create to Permission.objects.get_or_create and that worked find to sync with syncdb
An updated answer for Django 1.8. The signal pre_migrate is used instead of pre_syncdb, since syncdb is deprecated and the docs recommend using pre_migrate instead of post_migrate if the signal will alter the database. Also, #receiver is used to connect add_user_permissions to the signal.
from django.db.models.signals import pre_migrate
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import Permission
from django.conf import settings
from django.dispatch import receiver
# custom user related permissions
#receiver(pre_migrate, sender=auth_models)
def add_user_permissions(sender, **kwargs):
content_type = ContentType.objects.get_for_model(settings.AUTH_USER_MODEL)
Permission.objects.get_or_create(codename='view_user', name='View user', content_type=content_type)
This is a bit hacky but mentioning it here anyway for reference.
My site has a generic model called Setting, which stores various settings concerning the site I want certain users to be able to edit, without needing to go through me the developer (like registration limit, or an address, or the cost of items, etc).
All the permissions that don't nicely map onto other models (eg "Send Password Reminder Email to Student", "Generate Payment Reconciliation Report", "Generate PDF Receipt"), which really just relate to pages that get viewed in the admin area, get dumped onto this Setting model.
For example, here's the model:
class Setting(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(editable=False)
description = models.TextField()
value = models.TextField()
class Meta:
#for permissions that don't really relate to a particular model, and I don't want to programmatically create them.
permissions = (
("password_reminder", "Send Password Reminder"),
("generate_payment_reconciliation_report", "Generate Payment Reconciliation Report"),
("generate_pdf_receipt", "Generate PDF Receipt"),
)
Do each of those settings strictly relate to the Setting model? No, which is why I said this is a bit hacky. But it is nice that I can now just dump all those permissions here, and Django's migration commands will take care of the rest.