Extending user model is causing an HTTP 400 error - django

I followed the Django documentation to try to extend my user model to add a field called authentication_key. It is resulting in an HTTP 400 error when I test the site locally.
My models:
class AuthenticationKey(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
authentication_key = models.CharField(max_length=100)
My Admin:
class AuthenticationKeyInline(admin.StackedInline):
model = AuthenticationKey
can_delete = False
verbose_name_plural = 'AuthenticationKey'
# Defines a new User admin
class UserAdmin(BaseUserAdmin):
inlines = (AuthenticationKeyInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
And how I'm referring to the field in my views.py
#login_required(login_url='/login/')
def home_page(request):
u_id = request.user.authenticationkey
url = "http://example.com/api/allrequests/?format=json"
response = urlopen(url)
data = response.read().decode("utf-8")
j_data = json.loads(data)
j_data = json.dumps(j_data)
url = "http://example.com/api/past24hrdialoguebyid/" + str(u_id) + "/?format=json"
response = urlopen(url)
m_data = response.read().decode("utf-8")
return render(request,'index.html',{"u_id":u_id,"j_data":str(data),"m_data":str(m_data)});
I'm thinking the error may be how I'm referring to the field in views but I can't figure out quite what's wrong.
Here are my URL Patters:
urlpatterns = [
path('admin/', admin.site.urls),
path('home/', home_page),
path('public/', public),
path('room-queue/', room_queue),
path('all-requests/', all_requests),
path('add-data/', add_data),
path('room-api/', room_api),
path('delete-data/', delete_data),
path('login/', auth_views.LoginView.as_view(template_name='admin/login.html')),
path('index-add-guest/', add_guest),
path('send-reply/', send_reply),
path('room-ready/', room_ready),
]

request.user.authenticationkey does not exist, since you have not defined authenticationkey as a property of the User model.
As already defined in your code, you should access the authentication key this way:
from .models import AuthenticationKey
authkey = AuthenticationKey.objects.get(user=request.user)
u_id = authkey.authentication_key
if you want to access authenticationkey as a property of user then you have to extend the User model by subclassing AbstractUser or AbstractBaseUser.
For instance, in your models.py
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
authenticationkey = models.CharField(max_length=100)
In settings.py file, update the AUTH_USER_MODEL
AUTH_USER_MODEL = 'appname.models.User'
make sure you apply the migrations. You should then be able to access
request.user.authenticationkey
remember to update your admin too
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)

Related

TypeError: 'MediaDefiningClass' object is not iterable | summernote integration in django admin (SOLVED)

I am trying to intregrate django-summernote in my blog post admin area.
when I set summernote_fields = ('description',) and register to admin area, I am getting error like below :
for model in model_or_iterable:
TypeError: 'MediaDefiningClass' object is not iterable
My admin.py is given below :
from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin
from .models import Blog
class BlogPostSummerNote(SummernoteModelAdmin):
summernote_fields = ('description',)
#admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
list_display = ('title','slug','author','publish','status')
prepopulated_fields = {'slug':('title',)}
admin.site.register(BlogPostSummerNote)
I can't able to figure this out . Can any one tell me why this is happening ??
############# SOLUTION #################
I Solved this problem by doing as below in admin.py:
from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin
from .models import Blog
#admin.register(Blog)
class BlogPostSummerNote(SummernoteModelAdmin):
list_display = ('title','slug','author','publish','status')
summernote_fields = ('description',)
prepopulated_fields = {'slug':('title',)}

Getting AttributeError while registering my model to Django admin?

What i am trying to do:
Trying to registering my model to django admin
What problem do i get:
I am getting the following error:
My Code:
admin.py:
from django.contrib import admin
from .models import UserProfile, Post
admin.site.register(UserProfile,Post)
model.py:
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='static/media/',max_length=100)
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
urls.py:
from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^register/$',views.registerUser),
url(r'^$', views.index, name="Index"),
url(r'^validateRegisterForm/$',views.validateRegisterForm),
url(r'^validateLoginForm/$',views.validateLoginForm),
url(r'^article/$', views.article, name="Article"),
url(r'^Login/$',views.loginUser, name="Login"),
url(r'^Logout/$',views.logoutUser, name="Logout"),
]
Note: I am new to django so, don't know much about it.
This should be
admin.site.register(UserProfile)
admin.site.register(Post)
Admin.site.register takes two parameters, the first is the model class and the optional second parameter is an admin class. In your code, you were passing another model as the admin class.
for more information, please refer to :https://docs.djangoproject.com/en/1.10/ref/contrib/admin/

Django-registration-redux adding custom fields to app

I need to add custom fields to Django-registration-redux such as picture and few other fields. Is there a ref or 2 liner guide for how to do it? As per docs I can call RegistrationView in my app views and import my own created model fields to override it. If this is right approach please let me know.
You have to define your custom form and then set your registration url to use the custom form.
Defining your custom form:
users/form.py
from registration.forms import RegistrationForm
from users.models import User
class CustomRegistrationForm(RegistrationForm):
class Meta:
model = User
fields = ('email', 'picture', 'password',)
Your main urls file:
project_name/urls.py
from users.forms import CustomRegistrationForm
urlpatterns = [
[...]
url(r'^registration/register/$', RegistrationView.as_view(
form_class=CustomRegistrationForm), name='registration_register',),
url(r'^registration/', include('registration.backends.default.urls')),
[...]
]

Can't create HyperlinkedRelatedField in Django Rest Framework

I'm struggling to get HyperlinkedRelated fields working, and I can't figure out where I'm going wrong. No matter what I do, I get an error like:
Could not resolve URL for hyperlinked relationship using view name "court-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.
I feel that I've tried everything and I don't know where my error could be, nor how to identify it. My reading of this error message is that I am looking for a URL that corresponds to the court-detail view, but that that view doesn't exist.
Some piece of magic isn't working and any help would be greatly appreciated.
URLs:
from cl.api import views
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'courts', views.CourtViewSet)
router.register(r'dockets', views.DocketViewSet)
router.register(r'clusters', views.OpinionClusterViewSet)
router.register(r'opinions', views.OpinionViewSet)
router.register(r'cited-by', views.OpinionsCitedViewSet)
urlpatterns = [
# url(r'^api/rest/(?P<version>[v3]+)/', include(router.urls)),
url(r'^api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
url(r'^', include(router.urls)),
]
Views:
class DocketViewSet(viewsets.ModelViewSet):
queryset = Docket.objects.all()
serializer_class = serializers.DocketSerializer
class CourtViewSet(viewsets.ModelViewSet):
queryset = Court.objects.all()
serializer_class = serializers.CourtSerializer
class OpinionClusterViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
"""
queryset = OpinionCluster.objects.all()
serializer_class = serializers.OpinionClusterSerializer
class OpinionViewSet(viewsets.ModelViewSet):
queryset = Opinion.objects.all()
serializer_class = serializers.OpinionSerializer
class OpinionsCitedViewSet(viewsets.ModelViewSet):
queryset = OpinionsCited.objects.all()
serializer_class = serializers.OpinionsCitedSerializer
Serializers:
from cl.audio import models as audio_models
from cl.search import models as search_models
from rest_framework import serializers
class DocketSerializer(serializers.HyperlinkedModelSerializer):
court = serializers.HyperlinkedRelatedField(
many=False,
view_name='court-detail',
read_only=True
)
class Meta:
model = search_models.Docket
fields = ('date_created', 'date_modified', 'date_argued',
'date_reargued', 'date_reargument_denied', 'court')
class CourtSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = search_models.Court
class AudioSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = audio_models.Audio
class OpinionClusterSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = search_models.OpinionCluster
fields = ('judges', 'per_curiam', )
class OpinionSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = search_models.Opinion
fields = ('pk',)
class OpinionsCitedSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = search_models.OpinionsCited
When I go to:
http://127.0.0.1:8000/dockets/
It tells gives me the error message above. Of course, if I remove the court reference from the serialization, it works fine...
I imagine this can be caused by a number of things, but in my case, I figured out that it was caused by having DEFAULT_VERSIONING_CLASS set without having it configured in the urls.py:
REST_FRAMEWORK = {
# Use URL-based versioning
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning',
'DEFAULT_VERSION': 'v3',
'ALLOWED_VERSIONS': {'v3'},
}
The solution, therefore, was either to disable it in the settings, or to set up a url in in urls.py that accepted the version parameter:
url(r'^api/rest/(?P<version>[v3]+)/', include(router.urls)),
Ugh. Took a long time to realize I had this setting in place. Bad error message.

In Django admin, how to filter users by group?

It gives you filter by staff status and superuser status, but what about groups?
Since version 1.3 it can be done using this:
list_filter = ('groups__name')
Of course as #S.Lott explains you must register your customized class in the admin.py file:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyUserAdmin(UserAdmin):
list_filter = UserAdmin.list_filter + ('groups__name',)
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
See Customizing an Admin form in Django while also using autodiscover
Essentially, you define a customized Admin class with the features you want.
Then unregister and register your revised Admin class.
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
Here is a complete example, that inherits from SimpleListFilter, which is available in Django 1.4 and up.
https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
It support setting all available labels and parameters to create the completely custom filter.
It shows up as "By group" in the filter panel, with a list of all available groups.
from django.contrib.admin import SimpleListFilter
from django.contrib.auth.models import Group
from django.utils.translation import ugettext as _
class GroupListFilter(SimpleListFilter):
title = _('group')
parameter_name = 'group'
def lookups(self, request, model_admin):
items = ()
for group in Group.objects.all():
items += ((str(group.id), str(group.name),),)
return items
def queryset(self, request, queryset):
group_id = request.GET.get(self.parameter_name, None)
if group_id:
return queryset.filter(groups=group_id)
return queryset
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyUserAdmin(UserAdmin):
list_filter = UserAdmin.list_filter + (GroupListFilter,)
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
In later versions of Django, it works exactly as you'd expect:
list_filter = ('groups', )
No need to unregister/register the admin class.