Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to upload data from python to mysql, but the insertion is not commited
I'm trying to upload some rows of data from python to mysql, using django and mysql, as we also want to show data from the database in our webpage. The connection to the server does work correctly, and so the connection to the database. The problem comes when we execute the following query to insert data from python to mysql. def addInfo(request, T, P, A, Rx, Ry, Rz, Ax, Ay, Az, Fecha, Long, Lat, Vel): """conexion = mysql.connector.connect(user='root', password='admin', host='localhost', database='datos', port='3306') print(conexion) cursor = conexion.cursor() print("T:"+str(T))""" query = "use datos; INSERT INTO datos(Temperatura, Presion, Altitud, RotacionX, RotacionY, RotacionZ, AceleracionX, AceleracionY, AceleracionZ, Fecha, Longitud, Latitud, Velocidad) VALUES ('"+T+"','"+P+"','"+A+"','"+Rx+"','"+Ry+"','"+Rz+"','"+Ax+"','"+Ay+"','"+Az+"','"+Fecha+"','"+Long+"', '"+Lat+"', '"+Vel+"');" print(query) cursor.execute(query) documento = """<!DOCTYPE html> <html> <head> --HTML PART IS OMITTED-- </html>""" print(cursor) cursor.close() return HttpResponse(documento) When we execute this code, database does not update rows, but when we execute manually in mysql, it does work and the id auto-increments as if we had uploaded the previous query. (but the previous row doesn't appear ) -
Is there any way to get the value of multiplecheckboxes that the rendering in for loop with django-template-language
How to get value of mutiplecheckboxes in django. the below code showing the groups at frontend {% for group in groups %} <tr><td>{{group.name}}</td> <td><input type="checkbox" name="superuser" id="group-{{group.id}}" value="{{group.id}}"></td> </tr> {% endfor %} I want to get the values of all checked boxes at backend when I submit the record. -
How to build a django web app using huggingface model api's
I am a beginner and I want to build Django app having hugging face model api to do a specific task in that app. but I am not getting any helping material. please help me guide me about how can I do that. I tried but I failed. I am a beginner to this -
Django HttpResponse does not redirect after Javascript Post with fetch
With the following Post using Javascript function send_dialog() { fetch('dialog', { method: 'POST', body: JSON.stringify({ id_to_dialog }) }) .then(response => response.json()) .then(result => { // Print result console.log(result); }); } and the corresponding function of the django view: @csrf_exempt def dialog(request): print(request) data = json.loads(request.body) print(data) return HttpResponse("HEY") I'm able to print out the data, but the website doesn't get redirected to the simple page showing "Hey". So far I've tried several other methods reverse, redirect etc. from django, but could never successfully redirect to the "hey" page. -
Django get objects created by users, with those users belonging to a list of users
I have a model for followers. Here is the model: class Follow(models.Model): followee = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followee") follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = ["followee", "follower"] def __str__(self): return "{} is following {}".format(self.follower, self.followee) def save(self, *args, **kwargs): if self.followee == self.follower: return "You cannot follow yourself" else: super().save(*args, **kwargs) Users create multiple types of objects like posts and questions. I would like to show all the posts and questions of all the users that follow a specific user. Simplified show me all the posts and questions of users that follow me. I am using a module called drf_multiple_model and here is my view, which I cannot get to work. It gives me the following error that I don't understand: Cannot use QuerySet for "Follow": Use a QuerySet for "User". Here is the view I am using: def get_followers(queryset, request, *args, **kwargs): id = kwargs['user'] user = User.objects.get(id=id) followers = Follow.objects.all().filter(followee=user) return queryset.filter(user__in=followers) class HomeView(FlatMultipleModelAPIView): permission_classes = [IsAuthenticated] def get_querylist(self): querylist = [ {'queryset':Post.objects.all(), 'serializer_class': UserPostSerializer, 'filter_fn': get_followers, 'label':'post'}, {'queryset':Question.objects.all(), 'serializer_class': QuestionSerializer, 'filter_fn': get_followers, 'label':'question'}, ] return querylist What am I doing wrong please? -
Celery task is not sending message
I'm running a periodic task with Celery and Django. The web scraping task is executing well and saving the new data, if any, to the database. However, the task is not sending a LINE message throug messagebird. This is the task snippet: tsukisamu = suii_scrap(TSUKISAMU_URL) try: t_jikan = tsukisamu[0] t_suii = tsukisamu[1] except TypeError: print("Error at Tsukisamu.") tsukisamu_obj = Tsukisamu.objects.latest() if t_jikan and t_suii is not None: tsukisamu_obj = Tsukisamu.objects.get_or_create(jikan=t_jikan, suii=t_suii) if tsukisamu_obj[0].shussui: client.conversation_start({ 'channelId': '881d2c2f475b23e38ed6d8da2eb9645e', 'to': 'Ua918d75611833f8d933e5a941dd9494d', 'type': 'text', 'content': { 'text': 'test', } }) If the model shussui method is True (which it is for test purposes), a message should be sent by the messagebird client's conversation_start method (imports are also alright). This exact same code is working on a normal Django view code, but when inside the celery task it isn't being sent. I'm new to Celery so maybe there's something I'm missing but can't really find what it can be. Any ideas? -
Can't convert string to float. Its showing error "could not convert string to float: 'None'"
Im working a Django project that gets my deivce location and shows the nearest places. Ive manage to pass the cordinates to the views module but I cant change from "str" to "float". It shows the error "could not convert string to float: 'None'". This is my code Template (index.html) <h1> Pharmacy Finder </h1> <button onclick="getLocation()">Try It</button> <p id="demo"></p> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML =position.coords.latitude + "," + position.coords.longitude; var lat = x; $.ajax({ url:'', type: 'get', data: {location: $(lat).text()} }); } View (views.py) from contextlib import nullcontext from django.shortcuts import render from django.http import HttpResponse #finder imports import time import googlemaps import pandas as pd # pip install pandas import numpy as np import re #Google Maps API Key API_KEY = 'AIzaSyAffT1NSiYnE4n_4v8No2GCYUqKp-XLtcc' map_client = googlemaps.Client(API_KEY) Rlatitude = 0 Rlongitude = 0 def index(request): global Rlatitude global Rlongitude text = request.GET.get('location') a = str(text) cordinates = re.split('\,',a) for ls in range(len(cordinates)): if ls ==0: Rlatitude = cordinates[ls] elif ls>0: Rlongitude = cordinates[ls] #the error is here: print(type(Rlatitude)) print(Rlatitude) if Rlatitude != 0: print(Rlatitude) a = float(Rlatitude) … -
django not recognizing my index.html page, stuck on the install worked
I have an index.html page made and also referenced in views.py and urls.py. For some reason, the home page at http://127.0.0.1:8000/ only shows the install worked default page. Am I calling it wrong? I followed the installation step-by-step and it's not working at all views.py: from django.shortcuts import render # Create your views here. def index(request): return render(request, 'index.html') from django.urls import include, path from django.contrib import admin from . import views urlpatterns = [ path('', views.index, name='index'), ] index.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <p>index</> </body> </html> -
How to save in the DB multiple images along with text using Reactjs and Django Rest Framework?
I am creating an e-commerce like app and I am stuck on implementing the feature to add the item (text + multiple images). I am sending a POST request from a Reactjs form, containing text and multiple images and I am able to save the text to the DB, and the images to the media folder, but I cannot save the images (path to media folder) in the DB (Psql). This is the error message: "IntegrityError at /api/image/multiple_upload/ null value in column "item_id_id" of relation "api_image" violates not-null constraint" My assumption is, as I am sending 2 different fetch POST requests on submit, one for the text and the other one for the images, and as each image has a FK to the item_id, the image's column cannot be filled as the item has not been yet created. Am I wrong? Is there any suggestion on how to implement that? models.py class Image(models.Model): image = models.ImageField(blank=True, null=True, upload_to='%Y/%m/%d') item_id = models.ForeignKey('Item', default="", on_delete=models.CASCADE) class Item(models.Model): item_name = models.CharField(max_length=200, default="") user_id = models.ForeignKey('User', on_delete=models.CASCADE,) serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ['id', 'item_name', 'user_id', 'details', 'desire'] class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class MultipleImageSerializer(serializers.Serializer): … -
Can anyone explain how to list the objects vertically instead of horizontal?
*Here is the code. With this code listing is done vertically.Here is the current output I want to make this vertically. *This is the current code I written. {% extends 'index.html' %} {%block body_block%} {%for p in carslist%} <section class="py-5"> <div class="container px-4 px-lg-5 mt-2"> <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center"> <div class="col mb-5"> <div class="card h-100"> <!-- Product image--> <img class="card-img-top" src="{{p.carpic.url}}" alt="..." /> <!-- Product details--> <div class="card-body p-4"> <div class="text-center"> <!-- Product name--> <h5 class="fw-bolder">{{p.carcompany}}</h5> <p>{{p.carmodel}}</p> <!-- Product price--> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Price: {{p.carprice}}</li> <li class="list-group-item">Kms: {{p.carkms}}</li> </ul> </div> <!-- Product actions--> <div class="card-footer p-4 pt-0 border-top-0 bg-transparent"> <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="#">View Details</a></div> </div> </div> </div> </div> </div> </section> {%endfor%} -
django query use aggregate on joined table
In my project , Each candidate can take part in some assessments, each assessment has some tests and each test has some questions in it and candidates should answer the questions. at the end of the test , scores of the questions are saved in question_score automatically and the score of test is saved in test_score table(which is average of question scores) each test has a weight and I want to add a field to candidate model as assessment_score and write a method in candidate class model which calculate the score of assessment based on weight of each test and score of it How can I use aggregate in my query with these joins on tables? the simplified models are : Assessment: class Assessment(BaseModel): title = models.CharField(max_length=255) tests = models.ManyToManyField( 'exam.Test', related_name='assessments', blank=True, through='TestOfAssessment', ) candidates = models.ManyToManyField( 'user.User', related_name='taken_assessments', blank=True, through='candidate.Candidate' ) def __str__(self): return self.title Test: class Test(BaseModel): class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 questions = models.ManyToManyField( 'question.Question', related_name='tests', blank=True, help_text='Standard tests could have multiple questions.', ) level = models.IntegerField(default=1, choices=DifficultyLevel.choices) title = models.CharField(max_length=255) summary = models.TextField() def __str__(self): return self.title TestOfAssessment: class TestOfAssessment(models.Model): assessment = models.ForeignKey('Assessment', on_delete=models.CASCADE) test = models.ForeignKey('exam.Test', on_delete=models.CASCADE) weight … -
Python - missing 1 required positional argument
Here is my first Django project. I am trying to develop a Scholarship system whereby the admin can add Countries that offer Scholarships into the system. Everything works fine at the level of my database and I'm able to add the countries. However, I have a sidebar menu and want any new country I add to the system, added to the menu automatically. **Views.py ** class CountryListView(ListView): template_name = "base.html" models = Country context_object_name = "countrys" Sidebar HTML Snippet -
Accessing Data from an Intermediate Model and the Main Model at the same time?
We've run into an interesting problem. We're using an intermediate model to track the quality of an item (PlayerProfile in this case) that belongs to a specific UserInventory. We'd like to be able to find the "total value" of that UserInventory by multiplying the "quantity" (in UserInventoryItemModel) by the "best_buy_price (in the MarketListing model). Here is what I have in the serializer now, but it fails at card.quantity. def get_owned_value(self, obj): inventory = obj.inventory.all() value = 0 for card in inventory: try: best_buy_price = card.marketlisting.best_buy_price quantity = card.quantity #this fails total = best_buy_price * quantity value = value + total except: continue return value I tried this - and it is able to get the quantity, but it can not longer access marketlisting.best_buy_price. def get_owned_value(self, obj): inventory = obj.userinventoryitem_set.all() value = 0 for card in inventory: try: best_buy_price = card.marketlisting.best_buy_price #this fails quantity = card.quantity total = best_buy_price * quantity value = value + total except: continue return value How can I access quantity and best_buy_price in the same loop? Here is a simplified version of the models: class PlayerProfile(auto_prefetch.Model): card_id = models.CharField(max_length=120, unique=True, primary_key=True) game = models.CharField(max_length=120, null=True) class MarketListing(auto_prefetch.Model): item = models.CharField(max_length=120, unique=True, primary_key=True) player_profile = auto_prefetch.OneToOneField( PlayerProfile, … -
how to schedule a task to run every n minutes at a specific time (celery-django)
When using the celerybeat in django, I would like to schedule a task to start at a specific time, and then run every 5 minutess. I was able to get the task to run every 5 minutes, using crontab(minute='*/5') and this will run after celerybeat is up but i want to run it for example at 8:30, how to do this? -
Django on nginx showing logs for both basic auth logged in and logged out for same device
Project setup: I have a Django app deployed on my VPS with nginx (using docker compose). The nginx has BASIC auth, so users have to login with BASIC auth in order to use the app. I also have fail2ban installed on my host machine, so if 4xx errors are returned for the same IP address multiple times, that IP address is banned. My app is primarily used for staff members at my store, and there are at most 3 people using the app on their respective computers. Problem: fail2ban is banning even my staff members, who should have been logged in via BASIC auth. Checking the logs, it seems that for the same IP address, there are logs for both logged in and logged out user. The logs look something like this: (masked IP address is the staff's, who should have been logged in) xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:00 +0900] "POST /search/ HTTP/1.1" 200 406 Chrome/108.0.0.0 xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:00 +0900] "POST /search/ HTTP/1.1" 200 406 Chrome/108.0.0.0 xxx.xxx.xxx.xx - - [08/Jan/2023:11:24:11 +0900] "GET /page-one/ HTTP/1.1" 401 574 Chrome/108.0.0.0 xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:11 +0900] "GET /page-one/ HTTP/1.1" 200 58526 Chrome/108.0.0.0 xxx.xxx.xxx.xx - staff [08/Jan/2023:11:24:14 +0900] "POST /page-one/ HTTP/1.1" 302 0 Chrome/108.0.0.0 xxx.xxx.xxx.xx … -
My django isn't working and won't let me do anything
I have been working on a project for the past 2 weeks. I deleted my migrations + pycache because I needed to record a video of myself freshly populating the db. However, once I tried to reboot my vscode and run migrations, suddenly I can't use python in my venv project % python manage.py runserver zsh: command not found: python i have been using the python command for 2 weeks straight, and all of a sudden it is not working :( when I try to use python3 manage.py migrate, I now get this error: TypeError: argument of type 'PosixPath' is not iterable all my django.db import models are all being highlighted too: I've already tried pip install django, but nothing seems to fix it!!! Idk what went wrong, if anyone could please help me fix this error -
correct websocket structure for django chat app
I am building the chat functionality on my app with django-channels and redis, and I am new to websocket. after collecting enough infomation, here's my sketch of the application. basically there are two types of chat: team chat user chat they are all integrited into one chat friends view. for team chat, such a team with pk=8, the user connects to let route = `ws://${window.location.host}/ws/team/${team.pk}/` to send and receive messages. and if the user is not in the team, the connection will be rejected. this means if you joined to team8, team12, team13... you be connected to ws8, ws12, ws13... for user app, establish ws connection between two user: for example, ws1 is used for user1 to receive message, which if user2 want to send message to user1, user2 must connect to the socket. this means if you have n contacts, it will be n ws connections. the chat consumer only applies in chat view, and I have a notification app uses ws and is implemented throughout the application. user1 connect to note1 to receive system infomation. this means if n user is online, n note socket connections will be established. soon I noticed the performance and number limit issue, … -
Django M2M through table delete and save methods
I have a many to many relation between two tables and relation is saved in a through table: class Book(models.Model): likes = models.ManyToManyField(User, through=BookLike) class User(models.Model): ... class BookLike(models.Model): user = models.ForeignKey(User) book = models.ForeignKey(Book) When a user likes or dislikes a book I want to carry out some actions like increasing/decreasing the like count of book for example. I tried overwriting save and delete functions of BookLike but they are not called when I call book_instance.likes.remove(user) and book_instance.likes.add(user). How can I achieve this? -
How to save the number of child paragraph in Django Model?
im beginner in django. Here im trying to save number like as MS word headings 1,2,3 levels. This model would save each paragraph items with numbers For example if there is no uplevel, numbers should be 1, 2, 3 else 1.1, 1.2 or 1.1.1, 1.1.2 But i can't do this. Please help to me. models class Document (models.Model): drafttype=models.ForeignKey(DraftType, on_delete=models.CASCADE,verbose_name='GroupItem') draft=models.CharField(max_length=500) number=models.CharField(max_length=500) uplevel=models.ForeignKey('self', on_delete=models.CASCADE, related_name='+') def __str__(self): return self.title def get_absolute_url(self): return reverse('doc-detail', args=[str(self.id)]) def get_update_url(self): return '/doc/update/{}'.format(self.id) def get_delete_url(self): return '/doc/del/{}'.format(self.id) def save(self): if self.uplevel: counter=Document.objects.filter(uplevel=self.uplevel) # increasing by 1 , should be 1.1, or 1.1.1 self.number=counter.number+'.'+counter.count() else: # getting last number and next one should be 2 or 3 counter=Document.objects.all().order_by('number').last() self.number=counter.number+1 Im tried separated model as like below. But i think this is not solution Models class Buleg (Authors): norm=models.ForeignKey(Norm, on_delete=models.CASCADE, verbose_name='Төсөл') text = models.TextField(verbose_name='Бүлэг') class Heseg (Authors): norm=models.ForeignKey(Buleg, on_delete=models.CASCADE, verbose_name='Бүлэг') text = models.TextField(verbose_name='Хэсэг') class Zaalt (Authors): norm=models.ForeignKey(Heseg, on_delete=models.CASCADE, verbose_name='Хэсэг') text = models.TextField(verbose_name='Заалт') -
How to change page content when changing in db Django
I am trying create notifications system in my site. Button with notifications situated on the ever page, this is make by using context processor. But I want that AJAX work, when update my model Notifications Now, I am make AJAX request which work ever 5 seconds, this request checking DB and change content on the page. How this make? If need, I can attach my code. -
NoReverseMatch at / Reverse for 'home' not found. 'home' is not a valid view function or pattern name
I'm working on my Django blog. I was working on a registration form, everything it was working until I tested it and redirection was not working properly. Trying to fix errors, I got this message django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found. 'home' is not a valid view function or pattern name. blog/urls.py from . import views from django.urls import path app_name = 'my_blog' urlpatterns = [ path('', views.home, name='home'), path('post/<slug:slug>/', views.post_detail, name='post_detail'), path('category/<slug:slug>/', views.category_detail, name='category_detail'), path('register/', views.register_request, name='register'), path('login/', views.login_request, name='login'), ] views.py def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successful." ) return redirect("my_blog:homepage") messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm() return render (request=request, template_name="register.html", context={"register_form":form}) def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("my_blog:homepage") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) In base.html I used "{% url 'home' %}", and now this is error when I try to reload page, I have no idea why this is … -
How are adapters used in django-allauth?
Hi everyone this is my first post on StackOverflow. I'm building a web application using Django and I would like to: Only allow people that have a Google account to sign up / log in Only people with a specific email domain can access the web app and their UserModel will be saved to the database. I started with coding a middleware, and it worked, I managed to log out those that tried to log in with a Google account associated with a not allowed email BUT they were saved in the database User model. I then found out about Adapters (for django-allauth) and I saw I could use them to achieve my goals but in the documentation, they are only cited once. I then started looking at the GitHub repo and found some more info but I'm still not able to implement this myself. Can anyone help me? Btw this is my code so far: Disclaimer: This code does not work, it's not even called when I try to test it. ( I tried to log in with a wrong Google account to see it it gets triggered but nothing appened) main_app/adapters.py from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from allauth.account.adapter import … -
Django NoReverseMatch at /account/register/
I am new in Django, trying to get an activation email but can't figure out what's the problem. Reverse for 'activate' with keyword arguments '{'uidb64': 'MTU', 'token': 'bhp5py-6f0679ec02bc2863df780ea30d2984da'}' not found. 1 pattern(s) tried: ['account/activate/(?P[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)\Z'] views.py def account_register(request): if request.method == 'POST': registraionForm = RegistraionForm(request.POST) if registraionForm.is_valid(): user = registraionForm.save(commit=False) user.email = registraionForm.cleaned_data['email'] user.set_password(registraionForm.cleaned_data['password']) user.is_active = False user.save() # setup email current_site = get_current_site(request) subject = 'Activate your account' message = render_to_string('account/registration/account_activation_email.html',{ 'user': user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) user.email_user(subject=subject, message=message) return HttpResponse('Successful') else: registraionForm = RegistraionForm() return render(request, 'account/registration/register.html', {'form':registraionForm}) def account_activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = UserBase.objects.get(pk=uid) except: pass if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('account:dashboard') else: return render(request, 'account/registraion/activation_invalid.html') urls.py from django.urls import path from . import views app_name = 'account' urlpatterns = [ path('register/', views.account_register, name='register'), path('activate/<slug:uid64>/<slug:token>', views.account_activate, name='activate'), path('dashboard/', views.account_dashboard, name='dashboard'), ] token.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( text_type(user.pk) + text_type(timestamp) + text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() html {% autoescape off %} Hi {{ user.user_name }}, Your account has successfully created. Please click below link to activate your account http://{{ domain }}{% url … -
Page not found at /register/... Raised by: my_blog.views.post_detail... Django
I'm working on Django blog, and I'm working on register form. I got error Page not found at /register/ like you can see on image. But it say that error was raised by post_detail - Raised by: my_blog.views.post_detail This is register.html {% extends "base.html" %} {% load static %} {% block content %} {% load crispy_forms_tags %} <!--Register--> <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form|crispy }} <button class="btn btn-primary" type="submit">Register</button> </form> <p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p> </div> {% endblock %} Views.py def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successful." ) return redirect("main:homepage") messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm() return render (request=request, template_name="register.html", context={"register_form":form}) def post_detail(request, slug): latest_posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9] post = get_object_or_404(Post, slug=slug) context = {'post': post, 'latest_posts': latest_posts} return render(request, 'post_detail.html', context) blog/urls.py from . import views from django.urls import path urlpatterns = [ path('', views.home, name='home'), path('<slug:slug>/', views.post_detail, name='post_detail'), path('category/<slug:slug>/', views.category_detail, name='category_detail'), path('register/', views.register_request, name='register'), ] forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() … -
I'm getting a 403 Forbidden response when using axios instance in react to access my api endpoint in Django rest framework
I am working on a blog project, following a certain tutorial, using django 4.1.4, DRF-3.14, React 18.2, and using drf-social-oauth2 1.2.1 module for social logins When I use postman or that DRF API Interface to make request to the api everything is working fine, I can do all the request when authenticated but when I use exios instance I keep getting the 403 Forbidden error. Here is axios file: import axios from 'axios'; const baseURL = 'http://127.0.0.1:8000/api/'; const token = localStorage.getItem('access_token') console.log(token); const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'multipart/form-data', accept: 'application/json', }, }); axiosInstance.interceptors.response.use( (response) => { return response; }, async function (error) { const originalRequest = error.config; if (typeof error.response === 'undefined') { alert( 'A server/network error occurred. ' + 'Looks like CORS might be the problem. ' + 'Sorry about this - we will get it fixed shortly.' ); return Promise.reject(error); } if ( error.response.status === 401 && originalRequest.url === baseURL + 'token/refresh/' ) { window.location.href = '/login/'; return Promise.reject(error); } if ( error.response.data.code === 'token_not_valid' && error.response.status === 401 && error.response.statusText === 'Unauthorized' ) { const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken) { const tokenParts = JSON.parse(atob(refreshToken.split('.')[1])); // exp date …