How to get user details in serializer in Django rest framework? - python

I am trying to get users details from django using rest framework. but there is error:
module 'core.model' has no attribute 'Users'
to do that I added this line in settings.py:
REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER':'users.serializers.userSerializer' }
Since it is a model of Django auth and in my models.py there is no model of such users it is from Django auth model and I don't know how to access the data from it.
from rest_framework import serializers
from core import models
class userSerializer(serializers.ModelSerializer):
class Meta:
fields=(
'id',
'username')
model=models.Users
Here is the screenshot of my django admin:

We must import User model like:
from django.contrib.auth.models import User

It seems that you have a custom User model inside the core app.
Be sure you have substituted your User model inside settings.py:
AUTH_USER_MODEL = 'myapp.MyUser'
Would be 'core.User' in your case, I believe.
Then to reference your custom user model you can possibly:
from rest_framework import serializers
from django.conf import settings
from core import models
class userSerializer(serializers.ModelSerializer):
class Meta:
fields=(
'id',
'username')
model=settings.AUTH_USER_MODEL
or
from rest_framework import serializers
from django.contrib.auth import get_user_model
from core import models
class userSerializer(serializers.ModelSerializer):
class Meta:
fields=(
'id',
'username')
model=get_user_model()

Related

Import-export module works not with User model for me in Django

I am trying to import new users to original User model form the Django admin site. I used to add the users one-by-one manually to the model but now I need to import lots of users and I need a solution to bulk import. I tried the code below, but I have an error:
django.contrib.admin.sites.NotRegistered: The model User is not registered
Please help me to solve this.
admin.py
from django.contrib import admin
from django.contrib.auth.models import User
from import_export.admin import ImportExportModelAdmin
from import_export import resources
class UserResource(resources.ModelResource):
class Meta:
model = User
fields = ('id','username','first_name', 'last_name', 'email' 'password1', 'password2')
class UserAdmin(ImportExportModelAdmin):
list_display = ('id','username','first_name', 'last_name', 'email')
resource_class = UserResource
pass
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

No user link in auth section of Django admin

I am trying to implement a custom user model, but under the auth url localhost:8000/admin/auth/ of the Django admin website my model is not showing up.
I found an answer at the link below to the overall problem, but when trying to implement it myself I still do not see the users in the auth section of the Django admin.
No “Users” link in “Auth” section of Django admin site
what am I doing wrong here ?
models.py
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
CustomUser = get_user_model()
class CustomUserAdmin(UserAdmin):
form = CustomUserChangeForm
add_form = CustomUserCreationForm
model = CustomUser
list_display = (
"email",
"username",
)
fieldsets = (
(None, {"fields": ("email", "password")}),
("Permissions", {"fields": ("is_admin", "groups", "user_permissions")}),
)
admin.site.register(CustomUser, CustomUserAdmin)
forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ("email", "username")
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ("email", "username")
I faced the same problem:
created my own user model
in admin, groups and my user model are not listed in same (auth) section
My solution was basically to put django groups into my app to have it displayed in the same section, because django creates admin sections for each app.
create your own group model as proxy object in your models.py
from django.contrib.auth.models import Group as DjangoGroup
...
class Group(DjangoGroup):
class Meta:
proxy = True
verbose_name = _('group')
verbose_name_plural = _('groups')
(un)register your models in admin.py
from django.contrib.auth.admin import GroupAdmin as DjangoGroupAdmin
from django.contrib.auth.models import Group as DjangoGroup
from .models import CustomUser, Group
...
admin.site.register(CustomUser, CustomUserAdmin)
admin.site.unregister(DjangoGroup)
admin.site.register(Group, DjangoGroupAdmin)

Multiple view set into router Django rest framework

I have a problem with DRF
I have a model
from django.contrib.sites.models import Site
class Person(models.Model):
site = ForeignKey(Site, on_delete=models.CASCADE)
I want to create a viewset and serializer and I want to get the specific url:
/api/sites/{pk}/persons/
And get all persons that They have associate site
Or
/api/sites/{pk}/persons/{pk}
How can I do?
Try this
# serializers.py
from rest_framework import serializers
class PersonSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Person
# views.py
from rest_framework.viewsets import ModelViewSet
class PersonViewset(ModelViewSet):
serializer_class = PersonSerializer
def get_queryset(self):
return Person.objects.filter(site_id=int(self.kwargs['site_id']))
router config will be as
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'/api/sites/<site_id>/persons', views.PersonViewset)

django.core.exceptions.FieldError: Unknown field(s) (email) specified for Profile

I am trying to customize djoser's createuser end point. For that I have installed django custom user following this link https://github.com/jcugat/django-custom-user. Here is my models.py
from django.db import models
from custom_user.models import AbstractBaseUser
class Profile(AbstractBaseUser):
account_address = models.CharField(max_length=30, blank=True)
and serializers.py
from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer
class UserRegistrationSerializer(BaseUserRegistrationSerializer):
class Meta(BaseUserRegistrationSerializer.Meta):
fields = ('url', 'id', 'email', 'first_name', 'account_address', 'password')
and in app.admin.py i have registered it in following way.
from django.contrib import admin
from custom_user.admin import UserAdmin
from .models import Profile
class MyCustomEmailUserAdmin(UserAdmin):
"""
You can customize the interface of your model here.
"""
pass
# Register your models here.
admin.site.register(Profile, UserAdmin)
but when I am trying to makemigrations i am running into following error.
any clue what's wrong here?
From the looks of it, you seem to have the following in your settings:
AUTH_USER_MODEL = "your_app.Profile"
And for your profile model, you are inheriting from AbstractBaseUser which is actually from from django.contrib.auth.models import AbstractBaseUser.
I believe you meant to inherit from AbstractEmailUser. Thus, your "Profile" model would actually need be:
from custom_user.models import AbstractEmailUser
class Profile(AbstractEmailUser):
account_address = models.CharField(max_length=30, blank=True)

How to move model to the other section in Django's site admin

Is it possible to move default Groups model from 'Authentication and Authoriation' section (on the Django admin site) to custom one and how to achieve that?
Let's start from the beginning in the other words.
I have a very simple application 'accounts' in my Django project.
models.py file looks like below:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
def __str__(self):
return self.email
serializers.py file:
from rest_framework import serializers
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
class UserSerializer(serializers.HyperlinkedModelSerializer):
groups = serializers.HyperlinkedRelatedField(
many=True,
required=False,
read_only=True,
view_name="group-detail"
)
class Meta:
model = get_user_model()
exclude = ('user_permissions',)
Now, on the admin site I have two sections: 'Accounts' and 'Authentication and Authorization'. 'Accounts' section contains my 'Users' table (for User model) and 'Authentication and Authorization' section contains 'Groups' table (for Django's default authorization Group model).
My question is - is it possible and how to move Groups table (model) to the 'Accounts' section?
I've even tried to create a custom 'Group' model based on Django's default auth Group model but have stuck on migration exceptions.
Is it possible to move default Groups model from 'Authentication and Authoriation' section (on the Django admin site) to custom one and how to achieve that?
Yes, it's possible.
1) You can move your model to section auth, just add to your class:
class Meta:
app_label = 'auth'
2) You can move Group and User models to your app section, for that variant need to:
Override user model and add it to your app
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
also need add to your project settings AUTH_USER_MODEL = 'your_app.CustomUser'
Don't forget declare in admin.py from your app:
class UserAdmin(admin.ModelAdmin):
pass
admin.site.register(CustomUser, UserAdmin)
For group model put this code in admin.py:
from django.db.models.loading import get_models
from django.contrib.auth import models
models = get_models(models)
models[1]._meta.app_label = 'your_app'
3) You can look at django-admin-tools

Categories