Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pdf format output is scattered in django
Hi I wanted to create invoice using WeasyPrint. I would like get a well formatted print as output for invoice. I'm using following function to create pdf: from weasyprint import CSS, HTML def render_to_pdf(context, file_name): file_data = render_to_string('order_detail.html', context) html = HTML(string=file_data).write_pdf( target='collections/%s' % (file_name), stylesheets = [CSS(string='body { font-size: 7px }')] ) fs = FileSystemStorage("") with fs.open("collections/" + file_name) as pdf: response = HttpResponse(pdf, content_type="application/pdf") response['Content-Disposition'] = '"attachment; filename="%s"'% (file_name) print("pdf working") return response In the latest version I used stringformat but earlier I tried with normal jinja templating and output was same. here is my html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Email</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <style> .container { border: 1px solid #585696; padding: 0; } .header { background-color: #585696; padding: 1.5rem; } h1.text-center { color: #fff; text-align: center; } .text-center { text-align: center; color: #585696; } .text-content { padding: 2rem; } .order-header{ color: #585696; margin-top: 1rem; } .table-stripped{ width: 100%; border: 1px solid #585696; } .title-bar { background-color: #585696; color: #fff; } th, td { text-align: center; border-bottom: 1px solid #585696; } tr { border-bottom: 1px solid #585696; } .address-time { margin-top: 0; … -
How to get a list of celery tasks that are queued but not yet started
Django 2.2.13 Celery 5.0.5 Redis = 3.5.3 I would like to know, given a task id how can i see if it's in the queue and not yet in the "STARTED" state ( i do have CELERY_TASK_TRACK_STARTED=True). Is the only way to make a key in Redis and query for that key, and if it's not present then i can enqueue? -
New Django project admin urls are somehow being overridden by prior project Django-Allauth settings
I have a new project, using DRF, and when trying to login to admin panel I get an error stating that the page not exist. The problem is that the url being generated when entering the current url is the same url that I used in my prior project using Django-Allauth. I have checked the current project for any traces of Django-Allauth and there are none. I checked the DB to make sure it was empty upon initiation of the project, and it was. What could be the problem here? current url.py urlpatterns = [ path('admin/', admin.site.urls), ..., ] prior urls.py path("accounts/", include('allauth.urls')), When I try to login to admin on localhost: http://127.0.0.1:8000/admin/ it redirects to old project's path of: http://127.0.0.1:8000/accounts/login/?next=/admin/login/%3Fnext%3D/admin/ resulting in an error stating page not found. I cleared cache by restarting project with Pycharm's Invalidate Cache/Restart but that did not resolve the issue. Any guidance is appreciated. -
Why am I getting no reverse match error in django 3.2?
I am making a simple todo list application but while adding a delete button, I am receiving the error. I tried many things searching on internet but couldn't solve the issue, probably because i am new to django.So, your help will be very important. urls.py(of app): from django.conf.urls import url from django.urls import path from . import views urlpatterns=[ path('',views.home,name='home'), url('delete/<str:id>', views.delete_data,name='deldata'), ] views.py: from django.shortcuts import get_object_or_404, render,redirect from todo.models import value from django.http import HttpResponseRedirect # Create your views here. from .forms import TitleForm from django.urls import reverse def home(request): values=value.objects.all() form=TitleForm if request.method=='POST': form=TitleForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form=TitleForm() return render(request,'home.html',{'values':values,'form':form}) #delete def delete_data(request, id ): ggwp=value.objects.get(id=id) if request.method=="POST": ggwp=value.objects.get(id=id) ggwp.delete() return HttpResponseRedirect(reverse('deldata', kwargs={'id':id})) context={'ggwp':ggwp} return render(request,'/',context) models.py: from django.db import models # Create your models here. class value(models.Model): task=models.CharField(max_length=200) complete=models.BooleanField(default=False) created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.task home.html(One and only html page): <h3>TO DO LIST</h3> <form method="POST" action="\"> {% csrf_token %} {{form.task}} <input type='submit' name='add' value="add" > </form> {% for val in values %} {{val}} <form action="{% url 'deldata' val.id %}" method="POST" class="in-line"> {% csrf_token %} <input type="submit" value="Delete" > </form> {% endfor %} traceback: raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'deldata' with arguments '(15,)' not found. … -
Django doesn't see static files (404 error)
I faced with problem when django can't see static files and i'm getting 404 error every time visiting page. [05/Oct/2021 19:25:07] "GET /static/main/css/index.css HTTP/1.1" 404 1813 Here is my setting.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join('static'), ) # Default primary key field type Another part was cut HTML file {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello World</title> <link rel="stylesheet" href="{% static 'main/css/index.css' %}" /> </head> Another part was cut too My files (png) -
Inaccessible class via "manage.py"
Class used to create pickled object in another module is inaccessible via running "python manage.py runserver". How do I point "manage.py" to that class (Classify)? Here's my stack trace below: Internal Server Error: /api/digits/ Traceback (most recent call last): File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\mixins.py", line 19, in create self.perform_create(serializer) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create serializer.save() File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\serializers.py", line 205, in save self.instance = self.create(validated_data) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\rest_framework\serializers.py", line 939, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\DELL\Desktop\mnist-env\lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) File "C:\Users\DELL\Desktop\mnist-env\MNIST_API\digits\models.py", line 62, in save pred = pickle.load(f) AttributeError: Can't get attribute 'Classify' on <module '__main__' from 'C:\\Users\\DELL\\Desktop\\mnist-env\\MNIST_API\\manage.py'> [05/Oct/2021 17:22:43] "POST /api/digits/ HTTP/1.1" 500 54505 Here's an image of my project file structure P.s: The class … -
SMTP Data Error when using sendgrid in django
I am encountering the following error when I try to send emails from my django app despite having setup sendgrid correctly here is my configuration in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = 'MY_API_KEY' EMAIL_PORT = 587 EMAIL_USE_TLS = True could django be having a from email that it is set to by default that needs to be overridden? -
How do i display multi images in two column grid in django
I Have tried using the forloop.counter but it makes the whole grid look messy and plus it only shows three pictures in the grid when you click a picture to have a detail view and sliding to see the other pictures it wont show other pictures as i have about eight pictures posted in the same grid. if the pictures are few i have to go back into the forloop.counter and change the divisible number which is not a good practice how best do i go about it. <div uk-lightbox> <div class="grid grid-cols-2 gap-2 p-2"> {% for p in photos %} {% if forloop.counter|divisibleby:3 %} # The First image goes here <a href="{{ p.pic.url }}" class="col-span-2"> <img src="{{ p.pic.url }}" alt="" class="rounded-md w-full lg:h-76 object-cover"> </a> The second goes here <a href="{{ p.pic.url }}"> <img src="{{ p.pic.url }}" alt="" class="rounded-md w-full h-full"> </a> # the rest of the pictures goes <a href="{{ p.pic.url }}" class="relative"> <img src="{{ p.pic.url }}" alt="" class="rounded-md w-full h-full"> <div class="absolute bg-gray-900 bg-opacity-30 flex justify-center items-center text-white rounded-md inset-0 text-2xl"> + {{ forloop.counter }} more </div> </a> {% endif %} {% endfor %} </div> </div> After i tried the above this what i did again but … -
Unauthorized response using Firebase auth with DRF
I have created a drf API which I have connected to a react-admin frontend in order to have a ready-to-go dashboard interface and it works. But I want to implement firebase authentication into the frontend, and when I try to do that I get errors, and seems that my backend is reading my auth header because it is giving me the bearer token into the console but still gives me an unauthorized response. The backend I am using for the moment is sqlite and I have not created any custom user models, for the moment I am trying to log in from the front-end with an account from firebase. Here are my code samples: class FirebaseAuthentication(authentication.BaseAuthentication): def authenticate(self, request): token = request.headers.get('authorization') print(token) if not token: raise NoAuthToken("No auth token provided") try: decoded_token = auth.verify_id_token(token) uid = decoded_token['uid'] except Exception: raise InvalidAuthToken("Invalid auth token") if not token or not decoded_token: return None try: user = User.objects.get(username=uid) return user except Exception: raise FirebaseError("User does not exist") and here is the react configuration for the firebase auth provider const authProvider = FirebaseAuthProvider(firebaseConfig, firebaseOptions) const dataProvider = drfProvider('http://127.0.0.1:8000/api') export { authProvider, dataProvider } -
Stop a C /C++ extension in Django
Summary of the problem I am implementing a long-running C/C++ extension within a Django framework (called via a request POST). In some cases, the user may want to interrupt the calculation by just leaving/unloading the specific web page that calls the C extension. Is it possible to kill the extension from Python? Minimal Reproducible Example In order to reproduce the problem, we can make our own Fibonacci C extension. The call in Django is as follows: import fibonacci from django.views.generic.base import TemplateView # Computation class ComputationView(TemplateView): template_name = 'Generic/computation_page.html' @staticmethod def get_results(request): N=1000 if request.method == "POST": # When button is pressed # Long computations cs_min = fibonacci.fib(N) else: cs_min = None return render(request, ComputationView.template_name, {'cs_min': cs_min}) While the code in C is: #include <Python.h> // Compute the Minimal cutsets int Cfib(int n) { int fib1; int fib2; if (n < 2) return n; else{ Py_BEGIN_ALLOW_THREADS // Release GIL // Some stric operations in C Py_END_ALLOW_THREADS // Reacquire GIL return Cfib(n-1)+Cfib(n-2); } } // Our Python binding to our C function // This will take one and only one non-keyword argument static PyObject* fib(PyObject* self, PyObject* args) { // instantiate our 'n' value int n; // Order of cutset // … -
TypeError: cannot unpack non-iterable Responses object
I am trying to save some data (fetched from an API) into my database. A list (named GetQuestion_response) was obtained from that API is kinda like this (The actual data from the API is a lot bigger, so I show the first 2 elements of the list here.): GetQuestion_response = [ { "Id":1, "GroupId":0, "QuestionTitle":"What is your first name?", "GroupName":null, "QuestionType":"TEXT","IsMappingAvailable":null,"BodyRegion":0,"EnableCalculation":false,"Responses":[] }, { "Id":2, "GroupId":0, "QuestionTitle":"And your last name?", "GroupName":null, "QuestionType":"TEXT","IsMappingAvailable":null,"BodyRegion":0,"EnableCalculation":false,\"Responses\":[] } ] my models.py: class Responses(models.Model): Answer_Id = models.IntegerField(primary_key=True) QuestionId = models.IntegerField(default=0) ResponseText1 = models.CharField(max_length=500, null=True, blank=True) ResponseText2 = models.CharField(max_length=500, null=True, blank=True) ResponseText3 = models.CharField(max_length=500, null=True, blank=True) IsDeleted = models.BooleanField(default=False) class GetQuestion_API(models.Model): Question_Id = models.IntegerField(primary_key=True) GroupId = models.IntegerField(default=0) QuestionTitle = models.TextField() GroupName = models.CharField(max_length=500, null=True, blank=True) QuestionChoice = [ ('TEXT', 'TEXT'), ('BUTTON', 'BUTTON'), ('NUMBER', 'NUMBER') ] QuestionType = models.CharField(max_length=50, choices=QuestionChoice, default='TEXT', null=True, blank=True) IsMappingAvailable = models.CharField(max_length=500, null=True, blank=True) BodyRegion = models.CharField(max_length=200, null=True, blank=True) EnableCalculation = models.BooleanField(default=False) Responses = models.ForeignKey(Responses, on_delete=models.CASCADE, related_name="QuestionReletedResponses", null=True, blank=True) In my views.py: for i in GetQuestion_response: this_Id = i['Id'] this_GroupId = i['GroupId'] this_QuestionTitle = i['QuestionTitle'] this_GroupName = i['GroupName'] this_QuestionType = i['QuestionType'] this_IsMappingAvailable = i['IsMappingAvailable'] this_BodyRegion = i['BodyRegion'] this_EnableCalculation = i['EnableCalculation'] GetQuestion_API_obj = GetQuestion_API.objects.create( Question_Id = this_Id, GroupId = this_GroupId, QuestionTitle = this_QuestionTitle, GroupName = this_GroupName, … -
Django create Email Change Confirmation Email
I want to create an confirm email for changing the email from the django user. For this I need an unique url which reffers to the site on which I can change it which expires after like 1hour. I also need to know how to send that unique url to the user's old email. How can I do that? -
Problem with serializers creating an API with Django
I am writing an API with django and I am having this problem: When I create a serializer object, if I do it like this: document_serializer = DocumentSalesforceSerializer(data={ "AccountId": patient_id, "ContactId": patient_id, "Proveedor__c": "docline", "Servicio_asociado__c": "report", "Mapfre_Id__c": patient_id, "Status": "In Progress", "StartDate": document["createdAt"], "EndDate": "hoy", "Subject": document["category"], "Description": description, "SAV_fld_source__c": "docline", "SAV_fld_doclineExtId__c": id, "SAV_fld_doctor__c": "", }) document_serializer.is_valid(raise_exception=True) I get the following error: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time. Reading on the internet some people said that I whould delete the data= part, so I left it like this: document_serializer = DocumentSalesforceSerializer({ "AccountId": patient_id, "ContactId": patient_id, "Proveedor__c": "docline", "Servicio_asociado__c": "report", "Mapfre_Id__c": patient_id, "Status": "In Progress", "StartDate": document["createdAt"], "EndDate": "hoy", "Subject": document["category"], "Description": description, "SAV_fld_source__c": "docline", "SAV_fld_doclineExtId__c": id, "SAV_fld_doctor__c": "", }) document_serializer.is_valid(raise_exception=True) But then I am getting this error: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance. Does anyone have and idea of what is causing the error? Thanks in advance for reading this question. -
How to get the template after rendering (Django)
I want to have the site template that is sent to the user after rendering in middleware. -
503 Service Unavailable Error while hosting Django website on CyberPanel
I am trying to host my Django website using CyberPanel on OpenLiteSpeed. I have completed website development. The website is running properly when I run in debug mode (using runserver command). I am trying to deploy the website. I am using CyberPanel as I wish to deploy my own SMTP server. I have used the following article to install cyber-panel on my digital ocean server : https://cyberpanel.net/docs/installing-cyberpanel/ I have used the following article to install and configure Django based website on Openlitespeed server https://cyberpanel.net/blog/2019/01/10/how-to-setup-django-application-on-cyberpanel-openlitespeed/ When I try to open website unionelectronics.in I get 503 Service Unavailable (The server is temporarily busy, try again later!) error. I have updated A record in DNS Management on godaddy to point to my cloud service provider (digital ocean). Error Log : 2021-10-05 14:53:37.241089 [INFO] [817] [config:server:vhosts:vhost:Example] config context /docs/. 2021-10-05 14:53:37.241103 [INFO] [817] [config:server:vhosts:vhost:Example] config context /protected/. 2021-10-05 14:53:37.242757 [INFO] [817] [PlainConf] [virtualHostConfig:] start parsing file /usr/local/lsws/conf/vhosts/unionelectronics.in/vhost.conf 2021-10-05 14:53:37.243519 [INFO] [817] [PlainConf] [virtualHostConfig:] Finished parsing file /usr/local/lsws/conf/vhosts/unionelectronics.in/vhost.conf 2021-10-05 14:53:37.243533 [INFO] [817] [PlainConf] [virtualHostConfig:] context [/] add param [envtype 1] 2021-10-05 14:53:37.251116 [NOTICE] [817] [SSL_CTX: 0x124eb20] OCSP Stapling can't be enabled: [OCSP] /etc/letsencrypt/live/unionelectronics.in/fullchain.pem: X509_STORE_CTX_get1_issuer failed!. 2021-10-05 14:53:37.251224 [INFO] [817] [config:server:vhosts:vhost:unionelectronics.in] config context /. 2021-10-05 14:53:37.257606 … -
Cant write correct queryset in Django
i have three models:subplan,subplanfeature and price.I wanna show gym price table,but it shows wrong result class SubPlan(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class SubPlanFeature(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Price(models.Model): gym=models.ForeignKey(Gym,on_delete=CASCADE) subplan=models.ForeignKey(SubPlan,on_delete=CASCADE,related_name='subplans') feature=models.ForeignKey('SubPlanFeature',on_delete=CASCADE,related_name='features') price = models.IntegerField() highlight_status = models.BooleanField(default=False,null=True) here is my view def pricing(request,slug): gym=models.Gym.objects.get(slug=slug) price=models.Price.objects.all() banners=models.Banners.objects.filter(gym=gym) plans1= models.Price.objects.filter(gender='man',gym=gym) dfeatures1=models.Price.objects.filter(gender='man',gym=gym) return render(request, 'pricing.html',{'plans1':plans1,'dfeatures1':dfeatures1,'gym':gym}) and template here <thead> <tr> <th style="width: 34%;"></th> {% for plan in plans1 %} <th style="width: 22%;">{{plan.subplan}}</th> {% endfor %} </tr> </thead> <tbody> {% for feature in dfeatures1 %} <tr> <th scope="row" class="text-start">{{feature.feature}}</th> {% for plan in plans1 %} <td> {{plan.price}} Azn. </td> {% endfor %} </tr> {% endfor %} </tbody> it should display as this enter image description here but shows this enter image description here what should i change? -
Send a zip file as a response using python
This is probably a question already asked but posting it again since I didn't find a way to resolve my issue. I am given a zip file that I need to send to UI from where it should be downloaded for the user. While testing on POSTMAN, using Send & Download button associated with POST, I am able to download the file. But when opening it, it says: Windows cannot open the folder. The Compressed(zipped) folder <zip path> is invalid Here's the code I am trying: from django.response import Response from rest_framework.views import APIView def get_response(): with open(zip_file_path.zip, 'r', encoding='ISO-8859-1') as f: file_data = f.read() response = Response(file_data, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="ReportTest.zip"' return response class GenerateZIP(APIView): def post(self, request): zip_file_response = get_response() return zip_file_response The zip file read is valid as it's already on the local. Any ideas? -
form-data(POSTMAN) only showing "This field is required" in django
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them. In post request, raw-data input works, but not form-data. It only shows 'rooms' field is required. module/models.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() rooms = models.ManyToManyField(Rooms, blank=True) room_list = models.CharField(max_length = 100, blank=True) rooms/models.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializerWrite(many=True) class Meta: model = Module fields = '__all__' def create(self, validated_data): rooms_data = validated_data.pop('rooms') module = Module.objects.create(**validated_data) for data in rooms_data: room = Rooms.objects.get(**data) module.rooms.add(room) return module def update(self, instance, validated_data): # Updating rooms rooms_data = validated_data.get('rooms') instance.rooms.clear() for room_data in rooms_data: room = Rooms.objects.get(**room_data) instance.rooms.add(room) # Updating other fields fields = [ 'title', 'desc', 'thumbnail', 'is_deleted', ] for field in fields: setattr(instance, field, validated_data[field]) instance.save() return instance rooms/serialier.py - class RoomSerialize(serializers.ModelSerializer): room_id = serializers.IntegerField() class Meta: model = Rooms fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): # Adding the rooms to module from room_list new_request = request.data.copy() room_list=[] if … -
djangochannelsrestframework websocket connection failed with error 500
I am building a simple chat application using djangochannelsrestframework but it gives me error while compiling WebSocket connection to 'ws://localhost:8000/ws/' failed: Error during WebSocket handshake: Unexpected response code: 500 trackback of error at django Internal Server Error: /ws/ Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Python39\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Python39\lib\site-packages\django\template\response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "C:\Python39\lib\site-packages\django\template\response.py", line 63, in resolve_template return select_template(template, using=self.using) File "C:\Python39\lib\site-packages\django\template\loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html [05/Oct/2021 19:21:55] "GET /ws/ HTTP/1.1" 500 83990 My Code(chat app) consumers.py from .models import Messages from .serializers import MessagesSerializer from djangochannelsrestframework.generics import GenericAsyncAPIConsumer from djangochannelsrestframework import permissions from djangochannelsrestframework.mixins import ( ListModelMixin, RetrieveModelMixin, PatchModelMixin, UpdateModelMixin, CreateModelMixin, DeleteModelMixin, ) class UserConsumer( ListModelMixin, RetrieveModelMixin, PatchModelMixin, UpdateModelMixin, CreateModelMixin, DeleteModelMixin, GenericAsyncAPIConsumer, ): queryset = Messages.objects.all() serializer_class = MessagesSerializer permission_classes = (permissions.AllowAny,) routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"^ws/$", consumers.UserConsumer.as_asgi()), ] serializers.py #from django.db import models #from django.db.models import fields #from djoser.serializers import UserCreateSerializer from rest_framework import serializers from … -
How to display a value in another table by using a function in django
I have been trying to make search_fields able to search for fields in another table on the django admin page. I discovered that I could use a function to achieve my goal, but when I went to the admin page, in place of the data I wanted it to display, it would display <django.db.models.query_utils.DeferredAttribute object at 0x00000208375C9280> Here is my admin.py file: from django.contrib import admin from .models import RiskRegister, Category, Severity, RSev from account.models import Account class RiskRegisterAdmin(admin.ModelAdmin): list_display = ['id', 'user', 'user_dept', 'date', 'category', 'roles', 'responderID', 'severity', 'action_taken_explanation', 'created_at'] list_filter = ['id', 'user', 'date', 'category', 'roles', 'responderID', 'severity', 'action_taken_explanation'] search_fields = ['id', 'user', 'user_dept', 'date', 'category', 'roles', 'responderID', 'severity', 'created_at'] def user_dept(self, obj): return Account.department And my models.py file containing the Account model: class Account(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=150, unique=True) email = models.EmailField(verbose_name='email', max_length=254, unique=True) department = models.CharField(verbose_name='department', max_length=100, editable=True) first_name = models.CharField(verbose_name='first name', max_length=254, blank=True) last_name = models.CharField(verbose_name='last name', max_length=254, blank=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) How can I make it display what is in the department? -
I am getting 500 Internal Server Error in django app during deloying on production server ModuleNotFoundError: No module named 'main' (wsgi:error)
I want to serve my project using mod_wsgi. When i run development server, It's started but it gives error on production server.My os is RedHat and using httpd(apache) virtual host configured with python3-mod_wsgi. This is my error [Tue Oct 05 14:01:48.998236 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] mod_wsgi (pid=423542): Failed to exec Python script file '/var/www/public_html/main/main/wsgi.py'. [Tue Oct 05 14:01:48.998291 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] mod_wsgi (pid=423542): Exception occurred processing WSGI script '/var/www/public_html/main/main/wsgi.py'. [Tue Oct 05 14:01:48.998461 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] Traceback (most recent call last): [Tue Oct 05 14:01:48.998506 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] File "/var/www/public_html/main/main/wsgi.py", line 17, in <module> [Tue Oct 05 14:01:48.998523 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] application = get_wsgi_application() [Tue Oct 05 14:01:48.998530 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] File "/usr/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Tue Oct 05 14:01:48.998534 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] django.setup(set_prefix=False) [Tue Oct 05 14:01:48.998540 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 19, in setup [Tue Oct 05 14:01:48.998543 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Tue Oct 05 14:01:48.998548 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ [Tue … -
Django + NGINX 404 Not Found
Whenever I run server using gunicorn --bind command, all static files load without any error. but when I try to access my domain It gives 404 error. I am mentioning all my settings related to the static file: STATIC_ROOT (Django): '/var/www/html/static' STATIC_URL = '/static/' /etc/nginx/sites-available/default: (Nginx) server{ root /var/www/html; index index.php index.html index.htm index.nginx-debian.html; server_name 65.1.254.234; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; include proxy_params; proxy_pass http://unix:/home/ubuntu/Application_Code/app.sock; } location /static { autoindex on; alias /var/www/html; } } Is there any problem happening due to .env file? -
How can I transfer this SQL query to Django orm code
The model(the pk/id is auto generated) class Comments(models.Model): parent = models.ForeignKey(to="self", null=True) And the SQL query SELECT * FROM comments WHERE ( parent_id IN ( 1, 2, 3, 4 ) AND ( SELECT COUNT(*) FROM comments AS f WHERE ( f.parent_id = comments.parent_id AND f.id <= comments.id ) )<= 2 ) -
Key 'fieldname' not found in 'ModelForm'. Django 3.2
I am trying to override the get_form function in admin class in Django 3.2. I defined a custom permission for a specific user that can only view some defined fields of a model. It worked fine but when I tried to navigate to the change form of an object with the non-permitted users, I cannot be able to view the change form as superuser until other user closes the change form. So basically, override get_form method is not working at the same time for different kind of users. By the way I did not have any defined view because I am only using admin template as view, I am just only overriding admin template. I am new in django so I don't know that I am doing this correctly... Here is the admin class that I created and override get_form method(for instance I do not want to display surname if the user does not have the custom permission): class HumanAdmin(admin.ModelAdmin): fieldsets = ( ('Fields 1', {'fields': ('id','name', 'surname'),}), ) def get_form(self, request, obj=None, **kwargs): if request.user.has_perm('app_name.custom_permission'): self.fieldsets[0][1]["fields"] = ('id','name', 'surname') form = super(InventoryAdmin,self).get_form(request, obj, **kwargs) else: self.fieldsets[0][1]["fields"] = ('id','name') #I do not want to see if user does not have … -
DRF Pagination custom response without model APIView
Hello I have a project in Django, which performs several queries to different databases returning them in several endpoints, for this I use Pandas and DRF (APIViews). The problem arises when the response is very long and logically the server runs out of memory, I understand that I need to paginate the result but I have not found the way to do it because I do not use models or serializers, I do raw queries with pandas to make the queries. Is there any way to paginate the results the way I'm doing it? I leave some snippets of my code. class AffiliateAPIView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): insurance = self.request.query_params.get('insurance', None) emergensys_df = pd.read_sql_query(general_attention(insurance), engine()) return Response(emergensys_df.to_dict(orient='records'))