banner



How To Use Poll In Python

Django Polls Tutorial API

The polls tutorial is the official guide to Django. As a fun exercise, I wanted to show how piddling lawmaking information technology takes to transform it into a robust API using Django Residuum Framework.

This tutorial assumes yous already take Python3 and pipenv installed. You can find detailed instructions here.

Installation

To start we need to create a new directory for our code, install Django and Django Rest Framework, make a new projection config and then a new app polls.

            $ mkdir polls            &&            cd            polls $ pipenv install django~=            3.one.0            djangorestframework            ==            iii.12.0 $ pipenv shell            (polls)            $ django-admin startproject config .            (polls)            $ python manage.py startapp polls          

Update our settings.py file with our new apps and besides arrange the timezone since each poll is timestamped. I'yard based on the east coast of the U.S. so my timezone is New_York. Here is a list of all timezones.

                        # config/settings.py            ...            INSTALLED_APPS            =            [            ...            'rest_framework'            ,            'polls'            ,            ]            TIME_ZONE            =            'America/New_York'          

The simply code that carries over from the original polls tutorial is the database model. Here it is for a Question and and then a related Option.

                        # polls/models.py            import            datetime            from            django.db            import            models            from            django.utils            import            timezone            class            Question            (            models            .            Model            ):            question_text            =            models            .            CharField            (            max_length            =            200            )            pub_date            =            models            .            DateTimeField            (            'appointment published'            )            def            was_published_recently            (            self            ):            now            =            timezone            .            at present            ()            return            now            -            datetime            .            timedelta            (            days            =            ane            )            <=            self            .            pub_date            <=            now            def            __str__            (            self            ):            return            self            .            question_text            grade            Choice            (            models            .            Model            ):            question            =            models            .            ForeignKey            (            Question            ,            on_delete            =            models            .            CASCADE            )            choice_text            =            models            .            CharField            (            max_length            =            200            )            votes            =            models            .            IntegerField            (            default            =            0            )            def            __str__            (            cocky            ):            return            self            .            choice_text          

Now we demand to fix our urls. We'll place our polls content at api/ as follows.

                        # config/urls.py            from            django.urls            import            include            ,            path            from            django.contrib            import            admin            urlpatterns            =            [            path            (            'api/'            ,            include            (            'polls.urls'            )),            path            (            'admin/'            ,            admin            .            site            .            urls            ),            ]          

Within the polls app we demand to create urls.py and serializers.py files.

                        (polls) $ touch polls/urls.py            (polls) $ bear on polls/serializers.py          

For the polls/urls.py file we'll be using viewsets to simplify the code.

                        # polls/urls.py            from            django.urls            import            path            from            .views            import            QuestionViewSet            from            rest_framework.routers            import            DefaultRouter            router            =            DefaultRouter            ()            router            .            register            (            ''            ,            QuestionViewSet            ,            basename            =            'questions'            )            urlpatterns            =            router            .            urls          

Our serializer exposes all fields plus the id field Django automatically adds for us.

                        # polls/serializers.py            from            rest_framework            import            serializers            from            .models            import            Question            class            QuestionSerializer            (            serializers            .            ModelSerializer            ):            grade            Meta            :            fields            =            (            'id'            ,            'question_text'            ,            'pub_date'            ,            )            model            =            Question          

And our view will expose everything for now with DRF's ModelViewSet.

                        # polls/views.py            from            rest_framework            import            viewsets            from            .            import            models            from            .            import            serializers            class            QuestionViewSet            (            viewsets            .            ModelViewSet            ):            queryset            =            models            .            Question            .            objects            .            all            ()            serializer_class            =            serializers            .            QuestionSerializer          

Equally a last stride nosotros need to make a new migrations file and migrate our database changes.

                        (polls) $ python manage.py makemigrations polls            (polls) $ python manage.py migrate          

We're done! That's it. We at present accept a functioning, complete API for the polls tutorial. Only nosotros haven't populated it with any content. In the polls tutorial they do this in the Django shell, merely I detect the Django admin to be much easier to work with. First update our admin.py file so the polls app appears.

                        # polls/admin.py            from            django.contrib            import            admin            from            .models            import            Question            from            .models            import            Choice            admin            .            site            .            register            (            Question            )            admin            .            site            .            register            (            Choice            )          

Then create a superuser account and start the local server.

            $ python manage.py createsuperuser $ python manage.py runserver          

At present navigate to http://127.0.0.1:8000/admin to login.

Admin

Add a new questions by clicking on "+ Add together" next to Questions.

Admin question

Then add together a Choice option past clicking on "+ Add together" next to Choices on the admin homepage.

Admin choice

Now we can navigate to our actual API for which DRF provides a prissy graphical view of both the listing view at http://127.0.0.1:8000/api/ and detail view at http://127.0.0.1:8000/api/ane/.

API list view

API detail view

Adjacent Steps

The official polls tutorial can exist overwhelming for beginners but at the cease of the day there'due south not much code involved. And thanks to the power of DRF nosotros can create web APIs with a shockingly pocket-size amount of code, yet yet have the flexibility to modify things as needed.

How To Use Poll In Python,

Source: https://learndjango.com/tutorials/django-polls-tutorial-api

Posted by: tusseyfalf1986.blogspot.com

0 Response to "How To Use Poll In Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel