Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to connect Django project to a SQL server 2019 database?
Django + MSSQL + Apple M1: ImportError with pyodbc Symbol Not Found in flat namespace '_SQLAllocHandle' I'm trying to connect a Django project running on an Apple M1 (ARM) architecture to a Microsoft SQL Server database. I'm using the mssql-django package, and I've encountered an issue with the pyodbc module. When I run python manage.py dbshell, I get the following error: Traceback (most recent call last): File ".../site-packages/mssql/base.py", line 17, in <module> import pyodbc as Database ImportError: dlopen(.../site-packages/pyodbc.cpython-312-darwin.so, 0x0002): symbol not found in flat namespace '_SQLAllocHandle' During handling of the above exception, another exception occurred: ... django.core.exceptions.ImproperlyConfigured: Error loading pyodbc module: dlopen(.../site-packages/pyodbc.cpython-312-darwin.so, 0x0002): symbol not found in flat namespace '_SQLAllocHandle' I've tried the following solutions: Reinstalling pyodbc with the specified architecture flags. Switching to pymssql as an alternative. Follow this tutorials: Install MSODBC MacOS, Cómo Conectar Django con SQL Server | django-mssql-backend However, the issue persists. Has anyone encountered a similar problem on Apple M1 and found a solution? Additional Information: Django version: [5.0.1] mssql-django: [1.4] pip: [23.3.2] pyodbc: [5.0.1] Python version: [3.12.0] Operating System: macOS [macOs Monterey v12.3] Database backend: mssql-django When executing the command python manage.py dbshell, I anticipate a successful connection to the database without encountering the … -
All msgstr empty inside django.po
I have implemented multi-language on my app but translations end up all empty, both from html and views: Inside django.po (there is more to this, all of them empty): #: .\src\playstyle_compass\templates\playstyle_compass\index.html:11 #: .\src\playstyle_manager\settings.py:143 msgid "English" msgstr "" #: .\src\playstyle_compass\templates\playstyle_compass\index.html:18 #: .\src\playstyle_manager\settings.py:144 msgid "Romanian" msgstr "" #: .\src\playstyle_compass\templates\playstyle_compass\index.html:25 msgid "Discover Your Perfect Games" msgstr "" #: .\src\playstyle_compass\templates\playstyle_compass\index.html:26 #: .\src\playstyle_compass\templates\playstyle_compass\index.html:27 msgid "text to be translated" msgstr "" #: .\src\playstyle_compass\views.py:61 msgid "Home :: PlayStyle Compass" msgstr "" Here is my configuration: settings.py: from django.utils.translation import gettext_lazy as _ MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ... ] LOCALE_PATHS = [ os.path.join(BASE_DIR, "src", "locale"), ] LANGUAGES = [ ('en', _('English')), ('ro', _('Romanian')), ] USE_I18N = True urls.py: urlpatterns = i18n_patterns( path("admin/", admin.site.urls), path("", include("playstyle_compass.urls")), path("users/", include("users.urls")), ... ) urlpatterns += [path("i18n/", include("django.conf.urls.i18n")),] HTML: {% extends "base.html" %} {% load i18n %} {% load static %} {% block page_header %} <link rel="stylesheet" type="text/css" href="{% static 'css/playstyle_compass/index.css' %}"> <ol> <li class=""> <a class="nav-link nav-user mr-0 waves-eff" href="/en{{ request.get_full_path|slice:'3:' }}" role="button"> <span class="pro-user-name ml-1"> {% trans "English" %} </span> </a> </li> <li> <a class="nav-link nav-user mr-0 waves-eff" href="/ro{{ request.get_full_path|slice:'3:' }}" role="button"> <span class="pro-user-name ml-1"> {% trans "Romanian" %} </span> </a> </li> </ol> <div class="jumbotron"> <div class="my-header"> <h1 … -
Problem with test automation django app with Jenkins
so generally I'm trying to automate some simple tests in my django app with Jenkins. The structure looks like this structure. I tried many different setups like: installing pacakges right into cointiner and trying to test, creating virtualenv inside of it or creating venv outside and importing it from my source version control and running in jenkins but nothing worked. Always i got message that it can't find django module like it could't find enviroment: Log examples from one of the builds logfileslogfileslogslogfiles My pipeline looked like this: pipeline steps. -
ImportError: cannot import name 'views' from 'drewmix' (C:\Users\USER\Desktop\storefront\drewmix\drewmix\__init__.py)
i am trying to use the python manage.py runserver command and i am getting the following error: ImportError: cannot import name 'views' from 'drewmix' (C:\Users\USER\Desktop\storefront\drewmix\drewmix_init_.py) ----break-------break----- my workspace setup i believe my view.py is in the correct place in my workspace. also i believe my urls.py is in the correct place in my workspace. below is the code for my urls.py sheet: from django.urls import path from django.contrib import admin from django.urls import path, include from . import views app_name = 'blog' urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), path('', views.post_list, name='post_list'), path('<int:id>/', views.post_detail, name='post_detail'), ] -----break---------------break------------- below is the code for my views.py sheet: from django.shortcuts import render from .models import Post from django.http import Http404 from django.shortcuts import render, get_object_or_404 def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, id): post = get_object_or_404(Post, id=id, status=Post.Status.PUBLISHED) try: post = Post.published.get(id=id) except Post.DoesNotExist: raise Http404("No Post Found.") return render(request, 'blog/post/detail.html', {'post': post}) ---break-----------------break--------------- can anyone tell me what i am missing? this is getting frustrating. i am using python 3.8 and django 4.2 so far i have tried jumping around the code and deleting different portions and running the commands, but i am not getting anywhere. … -
What is the best backend language to use for chat app
Which language is best for me to use for the backend of my chat application. I was thinking NodeJS is good but i am seeing a recommendation from friends that Django or flask is better. Should i consider using laravel or anyother available. -
How does the server know that API call has been made from the client?
I am currently reading articles on REST API and how the client and server interaction works. I had a question in my mind which is as follows: How does the server know that REST API call has been made from the client? (Eg: I get a notification when a receive a message. So, from that I know I message in my inbox. How does server know about the REST api) Tried to find it on internet but didn't find any relevant answers. -
How can i filter displaying data from table by own order?
Don't have any idea how to sort the list of items. I have an existing data of types /class/order/family.... They taken from database . here output is look like this :output I want output with my own order : Type : PROTOZOA Klass: EUCILIATA Klass: MASTIGOPHORA klass: CILIATA Type: APICOMPLEXA klass: SPOROZOA Type: PLATHELMINTHES Type: NEMATHELMINTHES my models.py looks like this: class table_of_matches(models.Model): kingdom= models.CharField(max_length=250) type= models.CharField(max_length=250) klass= models.CharField(max_length=250) order= models.CharField(max_length=250) suborder= models.CharField(max_length=250, blank=True, null=True) superfamily= models.CharField(max_length=250, blank=True, null=True) family= models.CharField(max_length=250) subfamily= models.CharField(max_length=250, blank=True, null=True) tribus= models.CharField(max_length=250, blank=True, null=True) genus= models.CharField(max_length=250) subgenus= models.CharField(max_length=250, blank=True, null=True) species= models.CharField(max_length=250) subspecies= models.CharField(max_length=250, blank=True, null=True) author= models.CharField(max_length=250) ru_name= models.CharField(max_length=250, blank=True, null=True) en_name= models.CharField(max_length=250, blank=True, null=True) kz_name= models.CharField(max_length=250, blank=True, null=True) species_id = models.CharField(max_length=250) and this is my html <ul class="parent"> {% for ttype, klasses in data.items %} <li > <details > <summary>-Тип: {{ ttype }}</summary> <ul> {% for klass, orders in klasses.items %} <li> <details> <summary>- Класс: {{ klass }}</summary> <ul> {% for order, families in orders.items %} <li> <details> <summary>- Порядок: {{ order }}</summary> <ul> {% for family, items in families.items %} <li> <details> <summary>- Семейство: {{ family }}</summary> <ul> {% for item in items %} <p> <a href="{{item.species_id}}"> <i> {{item.genus}} {{item.species}} </i> / … -
I am getting below error while creating multiple custom get request inside single APIview class
My Views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class Sample(APIView): http_method_names = ['get', 'post', 'put', 'patch', 'delete'] def get(self, request): # Your logic for the default GET method response_data = {'message': 'Default GET method'} return Response(response_data, status=status.HTTP_200_OK) def get_fruits(self, request): # Your logic for a custom GET method fruits = ["apple", "mango", "orange"] response_data = {'fruits': fruits} return Response(response_data, status=status.HTTP_200_OK) def get_films(self, request): # Your logic for another custom GET method films = ["Saj", "don", "Man"] response_data = {"fnames": films} return Response(response_data, status=status.HTTP_200_OK) My Urls.py from django.urls import path from .views import Sample from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'Apiapp', Sample, basename='Sample') urlpatterns = [ path('sample/get_fruits/', Sample.as_view({'get': 'get_fruits'}), name='custom-endpoint-1'), path('sample', Sample.as_view(), name='get-fruits'), path('sample/films/', Sample.as_view({'get': 'get_films'}), name='get-films'),] i am getting this error -
how to solve error problems in django settings.py
When my friend used the same coding, but in coding he experienced an error in the settings.py file with the source code error in this section BASE_DIR = Path(file).resolve().parent.parent the resukts in cmd when he wants running the server NameError: name 'file' is not defined. Did you mean: 'file'? I've looked for it but don't know the answer -
ModuleNotFoundError: No module named 'kdconnector' in test script after checking things like PYTHONPATH, __init__.py etc
I created the following script to test for ModuleNotFound error I am getting in other scripts. #kdconnecotsite/facebookapi/methods/testing.py from kdconnector.models import Master, ClientAccounts, Client, Campaigns, Ads def Execute(access_token, app_secret, ad_id): return "test completed" # Example usage if __name__ == '__main__': print('example usage test') access_token = 'EAAUIU8EilCcBABhtG7ZAQKUPMuZBo8NWOUwhBhma5MaKS2VI3s0U8W3aARwkbqKoxe0zyo4Vsdc7MStyEvyRoWvptiDICaiFTSaU5ZAlANea2nziOHuNxyNaBn9w1O3y0ZCZCk03dpd2NeBr7q6qmOixYCaHYMaEuZCn7ZCO1llBKYYHGPGtA6TVOucsPWZBLHcZD' ad_id = '23853970342650529' app_secret = '123456789' result = Execute(access_token, app_secret, ad_id) print('result = %s', result) the PYTHONPATH includes the kdconnectorsite folder above the testing.py script as well as the kdconnector folder. On creating the script, vscode finds kdconnector, models, and all the models as I type in the script. Running the script in vscode yields, File "c:\Users\MikeOliver\KDConnectorSite\kdconnectorsite\facebookapi\methods\testing.py", line 3, in <module> from kdconnector.models import Master, ClientAccounts, Client, Campaigns, Ads ModuleNotFoundError: No module named 'kdconnector' Running check does not complain. (venv) PS C:\Users\MikeOliver\KDConnectorSite\kdconnectorsite> python manage.py check kdconnectorsite.__init__ opened logging.yaml 2024-01-20 10:46:38,394 - kdconnectorsite - INFO - Configured the logger! 2024-01-20 10:46:38,897 - kdconnector.models - INFO - Now logging in models 2024-01-20 10:46:38,897 - kdconnector.models - INFO - Now logging in models 2024-01-20 10:46:38,919 - kdconnector.admin - INFO - Now logging in admin 2024-01-20 10:46:38,919 - kdconnector.admin - INFO - Now logging in admin 2024-01-20 10:46:39,217 - kdconnector.fbugenerator - INFO - Now logging in FBUGenerator 2024-01-20 10:46:39,217 …