Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "::1", user "XXXXX", database "XXXX", SSL off
I am new to this after successfully created the Django app and Postgres install, I try to run migration using python manage.py runserver. But I am getting this error django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "::1", user "XXXXX", database "XXXXX", SSL off. I am running this on namecheap cPanel terminal. Anyone with a hint? -
TypeError can't multiply sequence by non-int of type 'str' (Python, Django, Bootstrap)
I am just trying to make a website that calculates force=mass*accleration I have tried adding int it gives, string error or some base 10 error. #mass=int(request.GET['mass']) ...this too gives an error & all the variations of it!!! views.py ```from django.http import HttpResponse from django.shortcuts import render def home(request): return render(request, 'home.html') def calculator1(request): mass = request.GET.get('mass') acc = request.GET.get('acc') print(mass) print(acc) force=mass*acc return render(request, 'calculator1.html', {'result':force})``` urls.py ```from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('calculator1', views.calculator1, name='calculator1'), ]``` calculator.html(a part of it) ```<a href="#" class="list-group-item list-group-item-action"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1">Newton's Second Law of Motion</h5> </div> <form action="calculator1" method="get"> Force = mass * accleration<br> mass = <input type="text" name="mass" size="7"><br> accleration = <input type="text" name="acc" size="7"><br> </form> force = {{result}} </a> <button type="submit" class="btn btn-dark">Calculate</button><br> </div>``` *help pleaseeee -
No module named django_elasticsearch
I try to add elastic search support to my model. I installed via: pip install git+https://github.com/liberation/django_elasticsearch.git --user I added to installed apps, runserver gives no error. INSTALLED_APPS = [ ... 'django_elasticsearch', ] But when I import in the model: from django.db import models from django_elasticsearch.models import EsIndexable class Building(EsIndexable, models.Model): ... and try to makemigrations, I get the following error: ModuleNotFoundError: No module named 'django_elasticsearch' What am I missing? -
Object of type 'Decimal' is not JSON serializable error for using session
I used Django3-by-example book for learning django. I used cart creating procedure from this book step by step and It worked correctly. I wanted to add compare list with the same procedure.after this I ran my django app correctly but I found a bug. If the first session(for example cart session)was empty and I wanted to add a product to second session(for example compare list) I got this error: TypeError: Object of type 'Decimal' is not JSON serializable if the second session was empty the first session worked correctly Also if the first session wasn't empty ,It worked correctly. what is my mistake? -
importError:cannot import name 'home_page' from 'shop.views'
I am a newcomer and I wrote Hello Word to start practicing and I use Django==3.1 and python3 and I encountered this problem ImportError: cannot import name 'home_page' from 'shop.views' and this is my code... views.py from django.shortcuts import render from django.http import HttpResponse def home_page(request): return HttpResponse('Hello world') urls.py from django.contrib import admin from django.urls import path from .views import home_page urlpatterns = [ path('admin/', admin.site.urls), path('',home_page), ] -
Monkey patch created_by and modified_by django
I have an application deployed an year ago. In production I am unwilling to change all models manually to add the created_by and modified_by fields as it would be little risky. Is there anyway, we can achieve it with less amount of coding we could fix it (at least for the future transactions it should add those fields to every model?) I was thinking of monkey patching it, but dont know how to implement it? from django.apps import apps from django.db import models from django.contrib.auth import get_user_model model_list = apps.get_models() #-- Monkey Patch for model in model_list: if model != get_user_model(): model.add_to_class('created_by', models.CharField(max_length=250,blank=True, null=True)) model.add_to_class('modified_by', models.CharField(max_length=250,blank=True, null=True)) def save(self): if self.pk: self.created_by = request.user.id #not sure, how I would get the user here from request self.modified_by = request.user.id return super(model, self).save(*args, **kwargs) model.add_to_class("save", save) -
how to get total price of books django?
if i add some books in store then how can i get the total_price of selected books in store? i am using override save method to get total_price but it's not working... store from django.db import models class Book(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(default=0) class Store(models.Model): books = models.ManyToManyField(Vital) total_price = models.IntegerField(default=0) def save(self): super(Book, self).save() self.total_price = self.books.all().aggregate(Sum('price')).self.save(commit=True) -
Django: update field of ManyToMany instance when it's set
Is it possible to do something when setting ManyToMany relations with .set()? Let's say, we have: class ModelA(): b_models = models.ManyToManyField(ModelB, related_name="as", through="ModelMN") class ModelMN(): model_a = models.ForeignKey(ModelA) model_b = models.ForeignKey(ModelB) And when we have an instance of Model A and list of Model B instances: a = ModelA() a.set([b1, b2, b3]) When calling .set(), an instace of ModelMN is created for every a-b relationship. Is it possible to modify a field of that instance (every ModelMN instance), everytime it is created? Overriding .save() method on ModelMN seems not to be working. -
Django session via CORS request
I have runnig django app on host "example.com". I enabled CORS and getting POST request from host "test.net". When I try to set cookie on that response, it is sent back to "test.net" with cookie domain "test.net" - so cookie can not be set. I want to process that request and authorize user on "example.com" (set "sessionid" cookie with domain "example.com"). How can I achieve that? -
how can i get hackerrank ranks and display it on my own website with python?
I want to compare my ranking in Hackerrank with the rankings of my friends and the results I save on the website that I process with django. So how do I access the hackerrank ranking and display it on my website? -
Django query More than one row returned by a subquery used as an expression
I have a pretty simple query and I need to add one field to get an average price grouped by benefit - I tried with ArrayAgg but is not working. properties = ( House.objects.filter( # a lot of filters ).annotate( prices=ArrayAgg( HousePrice.objects.all().values("benefit").annotate(price_avg=Avg("price")).values("benefit_id" "price_avg") ), ) ) more than one row returned by a subquery used as an expression Any ideas on how to resolve that? I'm not sure if this way is good to use ArrayAgg. -
Sending data to the html that is not connected with any view
How can i send a dictionary data to one of my html that is not operated by any view in django. In this case, it's my navbar.html - i would like to insert few data about messages notifications etc. How can i do that? Thanks in advance -
How to restrict an anonymous user not to vote again in poll app in Django
Hi im new to django and working on simple poll app in django.I want both registered and anonymous users to vote. I want to restrict anonymous user from not voting more than once.Also i want anonymous user to post a new poll question, and then i dont want to give anonymous users access to certain pages.How can i achieve this.can someone please brief me so i can work on it. -
Unable to use django multiple databases with admin
I've been following this tutorial https://docs.djangoproject.com/en/3.1/topics/db/multi-db/ to try using multiple databases with django (Django==2.2) My sample django server can be found from https://github.com/miettinj/databaseRouter/tree/master/mysite The problem is that as I cannot modify the code of admin, thus when I try to go to admin page I get the error 'db_for_read() missing 1 required positional argument: 'model'. In the settings of the code in github I've been using also a router for default data base (in which the admin-related stuff is stored). Removing the 2nd router (polls.database_router.DatabaseDefaultRouter) from settings-file neither helps, tough the documentation states that all database queries should be automatic routed to the default database if defined. -
Django - Debug set to True, when it is actually not
I have deployed my Django project on Ubuntu and I forgot to set the Debug to False till the very end, now I have pulled the last commit to the server with the debug set to False. So now when I try to access a non existing url, for example, it should display my custom 404.html template. Instead it displays the Debug mode 404 error instead telling me that Debug = True even if it's not, I checked the settings.py file on the server and Debug is set to False. I tried restarting nginx and supervisor with service nginx restart and supervisorctl restart my_app_name but when I enter a non existing url it still says that Debug is set to True. Why does it still say that Debug is set to True? -
django running server error while executing command in cmd
please help me solve this problem when I execute "python manage.py runserver " I get this error. I have already activated the virtual environment Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\projects\AM\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\projects\AM\lib\site-packages\django\core\management\__init__.py", line 327, in execute django.setup() File "C:\projects\AM\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\projects\AM\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\projects\AM\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\projects\AM\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\projects\AM\lib\site-packages\django\contrib\auth\base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? and it's my setting.py file. I could run the server without any problem in the morning but I don't know what happened I get this error all the time. """ Django settings for mysite project. Generated by 'django-admin startproject' using … -
how to create round robin fashion between Django admin users
I have created a Inquiry Form in Django & created 3 user in Django admin page How can i send Each query to each user in round robin fashion means if some one submit my query form at front-end it goes to 1st user than 2nd submission to 2nd user & so on & than Each user can transfer there query to another user. like 2nd user can transfer to 1st. -
404 - File not found error for static files while deploying Django and Vue js integrated project in Azure web services
I created a project with Django as backend and Vue js as frontend. Initially I ran Django on one server(8000) and Vue js on another (8080) with node.js . Then, I integrated Both to the same server with proxy changes in vue.config.js. Then I ran the command NPM RUN BUILD on terminal and I moved the dist folder to Django's static folder to render. This worked perfectly in local development environment but I'm getting 404 error for static files while deploying the project in Azure web services through git-hub. Thanks for any fix or sugesstions. Here is my settings.py file. I have also tried commenting STATIC_ROOT STATIC_URL = '/static/' # Vue assets directory (assetsDir) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') Here is my vue.config.js module.exports = { devServer: { proxy: { '^/api/': { target: 'http://127.0.0.1:8000/api/', ws: false, } } }, // outputDir must be added to Django's TEMPLATE_DIRS outputDir: './dist/', // assetsDir must match Django's STATIC_URL assetsDir: 'static', publicPath: '', baseUrl: '', } Here is my project file structure Here is the error in my console -
Django: WARNING - Method Not Allowed (POST)
I know what above error means. Seems I can't handle form when it is posted. I can do it in function based views, but in class based views I am tad lost. I am creating a comment app and here is forms.py content in comment app: class CommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.CharField(widget=forms.HiddenInput) body = forms.CharField(widget=forms.Textarea) then in DetailView of the blog app, I handled it this way: class BlogDetail(DetailView): model = Blog template_name = 'blogs/blog_detail.html' context_object_name = 'blog' def get_object(self): blog_slug = self.kwargs.get('blog_slug') return get_object_or_404(Blog, slug=blog_slug) def get_context_data(self, *args, **kwargs): obj = self.get_object() context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter_by_instance(obj) """ comment form """ initial_data = { 'content_type': obj.get_content_type, 'object_id': obj.id } if self.request.method == 'POST': form = CommentForm(self.request.POST, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) object_id = form.cleaned_data.get('object_id') body = form.cleaned_data.get('body') new_comment, created = Comment.objects.get_or_create( user=self.request.user, content_type=content_type, object_id=object_id, body=body ) else: form = CommentForm(initial=initial_data) context['comment_form'] = form return context albeit I passsed form = CommentForm(self.request.POST, initial=initial_data) but there sounds something is going wrong, Can anyone help? Thank you -
How to solve AttributeError: 'str' object has no attribute 'get' in django
I have created input fields in my html page and on post request I expect to retrieve data from these input fields and fill my Signup form(imported from forms.py) and save the form. However i get this error: AttributeError at /signup 'str' object has no attribute 'get' Request Method: POST Request URL: http://localhost:8000/signup Django Version: 3.0.8 Exception Type:AttributeError Exception Value: 'str' object has no attribute 'get' forms.py: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class Signup(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] views.py: def signup(request): if request.method == 'POST': print(request.POST) username = request.POST.get('username') password1 = request.POST.get('password1') password2 = request.POST.get('password2') form = Signup(username,password1, password2) print(form.is_valid()) form = Signup() return render(request, 'signup.html') -
$.ajax not working when used in ("click") event listener
This is my Javascript code: const checkbox = document.querySelector("#checkbox"); const button = document.querySelector("#button"); button.addEventListener("click", function(e){ var text = ""; if(checkbox.checked === true){ text = "Is Checked"; } $.ajax({ url: '/update_if_checked/', data: {'is_checked': text}, type: 'POST' }).done(function(response){ console.log(response); }); }); I am getting an error which says $.ajax is not a function at HTMLButtonElement. Here, checkbox is an input of type checkbox and when the button whose id is "button" is clicked, I want to send the data i.e. if the checkbox is checked to the Django Server. I have imported this version of jquery in HTML: <script src="https://code.jquery.com/jquery-3.1.1.min.js"> HTML: <div>Check<input type="checkbox" id="checkbox"></div> <button id="checkbox">Submit</button> -
I have a OS Error when I did my Django when I followed the tutorial
I followed the tutorial at Django for Beginners (I am at part 3 right now). I am having trouble fixing an OS Error when I ran the site at 127.0.0.1:8000. I got a ModuleNotFoundError, and I feel that the trouble is in my settings.py. I typed in python manage.py runserver when my virtual environment was active. The errors I got were the following: OSError: [WinError] 123 The filename, directory name, or volume label syntax is incorrect. ModuleNotFoundError: No module named widget-tweaks. Here's my settings.py file. This is where I added django-widget tweaks. Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(6@pj06#0x%r)xyw3#!79hys%aba*)b8-6+c=jncuk5+5ei#(i' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget-tweaks', 'boards', … -
How do I find the most up to data/stable verison of a python package FOR A PARTICULAR PYTHON VERSION
I have been following this book: Test-Driven Development with Python Obey the Testing Goat Using Django, Selenium, and JavaScript [Percival 2014-06-29] and I am just using it to learn about Test Driven Development (i.e. TDD). This book however, is written with Django 1.7. This means that for me to follow with the exercises [almost] identically, I should have at most Python 3.2. That said, I have installed Python 3.2 and some of the packages (notably urllib3==1.25.10 and selenium==3.141.0) aren't behaving or executing properly. Besides, when installing urllib3 there was an error. Even with the error while installing urllib3, pip still reported that the install was successful.... My question is: Is there any way to browser python packages by the version of python they are compatible with? If so, I would really appreciate it that you would point me to how. This would help me get the optimal version of pip, selenium, urllib3 and even django compatible with Python 3.2. JUST AS A NOTE, MY VERSION OF PIP THAT CAME WITH THE VIRTUAL ENVIRONMENT FOR PYTHON 3.2 IS PRETTY OLD. I CAN SEE SO FROM THE WAY IT DISPLAYS THE TEXTS AND THE DOWNLOAD PROGRESS.. I BELIEVE THAT THE OLD VERSION … -
Django - sending data with redirect
I am sending sending database objects with my home view as follow: views.py def home(request): questions = list(Question.objects.filter(cat=102)) random.shuffle(questions) context = {'questions': questions[:10]} return render(request, 'learning/home.html', context) def draw_question(request): return redirect('home') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('draw_question/', views.draw_question, name='draw_question') ] But I would like to this the other way round. I would like to load empty home page with button to draw question only. After that I would like to load data my filtered data with 'draw_question' view and then redirect to my home page with this random values. Does anyone know how to obtain this? -
Django channel visitor counter realtime
I am trying to show visitor counter on realtime basis with django. like how many visitor are online at my webiste. I written a websocket consumer but it alwasy give me 0 even if i open the site in multiple browser. this is my django channel consume: class VisitorConsumer(WebsocketConsumer): user_count = 0 def connect(self): self.room_name = 'visitors' self.room_group_name = 'counter_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'send_visitor_count', 'count': self.user_count } ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from room group def send_visitor_count(self, event): count = event['count'] # Send message to WebSocket self.send(text_data=json.dumps({ 'count': count })) adn this is the routing: websocket_urlpatterns = [ re_path(r'ws/visitors/$', consumers.VisitorConsumer), ] I am not getting why it's always firing 0. Can anyone help to fix this?