Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to link two Django models created by a logged in user?
For my web application, people who are registered as authenticated users are able to create one Trainer object and as a trainer, upload many different Pokemon. So on Django admin, if I check the data entries for the Trainer and Pokemon objects, I am able to tell that different users have successfully uploaded their own Pokemon to the database. However, I'm having trouble establishing the relationship between the Trainer and Pokemon objects. This also means that my HTML template to view each Trainer and their Pokemon is messed up. Here's what I have so far: # pokeweb/models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User # Create your models here. class Trainer(models.Model): '''Represents a trainer with a Pokeweb account''' #data attributes: user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) last_name = models.TextField(blank=True) first_name = models.TextField(blank=True) email = models.TextField(blank=True) birthday = models.DateField(blank=True) region = models.TextField(blank=True) image_url = models.URLField(blank=True) def __str__(self): '''Return a string representation of this trainer''' return f'{self.first_name} {self.last_name}, {self.region}' def get_pokemons(self): ''' Return pokemon of trainer via object manager''' return Pokemon.objects.filter(trainer=self) def get_absolute_url(self): ''' Provide a url to show trainer object''' return reverse('show_trainer', kwargs={'pk':self.pk}) class Pokemon(models.Model): '''Represents a Pokemon that belongs to a user''' #data attributes: name = … -
Is there any other way to save and load keras models?
I was deploying a tf.keras model to a django app on shared hosting. I have saved it as a .h5 file and it works. Here is the problem, when it loads on the browser for the fist time it takes too much time to import tensorflow and gives a 403 error. It only works after that. Is there any other way to load the model faster? Thanks in advance for your help. -
How does Heroku Django picks up settings file during production? Multiple settings
It's my first time deploying so I just want to make sure that I understand. Basically, how does heroku django determine which setting file to choose when its deployed? Are there any command that I can type in order to check which setting file its currently using? like if its a prod or dev. ^^ To answer the above question on my own, you set myproject.settings.prod in wsgi file and heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings.prod to tell it to choose your prod settings for production/deploymnent. Am I correct in my understanding? Thanks in advance. Any advice or feedback would be apprecated! -
403 Forbidden nginx/1.18.0 (Ubuntu) for Django 3.1, facing issue in media files and admin css
I have django 3.1 installed on digitalocean ubuntu 20.04 and nginx/1.18.0 (Ubuntu) and using rest api Following are my static and media files settings. STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = BASE_DIR / 'static_in_env' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' Following is my Digital Ocean Nginx Conf location /static/ { root /home/username/backend/src; } location /media { root /home/username/backend/src; } it's giving me forbidden on even files less than 100kb. -
Django Deployment Failure in Pythonanywhere
Getting this error in my error logs when deploying my site 2021-04-23 16:20:38,663: Error running WSGI application 2021-04-23 16:20:38,676: django.core.exceptions.ImproperlyConfigured: The app module <module 'tracker' (namespace)> has multiple filesystem locations (['/home/jpf911/COVID19-Vaccination-Tracker/COVID19-Vaccination-Tracker/vaccination_tracker/tracker', './tracker']); you must configure this app with an AppConfig subclass with a 'path' class attribute. 2021-04-23 16:20:38,676: File "/var/www/jpf911_pythonanywhere_com_wsgi.py", line 14, in <module> 2021-04-23 16:20:38,677: application = get_wsgi_application() 2021-04-23 16:20:38,677: 2021-04-23 16:20:38,677: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-04-23 16:20:38,677: django.setup(set_prefix=False) 2021-04-23 16:20:38,678: 2021-04-23 16:20:38,678: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2021-04-23 16:20:38,678: apps.populate(settings.INSTALLED_APPS) 2021-04-23 16:20:38,679: 2021-04-23 16:20:38,679: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate 2021-04-23 16:20:38,679: app_config = AppConfig.create(entry) 2021-04-23 16:20:38,679: 2021-04-23 16:20:38,679: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/apps/config.py", line 255, in create 2021-04-23 16:20:38,679: return app_config_class(app_name, app_module) 2021-04-23 16:20:38,679: 2021-04-23 16:20:38,679: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/apps/config.py", line 49, in __init__ 2021-04-23 16:20:38,679: self.path = self._path_from_module(app_module) 2021-04-23 16:20:38,680: 2021-04-23 16:20:38,680: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/apps/config.py", line 88, in _path_from_module 2021-04-23 16:20:38,680: raise ImproperlyConfigured( Here are my Configurations: Code: Source Code & Working Directory.jpeg Wsgi Configurations: Wsgi config.jpeg Virtual Environmet: Virtual env.jpeg Static Files & Security: Static_Files & Security.jpeg Settings.py: Settings 1.jpeg Settings 2.jpeg Console: Console.jpeg -
Call a javascript function of base template from another template in django
in my base.html template, I write a function. Can I call it from another template? I tried like this. It doesn't work. base.html: <!-- ...code... --> <script> function registration(){ if(document.getElementById("registration").className==='hide'){ document.getElementById("registration").className='show' }else{ document.getElementById("registration").className='hide' } } </script> another template {% extends 'base.html' %} {% block body %} <script> //if i re write the function here, it works registration() </script> {% endblock body %} -
Using Celery, execute a list of URLs in a single celery task. Is it Possible?
views.py urls=["https//:.....com,https//:.....com,etc.."] for i in urls: r=process.delay(i) When I'm calling the celery task it execute separate task. How to execute the set of lists in a single celery task? tasks.py @app.task def process(url): r = requests.get(url, allow_redirects=True) return r -
Django returning dictionary from front end?
I'm passing a dictionary from the front end to the back end in one of my Django views. The setup is something like this: $.ajax({ type: "POST", url: '/my/url', data: { 'patients': '{{ appointments.appointments.items }}' }, dataType: 'json', async: false, success: function (data) { console.log("yay") } }); which is passing back an dictionary of names, etc. and I'm then retrieving this on the python backend, like so: if request.method == "POST": patients = request.POST.get("patients", None) print("patients are", patients) However, when I do this and print out the patients dict() instead of getting an actual dictionary, I get a string like this: dict_items([(153, {&#x27;person&#x27;: &#x27;Samuel&#x27;, &#x27;time&#x27;: datetime.datetime(2021, 4, 22, 17, 0, tzinfo=&lt;UTC&gt;), &#x27;number&#x27;: &#x27;First&#x27;})]) that doesn't follow the dictionary format/even really allow for json parsing etc. Is there something I'm doing wrong here? The {{appointments.appointments.items}} is just passed into my HTML template page from the backend during the get request and I'm accessing it with JavaScript in the same file. Any advice here would be appreciated. -
How to access serialize method from another model?
I'm trying to show on my DOM the number of followers and following, I have made a new model called Profile, I want to send JSON data from my views function using the serialize method in the Profile model, but how can I access the method in the Profile model from the User model? In my views.py (display_profile function) I'm trying to send JSON data, How can I access the serialize method in Profile Model, from the User model? models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class NewPost(models.Model): poster = models.ForeignKey("User", on_delete=models.PROTECT, related_name="posts_posted") description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) def serialize(self): return { "id": self.id, "poster": self.poster.username, "description": self.description, "date_added": self.date_added.strftime("%b %d %Y, %I:%M %p"), "likes": self.likes } class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) following = models.ManyToManyField(User, blank=True, related_name="following") followers = models.ManyToManyField(User, blank=True, related_name="followers") def serialize(self): return { "profileID": self.user.id, "following": int(self.following.all().count()), "followers": int(self.followers.all().count()), } views.py def display_profile(request, profile): try: profile_to_display = User.objects.get(username=profile) profile_to_display_id = User.objects.get(pk=profile_to_display.id) except User.DoesNotExist: return JsonResponse({"error": "Profile not found."}, status=404) # Return profile contents if request.method == "GET": return JsonResponse(profile_to_display.serialize(), safe=False) else: return JsonResponse({ "error": "GET or PUT request required." }, status=400) index.js function load_user_info(user_clicked_on){ document.querySelector('#page-view').style.display = 'none'; … -
How to add a row to a database only if certain constraints are satisfied
I have a question bank and an application that can create tests. The application allows adding questions from the question bank to a test (make a copy from the question bank to a test) or adding (creating) a question directly in the test. Multiple people can add questions to a given test. I want to ensure the following: The number of questions in a test do not cross a given fixed limit. No duplicate questions are added from the question bank to a test. There are tables for the following: Questions of the question bank Questions that are in a test (has a reference to the question in the bank) Tests How can I ensure the constraints? I am trying to do this in Django and MySQL. And I will not be abe to add a unique_together constraint for the parent_question_id and test_id (due to certain limitations that I can add if and when required to answer this question) -
is it better to include token as a field in the User model for Django+SimpleJwt?
i'm looking at different ways of using django rest framework with jwt, and most cases would do it in a "normal" way (as the Getting started in the simple Jwt Documentation says), but i encoutred some ones that extends the User model and include the Token inside, something like : class User(AbstractBaseUser, PermissionsMixin): # .....(usual fields(username, password,...)) @property def token(self): return self._generate_jwt_token() def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token is this way better? or is it just a different way to handle it? what difference does it make? -
Unable to populate images in Django Rest Serializer
I'm developing a REST API using Django Rest Framework but I'm unable to populate image in Feed Serializer Django Version: 3.1.7 Python Version: 3.9.2 Models: class User(AbstractUser): age = models.PositiveIntegerField(null=True) address = models.TextField(null=True) email = models.EmailField(_('email address'), unique=True, null=False) first_name = models.CharField(_('first name'), max_length=150, blank=False, null=False) last_name = models.CharField(_('last name'), max_length=150, blank=False, null=False) image = models.ImageField(upload_to='storage', null=True) class Feed(models.Model): description = models.TextField() likes_count = models.PositiveIntegerField(default=0, null=True) comments_count = models.PositiveIntegerField(default=0, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') tags = models.ManyToManyField(User, related_name='tags', blank=True) class FeedImage(models.Model): path = models.ImageField(upload_to='storage', null=False) post = models.ForeignKey(Feed, on_delete=models.CASCADE, null=False, default='') Serializers: class FeedUserSerializer(ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'image') class FeedImageSerializer(serializers.ModelSerializer): class Meta: model = FeedImage fields = ('id', 'path', 'post') class FeedSerializer(ModelSerializer): user = FeedUserSerializer() images = FeedImageSerializer(many=True, read_only=True) class Meta: model = Feed fields = ('id', 'description', 'comments_count', 'likes_count', 'updated_at', 'created_at', 'tags', 'images', 'user') View: class FeedsListView(generics.ListAPIView): queryset = Feed.objects.all() return FeedSerializer Problem: I get this result without images [{ "id": 1, "description": "Hello world", "comments_count": 0, "likes_count": 0, "updated_at": "2021-04-26T03:01:44.219235Z", "created_at": "2021-04-26T03:01:44.219235Z", "tags": [], "user": { "id": 1, "first_name": "ZAIN", "last_name": "REHMAN", "image": "http://192.168.88.28:8000/storage/1_Facebook_1.jpg" } }] Expected Output: [{ "id": 1, "description": "Hello world", … -
how to filtering queryset in django template
I used a function in models.py to output the queryset result to the template. Now what I want to do is filter the output queryset back in views.py. Is it possible to filter with the code below? Please feedback if the logic is wrong [models.py] class Academy(models.Model): .... def student(self): return Student.objects.filter(academy_id=self.id) [views.py] @login_required() def academy_list(request): academy_list = Academy.objects.all() option_radio = request.GET.get('optionRadios') from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') count = Attribute.objects.filter( entry_date__gte=from_date, entry_date__lt=to_date) return render(request, 'academy_list.html', { 'academy_list': academy_list, 'option_radio': option_radio, 'from_date': from_date, 'to_date': to_date, 'count': count }) [academy_list.html] {% for academy in academy_list %} {% if option_radio == 'period' %} <tr> <td>{{ academy.academy_name }}</td> <td>{{ academy.student }}</td> ---- I want to filter again using the count variable in the academy_list function in views.py. </tr> {% endif %} {% endfor %} -
needs to restart supervisor everytime
i am using postgres sql and here is my queryset user_attempt_quiz_obj = UserAttemptQuiz.objects.filter(created_at__year=today.year, created_at__month=today.month, created_at__day=today.day) queryset is working fine but its response doesn't change for each days untill i restart my server. i am using nginx server with supervisor my time setting is below: TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True -
How to store in a JavaScript variable the selected rows in a table
Let's say we have a table like this: <table> <thead> <tr> <th class="active"> <input type="checkbox" class="select-all checkbox" name="select-all" /> </th> <th>A</th> <th>B</th> </tr> </thead> <tbody> {% for gene_variant in gene_variant_results %} <tr> <td class="active"> <input id="selectedGene" type="checkbox" class="select-item checkbox" name="select-item"/> </td> <td>{{ gene_variant.67 }}</td> <td> {{ gene_variant.72 }}</td> </tr> {% endfor %} </tbody> </table> <button id="select-all" class="btn btn-primary">Select all</button> <button type="submit" id="show-selected" class="btn btn-primary">Show selected</button> And let's say that gene_variant_results has for example, 4 results. Each result corresponds to a row (each row has about 100 columns, in this example I only put 11 for illustrative purposes): (1290, 'chr10', '73498294', '73498294', 'C', 'G', 'exonic', 'CDH23', 'DM', 'CM127233', 'DFNB12) (1291, 'chr11', '73498295', '73498295', 'D', 'H', 'exonic', 'CDH24', 'DM', 'CM127234', 'DFNB13) (1292, 'chr12', '73498296', '73498296', 'E', 'I', 'exonic', 'CDH25', 'DM', 'CM127235', 'DFNB14) (1293, 'chr13', '73498297', '73498297', 'F', 'J', 'exonic', 'CDH26', 'DM', 'CM127236', 'DFNB15) For example, if I click on the first two checkboxes and then click on the #show-selected button, I would like to store in a JavaScript variable the values of those selected rows. (The full gene_variant content, not just the selected <td> values) Some illustrative semi pseudo-code of what I want: $( "#show-selected" ).click(function() { var selected_checkboxes = //get the … -
why Search function is not working in django?
After I searched on a specific keyword, Django is not retrieving searched items that matches but it's showing all data. When I search for history it's showing all books though I have history books on the database. views.py def home(request): if request.method == 'POST': searchName = request.POST.get('Search') if not searchName : searchName = "" context={ 'data': Book.objects.filter(bookname__contains=searchName) } return render(request, 'library_site/home.html',context) else: context={ 'data': Book.objects.all() } return render(request, 'library_site/home.html',context) form field in html <form method="POST" action="{% url 'home' %}"> {% csrf_token %} <input class="search-input" type="text" name="searchBook" placeholder="Search Book Name here..."> <input class="btn" type="submit" name="search" value="Search"> </form> -
Django and google_streetview API
Is there a way to retrieve a street view image from google_streetview API in Python/Django and pass it to templates without having to save the image within Django? I know you can create an API call using Javascript, although I am looking to see if there is a method to do the API call in the backend to avoid showing my API Key in the frontend or is this even necessary? I am not even sure what might be best practice for this. I am currently using Javascript to allow for the Google Places Autocomplete API. Is it secure enough to simply have restrictions in place on your API key's for which API your key is good for and a Application Restriction? Currently I have this in place from the google_streetview package: import google_streetview.api def streetview(coord): params = [{ 'size': '300x200', 'location': coord, 'fov': '100', 'key': settings.STREETVIEW_KEY }] results = google_streetview.api.results(params) However, the only things I know you can do with results is .preview(), .save_links(), .download_links(), .save_metadata(). -
Saving data to database using form wizard
I am using form wizard to create a multi-page form in django, however I'm having trouble saving my data to a database using this method. Do I save the data based on the current step of each form I'm in (i.e. save it based on step 1, 2 or 3), if so how do I do this with the request? Below is my defective code, any help would be appreciated. class newWorkoutLinked(SessionWizardView): template_name = "workout_app/contact_form.html" def done(self, form_list, **kwargs): return render(self.request, 'workout_app/done.html', { 'form_data': [form.cleaned_data for form in form_list] }) if self.request.user.is_anonymous: messages.error(request, LE) return HttpResponseRedirect('/login/') if self.request.method == 'POST': form = WorkoutLinkedForm(request.POST) if form.is_valid(): ots = form.save(commit=False) ots.profile = self.request.user ots.save() return HttpResponseRedirect('/workout_linked_list') else: form = WorkoutLinkedForm() return render(self.request, 'workout_app/add_workout_linked.html', {'form': form}) -
in Django,what is the best way to store a content which consist of images and text?
I am building a website like a blog. On my website, I am going to have an article with at least 4 paragraphs and also a minimum of 4 pictures. I am planning to use RichTextField for it but I am here to get advice from you experienced people. As I said, I am totally new to Django. What is the best and fastest way to store an article with images? By the way, before I asked the question, I googled it but most questions came down to Django 2.0. There must be better ways now. Thank you all. -
Best way to handle LoginView login on all pages in Django
I am new to Django and I have spent a lot of time trying to find a solution to my problem but was not successful. I have a top navbar that is included in the base.html file and every page extends base.html. In my navbar, I have a button that shows a modal (bootstrap) and I want this modal to show the login form. My url.py is as follows: from django.urls import path, include from .views import RegisterView from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, PasswordChangeView, PasswordChangeDoneView urlpatterns = [ # Mapping django auth at the root # The URLs provided by auth are: # login/ [name='login'] # logout/ [name='logout'] # password_change/ [name='password_change'] # password_change/done/ [name='password_change_done'] # password_reset/ [name='password_reset'] # password_reset/done/ [name='password_reset_done'] # reset/<uidb64>/<token>/ [name='password_reset_confirm'] # reset/done/ [name='password_reset_complete'] #path('', include('django.contrib.auth.urls')), path('password_reset/', PasswordResetView.as_view(), name='password_reset'), path('password_reset_done/', PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password_reset/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('password_change/', PasswordChangeView.as_view(), name='password_change'), path('password_change/complete/', PasswordChangeDoneView.as_view(), name='password_change_done'), path('login/', LoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('register/', RegisterView.as_view(), name='register'), ] As you can see above, path('login/', LoginView.as_view(), name='login'), will only correctly resolve {{ form }} in localhost:8000/login but I want it to resolve in all paths to achieve what I want. Meaning, if I navigate to localhost:8000/login and open the … -
how to use request.GET['parameter'] from django models.py
I am trying to get self.request.GET['from_date'] value from django models.py. However, you cannot use the value. As a result of searching, I got feedback to use request in views.py, but I need a variable called self.id so the work has to be done in models.py. Is there a way to get parameter value from models.py? [models.py] class Academy(models.Model): def count(self): student = Student.objects.filter(academy_id=self.id) return Attribute.objects.filter( entry_date__gte=self.request.GET['from_date'], entry_date__lt=self.request.GET['to_date'], student_id__in=student ).count() -
Django user proxy
I'm using proxy model in Django to make multiple types of users (patient and doctors), I am trying to make a specific page to show all doctors signed up but I don't know how to access them in the template something like {% for doctor in Doctors.objects.all %} . this is the user model code class User(AbstractBaseUser, PermissionsMixin): class Types(models.TextChoices): DOCTOR = "DOCTOR", "Doctor" PATIENT = "PATIENT", "Patient" type = models.CharField( _("Type"), max_length=50, choices=Types.choices, default=Types.PATIENT ) class Patient(User): objects = PatientManager() class Meta: proxy = True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.PATIENT return super().save(*args, **kwargs) class Doctor(User): objects = DoctorManager() class Meta: proxy = True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.DOCTOR return super().save(*args, **kwargs) -
How to show Pagination for JSON data in DOM ( Django, JavaScript, HTML )
In my views function, I have added pagination that returns 3 posts for every page as JSON data, Right now my HTML page shows only the first 3 posts, How can I make my next and previous buttons work if I'm returning JSON data to my JavaScript and not returning as render for the HTML page? views.py def show_posts(request): all_posts = NewPost.objects.all() all_posts = all_posts.order_by("-date_added").all() all_posts_paginated = Paginator(all_posts, 3) page_number = request.GET.get('page', 1) page_obj = all_posts_paginated.get_page(page_number) return JsonResponse([website_post.serialize() for website_post in page_obj.object_list], safe=False) index.js function load_posts(){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#load-profile').style.display = 'none'; document.querySelector('#posts-view').style.display = 'block'; document.querySelector('#show-posts').style.display = 'block'; document.querySelector('#post-form').onsubmit = function() { compose_post(); } fetch('/posts/all_posts') // url with that API .then(response => response.json()) .then(all_posts => { // Loop and show all the posts. console.log(all_posts) all_posts.forEach(function(post) { // loop to loop over each object display_post(post) }); }); document.querySelector('#show-posts').innerHTML = "" } function display_post(post){ // create new div for each thing that needs to be shown const element = document.createElement('div'); const post_username = document.createElement('div'); const post_description = document.createElement('div'); const post_date_added = document.createElement('div'); const post_likes = document.createElement('div'); // add the text for each div post_username.innerHTML = 'Username: ' + post.poster post_description.innerHTML = 'Content: ' + post.description post_date_added.innerHTML = 'Date: ' + post.date_added post_likes.innerHTML … -
How do I loop through two models to get attribute differences in a django template?
I am trying to figure out how to get the attribute differences from two different django models. They have common attributes, and I want to compare the common attributes to see the differences. I have managed to define both querysets with values and I can get the primary attribute fine. The problem is when I am trying to loop through both of the models and get the attribute values and compare them. I have done something like this... {% for i in books.all %} {% if i not in author.all %} {% if i.author_name %} Author Name :{{ i.author_name }}. {% endif %} {% endif %} {% endfor %} The above works. The problem I'm having is when I try to do something like... {% for i in books.all %} {% if i not in author.all %} Author Name :{{ i.author_name }}. {% endif %} {% for j in author.all %} {% if j.publishers.name != i.author_name %} Print Don't Match {% endif %} {% endif %} {% endfor %} I tried the above example and it doesn't produce output. I've confirmed the values are identical, but I can't seem to get the template to show me the attribute differences. I … -
how to create a axios post request using react hooks with a backend framework like django
I have the following React codes using hooks and axios. I am trying to create a post request to "http://127.0.0.1:8000/api/products/create/" endpoint below. Unfortunately, I keep getting 405 (Method Not Allowed) as a response when I press the button submit ProductCreate.js function CompanyCreate() { const [fields, handleFieldChange] = FormFields({ name: "", email: "", }); function handleSubmit(e) { e.preventDefault(); console.log("submitted", fields); let axiosConfig = { headers: { 'content-type': 'application/json', } }; axios.post("http://127.0.0.1:8000/api/products/create/", fields, axiosConfig) .then(response => { console.log("Status", response.status); console.log("Data", response.data); }).catch((error => { console.log("error", error); })); } backend views @api_view(["POST"]) def product_create(request): if request.method == "POST": serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls path("products/create/", views.product_create, name="create_product"), I am not sure why the headers does not seem to work, any help would be appreciated.