Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to POST whole html table data using Django?
Created a html table with three columns and 26 rows which is mapped to the Django views.py file. Was trying to post all html table data into DB using Django views.py file. Please find my views.py: def create(request): form = Scrum.objects.all() if request.method == "POST" or "None": form.save() context = { 'form': DBData } return render(request, "scrum.html", context) scrum.html <form method="POST" action="."> {% csrf_token %} <table class="example-table multiselectable is-centered" id="table" contenteditable="true"> <tbody><tr><td class="selected">1</td><td class="selected">2</td><td>3</td><td>4</td><td>5</td></tr> <tr><td class="selected">1</td><td class="selected">2</td><td>3</td><td>4</td><td>5</td></tr> <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr> <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr> <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr> </tbody></table> <input type="submit" name="submit" class="btn btn-outline-primary btn-block" placeholder="Submit"> </form> After clicking "Submit" button, all my provided data in table should be saved in DB. My model will be shown as below: models.py Category = models.CharField(max_length=30) TaskName = models.CharField(max_length=70) AssignedTo = models.TextField(max_length=70) -
Any risk in upgrading postgres 9.6 to 12.7?
I have a project built in python/Django which uses Postgresql==9.6. Now that this version of Postgres is no longer supported, I am upgrading it to version 12.7. Writing this question to know if anybody faced any challenges while doing this upgrade. My project has a lot of direct SQL statements along with the ORM(Django's default ORM) queries and I am pretty worried about these. It would be great if someone can also list all the functions/features which are part of 9.x and deprecated in 12.x. My project is built on: python == 3.6 django == 1.11 postgresql == 9.6.22 (current), upgrading to postgres == 12.7 [fyi - Using AWS RDS] psycopg2 == 2.6.2 Thanks for any help:) -
What is the order of execution of the return statements for saving the form data?
def issuebook_view(request): form=forms.IssuedBookForm() if request.method=='POST': #now this form have data from html form=forms.IssuedBookForm(request.POST) if form.is_valid(): obj=models.IssuedBook() obj.enrollment=request.POST.get('enrollment2') obj.isbn=request.POST.get('isbn2') bk = models.Book.objects.get(isbn = obj.isbn) if bk.available_copies == 0: return render(request,'library/booksover.html') if bk.available_copies > 0: bk.available_copies = bk.available_copies - 1 bk.save() obj.save() return render(request,'library/bookissued.html') return render(request,'library/issuebook.html',{'form':form}) I am new to Django and finding it difficult to understand the order of execution of the return statements in the above function to save the form data. Can anyone explain the order of execution of the execution of the return statements.As per my understanding i think first the last return render statement with the form template is run and then the execution shifts back upwards and processes the rest of code from form.is_valid. Please help me with this. Thanks in advance. -
ClientError HeadObject when collecstatic AWS S3
I have a VPS and I'm trying to collectstatic (Django) using AWS S3. When I try to python manage.py collectstatic I got this error: botocore.exceptions.ClientError: An error occurred (400) when calling the HeadObject operation: Bad Request More context I have another VPS with same project and works. I tested with same aws credentials (user and bucket) and I get the same error. Testing localy works. -
I want to insert data into MySQL database with Django
I am doing web scraping and I want to store the information in the database. I have the connection with the database in the 'settings' file like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbname', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': 'port' } } The web scraping I have it in another file like this: from bs4 import BeautifulSoup import requests url = "https://www.somepage.com" result = requests.get(url) soup = BeautifulSoup(result.text, "html.parser") find_by_class = soup.find('div', attrs={"class":"body"}).find_all('p') I want to store what is in find_by_class in the database. Also I have created the models. from django.db import models class SomeModel(models.Model): description = models.TextField(max_length=1000) -
Trying to write a crispy form factory
I'm trying to write a form factory to return Crispy forms with an appropriate helper object attached. This is what I have. It seems to work, but also seems inelegant. def crispy_form_factory( schema): namespace = { '_schema': schema } for key, info in schema: # details omitted. I know this works because I've been using it without crispy. # it populates the namespace with things like namespace[key] = forms.Charfield( **kwargs) ## where kwargs is generated based on info from the schema dict form_class = type('Schema_Form', (forms.Form,), namespace ) class Crispier( form_class): def __init__( self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper=FormHelper(self) # Crispify self.helper.layout = make_layout( self._schema) return Crispier What I was hoping to do was define an inner function def init(self, *args, **kwargs): super().__init__( *args, *kwargs) self.helper = FormHelper( self) self.helper.layout = make_layout( self._schema) namespace['__init__'] = init return type('Crispy_PRSBlock_Form', (forms.Form,), namespace ) but 'magic' super() doesn't work when used this way. What's the elegant way to inject a Crispy layout object into a form factory function? (The answer may lie in Python metaclasses, which I confess to not reallty understanding) Elegance aside, is there any particular reason why not to do it the way I have found which appears to be … -
Django modelSerializer form.is_valid() is true when values are empty
When I run form.is_valid() it returns true except for branches_count and employee_count. When I run form.save() it returns key errors serializers.py class GeneralInformationFormSerializer(serializers.ModelSerializer): class Meta: model = Business fields = ['location', 'date_founded', 'employee_count', 'branches_count', 'business_premises'] def update(self, instance, validated_data): return update_business_details(instance, validated_data) This is models.py class Business(SyncedBusinessModel): location = models.TextField(blank=True) employee_count = models.IntegerField(blank=True, null=True) branches_count = models.IntegerField(blank=True, null=True) business_premises = models.CharField(max_length=255, blank=True, choices=BUSINESS_PREMISES_CHOICES) date_founded = models.DateField(blank=True, null=True) def __str__(self): return self.name class Meta: verbose_name_plural = "businesses" -
How to get the value of html radio button
In my html, I have the code below ... <div class="tab-pane fade" id="account-notifications"> <div class="card-body pb-2"> <h6 class="mb-4">Activity</h6> <div class="form-group"> <label class="switcher"> <input type="checkbox" class="switcher-input" checked> <span class="switcher-indicator"> <span class="switcher-yes"></span> <span class="switcher-no"></span> </span> <span class="switcher-label">Email me when someone comments on my article</span> </label> </div> <div class="form-group"> <label class="switcher"> <input type="checkbox" class="switcher-input"> <span class="switcher-indicator"> <span class="switcher-yes"></span> <span class="switcher-no"></span> </span> <span class="switcher-label">Email me when someone answers on my forum thread</span> </label> </div> </div> </div> ... There are two input fields, one is checked and the other one isn't. The user can also toggle On or Off the switch. My problem how to get the current state of the switch (toggled On or Off) so that I can send the value to my Django as True or False -
How to set an environment variable inside a Django management command (python script)
I am trying to make a Django management command that cache's a user's SUDO password, and the SSH deploy key password, so the second time they run the script it does not ask for them. However the root cause of the problem is that the Environment variables set within the child shell, do not persist to the parent shell when the child shell exits, as explained here: Is it possible to change the Environment of a parent process in Python? I don't wish to write this sensitive information to a file. So how does one pass info from the management command, back to shell, so next time the command is run it can access the cached credentials? when the shell is quit, it must destroy the cached info. Here's my code if anyone is interested: import os from subprocess import run, PIPE, Popen from getpass import getpass from django.core.management.base import BaseCommand SUDO_ENV_KEY = 'SUDO_PASSWORD' GIT_ENV_KEY = 'GIT_PASSWORD' class Command(BaseCommand): def handle(self, **options): # ----GET SUDO AUTH---- if not (sudo_pass := os.environ.get(SUDO_ENV_KEY)): sudo_pass = getpass(f"Please enter sudo password: ") os.environ[SUDO_ENV_KEY] = sudo_pass # Send password via STDIN as bash history is insecure command = ['echo', 'Getting sudo...'] p = Popen(['sudo', '-S'] … -
Field 'maca' expected a number but got ''
models.py class Boss(models.Model): class Maca(models.IntegerChoices): one_maca = 1, one_macas = 2, two_maca = 3, four_maca = 4, six_maca = 5, __empty__ = _('Select') maca = models.IntegerField( db_column='Maca', choices=Maca.choices, blank=True, null=True ) forms.py maca = forms.ChoiceField(required=False, choices=Boss.Maca.choices, widget=forms.Select) When I try to submit as empty value I got the following error ValueError: Field 'maca' expected a number but got ''. -
Django global variable disadvantages
What disadvantages are there when using django and defining variables like this then using them in the views??? logged_user = Logged_User.objects.all() def logged_user(request): a = B.objects.filter(a = request.user) return render(request, 'a.html',{'a':a,**'logged_user':logged_user**}) Rather than def logged_user(request): a = B.objects.filter(a = request.user) logged_user = Logged_User.objects.all() return render(request, 'a.html',{'a':a,**'logged_user':logged_user**}) With the first step, the logged_user is callable from any other view without having to rewrite everything. -
How to change python code formatting so that a single statement fits in one line, rather than being formatted into multiple?
I need to fetch all the Django ORM queries used in my project. I have written a script that goes through the project files and writes the matching LOC to a CSV. The problem is that some of these queries are written in multiple lines to improve readability, which is causing my logic to fail and give me incomplete results in the CSV. Does anyone have an idea how to remove the code formatting to make a single python statement fit in one line so that I can execute my script successfully? -
Django Separate Settings raises error TemplateDoesNotExist at /
I have been attempting to separate my settings via settings folder with base, dev prod and init files and ran the server with the dev settings it says it runs with no issues but when I click on the link I now get an error TemplateDoesNotExist at /, I was able to access the page before seperating my settings I decided to try the above on a fresh django project which appears to have worked on out of the box django main page and admin panel however again when I go to add a new url and view and template the same error is raised TemplateDoesNotExist at /. Please see the following code exlcuding settings/base.py as this is just fresh project settings but cut SECRET_KEY and placed in settings/dev.py which worked prior to adding url/view and template: urls from django.contrib import admin from django.urls import path, include, reverse_lazy from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), ] views from django.shortcuts import render, redirect def home(request): return render(request, 'test.html') template - projectroot/templates/test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> </head> <h1>Test</h1> <body> </body> </html> Help is much apprecaited in getting … -
Passing context from get_conext_data to get
I use to have book_a_room_form = BookARoomForm() in get_context_data but then I amended it to book_a_room_form = BookARoomForm(initial={'arrival_date': request.session['arrival_date']}) and put it in get (see reason for moving it to get here). get_context_data and get work individually. But I cannot get them to work together. I have read dozens of posts on the issue, looked at my traceback and been given a variety of different error messages. I am now just going round cirlces with the issue. def get_context_data(self, *args, **kwargs): context = super(HotelDetailSlugView, self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['hotel_extra_photos'] = AmericanHotelPhoto.objects.all().filter(title=AmericanHotel.objects.all().filter(slug=self.kwargs.get('slug'))[0].id) context['room_type'] = RoomType.objects.all().filter(title=AmericanHotel.objects.all().filter(slug=self.kwargs.get('slug'))[0].id) return context def get(self, request, *args, **kwargs): # This code is executed each time a GET request is coming on this view # It's is the best place where a form can be instantiate book_a_room_form = BookARoomForm(initial={'arrival_date': request.session['arrival_date']}) return render(request, self.template_name, {'book_a_room_form': book_a_room_form, }) -
How to Django ORM queryset on different language database while input query set language as English?
I have one database where all data are stored in english . But if i want to appy queryset filter on that database i Need to queryset language as french. But what if i want to filter database as queryset language as English. My problem is like this where i have one country_name field in my Country model. Problem is stored country data is in french language . I want to apply filter query on that but i have English country name as query and not french i am getting query result empty. ex : in Croatie in french but Croatia in English. Now if i query on country_name field i not get any result because it's not exact match. can we have any solution for problem like that where we can query on different language database while query input language as English. -
wkhtmltopdf is not rendering images to pdf
this is my image tag in django templates <img src="{{post.image.url}}" /> my url.py path( 'pdf/<int:pk>/', MyPDF.as_view(template_name='templates/post_detail.html', filename='post_pdf.pdf'), name='pdf-wk' ), this is my view.py class MyPDF(PDFTemplateView): template_name = 'templates/post_detail.html' def get_context_data(self, pk): context = {'post': Post.objects.get(pk=pk)} return context -
How can django-rules package be used to define different permissions per instance from the same database table?
There are multiple courses defined in a database table courses. I would like to explicitely define users who have the permission to enroll specific course. How can this be done using django-rules ? -
"python manage.py runserver" does not start a server
I am on a django project and python manage.py runserver command stopped working. It's so confusing because there is no error. I'm working on vs code powershell and I've tried it on cmd, and windows powershell but it's still the same thing (I typed in the command "python mange.py runserver", press "enter", and it just returns a new line with directory.This a screenshot of my terminal -
Filezilla Error "ECONNREFUSED - Connection refused by server"
I'm trying to create a litle FTP server on Django and i follow the documentation It's very simple: Add the app to django installed apps config Create ftp group and user Run command to start ftp serve The problem appears when i'm trying to connect from Filezilla Client on local machine, i get the error: "ECONNREFUSED - Connection refused by server" I try on differents hosts 0.0.0.0, 127.0.0.1, 192.168.0.30 and ports 20, 21, 2000, 2100 but the error message persist Anybody could help me please ? Thanks in advance. -
Django + ajax + modal form botstrap5
No matter how much I did not try to fasten Ajax request. In case of success, a redirect should occur, in case of failure - an error output. All the ways that tried to implement already and I will not remember. I will be very grateful if somebody on this example will show how to work with Ajax. And where to register it correctly? In the basic template? Since if you specify inside the modal template, it is performed too early before downloading the page. View for authorization: def login_view(request): """ Обработчик авторизаций, обращение происходит через ajax """ # небольшая заглушка (Plug since one type of authorization is still disabled) if request.method == 'POST' and request.POST.get('type') == 'login': return JsonResponse({'status': 'error', 'login_type': 'login', 'msg': 'На данный момент данный метод авторизаций не доступен!'}) if request.method == 'POST': if request.POST.get('type') == 'login': try: user: User = auth.authenticate(login=request.POST.get('login'), password=request.POST.get('password')) except Exception as error: return JsonResponse({'status': 'error', 'login_type': 'login', 'msg': str(error)}) else: auth.login(request, user) elif request.POST.get('type') == 'token': try: user: User = auth.authenticate(token=request.POST.get('access_token')) except Exception as error: return JsonResponse({'status': 'error', 'login_type': 'token', 'msg': str(error)}) else: auth.login(request, user) else: return JsonResponse({'status': 'error', 'msg': 'Неизвестный тип авторизаций'}) return JsonResponse({'status': 'ok'}) else: return JsonResponse({'status': 'error', 'msg': 'Запрос … -
How can I make my docker container update on changes to my source files?
I'm building a Django/React app using docker-compose, and I'd like it to reload my apps when a change is made, so far I've tried adding CHOKIDAR_USEPOLLING, adding npm-watch to my package.json, but it doesn't seem to be able to detect changes in the host file. Ideally I don't want to have to run docker-compose up --build every time I make a change since it's making development tedious. Is there something wrong with my files or something else I should be doing here? docker-compose.yml version: "3.9" services: db: container_name: db image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres backend: container_name: backend build: ./backend command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/core ports: - "8000:8000" depends_on: - db frontend: container_name: frontend build: ./frontend command: npm start volumes: - '.:/frontend/app' - '/frontend/node_modules' ports: - "3000:3000" environment: # Allow hot reload on edits - CHOKIDAR_USEPOLLING=true depends_on: - backend # Enable interactive terminal (crucial for react container to work) stdin_open: true tty: true backend Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code/ COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ frontend Dockerfile FROM node:16 WORKDIR /app/ COPY package*.json /app/ RUN npm install COPY . /app/ EXPOSE 3000 CMD ["npm", … -
ImportError: No module named wsgi
hey guys i am struggling with this error while deploying my django app to centos. error from apache logs [Wed Nov 24 16:21:21.724707 2021] [core:notice] [pid 20646] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Wed Nov 24 16:22:19.137654 2021] [:error] [pid 20647] [remote 127.0.0.1:152] mod_wsgi (pid=20647): Target WSGI script '/var/www/reporting-service-dev/Cashlesso/wsgi.py' cannot be loaded as Python module. [Wed Nov 24 16:22:19.137792 2021] [:error] [pid 20647] [remote 127.0.0.1:152] mod_wsgi (pid=20647): Exception occurred processing WSGI script '/var/www/reporting-service-dev/Cashlesso/wsgi.py'. [Wed Nov 24 16:22:19.137815 2021] [:error] [pid 20647] [remote 127.0.0.1:152] Traceback (most recent call last): [Wed Nov 24 16:22:19.137832 2021] [:error] [pid 20647] [remote 127.0.0.1:152] File "/var/www/reporting-service-dev/Cashlesso/wsgi.py", line 21, in <module> [Wed Nov 24 16:22:19.138065 2021] [:error] [pid 20647] [remote 127.0.0.1:152] from django.core.wsgi import get_wsgi_application [Wed Nov 24 16:22:19.138085 2021] [:error] [pid 20647] [remote 127.0.0.1:152] ImportError: No module named wsgi my django.conf file: <VirtualHost *:80> ServerAdmin self@cash.com ServerName report.cash.com DocumentRoot /var/www/ Alias /static /var/www/reporting-service-dev/static <Directory /var/www/reporting-service-dev/static> Require all granted </Directory> WSGIPassAuthorization On WSGIDaemonProcess reporting-service-dev python-path=/var/www/reporting-service-dev:/home/neeraj/cashvenv/lib/python3.6/site-packages WSGIProcessGroup reporting-service-dev WSGIScriptAlias / /var/www/reporting-service-dev/Cashlesso/wsgi.py <Directory /var/www/reporting-service-dev/Cashlesso/> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> permissons on my project dir: drwxr-xr-x. 6 apache apache 135 Nov 24 14:55 reporting-service-dev location of my env [root@ip cashvenv]# pwd /home/neeraj/cashvenv -
__init__() missing 1 required positional argument: 'response' [closed]
def retrieve(self, request, slug=None): query_slug = slug query_obj = { 'slug' : query_slug} if query_obj: search_result = CardDocument.search().query("match", slug=query_slug) qs = search_result.to_queryset() serializer = self.get_serializer(search_result, many=True) return Response(serializer.data) Error occurs: return Response(serializer.data) TypeError: init() missing 1 required positional argument: 'response' Please help me to resolve it -
When overriding default create method in Django view,it is not calling to_internal_value() in serializer
I am trying to override the default creation function in my view.py. But when I try to use to_internal_value() it does not serialize the data. It only performs to_internal_value() when I don't override the default create() in my views.py. views.py class ContactViewSet(viewsets.ModelViewSet): queryset = ContactInformation.objects.all() serializer_class = TemplatesSerializer() #If this function is commented then everything works #fine and to_internal_value() is called while serializing def create(self, request): contact = ContactInformation() contact.name = request.data['name'] contact.address = request.data['address'] contact.save() return JsonResponse(data=TemplatesSerializer(contact).data) serializer.py class TemplatesSerializer(serializers.ModelSerializer): def to_internal_value(self, data): print('Printing from to_internal') return super().to_internal_value(data) def to_representation(self, instance): print('Printing from to_represent') data = super().to_representation(instance) return data class Meta: model = ContactInformation fields = '__all__' model.py class ContactInformation(models.Model): name = models.CharField(max_length=128) address = models.CharField(max_length=128) -
Is it better to store fk directly or get from another related table?
For example I have two models. What I get confused here is it will be better to store department_id directly on the Sale model or use product.department whenever you need it. The use case for the department in sales model can be, filter sales by department, reports sales of department or so on. class Product(): name = models.CharField() department = models.ForeignKey(Department) class ProductSale() product = models.ForeignKey(Product) department = models.ForeignKey(Department) # other fields Or just class ProductSale() product = models.ForeignKey(Product) # other fields