What is the best approach to extending the Site model in django? Creating a new model and ForeignKey the Site or there another approach that allows me to subclass the Site model?
I prefer subclassing, because relationally I'm more comfortable, but I'm concerned for the impact it will have with the built-in Admin.
I just used my own subclass of Site and created a custom admin for it.
Basically, when you subclass a model in django it creates FK pointing to parent model and allows to access parent model's fields transparently- the same way you'd access parent class attributes in pyhon.
Built in admin won't suffer in any way, but you'll have to un-register Sites ModelAdmin and register your own ModelAdmin.
If you only want to change behaviour of the object, but not add any new fields, you should consider using a "proxy model" (new in Django 1.1). You can add extra Python methods to existing models, and more:
This is what proxy model inheritance is for: creating a proxy for the original model. You can create, delete and update instances of the proxy model and all the data will be saved as if you were using the original (non-proxied) model. The difference is that you can change things like the default model ordering or the default manager in the proxy, without having to alter the original.
Read more in the documentation.
As of Django 2.2 there still no simple straight way to extend Site as can be done for User. Best way to do it now is to create new entity and put parameters there. This is the only way if you want to leverage existing sites support.
class SiteProfile(models.Model):
title = models.TextField()
site = models.OneToOneField(Site, on_delete=models.CASCADE)
You will have to create admin for SiteProfile. Then add some SiteProfile records with linked Site. Now you can use site.siteprofile.title anywhere where you have access to current site from model.
You can have another model like SiteProfile which has a OneToOne relation with Site.
It has been a long time since the question was asked, but I think there is not yet (Django 3.1) an easy solution for it like creating a custom user model. In this case, creating a custom user model inheriting from django.contrib.auth.models.AbstractUser model and changing AUTH_USER_MODEL (in settings) to the newly created custom user model solves the issue.
However, it can be achieved for also Site model with a long solution written below:
SOLUTION
Suppose that you have an app with the name core. Use that app for all of the code below, except the settings file.
Create a SiteProfile model with a site field having an OneToOne relation with the Site model. I have also changed its app_label meta so it will be seen under the Sites app in the admin.
# in core.models
...
from django.contrib.sites.models import Site
from django.db import models
class SiteProfile(models.Model):
"""SiteProfile model is OneToOne related to Site model."""
site = models.OneToOneField(
Site, on_delete=models.CASCADE, primary_key=True,
related_name='profiles', verbose_name='site')
long_name = models.CharField(
max_length=255, blank=True, null=True)
meta_name = models.CharField(
max_length=255, blank=True, null=True)
def __str__(self):
return self.site.name
class Meta:
app_label = 'sites' # make it under sites app (in admin)
...
Register the model in the admin. (in core.admin)
What we did until now was good enough if you just want to create a site profile model. However, you will want the first profile to be created just after migration. Because the first site is created, but not the first profile related to it. If you don't want to create it by hand, you need the 3rd step.
Write below code in core.apps.py:
# in core.apps
...
from django.conf import settings
from django.db.models.signals import post_migrate
def create_default_site_profile(sender, **kwargs):
"""after migrations"""
from django.contrib.sites.models import Site
from core.models import SiteProfile
site = Site.objects.get(id=getattr(settings, 'SITE_ID', 1))
if not SiteProfile.objects.exists():
SiteProfile.objects.create(site=site)
class CoreConfig(AppConfig):
name = 'core'
def ready(self):
post_migrate.connect(create_default_site_profile, sender=self)
from .signals import (create_site_profile) # now create the second signal
The function (create_default_site_profile) will automatically create the first profile related to the first site after migration, using the post_migrate signal. However, you will need another signal (post_save), the last row of the above code.
If you do this step, your SiteProfile model will have a full connection with the Site model. A SiteProfile object is automatically created/updated when any Site object is created/updated. The signal is called from apps.py with the last row.
# in core.signals
from django.contrib.sites.models import Site
from django.db.models.signals import post_save, post_migrate
from django.dispatch import receiver
from .models import SiteProfile
#receiver(post_save, sender=Site)
def create_site_profile(sender, instance, **kwargs):
"""This signal creates/updates a SiteProfile object
after creating/updating a Site object.
"""
siteprofile, created = SiteProfile.objects.update_or_create(
site=instance
)
if not created:
siteprofile.save()
Would you like to use it on templates? e.g.
{{ site.name }}
Then you need the 5th and 6th steps.
Add the below code in settings.py > TEMPLATES > OPTIONS > context_processors
'core.context_processors.site_processor'
# in settings.py
TEMPLATES = [
{
# ...
'OPTIONS': {
'context_processors': [
# ...
# custom processor for getting the current site
'core.context_processors.site_processor',
],
},
},
]
Create a context_processors.py file in the core app with the code below.
A try-catch block is needed (catch part) to make it safer. If you delete all sites from the database you will have an error both in admin and on the front end pages. Error is Site matching query does not exist. So the catch block creates one if it is empty.
This solution may not be fully qualified if you have a second site and it is deleted. This solution only creates a site with id=1.
# in core.context_processors
from django.conf import settings
from django.contrib.sites.models import Site
def site_processor(request):
try:
return {
'site': Site.objects.get_current()
}
except:
Site.objects.create(
id=getattr(settings, 'SITE_ID', 1),
domain='example.com', name='example.com')
You can now use the site name, domain, meta_name, long_name, or any field you added, in your templates.
# e.g.
{{ site.name }}
{{ site.profiles.long_name }}
It normally adds two DB queries, one for File.objects and one for FileProfile.objects. However, as it is mentioned in the docs,
Django is clever enough to cache the current site at the first request and it serves the cached data at the subsequent calls.
https://docs.djangoproject.com/en/3.1/ref/contrib/sites/#caching-the-current-site-object
Apparently, you can also create a models.py file in a folder that you add to INSTALLED_APPS, with the following content:
from django.contrib.sites.models import Site as DjangoSite, SiteManager
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.http.request import split_domain_port
# our site model
class Site(DjangoSite):
settings = models.JSONField(blank=True, default={})
port = models.PositiveIntegerField(null=True)
protocol = models.CharField(default='http', max_length=5)
#property
def url(self):
if self.port:
host = f'{self.domain}:{self.port}'
else:
host = self.domain
return f'{self.protocol}://{host}/'
# patch django.contrib.sites.models.Site.objects to use our Site class
DjangoSite.objects.model = Site
# optionnal: override get_current to auto create site instances
old_get_current = SiteManager.get_current
def get_current(self, request=None):
try:
return old_get_current(self, request)
except (ImproperlyConfigured, Site.DoesNotExist):
if not request:
return Site(domain='localhost', name='localhost')
host = request.get_host()
domain, port = split_domain_port(host)
Site.objects.create(
name=domain.capitalize(),
domain=host,
port=port,
protocol=request.META['wsgi.url_scheme'],
)
return old_get_current(self, request)
SiteManager.get_current = get_current
In my opinion, the best way to doing this is by writing a model related to the site model using inheritance
First, add the site id to the Django settings file
SITE_ID = 1
now create a model in one of your apps
from django.db import models
from django.contrib.sites.models import Site
class Settings(Site):
field_a = models.CharField(max_length=150, null=True)
field_b = models.CharField(max_length=150, null=True)
class Meta:
verbose_name_plural = 'settings'
db_table = 'core_settings' # core is name of my app
def __str__(self) -> str:
return 'Settings'
then edit the apps.py file of that app
from django.apps import AppConfig
from django.db.models.signals import post_migrate
def build_settings(sender, **kwargs):
from django.contrib.sites.models import Site
from .models import Settings
if Settings.objects.count() < 1:
Settings.objects.create(site_ptr=Site.objects.first())
class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'project.apps.core'
def ready(self) -> None:
post_migrate.connect(build_settings, sender=self)
now every time you run migrations a row will be auto-generated in core_settings that have a one to one relationship with your Site model
and now you can access your settings like this
Site.objects.get_current().settings.access_id
optional: if have only one site
unregister site model from admin site and disable deleting and creating settings model in admin site
from django.contrib import admin
from . import models
from django.contrib.sites.models import Site
admin.site.unregister(Site)
#admin.register(models.Settings)
class SettingAdminModel(admin.ModelAdmin):
def has_delete_permission(self, request,obj=None) -> bool:
return False
def has_add_permission(self, request) -> bool:
return False
Related
I borrowed ideas from this answer to extend the default Site object created during the initial migration with Django sites framework. The new model, SiteSettings, establishes a OneToOne relationship with the Site model to add additional fields. I then use signals to create the SiteSettings object.
When I made the first migration for the SiteSettings model everything appeared to work fine. A SiteSettings object was created that had a OneToOne relationship with the default Site object.
However, what I didn't notice is that a migration file wasn't created under my local app for this. I was able to makemigrations and migrate just fine, so I'm not sure where that migration went. It's not listed in my migrations table.
Anyway, since it worked I didn't notice. I then proceeded to add additional fields to SiteSettings a day or two later, and noticed when I made those migrations, they were for creating a SiteSettings model, not updating its fields. That's when I noticed that the first migration wasn't created in the right spot. The second migration was created, however it was created in site-packages/django/contrib/sites/migrations/. It looks like this:
class Migration(migrations.Migration):
dependencies = [
("sites", "0002_alter_domain_unique"), # the initial auto migration
]
operations = [
migrations.CreateModel(
name="SiteSettings",
fields=[
(
"site",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
primary_key=True,
related_name="settings",
serialize=False,
to="sites.site",
verbose_name="site",
),
),
# A bunch of other CharFields that aren't important
],
options={
"verbose_name_plural": "settings",
},
),
]
And my models.py looks like this. I'm assuming the issue may be with the app_label matching the name of django.contrib.sites, but I'm not sure. The reason I named the label that was so it shows up under sites in the admin.
class SiteSettings(models.Model):
"""
Extension of the Sites model that holds more info about the site.
"""
site = models.OneToOneField(
Site,
on_delete=models.CASCADE,
primary_key=True,
related_name="settings",
verbose_name="site",
)
# A bunch of other fields that aren't important
def __str__(self):
return self.site.name
class Meta:
app_label = "sites"
verbose_name_plural = "settings"
Here's what the apps.py looks like:
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import post_migrate, post_save
def create_default_site_settings(sender, **kwargs):
"""Creates default site settings after migration"""
# App config must be ready for import to work
from django.contrib.sites.models import Site
from .models import SiteSettings
site = Site.objects.get(id=getattr(settings, "SITE_ID", 1))
if not SiteSettings.objects.exists():
SiteSettings.objects.create(site=site)
class CoreConfig(AppConfig):
name = "apps.core"
label = "core"
default_auto_field = "django.db.models.BigAutoField"
def ready(self):
# App config must be ready for import to work
from django.contrib.sites.models import Site
post_migrate.connect(create_default_site_settings, sender=self)
from .signals import create_site_settings
post_save.connect(create_site_settings, sender=Site)
And lastly, signals.py.
from django.contrib.sites.models import Site
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import SiteSettings
#receiver(post_save, sender=Site)
def create_site_settings(sender, instance, **kwargs):
"""
Creates/updates a SiteSettings object after a Site object.
"""
site_settings, created = SiteSettings.objects.update_or_create(site=instance)
if not created:
site_settings.save()
Is this simply an issue with the app_label being the same? I'm trying to wrap my head around why that is if so.
I figured out the issue. Since I was running my app in a Docker container and had the app_label in my new model set to the same app_label as django.contrib.sites, the migrations were being created in path/to/site-packages/django/contrib/sites/migrations/ in the Docker container. Not in the app copied to the container, but the actual Django install inside the container.
So that initial migration was created in the container and not locally which I didn't notice at first. Once my container was rebuilt at some point, the migration file was wiped since it freshly reinstalls all Python packages onto the new image. When I went to make the second migration, it was like the model was never created despite the table existing in the db.
To fix it, I reverted the app_label of the new model back to its default. Then I had to I had to rebuild the container, delete the old table site_sitesettings and remove the "lost" migration record in django_migrations table. During the next round of migrations a new table was created for core_sitesettings and I could access my OneToOne relationships as expected.
I'm developing a site where I can manually add photographers to the Django adminpanel and then upload the images taken by them.
I used the default User system in Django and added a field here that shows this user is a photographer or not :
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
is_photographer = models.BooleanField(default=True)
Also, in the model that I need to put the images, I used ManyToMany field for photographers (because these photos may have been taken by several people) :
from registration import User
class Photo(models.Model):
...
photographers = models.ManyToManyField(User)
The problem is that when adding a new image to the admin panel, users who are not photographers and the is_photographer is False, is also displayed in the Photographers. I want only users who are photographers to be displayed and not normal users.
You can use Django formfield. Django has placed these formfields for different types of fields. To use formfields in ManyToMany relationships, you can use formfield_for_manytomany in the model admin_class.
Try putting this function in the Photo model admin class in the admin.py file of the application where the Photo model is located, and if you don't have a class admin, create one like this:
from .models import Photo
from django.contrib import admin
from registration.models import User
class PhotoAdmin(admin.ModelAdmin):
def formfield_for_manytomany(self, db_field, request, **kwargs):
kwargs["queryset"] = User.objects.filter(is_photographer=True)
return super(PhotoAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Photo, PhotoAdmin)
In your admin.py file do this:
class PhotoAdmin(admin.ModelAdmin):
def formfield_for_manytomany(self, db_field, request, **kwargs):
kwargs['queryset'] = Users.objects.filter(is_photographer=True)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Photo, PhotoAdmin)
You can work with the limit_choices_to=… [Django-doc]:
from django.conf import settings
class Photo(models.Model):
# …
photographers = models.ManyToManyField(
setting.AUTH_USER_MODEL,
limit_choices_to={'is_photographer': True}
)
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
I want to customize Django Admin to have specific section for objects of my models (Such as Post or Product models) that use as an archive section.
I now that, I need one field in my models that shown status of objects (Such as is_archive field), but I don't have any idea about how to display them in Django Admin.
Does anyone have an opinion on this?
Create Proxy model for model you need
Create separate section in your admin panel for this proxy model
Override get_queryset() for it.
models.py
from django.db import models
class Post(models.Model):
...
is_archive = models.BooleanField(default = False)
...
class PostProxy(Post):
class Meta:
proxy = True
admin.py
from django.contrib import admin
from .models import *
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
...
#admin.register(PostProxy)
class PostProxyAdmin(admin.ModelAdmin):
...
def get_queryset(self, request):
return super().get_queryset(request).filter(is_archive=True)
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.
I have a model called "Organization" that I've setup as a User profile and I would like to have the fields from the "Organization" model show up on the registration page. How do I go about doing this with django-registration.
# models.py
class Organization(models.Model):
user = models.ForeignKey(User, unique=True)
logo = models.ImageField(upload_to='organizations')
name = models.CharField(max_length=100, null=True, unique=True)
# more fields below etc.
# settings.py
AUTH_PROFILE_MODULE = 'volunteering.organization'
The easiest way to do this would be [tested on django-registration 0.8]:
Somewhere in your project, say forms.py in your organization app
from registration.forms import RegistrationForm
from django.forms import ModelForm
from models import Organization
class OrganizationForm(forms.ModelForm):
class Meta:
model = Organization
RegistrationForm.base_fields.update(OrganizationForm.base_fields)
class CustomRegistrationForm(RegistrationForm):
def save(self, profile_callback=None):
user = super(CustomRegistrationForm, self).save(profile_callback=None)
org, c = Organization.objects.get_or_create(user=user, \
logo=self.cleaned_data['logo'], \
name=self.cleaned_data['name'])
Then in your root urlconf [but above the regex pattern that includes registration.urls and assuming that regex is r'^accounts/'] add:
from organization.forms import CustomRegistrationForm
urlpatterns += patterns('',
(r'^accounts/register/$', 'registration.views.register', {'form_class':CustomRegistrationForm}),
)
Obviously, you can also create a custom backend, but IMHO this is way easier.
The best way would be to create in the app where you have Organization a file (say, "forms.py"), and do this:
from registration.forms import RegistrationForm
from forms import *
from models import Organization
class RegistrationFormWithOrganization(RegistrationForm):
organization_logo = field.ImageField()
organization_name = field.CharField()
def save(self, profile_callback = None):
Organization.objects.get_or_create(user = self.cleaned_data['user'],
logo = self.cleaned_data['organization_logo'],
name = self.cleaned_data['organization_name'])
super(RegistrationFormWithOrganization, self).save(self, profile_callback)
And then in your base URLs, override the existing URL to registration, and add this form as your the form to use:
form organization.forms import RegistrationFormWithOrganization
url('^/registration/register$', 'registration.views.register',
{'form_class': RegistrationFormWithOrganization}),
url('^/registration/', include('registration.urls')),
Remember that Django will use the first URL that matches the regexp, so will match your call and not django-registration's. It will also tell registration to use your form, not its own. I've skipped a lot of validation here (and, probably, the derivation of the user object... if so, go read the source code to registration to see where it comes from), but this is definitely the right track to get a few things into the page with a minimum amount of effort on your part.
Modify the code as below and try again
urlpatterns += patterns('',
(r'^accounts/register/$', 'registration.views.register', {'form_class':CustomRegistrationForm,'backend': 'registration.backends.default.DefaultBackend'}),
)
"Previously, the form used to collect data during registration was expected to implement a save() method which would create the new user account. This is no longer the case; creating the account is handled by the backend, and so any custom logic should be moved into a custom
backend, or by connecting listeners to the signals sent during the registration process."
Details:
more info can be found here