Django REST Framework without Auth - python

Im trying to create a basic view using the Django REST framework without requiring authentication.
Settings.py
THIRD_PARTY_APPS = (
'south', # Database migration helpers:
'crispy_forms', # Form layouts
'rest_framework',
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
)
}
urls.py
router = routers.DefaultRouter()
router.register(r'ticket', views.TicketViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^test', include('rest_framework.urls', namespace='rest_framework')),
)
Serializers
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class TicketInputSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Abc
fields = ('test')
Models
from django.db import models
class Abc(models.Model):
test = models.CharField(max_length=12)
Error
When trying to get to the URI i get the following,
Page Not Found 404
Using the URLconf defined in config.urls, Django tried these URL patterns, in this order:
^test ^login/$ [name='login']
^test ^logout/$ [name='logout']
Any ideas ?

Related

How to HyperlinkedRelatedField into a model from different app?

bellow is urls.py of users app.
from django.urls import path
from . import views
app_name = 'users'
urlpatterns = [
path('', views.UserList.as_view(), name='user-list'),
path('<int:id>/', views.UserDetail.as_view(), name='user-detail'),
]
url conf of snippets app:
from django.urls import path
from . import views
app_name = 'snippets'
urlpatterns = [
path('', views.SnippetList.as_view(), name='snippet-list'),
path('<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'),
path('<int:pk>/highlight/', views.SnippetHighlight.as_view(), name='snippet-highlight'),
]
and here's SnippetSerializer
from rest_framework import serializers
from . import models
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Snippet
fields = ['id', 'owner', 'title', 'code', 'highlight', 'linenos', 'language', 'style']
highlight = serializers.HyperlinkedIdentityField(view_name='snippets:snippet-highlight', format='html')
owner = serializers.HyperlinkedRelatedField(
read_only=True,
view_name='users:user-detail'
)
The error I got
ImproperlyConfigured at /snippets/
Could not resolve URL for hyperlinked relationship using view name "users:user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.
My mistake was that I specified id instead of pk in url pattern of users app.
Such things make me feel frustrated.

SimpleJwtAuthentication problem ...Even after presence of user ,url not giving token

i am using this model extending from abstractuser but even after successfully creating user i am not able to get the tokens....
Tokens are genrerated only for those which i created through python manage.py createsuperuser ..others not working.
why????
i am using simplejwt authentication.
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class user_model(AbstractUser):
email=models.CharField(max_length=200,blank=True)
age=models.CharField(max_length=200,blank=True)
dob=models.CharField(max_length=200,blank=True)
phone=models.CharField(max_length=200,blank=True)
def __str__(self):
return self.username
urls.py
from django.contrib import admin
from django.urls import path,include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('signup/',include('userdata.urls')),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('loggedIn/',include("notes.urls")),
]

Django REST Framework got Server Error 500

I followed the turial at django-rest-framework quickstart
I have two URLs namely /users/ and /groups/
The group works perfectly:
but the user url gets a error like this:
server error 500
I set DEBUG to False then add some host to ALLOWED_HOST in settings.py:
DEBUG = False
ALLOWED_HOSTS = [
'127.0.0.1',
'localhost'
]
INSTALLED_APPS = [
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
my urls.py:
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from django_rest.django_rest_app import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
this is my serializers.py:
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url','username','email','group']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url','name']
and this is my views.py:
from django.shortcuts import render
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from django_rest.django_rest_app.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]
UPDATE
when I set DEBUG to True again, I got this:
Field name group is not valid for model User
I'm still a beginner, I hope you can help
Thanks.
You have made mistake in UserSerializer class
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url','username','email','group']
Please change as follows
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url','username','email','groups']
there is no field named 'group' in User model. Instead it is 'groups'.

Struggling to get django_comments to work with Django REST Framework

I'm using Django REST Framework for the first time on a project and I'm struggling with one particular part. The project is an issue tracker-type applicaton and it uses django_comments to allow for comments on issues. I'm now building an API on top of it to allow for creating a mobile app.
I've created the following serializers:
from django.contrib.auth.models import User
from todolist.models import Project, Issue
from rest_framework import serializers
from django_comments.models import Comment
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'first_name', 'last_name')
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ('name', 'description', 'owner')
class CommentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Comment
class IssueSerializer(serializers.HyperlinkedModelSerializer):
comments = CommentSerializer(many=True)
class Meta:
model = Issue
And here's my project-wide urls.py, where I define the routes:
from django.conf.urls import patterns, include, url
from todolist.views import HomeTemplateView, UserViewSet, ProjectViewSet, IssueViewSet, CommentViewSet
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'projects', ProjectViewSet)
router.register(r'issues', IssueViewSet)
router.register(r'comments', CommentViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'projectile.views.home', name='home'),
# url(r'^projectile/', include('projectile.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# Comments
(r'^comments/', include('django_comments.urls')),
# Login
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
# Logout
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login', {'login_url': '/accounts/login/'}),
# To-do list
url(r'^projects/', include('todolist.urls')),
# Home page
url(r'^$', HomeTemplateView.as_view(
template_name="todolist/home.html",
)),
# Router URLs
url(r'^api/', include(router.urls)),
# REST framework auth URLs
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api-token-auth/', obtain_auth_token),
# API docs
url(r'^docs/', include('rest_framework_swagger.urls'))
)
I'm seeing the following error when I run a test which tries to get all the comments:
ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "contenttype-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
Also, when I fetch an issue, it doesn't include the comments.
Now, this error appears to me to be that when fetching a comment, it's unable to match up the comment to its parent. I've experienced similar problems when using Tastypie in the past, and I'm unsure how to resolve it with DRF.
In your Comment serializer, specify comment instances fields explicitly and exclude field contenttype.
class CommentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Comment
fields = ('field_1','field_2','field_3') #here goes your comment fields and dont include contenttype field
The problem is that DRF will try to apply hyperlinks to represent all relationships, and for contenttype field you don't have a view or a serializer and you dont need it either.

Can we use the login page at /admin in django for our own use?

Can I use the login page available at: /admin for non-staff users to login? I'm using the following settings in my django settings file:
LOGIN_URL = '/admin/'
LOGIN_REDIRECT_URL = '/'
When I login, it doesn't redirect me to the root folder. Am I doing it the right way?
Note: I'm using decorator #login_required on my view.
Edit
It logs me in to admin site with this URL: http://127.0.0.1:8000/admin/?next=/
Non-staff members can't login through the admin view, so you can't.
There is a Django view that does exactly what you need, however: django.contrib.auth.views.login
You can easily add it to your urlconf:
from django.contrib.auth.views import login
urlpatterns = ('',
#snip
url(r'^login/$', login)
)
Check the documentation to see how you can customize its behavior: https://docs.djangoproject.com/en/dev/topics/auth/#limiting-access-to-logged-in-users
You'll only need to define a template for the view to use, by default, it should be located at registration/login.html, but that can be overriden.
UPDATE
1) For django 1.11+ better use LoginView (i.e. from django.contrib.auth.views import LoginView) since login code actually uses LoginView and the code of login even has a warning messge:
warnings.warn(
'The login() view is superseded by the class-based LoginView().',
RemovedInDjango21Warning, stacklevel=2
)
2) You may want to change the default header of admin's login page. That can be done by providing site_header in context.
So updated version would look like this:
from django.contrib.auth.views import LoginView
urlpatterns = [
# your patterns here,
url(r'^login/$',
LoginView.as_view(
template_name='admin/login.html',
extra_context={
'site_header': 'My custom header',
})),
]
With Django 1.6 I was able to use django's own admin login template with the following setup.
Then when I open '/' it will redirect me to the login screen, and after logging in it sends me back to '/'
settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
'south',
)
LOGIN_URL = '/login'
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.auth.views import login
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^', include('core.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^login/$', login, {'template_name': 'admin/login.html'})
# I didn't create this 'admin/login.html' template
# Django will use the one from the admin application ;-)
)
core/urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns(
'core.views.web_views',
url(r'^$', 'home'),
)
core/views/web_views.py
from django.shortcuts import render_to_response
from django.template.context import RequestContext
__author__ = 'tony'
from django.contrib.auth.decorators import login_required
#login_required
def home(request):
return render_to_response('home.html', {}, context_instance = RequestContext(request))

Categories