Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM queries
I've these tables: class ContestQuestions(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='contest_question_contest') quetions = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='contest_question_questions') class UserResponse(models.Model): user = models.ForeignKey(User, on_deleted=models.CASCADE, related_name='user_response') response = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='user_answer') Other related tables I've: class Contest(models.Model): name = charfield date = charfield is_active = bool class Question(models.Model): title = charfield created_at = datetimefield class Answer(models.Model): question = FK(Question) answer = charfield #4 options of 1 question is_true = bool I need to get some stat about every quiz. So from every quiz, I want to know the top 5 most correctky answered questions and most incorrectly answered questions and total number of people who attempted that question. How can I write a query for it? -
I am getting a SignatureDoesNotMatch error while generating a presigned url for aws s3
I am trying to create a presigned url to upload images to aws s3. The server is successfully generating the upload link but when I click on the link, I am getting a SignatureDoesNotMatch error -
Celery task is delayed when another task runs, how do I make sure multi-threading here?
We have a celery worker and a beat scheduler running in production, in a dedicated Kubernetes POD. We used gevent and run celery with concurrency set to 200. celery -A app worker -l info --pool=gevent --concurrency=200 Recently, we needed to have a periodic task to be triggered every 5 seconds. But when there is another celery task in progress (especially the ones that interact with the database), we noticed the task is delayed a lot. Checking the beat-scheduler, the tasks are sent every 5 seconds without problems but they are waiting in the broker. We hoped this periodic task was not affected by other tasks because we used concurrency. Please see screenshot of logs We need to make sure this task runs every 5 seconds regardless of other tasks. -
Django urls configuration
I have an example website using django. I have 2 link "about" and "blog". When I click "blog" it become localhost/blog and nothing problem, but when I click "blog" once more it become localhost/blog/blog and error happen. What's the solution? -
submit form with <a></a> tag via javascript
I use this code to submit my form with a tag but its not working html file <form id="my_form" method="post"> {% csrf_token %} {{form.as_p}} <input type="number" name="conf" ><a onclick="document.getElementById('my_form').submit();" href="{% url 'signup' 0 %}">ارسال کد</a> <br><br> <button type="submit">ثبت نام</button> </form> console log "GET /signup/0 HTTP/1.1" 200 1531 -
Django formset can't got a NaN number in the field name
As you can see , the first form set is using form-0. Which is expected, but for the next item is using NaN. Here is how I did: https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html -
how solve django create model class dynamically
When dynamically creating and generating Model class, modify some properties, fill in the information required by the sub-table, the first time can return the normal result, the second result error, after the analysis of the second result field to retain the first table name: class Object: def __init__(self, **kwargs): self.__dict__.update(kwargs) def _model_new(cls, *args, **kwargs): return cls(*args, **kwargs)enter code here class ShardModel(object): _shard_db_models = {} temp_class = [] def __new__(cls, *args, **kwargs): shard_key = kwargs.pop('shard_key', 0) % cls.Config.table_num model_name = cls.__name__ model_name += '_%s' % shard_key model_class = cls._shard_db_models.get(model_name) if model_class is not None: return model_class # Deep copy attrs attrs = dict() attrs.update(cls.__dict__) if 'objects' in attrs: attrs['objects'] = attrs['objects'].__class__() # Set table name with shard_key meta = Object(**cls.Meta.__dict__) meta.db_table = meta.db_table % shard_key meta.abstract = False attrs['Meta'] = meta attrs['new'] = classmethod(_model_new) attrs['__module__'] = cls.__name__ cursor = connection.cursor() tables = [table_info.name for table_info in connection.introspection.get_table_list(cursor)] # Create model class dynamically model_class = type(model_name, tuple([models.Model] + list(cls.__bases__[1:])), attrs) print(model_class) if meta.db_table not in tables: for cmd in ('makemigrations', 'migrate'): exec_command(cmd, meta.app_label) cls._shard_db_models[model_name] = model_class return model_class this is my model class Nice(ShardModel): user_id = models.IntegerField() user_name = models.CharField(max_length=256) password = models.CharField(max_length=256) class Config: table_num = 3 class Meta: app_label = … -
Python- ValueError: too many values to unpack (expected 2) in Django
Models.py from django.db import models class Userreg(models.Model): username= models.CharField(max_length=100) fname= models.CharField(max_length=100) lname= models.CharField(max_length=100) email= models.CharField(max_length=100) pass1= models.CharField(max_length=100) class Meta: db_table="newapp2" Views.py from app1.models import Userreg from django.shortcuts import redirect, render from django.contrib import messages from django.contrib.auth import authenticate,login,logout def signup(request): if request.method== "POST": username= request.POST['username'] fname= request.POST['fname'] lname= request.POST['lname'] email= request.POST['email'] pass1 = request.POST['pass1'] pass2= request.POST['pass2'] if Userreg.objects.filter(username=username): messages.error(request, "Username already exist! Please try some other username.") return redirect('home') if Userreg.objects.filter(email=email).exists(): messages.error(request, "Email Already Registered!!") return redirect('home') if len(username)>20: messages.error(request, "Username must be under 20 charcters!!") return redirect('home') if pass1 != pass2: messages.error(request, "Passwords didn't matched!!") return redirect('home') if not username.isalnum(): messages.error(request, "Username must be Alpha-Numeric!!") return redirect('home') myuser= Userreg.objects.get(username,email,pass1) myuser.first_name= fname myuser.last_name= lname myuser.save() TRACEBACK: File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Desktop\app\app1\views.py", line 36, in signup myuser= Userreg.objects.get(username,email,pass1,fname,lname) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\Anaconda3\envs\anaconda\lib\site-packages\django\db\models\sql\query.py", line 1358, in … -
Django nested categories - path getting 404 on child slug
I try to create nested categories with django-treebeard. And in admin this solution work fine. But I need to show this categories. When I try reach root category eq.: /kategorie/wegetarianskie then works fine, but when I try to reach fullslug with children category eq.: /kategorie/wegetarianskie/obiady then I have error 404 and don't know why. Maybe someone have answer. My model: class Category(MP_Node): name = models.CharField(max_length=255, verbose_name='Nazwa kategorii') slug = AutoSlugField(populate_from='name', unique=True) fullslug = models.CharField(max_length=255, verbose_name='Pełny adres kategorii', blank=True) created_at = models.DateTimeField(default=datetime.datetime.now) node_order_by = ['name'] Then with signal I create full slug like this: @receiver(post_save, sender=Category) def save_parentname(sender, instance, **kwargs): if not instance.fullslug: if instance.is_root(): instance.fullslug = instance.slug instance.save() else: catslug = '/'.join([instance.get_parent().slug, instance.slug]) instance.fullslug = catslug instance.save() When child category is save, then signal create full slug like: /kategorie/wegetarianskie/obiady I have also get_absolute_url: def get_absolute_url(self): return reverse('categorydetail', args=[self.fullslug]) View: def category_detail(request, fullslug): category = Category.objects.get(fullslug=fullslug) return render(request, 'categories/category_detail.html', { 'category': category }) Urls: urlpatterns = [ path('wszystkie', views.category_list, name='categorylist'), path('<fullslug>/', views.category_detail, name='categorydetail'), ] -
How can I make the main category page?
Greetings! I have the following code: urls.py re_path(r'^category/(?P<hierarchy>.+)/$', show_category, name='category'), views.py def show_category(request, hierarchy=None): category_slug = hierarchy.split('/') parent = None root = Categories.objects.all() for slug in category_slug[:-1]: parent = root.get(parent=parent, slug=slug) try: instance = Categories.objects.get(parent=parent, slug=category_slug[-1]) except: instance = get_object_or_404(Goods, slug=category_slug[-1]) return render(request, "shop/product.html", {'instance': instance}) else: return render(request, 'shop/categories.g.html', {'instance': instance}) The category model has the structure: id, slug, imagePath, parent I googled a lot and didn't find a good answer to my question. Please help, this script displays only categories at localhost/category/(name of the parent category) and one level higher. And the problem is that I can't make the main category page at all (localhost/category), please help or point me in the right direction to solve this issue! I'm going crazy trying to solve this problem. Tried and google and dig into the documentation. Can't decide at all. -
psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist
I'm trying for the first time to deploy my Django project to heroku, but I'm running in some issues, when trying to: Register/Login heroku run python manage.py makemigrations heroku run python manage.py migrate (also with --fake) This error shows up: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 268, in handle emit_post_migrate_signal( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/sql.py", line 42, in emit_post_migrate_signal models.signals.post_migrate.send( File "/app/.heroku/python/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/app/.heroku/python/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/auth/management/__init__.py", line 42, in create_permissions create_contenttypes(app_config, verbosity=verbosity, interactive=interactive, using=using, apps=apps, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/contenttypes/management/__init__.py", line 119, in create_contenttypes content_types, app_models = get_contenttypes_and_models(app_config, using, ContentType) File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/contenttypes/management/__init__.py", line 94, in … -
Django's STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" creates hashed static file names, but doesn't read them
When I run collectstatic everything is as it should be. The appointed STATIC_ROOT directory has all the collected files with original and hashed filenames. When I run the server, however, Django throws me an 500 server error and doesn't load any of the files. When I change STATICFILES_STORAGE to "django.contrib.staticfiles.storage.StaticFilesStorage" instead of "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", everything works fine and the static files with their original filenames are served. Has anyone a clue? Do I need to import "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" somwwhere. I read the whole documentation, but nothing... -
How to get auto fill values(default values) on serializer create method in django?
I have a model like this: class Post(BaseModel): post_user_id = models.CharField(max_length=500, unique=True, default=create_uid) create_uid gerenrates a unique id serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' def create(self, validated_data): print(validated_data['post_user_id']) return super().create(validated_data) For each created post a post_user_id will be generated automatically and the user will not post the post_user_id On print(validated_data['post_user_id']) I want to print the generate number But I get error KeyError -
Why isn't my Jquery code working after the second form submit? Django - Ajax - Jquery
I have a follow/unfollow button. Currently my Jquery is working on the first submit but when I toggle the button again, the Jquery doesn't change any of the elements. html {% for user in followers %} <div class="flist" id="flist-{{ user.profile.pk }}"> <article class="media comment-section"> <a class="mr-2" href="{% url 'user-posts' user %}"> <img class="rounded-circle comment-img" src="{{ user.profile.image.url }}"></a> <div class="media-body mt-1"> {% if user.profile in following %} <div class="remove-follower-div-{{ user.profile.pk }}"> <form method="POST" action="{% url 'remove-follower-js' user.profile.pk %}" class="remove-follower-form" id="{{ user.profile.pk }}"> {% csrf_token %} <button class="btn btn-unfollow unfollow-link" type="submit" style="float:right;" id="unfollow-button-{{ user.profile.pk }}"><span>Following</span></button> </form> </div> {% else %} <div class="add-follower-div-{{ user.profile.pk }}"> <form method="POST" action="{% url 'add-follower-js' user.profile.pk %}" class="add-follower-form" id="{{ user.profile.pk }}"> {% csrf_token %} <input type="hidden" name="profile_id" value="{{ user.profile.pk }}"> <button class="btn btn-follow btn-light side-link mr-4" type="submit" style="float:right;" id="follow-button-{{ user.profile.pk }}">Follow</button> </form> </div> {% endif %} .js file $( document ).ready(function() { $('.add-follower-form').on("submit", function(e) { e.preventDefault(); const profile_id = $(this).attr('id'); console.log(profile_id) const url = $(this).attr('action'); console.log(url) $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'profile_id':profile_id, }, dataType: 'json', success: function(response) { console.log('success') console.log(response) console.log(profile_id) console.log(url) $(`.add-follower-div-${profile_id}`).find('.add-follower-form').attr('action', "/profile/"+ profile_id + "/followers/remove/js"); $(`.add-follower-div-${profile_id}`).find('.add-follower-form').attr('class', "remove-follower-form"); $(`.add-follower-div-${profile_id}`).attr('class', `remove-follower-div-${profile_id}`); $(`#follow-button-${profile_id}`).attr('class',"btn btn-unfollow unfollow-link"); $(`#follow-button-${profile_id}`).empty(); $(`#follow-button-${profile_id}`).append('<span>Following</span>'); $(`#follow-button-${profile_id}`).attr('id',"unfollow-button-"+profile_id); }, error: function(response) { console.log('error', response); } … -
Error Msg : "can't convert from BSON type string to Date
db.newc.aggregate( [ { $project: { _id: 0, formattedDate: { $dateToString: { format: "%d/%m/%Y", date: "applied_on" } } } } ] ) I am having the Code like this, and i am using mongodb compass and mongosh.The aggregation is not working. -
Sort a list from different classes by one field - Django
I connect multiple queryset from different objects into one list: query_1 = Room.objects.all() query_2 = Apartment.objects.all() query_3 = Plot.objects.all() all_user_objects = list(chain(query_1, query_2, query_3)) How can I add a sort by created_at date from the newest? I try this: all_user_objects.order_by('-created_at') and this: from operator import attrgetter all_user_objects = list(chain(query_1, query_2, query_3), key=attrgetter('-created_at')) -
Django cannot revert migration
im trying to undo my last migration by migrating previous migration but django throws an error "Cannot find a migration matching" how can i solve this ? -
One page to another page using JAVASCRIPT or JQUERY using Html anchor tag with dynamic Id
Basically I have two pages working on different categories. I am working on Sandbox. I have two pages with dynamic URL using anchor tag. I just want to call First page on button click when we are on Second page without changing windows location. The Windows location should be same. Avoid using windows.location functionalities in JS. Simple I want to jump from one page to another page with the help of JS or jQuery. <li> <a href="{% url "analysis" report.analysis.info.id "summary" %}" {% if env.view_kwargs.page == 'summary' %} class="active" {% endif %}> <div class="parent-icon"><i class='bx bx-home'></i> </div> <div class="menu-title">Summary</div> </a> </li> <li> <a href="{% url "analysis" report.analysis.info.id "reboot" %}" {% if env.view_kwargs.page == 'reboot' %} class="active" {% endif %}> <div class="parent-icon"><i class='fa fa-power-off'></i> </div> <div class="menu-title">Reboot Analysis</div> </a> Suppose, If I am on the page of Reboot Analysis so with the help of JS or jQuery I should jump to the Summary page. -
Docker django app running but cannot access the webpage
I am trying to run two separate django apps using docker (building on a linux server). The first application runs smoothly (using default ports) the second one apparently runs (it says starting development server at http://0.0.0.0:5000), I got no issues looking inside the portainer. Everything is running and no issue is there. When I try to connect to the page, it fails. docker-compose: version: '3' services: vrt: build: context: . dockerfile: Dockerfile ports: - "5000:5000" volumes: - ./nuovoProgetto:/VehicleRammingTool command: > sh -c "python3 manage.py wait_for_db && python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:5000" env_file: - ./.env.dev depends_on: - db db: image: postgres:14.1-alpine restart: always environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - db:/var/lib/postgresql/data redis: image: redis:alpine celery: restart: always build: context: . command: celery -A nuovoProgetto worker --pool=solo --loglevel=info volumes: - ./nuovoProgetto:/VehicleRammingTool environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - vrt - redis volumes: db: driver: local Dockerfile: FROM ubuntu:18.04 ENV http_proxy=http://++++++++++proxyhere ENV https_proxy=http://+++++++++proxyhere ENV PATH="/root/miniconda3/bin:${PATH}" ARG PATH="/root/miniconda3/bin:${PATH}" RUN apt-get update RUN apt-get install -y wget && rm -rf /var/lib/apt/lists/* RUN wget \ https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \ && mkdir /root/.conda \ && bash Miniconda3-latest-Linux-x86_64.sh -b \ && rm -f Miniconda3-latest-Linux-x86_64.sh RUN python --version RUN conda install -c conda-forge django psycopg2 celery redis-py django-leaflet … -
How to write unit test ValidationError case in response by use client.post()
I have a model with a time validator raise ValidationError('End time cannot be earlier than start time') So I want to write a unit test using client.post() with data invalid (from_time > to_time), and I expected ValidationError to appear in this test. -
cannot print an integer to a pdf python django
As the title says, I want to print integers to a pdf, because it will be a receipt, and the data for them are on FK. But I get an error named "bad argument type for built-in operation", is there any workarounds for it? here is the view of the function: def receipt(request): buf = io.BytesIO() c = canvas.Canvas(buf, pagesize=letter, bottomup=0) textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont ("Helvetica", 10) items = ShopCart.objects.all() lines = [] for item in items: lines.append(item.product) lines.append(item.size) lines.append(item.sugar) lines.append(item.ice) lines.append(item.addOn) lines.append(item.quantity) lines.append("") for line in lines: textob.textLine(line) c.drawText(textob) c.showPage() c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='Receipt.pdf') Also, I've tried printing the said items columns on the terminal and got their values but, noticed that whenever I try to generate the PDF it will look like this: using print() tea1 Petite 10 normal milk 1 Im guessing this is the for line in lines: textob.textLine(line) tea1 Petite 10 -
creating custum user and login without registering through mobile in Django
I want that user should login without register he should login through mobile and otp so how to implement this in django .application to login without registration in django.when the user enter mobile no it should save in database how to do this without django own username n password field by changing the fields as mobile and then otp -
Django Migration error due to auth_user field not existing
django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... this is the error that I'm getting I'm using PostgreSQL as my database here is my connection to the database DATABASES = { 'default' : { 'ENGINE' : 'django.db.backends.postgresql', 'NAME' : 'listeners', 'USER' : 'postgres', 'PASSWORD' : '***********', 'HOST' : 'localhost' } } this is my models: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from flask_login import user_accessed class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, username, email, phone_number, password=None): if not email: raise ValueError("User must have an email address") if not username: raise ValueError("User must have a username") user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, phone_number = phone_number ) user.is_admin = False user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, email, username, password): user = self.create_user( email = self.normalze_email(email), username = username, pasword = password, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50,unique=True) email = models.CharField(max_length=50, unique=True) phone_number = models.CharField(max_length=10,unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) … -
How to use django-star-ratings
I got an error when I use django-star-ratings. Error 'str' object has no attribute '_meta' menu.html error at line 33 {% load ratings %} <div class="col-md-7"> <img src="{% static 'image/Indian-vegetarian-mark.svg' %}"> <h4 class="card-title" style="color: #FFC222;">{{i.product}}</h4> <h6 class="price-tag text-left mt-2 mb-1" style="font-size: 0.9rem;" > MRP:<span id=""> {{i.price}}</span> RS. </h6> {% ratings object %} </div> line 33 is {% rating object %} I also follow the document -
Method \"POST\" not allowed django
I am getting error as Method "POST" not allowed. urls.py from django.conf.urls import url from . import views urlpatterns = [ url('', views.listTutorials), url('create/', views.createTutorial), url('<str:pk>/update/', views.updateTutorial), ] views.py from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .serializers import TutorialSerializer from .models import Tutorial @api_view(['POST']) def createTutorial(request): serializer = TutorialSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['PUT']) def updateTutorial(request, pk): tutorial = Tutorial.objects.get(pk=pk) serializer = TutorialSerializer(tutorial, data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_204_NO_CONTENT) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def listTutorials(request): tutorials = Tutorial.objects.all() serializer = TutorialSerializer(tutorials, many=True) return Response(serializer.data) serializers.py from rest_framework.serializers import ModelSerializer from .models import Tutorial class TutorialSerializer(ModelSerializer): class Meta: model = Tutorial fields = '__all__' models.py from django.db import models class Tutorial(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) def __str__(self): return self.title project urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('tutorials/', include('tutorials.urls')) ] Now I am using POST request as http://localhost:8000/tutorials/create/ with body { "title": "Django framework", "description": "Learning django framework" } But I am getting error { "detail": "Method "POST" not allowed." }