Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automatically change password in Django
I'm a Django developer and I want to change the password automatically by system. This is my python code data = form.cleaned_data passw = data["password"] print(datax) us = User.objects.get(email = datax) us.set_password(passw) us.save() when I run it, it doesn't save the password. what can I do? It doesn't save that new password. -
Migrations not reflecting after making Migrations in Django in Docker
I creating Django app and connect it with Docker along postgres db. While start with docker server is running fine but I did migrations by going into container of Django app but those migrations are not reflecting into DB(tables not created as per the model). # ======Docker compose.yml file=== version: '3' services: db: image: postgres environment: - POSTGRES_DB=eshop - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: admin_db volumes: - ./data/postgres:/var/lib/postgresql/data ports: - 54321:5432 web: build: . command: bash -c "python eshop/manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - "8000:8000" depends_on: - db enter image description here I want to know how to do migrations while django and postgres are runing using docker such that after migrations tables will be created in postgres -
Hosting Webapp for internal use within a small company
I'm developing a web app using Django and Vue.js intended for internal use within a small company (around 20 employees). I'm considering hosting it on a Platform-as-a-Service (PaaS) like Heroku or Netlify. My primary concern is ensuring that external users can't access the app and, ideally, can't log in even if they manage to access it. Currently, I'm relying on user authentication provided by Django. I'd like to know if Django's user authentication alone is sufficient for restricting access or if additional measures are commonly recommended for securing internal applications. Hosting it myself is less preferable due to the associated challenges, but I'm open to suggestions. What are the best practices in such scenarios? Thanks in advance for any guidance! For context: I'm still new at web app development. If anyone have some kind of cheatsheet for best practices in web development, i'd love to see it. Thx! -
Stripe payment not showing in Stripe dashboard after successful payment
I’m facing an issue with Stripe integration with my Django e-commerce website. Even though I followed the Stripe docs of accepting online payments, so when i open the checkout and complete the payment form, I get redirected to the success page. However, upon checking the Stripe dashboard for the payment, they are not showing. Also, I’m sending all the products at once and I’m loading the Stripe JS in my checkout. I'm not sure if I've set it up correctly. Is my integration complete? @login_required(login_url='core:login_register') def checkout(request): user_profile = request.user.userprofile cart = get_object_or_404(Cart, user=user_profile) total_price = cart.calculate_total_price() has_existing_billing_address = Address.objects.filter(user=user_profile).exists() form = CheckoutForm(request.POST or None) if request.method == 'POST' and form.is_valid(): order, _ = Checkout.objects.get_or_create(user=user_profile, cart=cart) default_billing_address = form.cleaned_data['use_default_billing_address'] if default_billing_address: billing_address = Address.objects.filter(user=user_profile, default=True).first() order.billing_address = billing_address else: new_billing_address = Address( user=user_profile, street_address=form.cleaned_data['street_address'], apartment_address=form.cleaned_data['apartment_address'], zip_code=form.cleaned_data['zip_code'], country=form.cleaned_data['country'], default=True ) new_billing_address.save() order.billing_address = new_billing_address order.save() payment_method = form.cleaned_data.get('payment_method') if payment_method: return redirect('core:payment', payment_method='card') context = { 'total_price': total_price, 'form': form, 'has_existing_billing_address': has_existing_billing_address, 'STRIPE_API_KEY': settings.STRIPE_SECRET_KEY, } return render(request, 'checkout.html', context) @login_required(login_url='core:login_register') def payment(request, payment_method): user_profile = request.user.userprofile cart = get_object_or_404(Cart, user=user_profile) billing_address_exists = Address.objects.filter(user=user_profile).exists() cart_items = cart.items.all() if not billing_address_exists: return redirect('core:checkout') line_items = [{ 'price_data': { 'currency': 'usd', 'product_data': { 'name': … -
Django LogoutView is not working. How to resolve this problem using classbased default function?
I want to use django buildin LogoutView library but it is not working. When i use this, it shows "This page isn’t working" The logout function should work and logout the user. Below is the urls.py code. from django.urls import path from .views import TaskList, TaskDetail, TaskCreate, TaskUpdate, DeleteView, CustomLoginView, RegisterPage, TaskReorder from django.contrib.auth.views import LogoutView urlpatterns = [ path('login/', CustomLoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(next_page='login'), name='logout'), path('register/', RegisterPage.as_view(), name='register'), path('', TaskList.as_view(), name='tasks'), path('task/<int:pk>/', TaskDetail.as_view(), name='task'), path('task-create/', TaskCreate.as_view(), name='task-create'), path('task-update/<int:pk>/', TaskUpdate.as_view(), name='task-update'), path('task-delete/<int:pk>/', DeleteView.as_view(), name='task-delete'), path('task-reorder/', TaskReorder.as_view(), name='task-reorder'), ] -
from . import views returning an attribute error
I created a python file in myapp and named it urls.py It looks like from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path("", views.home), path("predict/", views.predict), path("predict/result", views.result) Also I edited The project's urls.py as instructed an it now looks like from django import views from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path("", views.home), path("predict/", views.predict), path("predict/result", views.result) The views.py in myapp looks like def result(request): data = pd.read_csv(r"C:\Users\user\Desktop\MAX\diabetes.csv") X = data.drop("Outcome", axis=1) Y = data['Outcome'] X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) model = LogisticRegression(max_iter=1000) model.fit(X_train, Y_train) val1 = float(request.Get['n1']) val2 = float(request.Get['n2']) val3 = float(request.Get['n3']) val4 = float(request.Get['n4']) val5 = float(request.Get['n5']) val6 = float(request.Get['n6']) val7 = float(request.Get['n7']) val8 = float(request.Get['n8']) pared = model.predict([[val1, val2, val3, val4, val5, val6, val7, val8,]]) result1 = "" if pared == [1]: result1 = "positive" elif pared == [0]: result1 = 'negative' return render(request, "predict", {"result": result1}) I expected the server to run successfully -
'Account' object has no attribute 'user'
I was implementing django email verification.I'm facing an issue with 'Account' object has no attribute 'user'. 'token': default_token_generator.make_token(user), from django.shortcuts import render, redirect from .forms import RegistrationForm from .models import Account from django.contrib import messages, auth from django.contrib.auth.decorators import login_required #verification email from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes from django.contrib.auth.tokens import default_token_generator from django.core.mail import EmailMessage def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] username = email.split("@")[0] user = Account.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username, password=password) user.phone_number = phone_number user.save() # USER ACTIVATION current_site = get_current_site(request) mail_subject = 'Please activate your account' verification_email_message = render_to_string('accounts/account_verification_email.html', { 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = email send_email = EmailMessage(mail_subject, verification_email_message, to=[to_email]) send_email.send() messages.success(request, 'Registration Successful') return redirect('register') else: form = RegistrationForm() context = { 'form': form, } return render(request, 'accounts/register.html', context) def login(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) # messages.success(request,"You are now logged in.") return redirect('home') else: messages.error(request,'Invalid login credentials') return redirect('login') return render(request, 'accounts/login.html') @login_required(login_url … -
Js is loading but not running in django
I have been creating a website using django but when I try to access a js file in the static folder it doesn't work. However, in the python terminal I get the following message (meaning that the file is in fact loading but not running): [21/Jan/2024 10:07:14] "GET /static/CACHE/js/output.10e324644ab8.js HTTP/1.1" 304 0 Also, using the debug_toolbar library which I have added to my project I can see the file is loaded and I can open it. This is my html code: <html lang="en"> <head> {% load static %} {% load compress %} <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Centro Psi-Clinico Pisa</title> {% compress css %} <link rel="stylesheet" type="text/x-scss" href="{% static 'scss/base.scss' %}" /> {% endcompress %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="{% static 'js/main.js' %}"></script> </head> <body> <header>{% include 'navbar.html' %}</header> <main>{% block content %} {% endblock %}</main> </body> </html> -
Django IntegrityError - NOT NULL constraint failed: app_comments.author_id
I'm posting this after trying to find answers from other threads without luck. Seems like the form is missing some data, which I can't understand why. I'm using save(commit=False) also the author has null=True, blank=True Don't know what is app_comments.author_id my code: models.py class Comments(models.Model): content = models.TextField() name = models.CharField(max_length=200) email = models.EmailField(max_length=200) website = models.CharField(max_length=200) date = models.DateTimeField(auto_now=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) views.py def post_page(request, slug): post = Post.objects.get(slug=slug) form = CommentForm() if request.POST: comment_form = CommentForm(request.POST) if comment_form.is_valid: comment = comment_form.save(commit=False) post_id = request.POST.get('post_id') post = Post.objects.get(id=post_id) comment.post = post comment.save() if post.view_count is None: post.view_count = 1 else: post.view_count = post.view_count + 1 post.save() context = { 'post': post, 'form': form } return render(request, 'app/post.html', context) post.html <form method="POST"> {% csrf_token %} {{form.content}} <div class="grid-3"> <input type="hidden" name="post_id" value="{{post.id}}"> {{form.name}} {{form.email}} {{form.website}} </div> <button class="btn btn-primary rounded"> Post comment </button> </form> forms.py from django import forms from app.models import Comments class CommentForm(forms.ModelForm): class Meta: model = Comments fields = { 'content', 'email', 'name', 'website' } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['content'].widget.attrs['placeholder'] = 'Type your comment..' self.fields['email'].widget.attrs['placeholder'] = 'Email' self.fields['name'].widget.attrs['placeholder'] = 'Name' self.fields['website'].widget.attrs['placeholder'] = 'Website (optional)' The error: The above … -
HttpResponseRedirect is working but the distination template can't render out the html
I'm working on a twitter like website for practice purpose using django framework. in follow function, I use js to post a information back to my view to add a follow relation to my database. after that, it suppose to redirect back to original page. But it turns out the HttpResponseRedirect is working, but the destination template won't render the template out. I have to refresh the page manually. this is where HttpResponseRedirect happens here is the destination view this is the page of the follow function urls.py here we can see it actually redirect back to views.profile and print "hello" out, but it didn't render the template, I have to refreash it myself. Why? I tryed redirect to 'index' page, it still not working. maybe I can return render(request, 'network/profile')? but I will have to give it the whole dictionary again. -
Django Google Sign-in Issue: Cookies not saving when deploying backend
I am currently working on a Django project that involves Google sign-in functionality. The setup works perfectly when both the frontend and backend are running locally. However, when I deploy the backend and test the frontend locally, the tokens do not get saved in cookies. Here's a simplified overview of the relevant code: Certainly! Here's a template for your question on Stack Overflow: Title: Django Google Sign-in Issue: Cookies not saving when deploying backend Description: I am currently working on a Django project that involves Google sign-in functionality. The setup works perfectly when both the front end and back end are running locally. However, when I deploy the backend and test the front end locally, the tokens do not get saved in cookies. Here's a simplified overview of the relevant code: Backend (Django): class GoogleLoginApi(PublicApiMixin, ApiErrorsMixin, APIView): class InputSerializer(serializers.Serializer): code = serializers.CharField(required=False) error = serializers.CharField(required=False) def create_user_with_profile(self, user_email, user_info): try: user = User.objects.get(email=user_email) except User.DoesNotExist: user = User.objects.create_user( email=user_email, username=user_email.split("@")[0], first_name=user_info["given_name"], last_name=user_info["family_name"], password=User.objects.make_random_password(), ) user_profile = UserProfile.objects.create(user=user) save_image_from_url( user_profile, user_info["picture"], f"{user.username}.{user_profile.id}.jpg", ) return user def get(self, request, *args, **kwargs): input_serializer = self.InputSerializer(data=request.GET) input_serializer.is_valid(raise_exception=True) validated_data = input_serializer.validated_data code = validated_data.get("code") error = validated_data.get("error") login_url = f'{config("BASE_FRONTEND_URL")}/login' if error or not code: … -
Creating a pass-through field with Model Serializer: Django
I am new to Django Rest Framework and appreciate the help from this community. I am making an AJAX call to some Django Rest Framework APIs in the backend and I would like to pass the name of the javascript function to be called in the UI upon successful completion of the request. AJAX Function var saveEditedData = function (event) { let parentElement = event.parentElement; let enctype = (event.enctype) ? event.enctype : "application/x-www-form-urlencoded"; let method = (event.method) ? event.method : "POST"; $.ajax({ cache: false, contentType: false, data: event.data, enctype: enctype, processData: false, type: method, url: event.url, success: function (response){ console.log(response); if (response['onSuccessFn']){ successFns[response['onSuccessFn']](response); } }, error: function (response) { let errors = response["responseJSON"]["errors"]; displayErrors(parentElement, errors); } }); } DJANGO REST Serializer Class class DocumentCategorySerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() on_success_fn = serializers.SerializerMethodField() class Meta: model = DocumentCategory fields = ['id', 'name', 'description', 'on_success_fn'] def get_on_success_fn(self, obj): return self.data['on_success_fn'] **Sample Inbound Data to Serializer** [name : TestCategory] [description: Testing this] [on_success_fn: addCategorySuccessFn] The idea is that I use on AJAX function across multiple UI interactions and the method to be called on success is dynamically executed on return. I have a model serializer but all the fields are derived from the database. I … -
mongodb aggregation pipeline the final results are getting duplicated
I'm using mongodb in Django with pymongo. Below is my pipeline: plan_id = 1 search_string = "" page = 1 limit = 25 pipeline = [ { "$lookup": { "from": "plans", "pipeline": [ { "$match": { "$expr": { "$and": [ {"$ne": ["$id", plan_id]}, ] } } } ], "as": "plansList", } }, { "$lookup": { "let": {"linkedPlansIds": "$linkedPlansIds"}, "from": "plans", "localField": "linkedPlansIds", "foreignField": "id", "as": "LinkedPlans", "pipeline": [{"$match": {"$expr": {"$eq": ["$planId", plan_id]}}}], } }, {"$set": {"mergedArray": {"$setUnion": ["$LinkedPlans", "$plansList"]}}}, {"$unwind": "$mergedArray"}, {"$match": {"mergedArray.name": {"$regex": search_string, "$options": "i"}}}, { "$addFields": { "mergedArray.isLinked": {"$in": ["$mergedArray.id", "$linkedPlansIds"]}, } }, {"$skip": (page - 1) * limit}, {"$limit": limit}, { "$group": { "_id": None, "limit": {"$first": limit}, "page": {"$first": page}, "totalCount": {"$count": {}}, "listData": {"$push": "$mergedArray"}, } }, { "$project": { "_id": 0, "totalCount": 1, "page": 1, "limit": 1, "listData.id": 1, "listData.name": 1, "listData.isLinked": 1, } }, ] data = list(collection.aggregate(pipeline)) The results are below: [ { "limit": 25, "page": 1, "totalCount": 18, "listData": [ {"id": 2, "name": "happ", "isLinked": True}, {"id": 3, "name": "ddd", "isLinked": True}, {"id": 4, "name": "sss", "isLinked": False}, {"id": 5, "name": "eee", "isLinked": False}, {"id": 2, "name": "happ", "isLinked": False}, {"id": 3, "name": "ddd", "isLinked": False}, {"id": 4, "name": "sss", … -
Making free payments in a Django projects
I am making a Django project for my final year of college. I also have a payment option in the project. But every payment gateway is charging some fees for processing transactions. I need some free payment option for my project, just a QR code for payment will also work. Can someone help me find a free payment option which I can easily get working on my Django project? I have tried finding a way through RazorPay, Paytm, etc. but no where I found what I was looking for. -
Issues using mysql with Django
When I try to make a migration in a Django project using mysql, I get this error. I have mysql 8.3.0, mysqlclient 2.2.1 and python 3.12.1 Traceback (most recent call last): File "/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/pedroformigo/Downloads/C7M3L2 Lab/myproject/manage.py", line 22, in <module> main() File "/Users/pedroformigo/Downloads/C7M3L2 Lab/myproject/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): File "/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/django/db/models/base.py", line 141, in __new__ new_class.add_to_class("_meta", Options(meta, app_label)) File "/Users/pedroformigo/.local/share/virtualenvs/myproject-lwEuww5V/lib/python3.9/site-packages/django/db/models/base.py", … -
Postgresql single-query to combine tables while replacing foreign keys with last names
I'm working with Postgresql and I am hoping to achieve this task with a single sql query. Generally, this would not be an issue, however, my tables are structured where I have multiple foreign key references to the same table on a per row basis: Two tables in question: People_Table: person_id (pk) firstName (text) lastName (text) age (int) years_of_employment (float) sal (int) position (fk to different table not provided) Statistics_Table stat_id supervisor_id (fk to people) secretary_id (fk to people) research_assistant (fk to people) department_id (fk to different table not listed) I need to query the statistics table and: get salaries for our 3 people and get years of service for all 3 sum all their years and salaries and return these details from my query in a specific format: people fkey references replaced with last_name, department_id with department_name, and insert each employees years and salary and add two columns for total_salary and cumulative_years deptName|supName|supSal|supYears|secName|secSal|secYears|rdName|rdSal|rdYears|totalSal|totalYears I can do this for each person individually, but it takes me three separate queries. I'm hoping there is a way to do it in one query so that the results of this one query is as follows (grouped by department and ordered by sum of … -
Python Django & SQLite3 Registration Issue
I am having troubles saving my customer's entry to the CustomerProfile table. It appears to save on User table, but not CustomerProfile table. I have two folder named app and user. Here are my codes. forms from app from django import forms from django.contrib.auth.forms import UserCreationForm from user.models import Customer, CustomerProfile, generate_customer_id class Customer_Register_Form(UserCreationForm): cus_name = forms.CharField( label="Customer Name", widget=forms.TextInput(attrs={"class": "form-control"}) ) email = forms.EmailField(widget=forms.EmailInput(attrs={"class": "form-control"})) phone_number = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}) ) address = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"})) username = forms.CharField( widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Enter your username"} ) ) password1 = forms.CharField( label="Password", widget=forms.PasswordInput( attrs={"class": "form-control", "placeholder": "Enter your password"} ), ) password2 = forms.CharField( label="Confirm Password", widget=forms.PasswordInput( attrs={"class": "form-control", "placeholder": "Confirm your password"} ), ) class Meta: model = Customer # Use your custom user model fields = [ "username", "cus_name", "password1", "password2", "email", "phone_number", "address", ] def save(self, commit=True): user = super().save(commit=False) user.cus_name = self.cleaned_data['cus_name'] user.email = self.cleaned_data['email'] user.phone_num = self.cleaned_data['phone_number'] user.address = self.cleaned_data['address'] if commit: user.save() # Assuming there's a one-to-one relationship between User and CustomerProfile CustomerProfile.objects.create(username=user, cus_id=generate_customer_id(user)) return user models from user from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db.models.signals import post_save from phonenumber_field.modelfields import PhoneNumberField from django.dispatch import receiver # Create your models … -
'TaggableManager' object has no attribute 'get_reverse_joining_fields'
I am trying to retrieve similar posts by tag. spent hours trying to fix this issues but couldn't. Thank you for any help here is my views.py def post_detail(request,id): post = get_object_or_404(Post, status=Post.Status.PUBLISH, id=id) post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.objects.filter(tags__in = post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags = Count('tags')).order_by('-same_tags', '-pblish')[:4] comments = post.comments.filter(active=True) form = commentForm() return render(request, 'blog/post/detail.html', context={"post":post, 'comments':comments, 'form':form, 'similar_posts':similar_posts}) ``` The error message i get is *'TaggableManager' object has no attribute 'get_reverse_joining_fields'* -
Django "CSRF cookie not set" error when calling server from cross origin frontend
I have a Vue application locally and a Vite dev server hosting the application. I am using a Vite ngrok plugin for testing resulting in an ngrok URL like the following: http://a709-73-72-42-7.ngrok-free.app I also have a Django application running locally on port 8000 servicing requests from the frontend (not hosting the frontend). To demonstrate the error I'm seeing, I have a login page that is submitting a POST request to the Django backend using the fetch method: async function login(username, password) { const token = await _getCsrfToken(); if (!token) { throw new Error('CSRF token not available'); } const resp = await fetch(`${API_URL}/account/login`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': token, }, credentials: 'include', body: JSON.stringify({ username, password }), }); return resp; } async function _getCsrfToken() { const resp = await fetch(`${API_URL}/account/csrf`, { credentials: 'include', }); return resp.headers.get('x-csrftoken'); } Notice the _getCsrfToken calls another endpoint, account/csrf to get a CSRF token from the Django backend. On the backend, the account/csrf is handled by: def csrf(request: HttpRequest) -> HttpResponse: resp = HttpResponse() resp['X-CSRFToken'] = get_token(request) return resp And the account/login endpoint is handled by: @require_POST def login(request: HttpRequest) -> HttpResponse: ... do stuff to authenticate ... The call to account/csrf is … -
Pythonanywhere not supporting audio
`i have created a project in which user can upload pdf and get speech in different voices, i have used python, django, jingaa, html css..., now the main problem is that i have 2 buttons 1st buttons plays audio and 2nd buttton downloads the audio.Im using elevenlabs api to convert text into audio, now the problem is in local everthing is working fine audio is coming as a output but in my hosted site the audio is getting download but 1st button not playing, when im playing audio im getting response that my audio is played successfully but its not working. My hosted website URL(gaganjeet99.pythonanywhere.com). type here # Handle the form submission for generating and playing audio from django.shortcuts import render from django.http import HttpResponse import elevenlabs def generate_and_play_audio(request): if request.method == 'POST': voice_input = request.POST.get('voice_input') text_input = request.POST.get('text_input') action = request.POST.get('action') voice_mapping = { "Adam": elevenlabs.generate, "Antoni": elevenlabs.generate, } if voice_input not in voice_mapping: return HttpResponse(f"Voice '{voice_input}' not recognized.") generate_function = voice_mapping[voice_input] audio = generate_function(text=text_input, voice=voice_input, model="eleven_multilingual_v2") if not generate_function: return HttpResponse(f"Error: Unable to find generate function for voice '{voice_input}'.") try: audio = generate_function(text=text_input, voice=voice_input, model="eleven_multilingual_v2") except Exception as e: return HttpResponse(f"Error generating audio: {str(e)}") if not audio or … -
EC2 and Django (in ASG) Connection Fails on Private IP, succeeds on private if I add/remove public IP
As part of the deployment of a Django website via an Application Loag Balancer + Auto Scaling Group, I'm running into a problem that I've found the origin of, but I can't see how to solve it. I've configured my instance so that gunicorn launches at startup, and nginx listens on port 80 (redirection of django port 8000 to 80) on the address of the Application Load Balancer. When my instances are in the auto-scaling-group -> They ping "Unhealthy" and are cut off in a loop. In order to test at instance level, I SSH directly to the instance via the private IP (the architecture is in a VPC, the ASG launch template is done without public IP). I check nginx and gunicorn, everything seems to work. When I try to check the return via : curl http://10.0.4.84:80 or curl http://10.0.4.84:8000 (10.0.4.84 being the private IP address), I get an error on port 80 : curl: (7) Failed to connect to 10.0.4.84 port 80 after 0 ms: Couldn't connect to server And a timeout on port 8000. On the other hand, here's what I don't understand: if I assign a public IP address to the instance and remove it immediately, … -
View.__init__() takes 1 positional argument but 3 were given
I am trying to register a user, and have the user logged into the page. The database fetches the data and stores it but shows this error on the front end ERROR enter image description here views.py enter image description here urls.py enter image description here models.py enter image description here tried adding arg*, kwarg** in different parts of the code but none of them work apparently -
Django + Next.js + Tailwind
I'm using pycharm and want to create a webapp by Django and Next.js and Tailwind but I just don't know how to combine these 3 together. I tried watching some youtube videos and search a bit in google which unfortunately wasn't helpful to me -
Load failed (IOS) and failed to fetch (Android) error in react app
Now im trying to simply post json to django with fetch API but as mentioned on title error occurred in mobile device.. my reac post code is like this fetch("http://127.0.0.1:8000/uploading_firstName", { method: 'POST', body : JSON.stringify({firstName: "kim",}), headers:{ 'Content-Type' : 'application/json', }, }); im getting hard time with solving it since it works perfectly in window browser. But when i do this on mobile device (IOS, Android) Load failed (IOS) and failed to fetch (Android) error occurs. I'm not using any localhost urls and it added CORS_ORIGIN_WHITELIST on django setting as well. Can anyone help me with these errors only happened in MOBILE device? -
Django website stuck on default Nginx welcome page
So I tried hosting my client's website on Linode and I made the site using django. I am using Nginx and gunicorn for hosting but I am stuck in the default Nginx page. The following is my Nginx config: server { listen 80; server_name my.ip.address scopeplus.org www.scopeplus.org; error_log /var/log/nginx/error.log debug; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/scope_website/scope; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The following is my gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/scope_website ExecStart=/root/venvPath/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ scope_website.wsgi:application [Install] WantedBy=multi-user.target The following is my gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target My settings.py file is located at the following path: root@localhost:~/scope_website/scope_website# pwd /root/scope_website/scope_website root@localhost:~/scope_website/scope_website# ls asgi.py __init__.py __pycache__ settings.py urls.py wsgi.py The following is the journalctl output from the Ubuntu terminal: Jan 20 14:24:33 localhost gunicorn[7619]: Forbidden (CSRF cookie not set.): / Jan 20 14:24:33 localhost gunicorn[7619]: - - [20/Jan/2024:14:24:33 +0000] "POST / HTTP/1.0" 403 2869 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36" Jan 20 14:45:50 localhost gunicorn[7617]: - - [20/Jan/2024:14:45:50 +0000] "GET / HTTP/1.0" 200 8692 "-" "Mozilla/5.0 zgrab/0.x" Jan …