How to connect with Django REST framework to front-end - python

I'm new on Django REST Framework. I have an index.html where I have simple form for adding items and back-end with Django. I can't understand, how I can connect index.html to Django REST Framework.
I have the next code-files:
models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
category = models.CharField(max_length=100)
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from django.views.generic import TemplateView
from .models import Book
from rest_framework import viewsets
from .serializers import BookSerializer
class Index(TemplateView):
template_name = "index.html"
def get_context_data(self):
context = super(Index, self).get_context_data()
return context
class BookViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Book.objects.all().order_by('title')
serializer_class = BookSerializer
urls.py
from django.conf.urls import url, include
from rest_framework import routers
from myapp import views
router = routers.DefaultRouter()
router.register(r'books', views.BookViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.Index, name='index'),
]
serializers.py
from .models import Book
from rest_framework import serializers
class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Book
fields = ('title','category')
And if I run localhost:8000/index I get an error 'Page not found'. I can't understand how correct I should include my html pages to the django code. Should I use a router.register for this?

Let's start by defining what django-rest-framework is and what it is not.
It is a nice toolkit to build web APIs. This means that you can define several endpoints (urls) that will handle incoming requests and will return a response in JSON or XML format.
It is not an html rendering tool though. This means that you can't return a response that contains html code to be rendered as a page in the browser. It will return pure json or xml data.
Now, your questions consists of 2 problems:
You can't access the index.html page.
You don't know how to connect this page with the books endpoint.
Regarding problem 1
Check the TEMPLATES settings. Where is your index.html placed? Does django know where to find it? Check out the TEMPLATES setting and assure you have set it up correctly.
Regarding problem 2
Because of the fact that the django-rest-framework endpoint handles incoming requests, you need to generate such a request. But if you will simply access the endpoint in your browser, the page will load/reload and you will see the data from your endpoint in json form on your page.
For your page to remain the same, but at the same time to make a request to your endpoint, you need to use ajax (Asynchronous JavaScript and XML) from within your index.html page. You can emit an ajax request by using one of the following:
With pure JavaScript, by means of XMLHttpRequest class. See this SO question and answers to see how this is made.
If you use jQuery, it has a jQuery.ajax() method to make an ajax request.
If you use any other frontend framework (angular, backbone, ember, etc.), all they have an implementation of ajax calls. Check their documentation for that.
And basically that's it. Good luck!

Could you try putting the api url after your index like this?
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.Index, name='index'),
url(r'^', include(router.urls)),
]
Or why not use /api/ for your REST Api urls:
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.Index, name='index'),
url(r'^api/', include(router.urls)),
]
And be sure that you have added 'rest_framework', to INSTALLED_APPS
EDIT:
To access /index/ you must fix your urls.py:
urlpatterns = [
url(r'^index/$', views.Index, name='index'),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

Related

how to read html file on Django

I started make a website for my school project, i use Django Frameworks
i want to make my homepage website, i already have html file, then what should i do to make Django read my homepage
enter image description here
this is my urls.py on main folder
urlpatterns = [
path('admin/', admin.site.urls),
path('katalog/', include('katalog.urls')),
path('', ) #what should i write here?
]
django doc: https://docs.djangoproject.com/en/3.0/topics/http/urls/#example, it offers the below example
from . import views
urlpatterns = [
path('articles/2003/', views.special_case_2003),
You have to create in your apps views.py file a FBV or CBV, the easiest is a FBV like below:
def someview(request):
context={}#if you want to add objects to the front end
return render(request, 'yourhtmlfile', context)
and then import it in your urls.py:
from . import views
urlpatterns = [
path('home/', views.someview),

Common start for url in all paths in team

I'm just working on a project in Django 1.11.
I have a problem with how to make a common beginning of the url.
For example, after creating a team, the address for all members should look like this:
domain.com/name_of_team
domain.com/name_of_team/blog
domain.com/name_of_team/blog/title_of_post
Main url file in project:
urlpatterns = [
url(r'', include('blog.urls', namespace='blog')),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^admin/', admin.site.urls),
]
Urls in blog:
url(r'^$', login_required(RedirectToHome.as_view()), name='redirect_home'),
url(r'^t/(?P<pk>[0-9]+)/$', login_required(BlogHome.as_view()), name='blog_list'),
url(r'create/$', login_required(BlogCreate.as_view()), name='blog_create'),
url(r'^(?P<pk>[0-9]+)/delete/$', login_required(BlogDelete.as_view()), name='blog_delete'),
url(r'^(?P<pk>[0-9]+)/update/$', login_required(BlogUpdate.as_view()), name='blog_update'),
url(r'^(?P<pk>\d+)?/?$', login_required(BlogDetail.as_view()), name='blog_detail'),
Maybe there are some good practices for dealing with url addresses?
To make the blog application specific to each team you could include it's URLs with;
url(r'^(?P<team_slug>[\w-]+)/', include('blog.urls', namespace='blog')),
This obviously assumes that your Team model has a slug field so that you can safely add it to the context & use it to form your URLs for the blog application.
You could then have a Mixin that could be shared by views in the blog or add something to a shared base view which loads the Team
from django.views.generic.base import ContextMixin
from .models import Team
class TeamMixin(ContextMixin):
def get_context_data(self, **kwargs):
context = super(TeamMixin, self).get_context_data(**kwargs)
context['team'] = Team.objects.get(slug=kwargs.get('team_slug'))
return context

django rest framework api documentation through swagger

It is already giving the swagger inbuilt page on localhost. It is reading my urls perfectly. But i am unable to define the interior headers, response body. I dont know where to define it and how to connect it with my django project.
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from users import views
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='Pastebin API')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/users/emailsignup/', views.SignUp.as_view()),
url(r'^api/v1/users/userget/', views.UserDetail.as_view()),
url(r'^$', schema_view),
]
Thus the schema_view is given . But plz expalain me how to define my response body in it with code.

TypeError: as_view() - Django

I got an error.
And i have no ideia how to fix it, take a look, this is the error:
TypeError: as_view() takes 1 positional argument but 2 were given
This as you can see is the code of my "model.py" page.
from django.db import models
from django.contrib.gis.db import models
class RoadsLines(models.Model):
gid = models.IntegerField()
geom = models.MultiLineStringField()
def __str__(self): # __unicode__ on Python 2
return '%s %s' % (self.gid, self.geom)
This as you can see is the code of my "views.py" page.
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from rest_framework import generics
from world.models import RoadsLines
from world.serializers import RoadsLinesSerializer
class ListCreateRoadsLines(generics.ListCreateAPIView):
queryset = RoadsLines.objects.all()
serializer_class = RoadsLinesSerializer
This as you can see is the code of my "urls.py" page.
from django.conf.urls import url, include
from rest_framework import routers, serializers, viewsets
from world import views
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'Roads', views.ListCreateRoadsLines)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api/', include('rest_framework.urls', namespace='rest_framework'))
]
What am I doing wrong?
Thank you in advance!
ListCreateRoadsLines is a view, not a viewset. You should include it in your url patterns, instead of trying to register it:
urlpatterns = [
url(r'^Roads$', views.ListCreateRoadsLines.as_view()),
url(r'^', include(router.urls)),
url(r'^api/', include('rest_framework.urls',
namespace='rest_framework'))
]

Django url not finding a template using CreateView in Class-Based Views

I have created a page where a user can add a new item (notes in this case) and I am making use of CBV which I have recently started learning.
This is my model form
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ('title', 'note', 'tags')
This is the view in views.py
class NoteCreate(CreateView):
model = Note
form_class = NoteForm
template_name = "add_note.html"
Then this is the url as I used in the urls.py of the app
from django.conf.urls import patterns, url
from . import views
from madNotes.views import NoteCreate, NoteIndex,
urlpatterns = patterns(
'',
url(r'^notes/add/$', NoteCreate.as_view(), name="new_note"),
url(r'^$', NoteIndex.as_view()),
url(r'^(?P<slug>\S+)/$', views.NoteDetail.as_view(), name="entry_detail"),
)
NB: I used the same url as the main page at 127.0.0.1:8000 in the projects urls.py file and it worked.
I have seen several tutorials and even the docs and can't seem to find what I am doing wrong. Will I also need to add a function in order for it to be saved in the db or the CBV will do it all?
EDit: The error I get is this
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/notes/add/
Here is the project's urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from MadNotez import settings
from registration.backends.default.views import RegistrationView
from madNotes.forms import ExRegistrationForm
if settings.DEBUG:
import debug_toolbar
urlpatterns = patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
url(r'accounts/register/$', RegistrationView.as_view(form_class = ExRegistrationForm), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^admin/', include(admin.site.urls)),
url('^markdown/', include('django_markdown.urls')),
url('^notes/', include('madNotes.urls')),
#url(r'^$', views.NoteCreate.as_view(), name="new note"), when I used it here it worked
)
you say that is the urls.py of the app, which means it is included by the project's urls.py.
As you show now, all the app's URIs go under the notes prefix:
url('^notes/', include('madNotes.urls')),
so as things stand at present the correct URI for the page is
http://127.0.0.1:8000/notes/notes/add/
In order to clean things up a bit, I'd suggest to modify the app's urls.py to
url(r'^add/$', NoteCreate.as_view(), name="new_note"),
so that the page can be reached at
http://127.0.0.1:8000/notes/add/
This way all the app's pages/services are available under the notes prefix and with a simple name that is consistent with their action (i.e. add, delete, etc)

Categories

Resources