Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django nested serializer instance update issue
I am building a django backend rest API and I have an issue which I can't overcome. So I have two models. #1 Company Model: class Company(models.Model): companyID = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50) email = models.CharField(max_length=50) description = models.CharField(max_length=500,blank=True, null=True) #2 Employee Model: class Employee(models.Model): JOB_CHOICES = [ ('software engineer', 'Software Engineer'), ('data scientist', 'Data Scientist'), ('product manager', 'Product Manager'), ('data analyst', 'Data Analyst'), ('software developer', 'Software Developer'), ('ui/ux designer', 'Ui/UX Designer'), ('manager', 'Manager'), ('software tester', 'Software Tester'), ('accountant', 'Accountant') ] employeeID = models.BigAutoField(primary_key=True) companyID = models.ForeignKey(Company, db_column="companyID", related_name='employees', on_delete=models.CASCADE) name = models.CharField(max_length=50) email = models.CharField(max_length=50) age = models.IntegerField(default=18, validators=[MinValueValidator(18), MaxValueValidator(100)]) job = models.CharField(max_length=50, choices=JOB_CHOICES, default='software engineer') cv = models.CharField(max_length=500, null=True, blank=True) I would like to create a serializer which is get one object like this (from PUT request): { "companyID": 3, "name": "New Name", "email": "test@gmail.com", "description": "test", "employees": [ { "employeeID": 31, "name": "Test USER", "email": "goreca7783@fulwark.com", "age": 18, "job": "data analyst" } ] } and it should update all of the values in the database. Here's my serializer this is how I tried to solve this problem which is almost works. class CompanyEmployeeSerializer(serializers.ModelSerializer): # Serialize the employees of a company employees = EmployeeCompanySerializer(many=True) class Meta: model = … -
Passing parameters to a database backend in Django
I have created a Django backend to manage databases. I need to be able to pass values to it based on the user. I have created this Middleware for that purpose, and it behaves correctly in the development environment, PyCharm. The question is, will it work correctly in production if it's running with multiple threads since I'm using Gunicorn? My code, I use the session variable SESSION_B2J for this, and from the backend, I call get_session_b2j to retrieve values: import threading def get_session_b2j(): thread_local = B2jBakendMiddleware.thread_local if hasattr(thread_local, 'session_b2j'): return thread_local.session_b2j def set_session_b2j(session_b2j): thread_local = B2jBakendMiddleware.thread_local thread_local.session_b2j = session_b2j class B2jBakendMiddleware(object): thread_local = threading.local() def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self.thread_local.session_b2j = request.session.get('SESSION_B2J') response = self.get_response(request) return response -
I need to show funds according to the category selected in point 1
django application, I need to take categories from the database (step 1) and based on them (step 3) show the funds that belong to these categories, how can this be done in js? Thank you models.py TYPE = ( (1, 'fundacja'), (2, 'organizacja pozarządowa'), (3, 'zbiórka lokalna'), ) class Category(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class Institution(models.Model): name = models.CharField(max_length=64) description = models.TextField() type = models.IntegerField(choices=TYPE, default=1) category = models.ManyToManyField(Category) def __str__(self): return self.name @property def type_name(self): return TYPE[self.type - 1][1] class Donation(models.Model): quantity = models.IntegerField() categories = models.ManyToManyField(Category) institution = models.ForeignKey(Institution, on_delete=models.CASCADE) address = models.CharField(max_length=64) phone_number = models.IntegerField() city = models.CharField(max_length=64) zip_code = models.CharField(max_length=10) pick_up_date = models.DateField() pick_up_time = models.TimeField() pick_up_comment = models.TextField() user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) is_taken = models.BooleanField(default=False) taken_timestamp = models.DateTimeField(auto_now=True) views.py class DonationView(LoginRequiredMixin, View): def get(self, request): all_category = Category.objects.all() all_institution = Institution.objects.all() context = { 'all_category': all_category, 'all_institution': all_institution, } return render(request, 'form.html', context) def post(self, request): try: institution_name = request.POST.get('organization') institution = Institution.objects.get(name=institution_name) categories_names = request.POST.getlist('categories') categories_ids = [] for category_name in categories_names: category = Category.objects.get(name=category_name) categories_ids.append(category.id) quantity = request.POST.get('bags') address = request.POST.get('address') phone_number = request.POST.get('phone') city = request.POST.get('city') zip_code = request.POST.get('postcode') pick_up_date_str = request.POST.get('data') pick_up_date = datetime.strptime(pick_up_date_str, '%Y-%m-%d').date() pick_up_time … -
error as Add or change a related_name argument to the definition for 'accounts.CustomUser.groups' or 'auth.User.groups'
` from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): profile_picture = models.ImageField(upload_to='profile_pics/', blank=True, null=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=255, blank=True) date_of_birth = models.DateField(null=True, blank=True) interests = models.CharField(max_length=255, blank=True) twitter_profile = models.URLField(blank=True) instagram_profile = models.URLField(blank=True) linkedin_profile = models.URLField(blank=True) class Meta: db_table = 'tbl_profile' def __str__(self): return self.username class UserRelationship(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='following') followed_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='followers') class Meta: db_table = 'tbl_followers' def __str__(self): return f"{self.user.username} follows {self.followed_user.username}" ` error: HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.groups' or 'auth.User.groups'. accounts.CustomUser.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'accounts.CustomUser.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.CustomUser.user_permissions' or 'auth.User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'accounts.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'accounts.CustomUser.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'auth.User.user_permissions' clashes with reverse accessor for 'accounts.CustomUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'accounts.CustomUser.user_permissions'. basically i want create user profile by inherit abstractuser class in django models.py for my social chat app, but i m not able to migrate this models with above error. -
I am working with django and i got some errors .why BaseAuthentication from restframework showing me errors what is the reasons
Showing this after running server .What is the reason ? This is the code i wrote. I think i wrote the code correctly i asked the G.P.T it saying that you need to create custom authentications. can anyone explain what is the reason behind it? -
Sending email through Django, incorrect page rendered
Basically I am trying to send email to users when they click the activation link sent to their email when registered. The below code works fine and user does get the email however after email.sent() its goes to activation_invalid.html instead of activation_success.html def account_activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) current_site = get_current_site(request) subject = 'Activation Successful!' message = render_to_string('app/auth/email/account_activation_success_email.html', { 'user': user, 'domain': current_site.domain, }) to_email = user.email email = EmailMessage(subject, message, to=[to_email]) email.send() return render(request, 'app/auth/activation_success.html') else: return render(request, 'app/auth/activation_invalid.html') When I remove email.send(), activation_success.html is rendered like it should in the first place. -
How to redirect user to welcome page by authenticating its enterd details in login form with db in django
I have created a model for signup form and allowed user to enter its data ,which is further stored in DB , then I have created a login form which take the detail of user like email and password and then verifies it in db and allows user to redirect to welcome page I am attaching my code details INDEX.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>What do u want/?</h1> <button class="submit"><a href="{% url 'login' %}">login</a></button> <button class="submit"><a href="{% url 'signup' %}">signup</a></button> </body> </html> LOGIN.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST"> {% csrf_token %} <input type="email" id="email" name="email"><br> <input type="password" id="password" name="password" value="password"> <button class="submit">submit</button> </form> </body> </html> SIGNUP.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST" > {% csrf_token %} <input type="text" id="name" name="name" value="name"><br> <input type="email" id="email" name="email" value="email"><br> <input type="password" id="password" name="password" value="password"> <button class="submit"><a href="{% url 'welcome' %}">submit</a></button> </form> </body> </html> WELCOME.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Welcome {{name}}</h1> </body> </html> VIEWS.PY from django.shortcuts import render,redirect from .forms import Detailsform from … -
How can i get variable by call model and don't create new variable
I created a Mutation for my django project . At first i create an input class for get variable and now i want to send them without input class and make a new way like serializer in REST This is my Schema import graphene from graphene_django import DjangoObjectType from .models import Category class CategoryType(DjangoObjectType): class Meta: model = Category fields = '__all__' class DataInput(graphene.InputObjectType): name = graphene.String() class CategoryCreate(graphene.Mutation): class Arguments: input = DataInput(required=True) category = graphene.Field(CategoryType) @staticmethod def mutate(parent, info, input=None): category_instance = Category.objects.create(name=input.name) return CategoryCreate(category=category_instance) class Mutation(graphene.ObjectType): create_category = CategoryCreate.Field() Schema = graphene.Schema(query=GameQuery, mutation=Mutation) -
django.db.utils.OperationalError: no such column
I am working on an investment site that I have arranged the models like this and I don't know exactly where the problem is in the models.py. I have two users and one doer in the table I have defined a functor of project and another investor on that project my models.py code is : from django.db import models from django.db.models import Model from django.contrib.auth.models import User from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django.contrib.auth.models import AbstractUser import uuid from .validators import national_id_validator from django.utils.translation import gettext_lazy as _ class User(AbstractUser): natinal_id = models.CharField(_('national ID (username)'), unique=True, max_length=10,default="0000000000", validators=[national_id_validator]) is_user = models.BooleanField(default=False) is_functor = models.BooleanField(default=False) #PROFILE OF FUNCTORS class Profile(Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', blank=True, null=True) name = models.CharField(max_length=200, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_image = models.ImageField(null=True, blank=True, upload_to='profiles-functor/', default="profiles-functor/user-default.png") social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_website = models.CharField(max_length=200, blank=True, null=True) landing_phone = models.CharField( max_length=12, unique=True, help_text ='Required 10 digits in 9xx format') updated = models.DateTimeField(auto_now=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) class Meta: ordering = ['created'] @property def imageURL(self): try: url = self.profile_image.url except: url = '' … -
Where to put bussiness logic in Django (DRF)?
Despite it is very popular question and already has a lot of answers, I don't really get it. I understand that putting tons of logic in views is not a good idea, so in my projects I create files like utils, logic, helpers. But the problem is that I don't know where should I call those "logical" functions? Should I make them as a property or method of model instance, or should I call it in a view passing model instance as an argument? For example in my current pet-project I have Question and Answer models. Question has is_solved Boolean (default=False) field which means if the question is solved or not, and Answer has is_solving Boolean field (default=False) as well and if True, it means that the answer helped to solve an issue. I have a function in logic file which handles it. Here is the code: def vote_answer_solving(answer: Answer, related_question: Question): if answer.is_solving: answer.is_solving = False related_question.is_solved = False else: if related_question.question_answers.filter(is_solving=True).exists(): is_solving_answer = related_question.question_answers.get(is_solving=True) is_solving_answer.is_solving = False is_solving_answer.save() answer.is_solving = True related_question.is_solved = True related_question.save() answer.save() I call it in a view, where user requests the endpoint and the logic is handled by the function. I don't really … -
Python library for 3D human pose animation
I have some 3D human pose data with x, y and z coordinates estimated from a video. I want to be able to animate this data and display it on a web browser to produce something similar to the following: Currently I am using Matplotlib to animate the data and it works quite well however displaying it on a browser takes a long time (around 10 seconds) for a very short video clip and I am not sure how to place the image data/video onto the animation like the example above. Is there a better library I can use to animate this data and display it on a web browser in a reasonable amount of time. Here is the code for the 3D animation using Matplotlib and a frame from the animation it produces: store = DataStore() store.populate_poses(sid, clip_num): frames = [] for p in store.get_poses(): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') keypoints = [] for kp in p.get("keypoints3D"): x, y, z = kp['x'], kp['y'], kp['z'] # Swap Y and Z axes, and adjust X, Y, Z as needed x_new = x # X remains the same y_new = z # Y in Matplotlib is -Z in BlazePose z_new … -
Installing Python Frameworks on Respberry Pie
I use my laptop for things other than coding. My Python coding now consists only of what I can do on PieCharm, which is inside my VR Box. For projects, I need to install Flask and other frameworks. My laptop can barely handle the VR Box, so I don't want to subject it to a framework. Can I purchase a Raspberry Pie and install all my Python frameworks on that? What Python projects can't I do on Raspberry Pie? I haven't tried much because I haven't purchased a Raspberry Pie yet. Money is tight and I want to make sure I use it before I buy it. Things are also a little complicated because I've been living in Ukraine throughout the war -
How To download a functioning pdf in django using wkhtmltopdf?
I have a django project, where i download the template as a pdf using wkhtmltopdf.The pdf is downloaded when i click the download button, However when i open the pdf it says, "Error Failed to load PDF document." and i cant open the downloaded pdf. Upon looking at the terminal i see this error: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. What is causing this issue and how can it be solved? this is my views.py: @login_required def download_resume(request): # Retrieve data from your Django models personal_info = personalinfo.objects.filter(user=request.user).last() summaries = summary.objects.filter(user=request.user).last() experiences = experience.objects.filter(user=request.user) educations = education.objects.filter(user=request.user) certs = certificates.objects.filter(user=request.user) skillset = skills.objects.filter(user=request.user) # Generate the PDF content using a template template = get_template('template0.html') context = { 'personal_info': personal_info, 'summaries': summaries, 'experiences': experiences, 'educations': educations, 'certs': certs, 'skillset': skillset } # Render the template with the context data html_content = template.render(context) # Configure pdfkit with the path to wkhtmltopdf pdfkit_config = pdfkit.configuration(wkhtmltopdf='C:/Users/lulu/PProjects/resumebuilderproject/wkhtmltopdf/bin/wkhtmltopdf.exe') # Convert HTML to PDF using wkhtmltopdf pdf = pdfkit.from_string(html_content, False, configuration=pdfkit_config) # Create a response with the PDF content response = FileResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="resume.pdf"' … -
Django StreamingHttpResponse for text not streaming
I am having trouble with streaming a simple text response with django. it's a very straight-forward demo. python3.11.4 django4.2.5 python serve a text generator with delay @csrf_exempt def testPost(request): if request.method == 'POST': print('--- post') def gen1(): for i in range(10): time.sleep(0.5) print(f'----- {i}') yield str(i) return StreamingHttpResponse(gen1(), content_type="text/plain", buffered=False) js tries to get response bit by bit function testPost(messages, success, error) { const xhr = new XMLHttpRequest(); xhr.open("POST", apiUrl); xhr.responseType = "text"; xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onprogress = (event) => { const partialResponse = xhr.responseText.substring( xhr.loadedBytes || 0, event.loaded ); xhr.loadedBytes = event.loaded; success(partialResponse); // Handle the partial response }; xhr.onload = () => { console.log('---loaded'); success(xhr.responseText); // Handle the final response }; xhr.onerror = error; const requestData = new URLSearchParams({ messages: JSON.stringify(messages), }).toString(); xhr.send(requestData); } // Usage chatPost(messages, (partialResponse) => { console.log(partialResponse); // Handle the partial response }, (error) => { console.error(error); }); here's the output: server goes first 2023-10-01 07:21:02,946 INFO Listening on TCP address 127.0.0.1:8001 --- post ----- 0 ----- 1 ----- 2 ----- 3 ----- 4 ----- 5 ----- 6 ----- 7 ----- 8 ----- 9 127.0.0.1:35074 - - [01/Oct/2023:07:21:11] "POST /api/test/" 200 10 frontend result comes after all logging in server 0123456789 --loaded 0123456789 note that … -
Cart Popover is not working on all pages of my site the past added products only shows on that page where they are present. Django Problem
The Cart only works when the cart is empty or woks on the page where the added products are present. And if not then it stops working and cart +,- function also stops working and cart shows Cart(0). I have taken the navbar code from bootstrap. Base.html: //Navbar <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarColor01"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="/products">Products</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">About</a> </li> <li class="nav-item"> <a class="nav-link" href="/contacts">Contact Us</a> </li> </ul> <form class="form-inline" method="post" action="/search/">{% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" id=search> <button class="btn btn-outline-info my-2 my-sm-0" type="submit">Search</button> </form> <button type="button" class="btn btn-secondary" style="margin-left: 10px; background-color: darkcyan; border: 0;" data-container="body" data-toggle="popover" data-placement="bottom" id="popcart" data-html="true" data-content="Bottom popover"> Cart(<span id="cart">0</span>) </button> </div> </nav> //Normal Html has been removed form this code. Only JS script here. {% block js %} <script> if (localStorage.getItem('cart') == null) { var cart = {}; } else { cart = JSON.parse(localStorage.getItem('cart')); updateCart(cart); } //$('.cart').click(function(){ $('.divpr').on('click', 'button.cart', function() { var idstr = this.id.toString(); if (cart[idstr] != undefined) { qty = cart[idstr][0] + 1; } else { qty … -
Failed to access chromadb from django app with docker compose, HTTPConnectionPool(host='127.0.0.1', port=8989): Max retries exceeded with url
I am trying to build a REST api with django and chromadb, I built two containers: django for RESTApi, chroma for vector database. Two containers are running successfully. Here is my docker-compose file: version: '3.9' services: django: container_name: django build: context: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app:/Users/apple/Docker/app/ ports: - '8000:8000' expose: - 8000 chroma: container_name: chroma image: ghcr.io/chroma-core/chroma:latest volumes: - index_data:/Users/apple/Docker/app/data ports: - '8989:8989' expose: - 8989 volumes: index_data: name: my-db-data Here is my Dockerfile: FROM python:3.9 WORKDIR /Users/apple/Docker/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY ./requirements.txt /Users/apple/Docker/app/requirements.txt RUN pip3 install -r requirements.txt COPY ./entrypoint.sh /Users/apple/Docker/app/entrypoint.sh COPY . /Users/apple/Docker/app/ EXPOSE 8000 ENTRYPOINT ["/Users/apple/Docker/app/entrypoint.sh"] I am trying to establish a connect from django to chromadb, as following: from rest_framework.decorators import api_view from rest_framework.response import Response import chromadb from chromadb.config import Settings chroma_client = chromadb.HttpClient( host='localhost', port=8989, settings=Settings(allow_reset=True, anonymized_telemetry=False)) @api_view(['GET']) def index(request): sample_collection = chroma_client.get_or_create_collection(name="sample_collection") print(sample_collection) return Response({ 'info': 'Hello world.' }) I got this error message: urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=8989): Max retries exceeded with url: /api/v1/collections (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f35e0e3c4f0>: Failed to establish a new connection: [Errno 111] Connection refused')) I did some research, it seems like the problem of port conflict, … -
JWT Authentication Error (401) When Fetching Django API Data from React App via Cookies
I have an API created in Django, which uses a JWT token to validate the user's authentication. Once I log in, I obtain a token that I use to call the 'hello' endpoint to fetch information. Everything works perfectly in this regard, but the problem arises when I integrate it into my React app. My React app allows me to log in and store the JWT token in cookies. In the 'Home.js' file, there's a button responsible for fetching data from the 'hello' endpoint. When I make the request, the Django API responds with a 401, unauthorized error. If I add token into headers, it works but I don't know if this is the way or I should do in another way: const jwtToken = 'mytoken'; const response = await axios.get("http://localhost:8000/api/hello/", { withCredentials: true, headers: { 'Authorization': `Bearer ${jwtToken}`, } views.py: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated class HelloView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): content = {'message': 'Hello, World!'} return Response(content) settings.py """ Django settings for backend project. Generated by 'django-admin startproject' using Django 4.1.1. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see … -
Regarding the accessing the form field of a django wizard form
`Dear All, I am new to Django and eager to learn it. I have created a Django wizard form with three steps. I defined only one model and separated it into three form classes. Now I want to access these form classes manually to render it into the HTML. But I am not able to do it. Like in the case of forms we can access the files by using the below given syntax. {{all_forms.Participation_Year.label_tag}} {{all_forms.Participation_Year}} I want a similar type of syntax for this. models.py class Test_session(models.Model): Subject_ID = models.CharField(max_length=20) Participation_Year = models.CharField(max_length=20) Phone_Number = models.CharField(max_length=20) Gender = models.CharField(max_length=20) Blood_Group =models.CharField(max_length=20) Age = models.CharField(max_length=20) DOB = models.CharField(max_length=50) POB = models.CharField(max_length=100) City = models.CharField(max_length=100) District = models.CharField(max_length=100) views.py class MyWizard(SessionWizardView): form_list = [Step1Form, Step2Form, Step3Form] # List of forms for each step template_name = 'participants/test_session.html' # Create a template for your multi-page form #print(len(form_list)) def done(self, form_list, **kwargs): # Collect data from each form step data = {} for i, form in enumerate(form_list): data.update(form.cleaned_data) print(f"Step {i+1} data:", form.cleaned_data) # Create a new instance of your model and save the data form_data = Test_session(\*\*data) # form_data.save() # Redirect to a thank you page or another URL return HttpResponseRedirect('/thank-you') urls.py path('my-form/', MyWizard.as_view(), … -
csrf_exempt true on all callbacks
I've created some custom middleware for my django rest api to enforce a CSRF security policy of setting custom headers. I've subclassed CsrfViewMiddleware and overriden a few methods to suite my needs, most notably the check_token method. However, I noticed later on that all requests have been coming in with the attribute "csrf_exempt" set to true, even though nowhere have I used the csrf_exempt decorator. I've searched through the django docs to try and figure out why this has been happening to no avail. Here is my custom middleware: class CustomCsrfMiddleware(CsrfViewMiddleware): def _reject(self, request, reason): logger.warning("Forbidden (%s): %s", reason, request.path) return Response( {'detail': 'Forbidden', 'reason': reason}, status.HTTP_403_FORBIDDEN ) def _check_token(self, request): # Get the two relevant pieces of information, the # the returned csrftoken in the custom header and the hmac try: hmac = _get_hmac(request) except BadDigest as e: raise RejectRequest(e.reason) try: request_csrf_token = request.META[settings.CSRF_HEADER_NAME] token_source = settings.CSRF_HEADER_NAME except KeyError: raise RejectRequest(REASON_CSRF_TOKEN_MISSING) try: _check_token_format(request_csrf_token) except InvalidTokenFormat as e: reason = self._bad_token_message(e.reason, token_source) raise RejectRequest(reason) if not _does_match(request_csrf_token, hmac): reason = self._bad_token_message("incorrect", token_source) raise RejectRequest(reason) def process_request(self, request): try: csrf_secret = self._get_secret(request) if csrf_secret is None: raise InvalidTokenFormat(REASON_CSRF_TOKEN_MISSING) except InvalidTokenFormat: _add_new_csrf_cookie(request) else: if csrf_secret is not None: request.META["CSRF_COOKIE"] = csrf_secret def … -
Forbidden (Origin checking failed - https://api.example.com does not match any trusted origins.): /admin/login/
I'm running a Django app over DigitalOcean's Kubernetes, the site runs over https but when I try to use the Django Admin from the domain, it throws a 403 forbidden error but if I connect directly to the Pod it succeeds. I wondered if it has to do with the ingress set up that is not recognizing the paths of api.example.com. Here's the ingress.yaml file apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: backend-ingress annotations: kubernetes.io/ingress.class: "nginx" cert-manager.io/cluster-issuer: "letsencrypt-prod" spec: ingressClassName: nginx tls: - hosts: - example.com - api.example.com secretName: tls-secret-name rules: - host: api.example.com http: paths: - pathType: Prefix path: "/" backend: service: name: backend port: number: 8000 - host: example.com http: paths: - pathType: Prefix path: "/" backend: service: name: frontend port: number: 3000 Any clue? -
How to Update Django 1.6 Project to the Latest Version
I have an existing Django project that was originally developed using Django version 1.6. Now, I'd like to upgrade it to the latest version of Django to take advantage of new features, security updates, and improvements Updating Django Version Running pip install Reviewing the Official Documentation -
django channels closing external connection to websocket
Any one can help with it? So i open connection to external wesocket and i want if my boolean field in db is False, Close this connection. When im update my db i'm using signals.py for pass data from it to consumers.py, in consumer i get method that do like this async def receive(self, text_data): try: # Handle incoming WebSocket messages here data = json.loads(text_data["text_data"]) # Get the inner dictionary # Access specific fields from the data dictionary trade_id = data.get("id") symbol = data.get("symbol") interval = data.get("interval") length = data.get("length") barlimit = data.get("barlimit") user_id = data.get("user") monitoring_status = data.get("monitoring_status") if monitoring_status is True: logger.info( f"start binance websocket: {monitoring_status}, {trade_id}, {symbol}, {interval}, {length}, {barlimit}" ) await self.start_binance_websocket(user_id, trade_id, symbol, interval, length, barlimit) else: logger.info( f"stop binance websocket: {monitoring_status}, {trade_id}, {symbol}, {interval}, {length}, {barlimit}" ) await self.stop_binance_websocket(user_id, trade_id, symbol, interval, length, barlimit) # Now you can use these variables as needed in your consumer logic # For example, you can log them or perform other actions except Exception as e: logger.error(f"Error receiving message: {e}") in start_binance_websocket i save data for connection in self.active_connections and if i change value of monitoring_status to False im calling function async def stop_binance_websocket(self, user_id, trade_id, symbol, interval, … -
"django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured" Error in my site
The error: (venv) gamedeveloper@animechatapp:~$ sudo journalctl -u gunicorn -n 50 [sudo] password for gamedeveloper: Sep 30 13:10:33 animechatapp gunicorn[510664]: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not co> Sep 30 13:10:33 animechatapp gunicorn[510664]: [2023-09-30 13:10:33 +0000] [510664] [INFO] Worker exiting (pid: 510664) Sep 30 13:10:33 animechatapp systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Sep 30 13:10:33 animechatapp systemd[1]: gunicorn.service: Failed with result 'exit-code'. Sep 30 13:19:35 animechatapp systemd[1]: Started gunicorn.service - gunicorn daemon. Sep 30 13:19:35 animechatapp gunicorn[510824]: [2023-09-30 13:19:35 +0000] [510824] [INFO] Starting gunicorn 21.2.0 Sep 30 13:19:35 animechatapp gunicorn[510824]: [2023-09-30 13:19:35 +0000] [510824] [INFO] Listening at: unix:/run/gunicorn.sock (510824) Sep 30 13:19:35 animechatapp gunicorn[510824]: [2023-09-30 13:19:35 +0000] [510824] [INFO] Using worker: sync Sep 30 13:19:35 animechatapp gunicorn[510825]: [2023-09-30 13:19:35 +0000] [510825] [INFO] Booting worker with pid: 510825 Sep 30 13:19:35 animechatapp gunicorn[510826]: [2023-09-30 13:19:35 +0000] [510826] [INFO] Booting worker with pid: 510826 Sep 30 13:19:35 animechatapp gunicorn[510827]: [2023-09-30 13:19:35 +0000] [510827] [INFO] Booting worker with pid: 510827 Sep 30 13:19:40 animechatapp gunicorn[510827]: - - [30/Sep/2023:13:19:40 +0000] "POST /update_active_status/ HTTP/1.0" 200 21 "http://194.195.119.23> Sep 30 13:19:43 animechatapp gunicorn[510826]: - - [30/Sep/2023:13:19:43 +0000] "POST /update_active_status/ HTTP/1.0" 200 21 "http://194.195.119.23> Sep 30 13:20:01 animechatapp gunicorn[510826]: - - [30/Sep/2023:13:20:01 +0000] "POST /update_active_status/ HTTP/1.0" … -
How save the result from task in database using django_celery_results?
I am beginner with Celery, and i need to save the result of the task in the database here is tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task import hashlib from project.celery import app from .models import Puzzle @shared_task(ignore_result=False) def solve_puzzle(data, level): # try to find a nounce value that makes the SHA-1 hash of the data and the nounce start with a certain number of zeros solution = "" nounce = 0 while not solution.startswith("".join(["0" for _ in range(level)])): solution = hashlib.sha1(f"{data}{(nounce)}".encode()).hexdigest() nounce += 1 return nounce, solution the celery.py: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='redis://localhost', backend='db+sqlite:///results.sqlite') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.retry = 360 app.conf.timeout = 300 # Load task modules from all registered Django apps. app.autodiscover_tasks() settings.py: CELERY_RESULT_BACKEND = 'django-db' I run celery using the command: celery -A project worker -l INFO then got : `[2023-09-30 19:29:13,461: INFO/MainProcess] Task puzzle.tasks.solve_puzzle[e1960235-801d-4bc4-8f5d-e7fb923830ba] received [2023-09-30 19:29:15,909: INFO/SpawnPoolWorker-21] child process 624 calling … -
Can we implement Airflow in a Django project for scheduling tasks?
I'm working on a Django rest project to create different API endpoints. I want to implement airflow that reads a text file and stores it in a Django Model daily. I have installed Apache airflow, created a DAG, and changed my dag location in the airflow.cfg file. But when I run the webserver and the scheduler I cannot see my dag in the DAG's list. Can somebody help me with the airflow django implementation?