Manager isn't available while setting up django-fmc - python

I'm trying to get django-fmc set up with Django (v 1.97, Python v2.7.12, djangorestframework v3.3.3) to handle storing registration ids and sending notifications to devices. I am following the tutorial they provide but it doesn't seem to be working.
I am getting the following error when running my local server and python manage.py fcm_urls:
...
File "C:\Work\Dev\LiveTracking\Api\app\views.py", line 50, in DeviceViewSet
queryset = Device.objects.all()
File "C:\Work\Dev\LiveTracking\Api\env\lib\site-packages\django\db\models\manager.py", line 277, in __get__
self.model._meta.swapped,
AttributeError: Manager isn't available; 'fcm.Device' has been swapped for 'app.MyDevice'
I don't want to add additional fields to the MyDevice model for now. I've looked all over but can't fix this error. If anyone can shed some insight into this error it would be much appreciated.
Here are some of my code snippets:
settings.py
INSTALLED_APPS = (
'fcm',
)
# Firebase Cloud Messaging Key
FCM_APIKEY = 'AIzaSyCaqHZIcaGDOpfTZUmAHEowsqD-fCtow6A'
# Location of device model
FCM_DEVICE_MODEL = 'app.MyDevice'
serializers.py
from fcm.models import Device
class DeviceSerializer(serializers.ModelSerializer):
class Meta:
model = Device
fields = ('dev_id','reg_id','name','is_active')
views.py
from rest_framework import viewsets
from fcm.models import Device
from fcm.serializers import DeviceSerializer
class DeviceViewSet(viewsets.ModelViewSet):
queryset = Device.objects.all()
serializer_class = DeviceSerializer
urls.py
from rest_framework import routers
from fcm.views import DeviceViewSet
router = routers.DefaultRouter()
router.register(r'devices', DeviceViewSet)
urlpatterns = [
url(r'^v1/', include(router.urls)),
]

swappable is an undocumented feature, actually only supposed to be used for custom User models. The doc on custom user models clearly states that once you use a custom user model, directly referencing contrib.auth.models.User won't work:
If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model.
You probably want to read the rest of this chapter FWIW.
To make a long story short: as Daniel Roseman mentions, you very probably want to use your own MyDevice model instead of the default Device one. And eventually contribute back a patch to django-fcm doc if it solves the issue.

Related

Access Django DB objects without shell?

I have a request - can you help me access and manage django DB objects without using shell ?
I have created my models, but now (for example) i want to make a login system. I store users and passes(again, only an example), and i want to get the info from the DB, but i dont want to use shell.
What can i do in this case, im quite new to Django ?!
Best Regards
Why not use django-admin?
Maybe this is what you want:https://docs.djangoproject.com/en/3.0/ref/contrib/admin/
In views.py you can import
from .models import modelname
data = modelname.objects.all() - using this you can get all the data from the Database
Eg:-
for d in data:
print (d.email)
Will give all emails in the database
You can also use
t = modelname.objects.get(email='name#lk.com')
By this you can get the data of the person who's email is name#lk.com
Django already has database support where you can register your models and access them with a graphical interface.
See the documentation: django-admin-site
First you need to create a super user account, if you don't have one, create it with the terminal in the project directory, use this row:
python manage.py createsuperuser
For your model to appear on the admin site you need to register it
# models.py
class MyModel(models.Model)
field1 = models.CharField()
field2 = models.TextField()
# ...
# admin.py
from django.contrib import admin
from .models import MyModel
admin.site.register(MyModel)
So it's the basic way to register your model, if you want to personalize you need to check the documentation ModelAdmin.fieldsets
with this done, just access the admin site at the link http://localhost:8000/admin/ and log in with the super user account and you will see the model registered.

Wagtail: Creating a custom API endpoint

I've created a Snippet called "Spotlights," and I'm wondering how I can create a custom endpoint for Snippet data with the Wagtail API. My best guess would be:
api_router.register_endpoint('Spotlights', BaseAPIEndpoint)
Is the first arg there establishing the name of the endpoint, or referencing something?
I've figured it out: just subclass Wagtail's BaseAPIEndpoint. For example:
endpoints.py
from wagtail.api.v2.endpoints import BaseAPIEndpoint
class SpotlightsAPIEndpoint(BaseAPIEndpoint):
...
model = Spotlight
api.py
from .endpoints import SpotlightsAPIEndpoint
api_router.register_endpoint('spotlights', SpotlightsAPIEndpoint)
Plus there are tons of ways to customize it. Just take a look at the endpoints.py file in the Wagtail repo: https://github.com/wagtail/wagtail/blob/master/wagtail/api/v2/endpoints.py
According to Wagtail documentation, the first parameter is the name of the endpoint (eg. pages, images) and this is used in the URL of the endpoint.
The second parameter is the endpoint class that handles the requests.
For example:
api_router.register_endpoint('pages', PagesAPIEndpoint)
api_router.register_endpoint('images', ImagesAPIEndpoint)
api_router.register_endpoint('documents', DocumentsAPIEndpoint)
So, I advise you to make like:
api_router.register_endpoint('spotlights', BaseAPIEndpoint)
Latest Wagtail version - 2.15 +
in your views file, import your model and BaseApiViewSet
from .models import CustomModel
from wagtail.api.v2.views import BaseAPIViewSet
class BusinessLocationViewSet(BaseAPIViewSet):
model = BusinessLocation
body_fields = BaseAPIViewSet.body_fields + ['id', 'field1', 'field2', 'field3', 'field4', etc, etc...]
and in the api.py file in the project folder, import your model and expose it to the api as follows:
from custommodel.views import MyModel
api_router.register_endpoint('custom', MyModel)
and now your model will be accessible from the api/v2/custom endpoint
I needed to modify glls's solution a bit to make it work. To expose the endpoint in api.py:
from .views import CustomViewSet
api_router.register_endpoint("custom", CustomViewSet)
It's also common to add filtering functionality. In views.py:
from wagtail.images.api.v2.views import BaseAPIViewSet, FieldsFilter
from .models import Custom
class CustomViewSet(BaseAPIViewSet):
model = Custom
body_fields = BaseAPIViewSet.body_fields + [
"name"
]
filter_backends = [
FieldsFilter
]
You can now filter the Custom snippet like normal: /api/v2/custom/?name=something

django framework can't see new model online

I have to make some modification to a website built with the django framework (version 1.6).
The problem I am having is that I can not transfer the modification I made offline to the online server. I can see the new page, the database has been modified, but in the administration website the new category I created does not appear, thus i can not fill the fields with the new information.
The steps I went through are:
create the new model in models.py,
import the model in admin.py,
execute the command: touch wsgi.py
in order to reload the file.
In the offline version everything is working fine. I do not know that to do!
Code I added in admin.py file (I added the "Article" section):
from active.models import x, z, y, j, Article
class ArticleAdmin(admin.ModelAdmin):
ordering = ["title"]
list_display = ('title',)
search_fields = ['title']
admin.site.register(Article, ArticleAdmin)
Solved.
There was no problem at all, simply the user I access the administration site with did not have the right access to see the new section!
Have you imported admin in the admin.py file?
from django.contrib import admin

Remove (or hide) default Permissions from Django

I'm developing a Django app that will have two administration backends. One for daily use by "normal" users and the default one for more advanced tasks and for the developers.
The application uses some custom permissions but none of the default ones. So I'm currently looking for a way to remove the default permissions, or at least a way to hide them from the "daily" admin backend without large modifications.
UPDATE: Django 1.7 supports the customization of default permissions
Original Answer
The following is valid for Django prior to version 1.7
This is standard functionality of the auth contrib application.
It handles the post_syncdb signal and creates the permissions (the standard 3: add, change, delete, plus any custom ones) for each model; they are stored in the auth_permission table in the database.
So, they will be created each time you run the syncdb management command
You have some choices. None is really elegant, but you can consider:
Dropping the auth contrib app and provide your own authentication backend.
Consequences -> you will lose the admin and other custom apps built on top of the auth User model, but if your application is highly customized that could be an option for you
Overriding the behaviour of the post_syncdb signal inside the auth app (inside \django\contrib\auth\management__init__.py file)
Consequences -> be aware that without the basic permissions the Django admin interface won't be able to work (and maybe other things as well).
Deleting the basic permissions (add, change, delete) for each model inside the auth_permission table (manually, with a script, or whatever).
Consequences -> you will lose the admin again, and you will need to delete them each time you run syncdb.
Building your own Permission application/system (with your own decorators, middlewares, etc..) or extending the existing one.
Consequences -> none, if you build it well - this is one of the cleanest solutions in my opinion.
A final consideration: changing the contrib applications or Django framework itself is never considered a good thing: you could break something and you will have hard times if you will need to upgrade to a newer version of Django.
So, if you want to be as clean as possibile, consider rolling your own permission system, or extending the standard one (django-guardian is a good example of an extension to django permissions). It won't take much effort, and you can build it the way it feels right for you, overcoming the limitations of the standard django permission system. And if you do a good work, you could also consider to open source it to enable other people using/improving your solution =)
I struggled with this same problem for a while and I think I've come up with a clean solution. Here's how you hide the permissions for Django's auth app:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib.auth.models import Permission
class MyGroupAdminForm(forms.ModelForm):
class Meta:
model = MyGroup
permissions = forms.ModelMultipleChoiceField(
Permission.objects.exclude(content_type__app_label='auth'),
widget=admin.widgets.FilteredSelectMultiple(_('permissions'), False))
class MyGroupAdmin(admin.ModelAdmin):
form = MyGroupAdminForm
search_fields = ('name',)
ordering = ('name',)
admin.site.unregister(Group)
admin.site.register(MyGroup, MyGroupAdmin)
Of course it can easily be modified to hide whatever permissions you want. Let me know if this works for you.
A new feature introduced in Django 1.7 is the ability to define the default permissions. As stated in the documentation if you set this to empty none of the default permissions will be created.
A working example would be:
class Blar1(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, unique = True, blank = False, null = False, verbose_name= "Name")
class Meta:
default_permissions = ()
ShadowCloud gave a good rundown. Here's a simple way to accomplish your goal.
Add these line in your admin.py:
from django.contrib.auth.models import Permission
admin.site.register(Permission)
You can now add/change/delete permissions in the admin. Remove the unused ones and when you have what you want, go back and remove these two lines from admin.py.
As was mentioned by others, a subsequent syncdb will put everything back.
Built on top of the solution by #pmdarrow, I've come up with a relatively clean solution to patch the Django admin views.
See: https://gist.github.com/vdboor/6280390
It extends the User and Group admin to hide certain permissions.
You can't easily delete those permissions (so that syncdb won't put them back), but you can hide them from the admin interface. The idea is, as described by others, to override the admin forms but you have to do this for both users and groups.
Here is the admin.py with the solution:
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Permission
from django.contrib.auth.models import User, Group
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.contrib.auth.forms import UserChangeForm
#
# In the models listed below standard permissions "add_model", "change_model"
# and "delete_model" will be created by syncdb, but hidden from admin interface.
# This is convenient in case you use your own set of permissions so the list
# in the admin interface wont be confusing.
# Feel free to add your models here. The first element is the app name (this is
# the directory your app is in) and the second element is the name of your model
# from models.py module of your app (Note: both names must be lowercased).
#
MODELS_TO_HIDE_STD_PERMISSIONS = (
("myapp", "mymodel"),
)
def _get_corrected_permissions():
perms = Permission.objects.all()
for app_name, model_name in MODELS_TO_HIDE_STD_PERMISSIONS:
perms = perms.exclude(content_type__app_label=app_name, codename='add_%s' % model_name)
perms = perms.exclude(content_type__app_label=app_name, codename='change_%s' % model_name)
perms = perms.exclude(content_type__app_label=app_name, codename='delete_%s' % model_name)
return perms
class MyGroupAdminForm(forms.ModelForm):
class Meta:
model = Group
permissions = forms.ModelMultipleChoiceField(
_get_corrected_permissions(),
widget=admin.widgets.FilteredSelectMultiple(('permissions'), False),
help_text = 'Hold down "Control", or "Command" on a Mac, to select more than one.'
)
class MyGroupAdmin(GroupAdmin):
form = MyGroupAdminForm
class MyUserChangeForm(UserChangeForm):
user_permissions = forms.ModelMultipleChoiceField(
_get_corrected_permissions(),
widget=admin.widgets.FilteredSelectMultiple(('user_permissions'), False),
help_text = 'Hold down "Control", or "Command" on a Mac, to select more than one.'
)
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
admin.site.unregister(Group)
admin.site.register(Group, MyGroupAdmin)
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
If you are creating your own user management backend and only want to show your custom permissions you can filter out the default permissions by excluding permission with a name that starts with "Can".
WARNING:
You must remember not to name your permissions starting with "Can"!!!!
If they decide to change the naming convention this might not work.
With credit to pmdarrow this is how I did this in my project:
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.models import Permission
from django.contrib import admin
class UserEditForm(UserChangeForm):
class Meta:
model = User
exclude = (
'last_login',
'is_superuser',
'is_staff',
'date_joined',
)
user_permissions = forms.ModelMultipleChoiceField(
Permission.objects.exclude(name__startswith='Can'),
widget=admin.widgets.FilteredSelectMultiple(_('permissions'), False))
If you want to prevent Django from creating permissions, you can block the signals from being sent.
If you put this into a management/init.py in any app, it will bind to the signal handler before the auth framework has a chance (taking advantage of the dispatch_uid debouncing).
from django.db.models import signals
def do_nothing(*args, **kwargs):
pass
signals.post_syncdb.connect(do_nothing, dispatch_uid="django.contrib.auth.management.create_permissions")
signals.post_syncdb.connect(do_nothing, dispatch_uid="django.contrib.auth.management.create_superuser")

Nested inlines in the Django admin?

Alright, I have a fairly simple design.
class Update(models.Model):
pub_date = models.DateField()
title = models.CharField(max_length=512)
class Post(models.Model):
update = models.ForeignKey(Update)
body = models.TextField()
order = models.PositiveIntegerField(blank=True)
class Media(models.Model):
post = models.ForeignKey(Post)
thumb = models.ImageField(upload_to='frontpage')
fullImagePath = models.ImageField(upload_to='frontpage')
Is there an easy-ish way to allow a user to create an update all on one page?
What I want is for a user to be able to go to the admin interface, add a new Update, and then while editing an Update add one or more Posts, with each Post having one or more Media items. In addition, I want the user to be able to reorder Posts within an update.
My current attempt has the following in admin.py:
class MediaInline(admin.StackedInline):
model = Media
class PostAdmin(admin.ModelAdmin):
inlines = [MediaInline,]
This let's the user add a new Post item, select the relevant Update, add the Media items to it, and hit save - which is fine. But there's no way to see all the Posts that belong to a given Update in a single place, which in turn means you can't roderder Posts within an update. It's really quite confusing for the end user.
Help?
As of now there is no "built-in" way to have nested inlines (inline inside inline) in django.contrib.admin. Pulling something like this off is possible by having your own ModelAdmin and InlineModelAdmin subclasses that would enable this kind of functionality. See the patches on this ticket http://code.djangoproject.com/ticket/9025 for ideas on how to implement this. You'd also need to provide your own templates that would have nested iteration over both the top level inline and it's child inline.
There is now this egg available, which is a collation of the relevant patches mentioned in the other answer:
https://github.com/theatlantic/django-nested-admin
I have done this using https://github.com/theatlantic/django-nested-admin, for the following Data structure:
Contest
Judges
Contestants
Singers
Songs
My admin.pyfile:
from django.contrib import admin
import nested_admin
from .models import Contest, Contestant, Judge, Song, Singer
class SongInline(nested_admin.NestedTabularInline):
model = Song
extra = 0
class SingerInline(nested_admin.NestedTabularInline):
model = Singer
extra = 0
class ContestantInline(nested_admin.NestedTabularInline):
model = Contestant
inlines = [SongInline, SingerInline]
extra = 0
class JudgeInline(nested_admin.NestedTabularInline):
model = Judge
extra = 0
class ContestAdmin(nested_admin.NestedModelAdmin):
model = Contest
inlines = [ContestantInline, JudgeInline]
extra = 0
admin.site.register(Contest, ContestAdmin)
https://github.com/theatlantic/django-nested-admin appears to be much more actively maintained than the other apps already mentioned (https://github.com/BertrandBordage/django-super-inlines and https://github.com/Soaa-/django-nested-inlines)
I have just ran into this issue as well... Seems this thread which contains the request for the nested inlines feature (https://code.djangoproject.com/ticket/9025#no2) has been updated with further information.
A custom made app called "django-super-inline" has been released. More details here: https://github.com/BertrandBordage/django-super-inlines
Installation and usage instructions below.
Hope this is useful for whomever comes across this.
I ran into a similar issue to this. My approach was to make an UpdateAdmin that held inlines for both Media and Post... it basically just makes it so you have a list of all of the media entries followed by all of the posts in an update.
class MediaInline(admin.StackedInline):
model = Media
class PostInline(admin.StackedInline):
model = Post
class PostAdmin(admin.ModelAdmin):
inlines = [MediaInline,]
class UpdateAdmin(admin.ModelAdmin):
inlines = [MediaInline,PostInline]
It isn't an ideal solution but it works for a quick and dirty work around.
Use django-nested-admin which is the best package to do nested inlines.
First, install "django-nested-admin":
pip install django-nested-admin
Then, add "nested_admin" to "INSTALLED_APPS" in "settings.py":
# "settings.py"
INSTALLED_APPS = (
# ...
"nested_admin", # Here
)
Then, add "path('_nested_ad..." to "urlpatterns" in "urls.py":
# "urls.py"
from django.urls import include, path
urlpatterns = [
# ...
path('_nested_admin/', include('nested_admin.urls')), # Here
]
Finally, extend "NestedTabularInline" with "MediaInline()" and "PostInline()" classes and extend "NestedModelAdmin" with "UpdateAdmin()" class in "admin.py" as shown below:
# "admin.py"
from .models import Media, Post, Update
from nested_admin import NestedTabularInline, NestedModelAdmin
class MediaInline(NestedTabularInline):
model = Media
class PostInline(NestedTabularInline):
model = Post
inlines = [MediaInline]
#admin.register(Update)
class UpdateAdmin(NestedModelAdmin):
inlines = [PostInline]

Categories

Resources