Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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() -
Django Post-request within for-loop is not working
I am stuck with a page containing two post-requests where one of them is inside of a for-loop. The user has an input file that uses a autocomplete function. This function uses the shop-Model in Django. After submitting, the product will be added to the Shopping_List-Model in Django. It will be displayed in another div of the page. This is currently working without a problem. The user then should have the possibility to delete the product from the list by clicking a button. But the button is not working, it is not processing the post-request. I have also tried different elif-Statements (e.g. elif request.POST["shop_delete"]), but none of them worked. Please note as I have not figured out how to get the button to work, the action does only contain print("delete"). I would write the necessary code afterwards. Any suggestions are much appreciated! Many thanks in advance! Here is my code: HTML <div> <!--Input field and autocomplete--> <form id="product_add" action="{% url 'index' %}" method="post"> {% csrf_token %} <input type="text" name="shop_product" id="shop_product"> <!--Code for autocomplete--> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#shop_product").autocomplete({ source: "{% url 'index' %}", minLength: 2 }); }); </script> <input type="submit" name="button_add" value="Add"> </form> </div> <div> <table> … -
How to implement Specific field data into one list and Another filed data into another list in Django
I'm using Django 3x. I have one table called Book. When I write query for this I'm getting data like this: book_details = Book.objects.all().values() print(book_details) <QuerySet [{'id': 1, 'author': 'ABC', 'price': 150, 'category': 'Comic', 'available': 1}, {'id': 2, 'author': 'XYZ', 'price': 500, 'category': 'Historical Fiction', 'available': 1}, {'id': 3, 'author': 'MNO', 'price': 200, 'category': 'Horror', 'available': 0}]> I'm trying to create data in this below format {'id':[1,2,3], 'author':['ABC', 'XYZ', 'MNO'], 'price':[150,500,200], 'category':['Comic', 'Historical Fiction', 'Horror'], 'available':[1,1,0]} How to create data in this format. Please advise best way to do this. And explanation would be much appreciated. Thanks!. -
getting black image after converting base64 string(tiff format to jpeg) using python
I am converting base 64 string to jpeg format and it is working fine but in case of tiff format string I am getting black image img = Image.open(io.BytesIO(base64.b64decode(b64_string))).convert('RGB') temp_file = tempfile.TemporaryFile() img.save(temp_file, 'jpeg') temp_file.seek(0) return temp_file can anyone help me out -
Django fields for timing
I have the following codes: models.py class Job(models.Model): jobname = models.CharField(max_length = 1000) owner = models.CharField(max_length = 150) enabled = models.BooleanField() freq_type = models.IntegerField(default = 1) freq_interval = models.IntegerField(default = 0) freq_recurrence = models.IntegerField(default = 0) start_date=models.CharField(max_length=10) end_date=models.CharField(max_length=10, blank = True) start_time=models.CharField(max_length=6) end_time=models.CharField(max_length=6, blank = True) date_added = models.DateTimeField(auto_now_add = True, null = True) date_modified=models.DateTimeField(auto_now = True, null = True) version=models.IntegerField(default = 1) views.py def job_edit(request, pk): job = Job.objects.get(pk=pk) if request.method =="POST": job_form = JobForm(request.POST) if job_form.is_valid(): option = request.POST.get('check') time = request.POST.get('servicetime') date = request.POST.get('servicedate') version = request.POST.get('version') Job.objects.filter(pk=pk).update(enabled=option,start_time = time,start_date = date,version = version) return redirect('/job/', {'job':Job.objects.all}) return render(request, 'interface/job_edit.html',{'job': job}) When i create entry to Job, date_added and date_modified will have the same date and time stored. (Not sure if this is the intended way for auto_now_add and auto_now). But when i attempt to edit the same entry, this date_modified does not change at all. Is there something I am missing in my function? Like something to trigger this auto_now to insert the timing i edit the entry -
Azure web-app - Multi-container unit was not started successfully for Django app
Ok having a real issue here with Azure Web-app for multi-containers, no matter what I do, I can't get it to work. I've spend hours on this myself and also with Microsoft representatives. The issue is that I can't get web-apps for multiple containers to work with my docker-compose file with related Docker images. The service is in "preview-mode" i.e. being some sorts of beta-version (my guess) so it may be some bug here at Microsoft's end, but I still wanted to write this post in hope that someone may have insight to help me figure this out. This is the logs I'm getting when trying to access the application in the browser, and this is the only logs available, I have checked this with the Microsoft support: 2021-11-24T08:53:40.341Z INFO - Pull Image successful, Time taken: 0 Minutes and 0 Seconds 2021-11-24T08:53:40.357Z INFO - Starting container for site 2021-11-24T08:53:40.360Z INFO - docker run -d -p 9688:80 --name companybe_backend_0_df9f2437 -e WEBSITES_ENABLE_APP_SERVICE_STORAGE=false -e WEBSITES_PORT=8000 -e WEBSITE_SITE_NAME=companybe -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=companybe.azurewebsites.net -e WEBSITE_INSTANCE_ID=*** -e HTTP_LOGGING_ENABLED=1 companycontainerregistry.azurecr.io/companybe:latest 2021-11-24T08:57:30.785Z ERROR - multi-container unit was not started successfully 2021-11-24T08:57:30.799Z INFO - Container logs from companybe_backend_0_df9f2437 = 2021-11-24T08:53:44.889298525Z projectile/manage.py:8: UserWarning: Not reading projectile/.env - it …