Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django social network application - which machine learning model should I use and how to store it?
I am writing a Django project for a social network application. I need to create a machine learning model that - using existing data on a user's hobbies, interactions with content, current friends, etc - predicts the top 20 users to be matched. Which is the best model type to use for this situation? I thought about creating a model for each user but would that be optimal? How can I generalize the model to fit as many users as possible? Should I store the model on file or as part of the models.py in my Django project? -
issue with adding new category models and searching posts using it
Good afternoon! I have django application, on main(index) page i have posts, and there is side bar on that sidebar i have code for showing and searching posts in concrete category, (i copied it from tutorial, and teacher didnt showed how to work with that), now there is only 1 category that work succesfully (named just as "category"), i must add 2 new categories model, with same functionality, but with other models (datepublication and univercity) here is base html (sidebar with functionality here) {% load static %} {% load women_tags %} <!DOCTYPE html> <html> <head> <title>{{title}}</title> <link type="text/css" href="{% static 'women/css/styles.css' %}" rel="stylesheet" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" href="{% static 'women/images/main.ico' %}" type="image/x-icon"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <table class="table-page" border=0 cellpadding="0" cellspacing="0"> <tr><td valign=top> {% block mainmenu %} <div class="header"> <ul id="mainmenu" class="mainmenu"> <li class="logo"><a href="{% url 'home' %}"><div class="logo"></div></a></li> {% for m in menu %} <li><a href="{% url m.url_name %}">{{m.title}}</a></li> {% endfor %} {% if request.user.is_authenticated %} <li class="last"> {{user.username}} | <a href="{% url 'logout' %}">Выйти</a></li> {% else %} <li class="last"><a href="{% url 'register' %}">Регистрация</a> | <a href="{% url 'login' %}">Войти</a></li> {% endif %} </ul> <div class="clear"></div> </div> {% endblock mainmenu %} <table class="table-content" … -
Multiple Objects Returned. Django AllAuth
I am trying to get GitHub sign up option setup. But it keeps returning multiple objects. What I've learned until now is that there must be 2 entries in the social apps in Django admin. I checked and there is only 1. MultipleObjectsReturned at / No exception message supplied Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.10 Exception Type: MultipleObjectsReturned Exception Location: /usr/local/lib/python3.11/site- I have setup everything correctly in settings.py. I don't think that is causing the issue. <li class="nav-item"> <a href="{% provider_login_url 'github' %}">Git</a> </li> This in the template is causing the error. -
Django user_id from django db missing in application models.py
A few Days ago I started this tutorial on Django: https://www.youtube.com/watch?v=sm1mokevMWk The video is about how to set up your first django project, using some libraries from django, as well as bootstrap to style your website. He goes on about how to setup the database, website and everything else you need for the example of a todolist website and at the end of the video series he goes over setting up Users, as well as user specific todo lists. I tried recreating the process and up to the point of the user specific todo lists it was all very understandable and easy to follow. Yet as I tried implementing pretty much the last step of the implementation i get the following error: OperationalError at /create/ table main_todolist has no column named user_id Request Method: POST Request URL: http://127.0.0.1:8000/create/ Django Version: 5.0.1 Exception Type: OperationalError Exception Value: table main_todolist has no column named user_id Exception Location: C:\Entwicklung\Python\Python312\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in execute Raised during: main.views.create Python Executable: C:\Entwicklung\Python\Python312\python.exe Python Version: 3.12.0 Python Path: ['C:\Users\brenneckeo\Desktop\Django Projekt\meineSeite', 'C:\Entwicklung\Python\Python312\python312.zip', 'C:\Entwicklung\Python\Python312\DLLs', 'C:\Entwicklung\Python\Python312\Lib', 'C:\Entwicklung\Python\Python312', 'C:\Entwicklung\Python\Python312\Lib\site-packages'] Server time: Wed, 28 Feb 2024 14:18:52 +0000 The Error pops up when I try to create a ToDoList. When you do … -
smart_text from django-jenkins(sites-packages of my project) doesn't match with django 5.0.1 after upgrade. How to solve this problem?
jenkins test /../python3.11/site-packages/django_jenkins/runner.py", line 9, in <module> from django.utils.encoding import smart_text ImportError: cannot import name 'smart_text' from 'django.utils.encoding' (/../python3.11/site-packages/django/utils/encoding.py) Exit with return error: 1 -
How to run python script in django?
I have a python script which does web scraping and takes the input from the user for product name and then it displays the result. I want this same thing to be done on a webpage. Like user enters the input on webpage and result is displayed on webpage only (currently it is being displayed in python terminal) I tried doing django implementation but not able to do. Can I use streamlit library for this? If yes pls expand it steps how can I connect it to my existing webpage of website. -
Python social media Android application
I want to create a social media application with kivy for front end and django for backend, I never worked with this both together I need a src code or a reference video that how to work with kivy and django I searched many videos, but all are webapps and those who have made apks all are simple apps like task manger -
Heroku errors when upgrading Wagtail CMS
I'm attempting to update a very out-of-date Wagtail-based website that is hosted on Heroku. I'm upgrading from Wagtail 2.13 to 2.14. The upgrade goes fine on my local machine, but when pushing the upgrade to Heroku, and I'm struggling to interpret the errors: remote: -----> Requirements file has been changed, clearing cached dependencies remote: -----> Installing python-3.8.7 remote: -----> Installing pip 23.3.2, setuptools 68.2.2 and wheel 0.42.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting anyascii==0.1.7 (from -r requirements.txt (line 1)) remote: Downloading anyascii-0.1.7-py3-none-any.whl.metadata (1.6 kB) remote: Collecting asgiref==3.3.1 (from -r requirements.txt (line 2)) remote: Downloading asgiref-3.3.1-py3-none-any.whl.metadata (8.9 kB) remote: Collecting beautifulsoup4==4.8.2 (from -r requirements.txt (line 3)) remote: Downloading beautifulsoup4-4.8.2-py3-none-any.whl (106 kB) remote: Collecting boto3==1.17.15 (from -r requirements.txt (line 4)) remote: Downloading boto3-1.17.15-py2.py3-none-any.whl.metadata (6.0 kB) remote: Collecting botocore==1.20.15 (from -r requirements.txt (line 5)) remote: Downloading botocore-1.20.15-py2.py3-none-any.whl.metadata (5.3 kB) remote: Collecting certifi==2020.12.5 (from -r requirements.txt (line 6)) remote: Downloading certifi-2020.12.5-py2.py3-none-any.whl.metadata (3.0 kB) remote: Collecting chardet==4.0.0 (from -r requirements.txt (line 7)) remote: Downloading chardet-4.0.0-py2.py3-none-any.whl.metadata (3.5 kB) remote: Collecting dj-database-url==0.5.0 (from -r requirements.txt (line 8)) remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Collecting dj-static==0.0.6 (from -r requirements.txt (line 9)) remote: Downloading dj-static-0.0.6.tar.gz (3.4 kB) remote: Preparing metadata (setup.py): started remote: … -
Page not found (404). No Category matches the given query
I am building an Ecommerce site thru Django framework. While creating category section which takes user to individual category to access all its items, following error occurs. Page not found (404) No Category matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/search/ring/ Raised by: store.views.category_list Using the URLconf defined in core.urls, Django tried these URL patterns, in this order: admin/ [name='all_product'] item/<slug:slug>/ [name='product_detail'] search/<slug:category_slug>/ [name='category_list'] The current path, search/ring/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is the urls.py file from django.urls import path from . import views app_name = 'store' urlpatterns = [ path('', views.all_product, name='all_product'), path('item/<slug:slug>/', views.product_detail, name='product_detail'), path('search/<slug:category_slug>/', views.category_list, name='category_list'), ] views.py file from django.shortcuts import get_object_or_404, render from .models import Product, Category # Create your views here. def categories(request): return { 'categories': Category.objects.all() } def all_product(request): product = Product.objects.all() return render(request, 'store/home.html', {'product': product}) def category_list(request, category_slug): category = get_object_or_404(Category, slug=category_slug) product = Product.objects.filter(category=category) return render(request, 'store/products/category.html', {'category': category, 'product': product}) def product_detail(request, slug): product = get_object_or_404(Product, slug=slug, in_stock=True) return render(request, 'store/products/detail.html', {'product': product}) models.py file from django.db import models … -
Docker cannot assign requested address in Django
When I request the docker-compose up --build command, docker gives me an error: prediction-1 | django.db.utils.OperationalError: connection is bad: Cannot assign requested address prediction-1 | Is the server running on host "::1" and accepting prediction-1 | TCP/IP connections on port 5432? I downloaded PostgreSql from the official website. My settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get("DB_NAME"), 'USER': os.environ.get("DB_USER"), 'PASSWORD': os.environ.get("DB_PASSWORD"), 'HOST': 'localhost', 'PORT': '5432', } } My docker-compose.yml version: '3.8' services: postgres: restart: always image: postgres:latest container_name: postgres-db environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: 5332Dialog POSTGRES_DB: site ports: - "5432:5432" prediction: build: context: ./mysite ports: - "8000:8000" depends_on: - postgres environment: DEBUG: "False" DB_USER: "postgres" DB_PASSWORD: DB_HOST: "postgres" My Dockerfile FROM python:3.10.4 WORKDIR /app COPY . /app/ RUN apt-get update && apt-get install -y python3 && pip install -r requirements.txt CMD ["bash", "-c", "python manage.py migrate && python manage.py loaddata categories.json && python manage.py loaddata things.json && python manage.py runserver 0.0.0.0:8000"] I wanted to learn how to use Docker using your text this video: https://www.youtube.com/watch?v=0uLDObuutFs&ab_channel=ElenaDeykun-PythonBlog but somehow it didn’t work out that way -
Django/Python - Delete function in UpdateView is duplicating rather than deleting
i have created a Django app that allows users to enter their stock trades, as a journaling tool. When a user clicks on an individual journal entry from the index page, they will be taken to a detail page showing all the information on that individual entry (single_entry.html). This page is handled by an UpdateView. From this page, a user can edit/update any info, as well as DELETE that specific entry. To accomplish this, I've imported the DeletionMixin module from django.views.generic.edit. However, when I click on the "Delete" button in the form, the entry is duplicated instead of deleted! Does anyone know why that's happening?? Thanks for your help! Here's my class based view in views.py: class SingleEntryView(UpdateView): template_name = "single_entry.html" model = Entry fields = ['ticker', 'strategy', 'result', 'comments', 'image'] success_url = '/' def post(self, request, *args, **kwargs): if "delete_button" in self.request.POST: return self.delete(request, *args, **kwargs) def update_post(self, form, pk): if "update_button" in self.request.POST: form.instance.user = self.request.user return super(SingleEntryView, self).update_post(form) single_entry.html: {% extends 'base.html' %} {% block title %} Trading Journal - Entry {% endblock title %}Trading Journal {% block content %} <form method="POST" action="/"> {% csrf_token %} {% for field in form %} {{field.label_tag}} {{field}} {% if field.errors … -
Summenote doesn't send data values in nested fields
I'm trying to create nested fields with htmx and summernote: When the user clicks in the button "Adicionar nova alternativa" it returns another section. <button class="button is-info" hx-get="{% url 'create_alternativa' espaco=espaco.title %}" hx-target='#alternativas_criadas' hx-trigger="click" name="alternativa" hx-swap="beforeend" > <span class="icon is-small"> <i class="fa-solid fa-circle-plus" ></i> </span> <p>Adicionar nova alternativa</p></button> the problem is that summernotes dosen't send the text values. <div class="column is-9"> {% render_field form_alternativa.text style="height:291px;" %} </div> views.py if request.method == 'POST': print(request.POST) the print result for the same input as in the image when i try to submit the form: <QueryDict:{'text': ['<p>Test1</p>', '', '']}> The problem doesn't happen when I don't use summernote. When I use just a 'textarea', the form is submitted properly. Thanks! -
Django with Freenom [closed]
I just got started on Django and web development (i love it so far). I have gotten far enough to start considering deployment options. Getting a domain name for free is always a challenge. I have been using Heroku for quite sometime now but they put up some limits to it that has become a blocking stone. So I did a "little" research and found out that i could get a domain name for free on freenom.com that should last for a year. But then i could not figure out a way to connect that domain name to a Django project. How would I host the project files? Is there a better option that I can check out? I wanted to see if i could somehow connect my free domain at freenom.com and a django project i created. -
Making a post request to a Django app on MS Azure from a client that I do not own getting cors error
I have deployed a django app on azure and have been running it for a while. I recently added an endpoint to my app that should get a POST request from the jengahq website. However, I am able to simulate post requests from them to my endpoint and see the responses. Everytime I simulate my POST request, I get an error: Access to fetch at https://notification-webservice.azurewebsites.net/... from origin jengahq site has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource... However, I have enabled cors-origin for this website. It also requires a basic authentication header which I have added appropriately as shown below: CSRF_TRUSTED_ORIGINS = ( ["https://" + os.environ["WEBSITE_HOSTNAME"], "https://secondsite", ]) CORS_ALLOWED_ORIGINS = [ "https://" + os.environ["WEBSITE_HOSTNAME"], "https://secondsite", ] CORS_ALLOWED_HEADERS = [ 'Accept', 'Accept-Encoding', 'Authorization', ... ] The first website in my cors allowed is where my frontend is served and I am able to run requests well. This does not work for the second website. When I remove my frontend site from my cors allowed list, I get a similar error, but the endpoint seems different: Access to fetch at mysite from origin myfrontend has been blocked by CORS policy... Even with the addition … -
Can't send a labNumber into an sql query
I'm very confused as to why my _labNumber variable isn't getting sent into the method that I am using to call an SQL query, as it works for other methods in the same class. I have a try catch block in my class that calls the methods where I pass in _labNumber(This is correctly assigned, I have triple checked it) try: _comment = self.dataServices.GetComment(_labNumber) _value2 = self.dataServices.GetValue2(_labNumber) _value1 = self.dataServices.GetValue1(_labNumber) _results = self.dataServices.getResults(_labNumber) except AttributeError: _comment = None _value2 = None _value1 = None _results = None This is one of the methods in the class that is being used to retrieve the data from the database: def GetValue2(self, _LabNumber): _LabNumberStr = str(_LabNumber) try: with connection.cursor() as _cursor: _cursor.execute("{CALL dbo.uspShireXGetValue2(%s)}", _LabNumberStr) row = _cursor.fetchone() if row: return {'VALUE2': row[0]}#21 else: return {'VALUE2': None} except Exception as e: # Handle or log the exception as appropriate print(f"An error occurred: {e}") return {'VALUE2': None} And finally here is the query that I know works as it returns the data when I hard code a lab number: @LabNumber VARCHAR(10) AS SET NOCOUNT ON SELECT WDR.COMMENT FROM dbo.DNA_WORKSHEET_DET WD INNER JOIN dbo.DNA_WORKSHEET W ON WD.WORKSHEET = W.WORKSHEET LEFT OUTER JOIN dbo.DNA_TEST T ON W.TEST … -
127.0.0.1 slowness in django virtual environment running with vscode
After connecting to the server built in awsec2 with a remote of vscode, the django virtual environment was run to make a connection of 127.0.0.1. But its speed is too slow. When you connect using Chrome, the loading is too slow, sometimes it's infinitely loaded, and sometimes there's content that hasn't been loaded even if it's marked. There are even cases where only white pages are displayed. I'm currently using a MAC. Using a Windows laptop, connecting remotely to a remote server using vcode and then connecting to 127.0.0.1 will work fine I've been looking for other posts, but none of them correspond to my issues. I've tried many things. Turn off the process that currently uses 8000 ports on the Mac (but it was not there) Connect django to 8888 port or unused port and view it (this is the same error as well) It used to work very well, but it doesn't work well at some point. What should I do? -
Groups and Permissions in Django
When I am creating a new user, It is getting automatically assigned all the groups to new user. And, vice-versa. I am attaching code for models.py, serializers.py and views.py models.py serializers.py views.py I tried above solution and i am expecting that if I add a new group then It is not automatically assigned to every user or create a new user then also not assign all groups to them. And, in permissions file, I am not getting user groups why? permissions.py -
How to handle migrations in a big project?
i am currently working backend on a project with django and i have been facing problems with migrations mainly because i don't know when to make new migrations at all or only migrate the model i want, and my main problem is when i make a new branch do my work and migrate then merge it with develop the 0001 initial migrations make problems and conflict so i have to drop everything and repeat. Any help would be amazing. I tried creating a migrations.sh that removes migrations and database and migrates every model but surely this isn't the right way. -
ChoiceField renderer not working after update to Django 1.11
I have old project writen in Django 1.8. I try update it to newest version. At this moment i jave problem with version 1.11. I have this code: class HorizontalRadioRenderer(forms.RadioSelect.renderer): """ this overrides widget method to put radio buttons horizontally instead of vertically. """ def render(self): """Outputs radios""" #return mark_safe(u'\n'.join([u'%s\n' % w for w in self])) return mark_safe('\n'.join(['<td>%s</td>\n' % w.tag() for w in self])) medical_question1 = forms.ChoiceField(widget=forms.RadioSelect(_render=HorizontalRadioRenderer), choices=YES_NO) How can i repair it in new Django? This was the legacy code for Django <=1.10. How can i replace it? Please help me -
Wagtail publish images programatically doesn't reflect in FE
Created a management command to import content from Headway app to wagtail. Since headwayapp doesn't have any api's i copied the html to a separate file and parsed it. Everything works fine apart from images, Unless i click publish to that specific page in admin dashboard images doesn't reflect. All other content seems to work fine. Here is the management command Any help would be appreciated! from django.core.management.base import BaseCommand from wagtail.models import Page from wagtail.images.models import Image from wagtail.embeds.models import Embed from home.models import ChangelogPost, Category, Product from bs4 import BeautifulSoup from datetime import datetime import uuid from io import BytesIO import requests import re from django.core.files.images import ImageFile class Command(BaseCommand): help = "Import HTML content into Wagtail as ChangelogPost objects." def handle(self, *args, **kwargs): with open("subscription/migrateHTML/migrate.html", "r", encoding='utf-8') as f: html_doc = f.read() soup = BeautifulSoup(html_doc, 'html.parser') content = [] blog_divs = soup.find_all('div', class_='changelogItem published') for div in blog_divs: h2 = div.find('h2') content_div = div.find('div', class_='content') p = content_div.find('p') img_tags = content_div.find_all('img') img_htmls = [img.prettify() for img in img_tags] h3 = content_div.find('h3') if h3: span_text = h3.text.strip() # Get the content html, ignoring the img tag to_decompose = [] for child in p.next_siblings: soup = BeautifulSoup(str(child), 'html.parser') if … -
AWS SES VerifyEmailIdentity with lightsail
I am trying to use SES VerifyEmailIdentity in python. It works totally fine on my local systen however when we host on lughtsail instance the following error comes: An error occurred (AccessDenied) when calling the VerifyEmailIdentity operation: User: arn:aws:sts::480862114276:assumed-role/AmazonLightsailInstanceRole/i-0e2s3ff15c45e0eb1 is not authorized to perform: ses:VerifyEmailIdentity because no identity-based policy allows the ses:VerifyEmailIdentity action Python code working on localhost but having above error when hosted on lightsail import boto3 ses_client = boto3.client('ses', region_name='ap-south-1') def verify_email_address(email): response = ses_client.verify_email_identity(EmailAddress=email) return response I tried but their is no way to attach a role to lightsail instance in AWS through which i can attach permission. Expected result is just it works fine as on local and send email to intended address for verification. -
Elastic search with django parler
So i am trying to add Parler to my django application and it can't find a field that i want to index models.py class Document(models.Model): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' translations = TranslatedFields( header = models.CharField(max_length = 32) body = RichTextField() ) category = models.ForeignKey(Category, on_delete = models.CASCADE) timestamp = models.DateTimeField(auto_now_add = True) status = models.CharField(max_length = 10, choices = DocumentStatus.choices, default = DocumentStatus.ACTIVE) history = HistoricalRecords() language = models.ForeignKey(Language, related_name = "document_language", on_delete = models.CASCADE) def __str__(self): return self.header documents.py for elastic search: from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from . import models @registry.register_document class DocDocument(Document): class Index: name = 'documents' settings = { 'number_of_shards':1, 'number_of_replicas':0 } class Django: model = models.Document fields = [ 'header' ] the error it throws: Document has no field "header" I tried to do it with other fields that are not in translations but it throws the same error: Document has no field "whatever_field_i_have_used" -
Integration of WhatsApp with Python Django
I am currently working on a project that involves incorporating WhatsApp functionality into our web application developed using the Django framework. I am reaching out to inquire about the integration of WhatsApp with a Python Django project. I Want Whatsapp Business API Integration in Django -
importerror: couldn't import djano in windows powershell. im also using vscode [duplicate]
when i enter in WINDOWS POWERSHELL, PS C:\djangoapps\test\venv\src> **python manage.py startapp **stockmgmt, there's an error: importerror couldn't import django. are you sure it's installed and available in your PYTHONPATH environment variable? did you forget to activate a virtual environment? how to solve this? -
Difficulty with Django Rest Framework (DRF) Swagger Authentication Configuration
I'm encountering issues with configuring authentication for the Swagger in Django Rest Framework. I've set up the drf_yasg package along with the necessary configurations in settings.py and urls.py. However, when I try to log out using the Swagger, I'm getting a 403 Forbidden error, and subsequent attempts to access Swagger result in a blank page. settings.py: SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'basic': { 'type': 'basic' } }, 'LOGIN_URL': 'rest_framework:login', # Configuring login URL for Swagger 'LOGOUT_URL': 'rest_framework:logout', # Configuring logout URL for Swagger } REDOC_SETTINGS = { 'LAZY_RENDERING': False, } urls.py from django.contrib import admin from django.urls import path, include from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions API_TITLE = "Blog API" API_DESCRIPTION = "A Web API for creating and editing blog posts." # Configuration for drf-yasg schema_view = get_schema_view( openapi.Info( title=API_TITLE, default_version='v1', description=API_DESCRIPTION, ), public=True, permission_classes=[permissions.IsAuthenticated], # Setting permission for the schema_view ) urlpatterns = [ # Routes for admin views and API # ... (other routes) # Routes for Swagger UI documentation in different formats path('swagger<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), # Route for ReDoc documentation path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] I've configured the LOGIN_URL and LOGOUT_URL in SWAGGER_SETTINGS and used permission_classes=[permissions.IsAuthenticated] for …