Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Unsafe redirect to URL with protocol 'account'
I am trying to redirect to login page with return url through a middleware . I am getting this error so can anyone answer the question why i am getting this error and how to solve this error from django.shortcuts import redirect def auth_middleware(get_response): def middleware(request): print("Middleware") return_url = request.META['PATH_INFO'] if not request.session.get('user_id'): return redirect(f'account:login?return_url={return_url}') response = get_response(request) return response return middleware -
Django Channels Disconnect Notification Issue
I'm working on a project where we are using Django channels. We have to send a notification in the room if any of the users disconnect. To start with each room will be limited to 2 users only. I have a utility function inside websocket_disconnect(), to send messages to the room to notify other users. The issue, that notification is being sent for all requests even when a user is sending a message(using receive_json(), send_json()). Here message is sent, but still the function send_external_msg_to_channel() from websocket_disconnect() is being triggered. I am using AsyncJsonWebsocketConsumer. The frontend uses a reconnecting-websocket package. class InterviewConsumer(AsyncJsonWebsocketConsumer): async def websocket_disconnect(self, message): print("disconnecting") await send_external_msg_to_channel(self.room_name, {"type": "send_json", "event": "disconnect"}) return await super().websocket_disconnect(message) -
context must be a dict rather than JsonResponse
I want to send JsonResponse(convert python objects into JSON) to the HTML page. for that, I write a view like this: from django.shortcuts import render from django.http import JsonResponse def send_json(request): data = [{'name': 'Peter', 'email': 'peter@example.org'}, {'name': 'Julia', 'email': 'julia@example.org'}, {'name': True, 'data': None}] a = JsonResponse(data, safe=False) return render (request, 'index.html', a) But, It shows context must be a dict rather than JsonResponse. error. In HTML: {{ a }} -
Add user to "django-celery-results" table
we created one concurrency task in Django using celery. then we stored results in database using Django-celery-results. now my requirement is after some time i like to retrieve task results with user id. @shared_task(bind=True) def SayHello(self ,*args, **kwargs): return "Done" so help me how i can add and get data from celery table -
How to Restrict App Model from Django Admin
I am trying to create a system in django admin model where admin can see all apps in django admin index. Staff can see only restricted apps. I was able to change the app list index for different roles, but for restricted user they can access directly through url. Note - I am using AbstractBaseUser and unregister group model model.py class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(('first name'), max_length=30, null=True) last_name = models.CharField(('last name'), max_length=30, null=True) date_of_birth = models.DateField(null=True) date_joined = models.DateTimeField(('date joined'), auto_now_add=True) # avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) phone = PhoneNumberField(null=True) country = CountryField(null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) staff = models.BooleanField(default=False) is_consumer = models.BooleanField(default=True) # premium_referral = models.CharField(('Premium Referral Code'), max_length=30, null=True,blank=True, unique=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' … -
Highcharts Highstocks cumulativeSum Issue
I recently wanted to take advantage of the highcharts library to add a cumulative year existence unfortunately when I activate the cumulative option True implemented since version 9.3.2 my graph breaks the mouth yet it displays the correct information would there be an option to activate or deactivate to have the cumulative without all the graph is sorted graph before the activation of the cumulative option graph after the activation of the cumulative option I develop in python framework django with a url that I call in ajax My python code Thank you in advance for your help!! -
Django TemporaryUploadedFile different behavoiur under Python2/3 with delete=False
Why does the TemporaryUploadedFile get deleted in Python 3 while in Python 2 it stays in /tmp/ directory? And how would I keep the behavior of Python 2 while using 3? from django.core.files.uploadedfile import TemporaryUploadedFile with TemporaryUploadedFile('something.txt', 'text/plain', 0, 'UTF-8') as tmp_file: tmp_file_path = tmp_file.temporary_file_path() tmp_file.file.delete = False print(tmp_file_path) Running this block of code under Python 2 keeps the file in /tmp/ directory while on Python 3 it gets deleted. [ray@fedora tmp]$ ls | grep tmp tmpvSmI8b.upload #generated in Python 2 PY2 version 2.7.18 PY3 version 3.7.12 Django 1.11.29 -
kombu.exceptions.EncodeError: queryset is not JSON serializable. Celery task error in Django
that's my views.py def create(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) matching_fields = serializer.validated_data['matching_fields'] add.delay(matching_fields, instance, request) return Response(status=201, data={ 'total': '11', 'success': True }) for function add pass argument on request, but i get error kombu.exceptions.EncodeError: <ImportRecord: ImportRecord object (19)> is not JSON serializable that's my task.py @shared_task() def add(matching_fields, instance, request): helper = ImportData(matching_fields, instance, request) helper.import_data()