Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The view "..." didn't return an HttpResponse object. It returned None instead
I am currently getting a Value Error on my current application where the program is supposed to print a pdf file. The full error message states the following: ValueError at /accConnect/trialBalanceMonthly/8 The view main.views.trialBalanceMonthly didn't return an HttpResponse object. It returned None instead. I have tried to check if there was any module I am missing and checked to see if the bool value that printing this file depended on was True (it was )- So I can't seem to find what could be causing this problem. My current code is as follows: URL.py: path('accConnect/trialBalanceMonthly/<int:reports_pk>' , views.trialBalanceMonthly, name='trialBalanceMonthly'), path('accConnect' , views.reportsHome, name='reportsHome'), View.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from django.template.loader import render_to_string from weasyprint import HTML import tempfile def trialBalanceMonthly(self , reports_pk): pkForm = get_object_or_404(SettingsClass, pk=reports_pk) complexName = pkForm.Complex # CHECKING TRIAL BALANCE MONTHLY SETTINGS if pkForm.Trial_balance_Monthly == True: # SQL STATEMENT baseTRBMonth = 'SELECT Master_Sub_Account , cAccountTypeDescription ,Debit , Credit FROM PostGL AS genLedger ' \ 'Inner JOIN Accounts ' \ 'on Accounts.AccountLink = genLedger.AccountLink ' \ 'Inner JOIN _etblGLAccountTypes as AccountTypes ' \ 'on Accounts.iAccountType = AccountTypes.idGLAccountType ' \ 'WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122) ' \ 'AND genLedger.TxDate > ? ' xtrbMonth = … -
Create a django model for saving train and test data in database
I am trying to create a website by django which a user can upload a csv file. in server I want to save this csv file as train data for a machine learning model. and I can't make a Model by the csv file because I don't know the name of the fields. and these names can change in differant datas. for example for one data it may seem like this: class TrainData(models.Model): humidity = models.IntegerField(...) wind_speed = models.IntegerField(...) is_it_raining = BooleanField(..) and we want to run a machine learning algorithm on this model by fields. and another data will be like: class TrainData(models.Model): X1 = models.CharField(...) X2 = models.CharField(...) X3 = models.CharField(...) y = models.CharField(...) a bad approach is (I guess) to convert this csv file into a DataFrame and convert DataFrame into a Pickle file and save it in data base by a model like bellow: class TrainData(models.Model): data = PickledObjectField() is there a better way to create this model?? and is creating data to pickle a good practice? -
Python Django variables data duplication after page refresh
I am passing a string to template, and It works fine, but when I reload the page, that string is duplicated. The string is generated dynamically and contains html-table, I want to render a table from variable in my template Only server reset helps to see the actual table without duplicates Code from views.py: def test(request): headings = ('RED', 'GREEN', 'BLUE') tb = Table() tb.make_headings(headings) cell_1 = Cell('1') cell_2 = Cell('2') cell_3 = Cell('3') row_1 = Row() row_1.add_cell(cell_1) row_1.add_cell(cell_2) row_1.add_cell(cell_3) tb.add_row(row_1) html_table = tb.create_html_table() return render(request, 'test.html', context = { 'table' : html_table }) create_html_table() function: def create_html_table(self): html_table = '<table>' for row in self.raw_table: html_row = '<tr>' for cell in row.cells: html_cell = '<td>{}</td>'.format(cell.get_data()) html_row += html_cell html_row += '</tr>' html_table += html_row html_table += '</table>' return html_table Row code: from .cell import Cell class Row(): cells = [] def __init__(self): self.cells = [] def add_cell(self, cell: Cell): self.cells.append(cell) def get_cells(self): return self.cells Cell code: class Cell(): def __init__(self, data = []): self.data = data def get_data(self): return self.data -
Without AuthMiddlewareStack how can I get logged user in Django channels?
Without AuthMiddlewareStack how can I get logged, user? Because I am not used auth models that's why self.scope['user'] returning the 'Anonymous'. I tried to add this class AllowedHostsOriginValidator - doesn't work. I want a session user. please help me. routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from chat.consumers import ChatConsumer from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path('ws/chat/pm-with/<str:username>/',ChatConsumer()), ]) ) ) }) consumers.py from channels.consumer import SyncConsumer from asgiref.sync import async_to_sync from chat.models import user,Thread,Message from chat.views import ChatView from django.contrib.sessions.models import Session class ChatConsumer(SyncConsumer): def websocket_connect(self,event): me = self.scope['user'] other_user = self.scope['url_route']['kwargs']['username'] getOtheruser = user.objects.filter(username = other_user).first() self.send({ 'type': 'websocket.accept', }) def websocket_receive(self,event): print("new event is received") print(event) self.send({ 'type': 'websocket.send', 'text': event.get('text'), }) def websocket_disconnect(self,event): print("disconnect event is called") custom user models models.py class user(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50,default="", blank=True, null=True) last_name = models.CharField(max_length=50,default="", blank=True, null=True) username = models.CharField(max_length=50,default="", blank=True, null=True) password = models.CharField(max_length=100,default="", blank=True, null=True) image = models.ImageField(upload_to ='user_image',default="",blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) deleted = models.DateTimeField(default="",blank=True, null=True) is_deleted = models.BooleanField(default=False) I want login users from custom models, not auth user models. please help me for this -
How to delete old multiple images on edit
I have multiple images in my product model. I got parts from here: multiple images I want to change old images to new when I use change_view. Here's my model.py: class Product(models.Model): title = models.CharField(max_length = 45) description = models.TextField(null = True) image = models.ImageField(upload_to = 'store/full/', null = True, blank = True) def __str__(self): return self.title class Meta: ordering = ['title'] verbose_name = "Product" verbose_name_plural = "Products" def get_image_filename(instance, filename): title = instance.product.title idd = instance.product.id slug = slugify(title) return "store/additional//%s-%s-%s" % (idd, slug, filename) class ProductImage(models.Model): product = models.ForeignKey(Product, default = None, on_delete = models.CASCADE, related_name = 'image_set') image = models.ImageField(upload_to = get_image_filename, verbose_name = 'Image') Here's my views.py: def create_view(request): ImageFormSet = modelformset_factory(ProductImage, form = ProductImageForm, extra = 4) form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, files = request.FILES) formset = ImageFormSet(request.POST, files = request.FILES, queryset = ProductImage.objects.none()) if form.is_valid() and formset.is_valid(): obj = form.save(commit = False) obj.save() for form in formset.cleaned_data: if form: image = form['image'] photo = ProductImage(product = obj, image = image) photo.save() messages.success(request, "Created!") return redirect('shop.all') else: print(form.errors, formset.errors) else: formset = ImageFormSet(queryset = ProductImage.objects.none()) context = { 'form': form, 'formset': formset } return render(request, 'shop/products/create.html', context) def change_view(request, id): … -
Reload django template into ajax response
is it possible to reload a Django template after an ajax call? This is my code. script.js $('.test').click(function(){ var platform = $('#testModal').attr('test-attr'); $.ajax( { type:"POST", url:"test", headers: { 'X-CSRFToken': TOKEN }, dataType: "json", cache : false, processData : false, contentType : false, data: string, success: function(data) { location.reload(); } }); }); view.py return render(request, "user_interface/index.html", {'my_var': 'abc', 'my_var_2': 'cde'}) I tried to use return HttpResponse(json.dump({'res': 'Ok', 'err': None}), content_type = "application/json") but when i reload the page it fails. -
how to resolve getattr() error in django?
I am doing a project in Django, and I think i have made changes in some models, then after i am getting these errors, (env) PS C:\Users\ashwi\Documents\GitHub\Recruiters\recruiters> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ashwi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\ashwi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\ashwi\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\ashwi\Documents\GitHub\Recruiters\recruiters\AMCH_recruiter\models.py", line 6, in <module> class Candidate(models.Model): File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\db\models\base.py", line 161, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\db\models\base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\ashwi\Documents\GitHub\Recruiters\env\lib\site-packages\django\db\models\fields\__init__.py", line … -
Automatic connect gitlab pipline with azure web services
I have my webapp code on GitLab. I want to deploy it using Azure web services. But I want it in such a way that, when I push the code to branch it will first be pushed in GitLab then automatically on azure web services.. Is there any way to do this? I searched for a solution on the internet but not found the latest one. -
Django: Render list of model objects and post back the same list without changing item type in the list
On the first page, the user will click the upload button and several "model objects" will be stored into a list and render to one HTML component on the second page. Then if the user clicks the "save" button on the second page, the value in that input component will be posted back to the backend and further process will be done. view.py: def manual_upload_file(request): upload_objs = [TModel1.objects.get(m_id=1), TModel1.objects.get(m_id=2), TModel1.objects.get(m_id=3)] if "persist_data" in request.POST: objs_to_be_processed = request.POST["persist_data"] .... return render(request, 'components/page2.html', {'upload_objs':upload_objs }) page2.html: <form action="{% url 'page2' %}" method="post"> {% csrf_token %} <button class="btn btn-primary" name="persist_data" type="submit" value="{{upload_objs}}"> Save </button> </form> The problem here is that {{upload_objs}} in button value of page2.html will become pure string. And therefore all the model objects inside the list lose its property and all become part of string , i.e. when it post back, the request.POST["persist_save"] received in view,py is: "[<TModel1: TModel1 object (1)>, <TModel1: TModel1 object (2)>, <TModel1: TModel1 object (3)>]" Is there any template tag I can keep all objects as model object after render it to html page. For example, something like: value="{{upload_objs|list}}" Or is there any solution? Thank you -
Node.js and Django sharing a Postgresql database
I've built an application in Node.js and it's using a postgresql database. It's a mobile application for Android, which allows users to upload an image to the application using their mobile phone. We have another application that uses Django, and a model in python that uses OCR to extract text from images, and stores them in a table. I want to use the python code to run on the images that have been uploaded by the user using the mobile app, and process the image text and store it against the user record in the database. My problem is that the Node.js database doesn't use auth_user as the main table for users and I am unable to connect django to the existing postgresql db, because the tables are not standard django models. Any advice? The mobile app is how we collect images and pdfs, but python is the code that uses OCR and an ML library to process this - and we want to display them back to the user through the mobile app. Thanks p.s.: The database is hosted on Google Cloud, where all the images are stored too. -
TemplateDoesNotExist at / but filesystem loader says it does | happening in an extends tag
I am using Django 1.5.1 with Python 2.6.6. The error that I am getting is TemplateDoesNotExist at / when using the template extends {% extends "t_base_menu.html" %} The template that holds the extends is in the project/home/templates/home/index.html. The loader setting are (SITE_ROOT is correct): TEMPLATE_DIRS = ( join(SITE_ROOT, 'templates'), ) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) In the error page the Template-loader postmortem says it exists, using django.template.loaders.filesystem.Loader: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: /project/templates/t_base_menu.html (File exists) I have noticed that it is working if I move the t_base_menu.html to the project/home/templates folder. What am I missing? -
Form object not iterable in Django
I want to assign the input of a form to a function in my view but I keep getting this error. Please help do I fix it. Error receiver = list(ToolsForm.declared_fields['receiver_mail']) TypeError: 'CharField' object is not iterable -
Django returns image data as None
My utils.py: import base64, uuid from django.core.files.base import ContentFile def get_report_image(data): f , str_image = data.split(';base64,') print(f) print(str_image) decoded_img = base64.b64decode(str_image) img_name = str(uuid.uuid4())[:10] + '.png' data = ContentFile(decoded_img, name=img_name) return data When I try to get a report, I get the 500 server error: Internal Server Error: /reports/save/ Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python38\ go\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\1\AppData\Local\Programs\Python\Python38\ go\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, * File "C:\Users\1\PycharmProjects\StasProject\sales_proje line 13, in create_report_view img = get_report_image(image) File "C:\Users\1\PycharmProjects\StasProject\sales_proje line 5, in get_report_image f , str_image = img.split(';base64,') AttributeError: 'NoneType' object has no attribute 'split' Although, in the browser console I can find 23 kbs of the data that goes as data:image/png;base64, and a bunch of characters. I'm trying to get the latter. Why does it not see the data? I have views.py as this: from django.shortcuts import render from profiles.models import Profile from django.http import JsonResponse from .utils import get_report_image from .models import Report def create_report_view(request): if request.is_ajax(): name = request.POST.get('name') remarks = request.POST.get('remarks') image = request.POST.get('image') img = get_report_image(image) Report.object.create(name=name, remarks=remarks, image=img, author=author) author = Profile.objects.get(user=request.user) return JsonResponse({'msg': 'send'}) return JsonResponse({}) -
How to run django orm query without using field name?
So i have one json data that contain field name of model as json key with value. i want to run orm query and define field name on run time. Ex: json_data = {"postgres_id":"10"} query = AcronymSecurityControlMaster.objects.get(postgres_id=10) json_data = {"age":"10"} query = AcronymSecurityControlMaster.objects.get(age=10) -
DRF is not re-evaluating queryset as expected gotcha
This is a question about whether DRF is working as it should or whether it could be improved to account for this use case. I have a simple API that returns a custom queryset like this: class WorldRankingViewset(viewsets.ReadOnlyModelViewSet): queryset = Ranking.objects.world_ranking() Where the custom queryset is: class RankingQuerySet(models.QuerySet): def world_rankings(self, rank_type="World"): # get most recent update update = RankingUpdate.objects.issued().filter(rank_type=rank_type, date__lte=TODAY).order_by("-asat", "-date").first() # if there is one, get all the player rankings for that update if update: return self.filter(update=update, player_id__gt=0, points__gt=0) else: return self.none() In the generics.py code of DRF, the get_queryset function has this code: def get_queryset(self): .... queryset = self.queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset Given the comment "Ensure queryset is re-evaluated on each request" I was expecting it to do that. However, when I run my API test, the following sequence happens. Evaluation queryset Run setUpTestData() to populated data for test Make call to api without re-evaluating queryset Return no data If I put a custom get_queryset code into the api then it all works as I would expect and returns test data: class WorldRankingViewset(viewsets.ReadOnlyModelViewSet): queryset = Ranking.objects.none() def get_queryset(self): return Ranking.objects.world_rankings() Run setUpTestData() to populated data … -
django.core.exceptions.FieldError: Unknown field(s) (PhoneNumber, City, Email, KYCDocument, Image, Speciality) specified for Doctor
I am trying to make a form using modelsform, it was working fine but, suddenly I don't know what suddenly happens and it started giving me this error django.core.exceptions.FieldError: Unknown field(s) (PhoneNumber, City, Email, KYCDocument, Image, Speciality) specified for Doctor I have checked this error online and tried some solutions but nothing workout form me . here is forms.py file from django import forms from .models import Doctor class Doctorslist(forms.ModelForm): class Meta: model = Doctor fields = ('name','PhoneNumber','Email','City','Speciality','Image','KYCDocument') here is models.py file from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Doctor(models.Model): name = models.CharField(max_length=20) phone_number = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField(max_length = 100) city = models.CharField(max_length=100) speciality = models.CharField(max_length=50) doc_image = models.ImageField(upload_to = 'blog_images', verbose_name = "Image") kycdocument = models.ImageField(upload_to = 'blog_images', verbose_name = "kycImage") -
create page like html with some header and footer
i want to create some html page with div shape like some ms word pages, with some header and footer for every pages, this is not that hard with some dive with fixed height and width but i want to use table on them as the tables grew and become bigger than page height another page with same footer and header created. i can use of server side languages with template like Django or javascripts is allowed too -
Django generate one-time password for admin site
So I want to generate a one-time password, "everytime" there a new login to admin site (let say I set timeout for 30 minutes or so), and send that password via email or else. Thankyou:) -
Django erroneously triggers the post_save signal on instance delete
I'm trying to send an email notification when an Article instance is created or modified. I use signals and send_mail. Everything works great while I just create and modify articles. But, if I delete an Article, I've got a notification that it was updated! This is incorrect behavior. What can be a reason (and solution)? models.py from django.core.mail import send_mail from django.db.models.signals import post_save from django.dispatch import receiver # ... class Article(TimeStampedModel): title = models.CharField(_('Title'), max_length=255, db_index=True) slug = AutoSlugField(_('Slug'), unique_with=['year', 'month'], populate_from="title", db_index=True) picture = models.ImageField(verbose_name=_('Image'), upload_to = upload_to) category = models.ForeignKey('Category', blank=True, null=True, on_delete=models.SET_NULL, db_index=True, related_name='articles') author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) annotation = models.TextField(_('Brief annotation'), blank=True) # Brief annotation (1 paragraph) date = models.DateTimeField(_('Date'), default=timezone.now, db_index=True) modified = models.DateTimeField(_('Modified'), db_index=True, auto_now=True) year = models.PositiveIntegerField(_('Year'), db_index=True, blank=True) month = models.CharField(_('Month'), db_index=True, max_length=2, blank=True) is_published = models.BooleanField(_('Is published'), default=False) def delete(self, *args, **kwargs): # Remove the media files of the article together with their folder from django.core.files.storage import default_storage if self.picture: with contextlib.suppress(FileNotFoundError): default_storage.delete( self.picture_thumbnail.path ) self.picture.delete() path = os.path.join(settings.MEDIA_ROOT, settings.CKEDITOR_UPLOAD_PATH, 'news', str(self.year), str(self.month), str(self.slug)) if os.path.isdir(path): shutil.rmtree(path) # Remove folder super().delete(*args, **kwargs) def __str__(self): # Потом допилить, чтобы год и месяц тоже выводился return self.title # There can be … -
Function() got multiple values for argument 'pk'
My program currently needs to print reports for each database entry in the settings model. It reads the pk of the model and uses that to check the items of the settings entry. However I get a trialBalanceMonthly() got multiple values for argument 'TBMreports_pk' error when I click on the button that is supposed to print the report. Here is my code : reportsHome.html: {% for x in model %} <a href="#" class='list-group-item active'>{{ x.Complex }} Reports</a> <div> <hr> <a href="{% url 'trialBalanceMonthly' TBMreports_pk=x.pk %}" type="button" class="btn btn-outline-primary btn-sm" >{{ x.Complex }} Trial Balance Monthly</a> <a href="{% url 'trialBalanceYearly' TBYreports_pk=x.pk %}" type="button" class="btn btn-outline-primary btn-sm" >{{ x.Complex }} Trial Balance YTD</a> <br> <a href="{% url 'incomeStatementMonthly' ISMreports_pk=x.pk %}" type="button" class="btn btn-outline-primary btn-sm" >{{ x.Complex }} Income Statement Monthly</a> <a href="{% url 'incomeStatementYearly' ISYreports_pk=x.pk %}" type="button" class="btn btn-outline-primary btn-sm" >{{ x.Complex }} Income Statement YTD</a> <hr> </div> <br> {% endfor %} Views.py (I have removed some of the code that generates the variables to make this a more reproducible question) --This is what each of the reports views functions look like def trialBalanceMonthly(TBMreports_pk): pkForm = get_object_or_404(SettingsClass, pk=TBMreports_pk) complexName = pkForm.Complex ### Printing Trial Balance PDF response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; … -
How to fix 504 error caused by Docker image update
I have Django project. It works with nginx, uwsgi and google cloud run. This project is using docker which python:3.9 image. I have got this error since 17,Aug. 2021-10-13 17:22:29.654 JSTGET504717 B899.9 sGoogleStackdriverMonitoring-UptimeChecks(https://cloud.google.com/monitoring) https://xxxx/ The request has been terminated because it has reached the maximum request timeout. To change this limit, see https://cloud.google.com/run/docs/configuring/request-timeout and also this error occur on all my pages. However when I open my pages myself, I can see my pages. It means I can't see this 504 error by myself. I added a line in admin.py at 17, Aug. I didn't think this line is no related with this error. Because this change is only effect in admin page. However I needed confirm what is cause this error. So I had rollback my code before the error. Now I'm still can't fix this error. Builded docker image is different size before after error. And Vulnerability has decreased. I think this is caused by some small change on python image. In this case, how can I solve this problem? What I did I changed docker image to python:3.8 and python:3.9.6-buster. I couldn't fix the error. -
I want to improve performance of my api endpoint(DJANGO)
I'm using Django rest to request data of customers from an endpoint suppose the endpoint is '/customers/list' and my Query set is to get all customers queryset = Customers.objects.all() I am expecting to get so many customers which will affect the performance of the application that will consume this endpoint. I am not willing to return the result set paginated so how can i improve the response time in case of too many records are processed. -
How can i solve the heroku deployment application error?
When you run py manage.py runserver, everything works without error. There was a need to test on the heroku server. When uploading to heroku, Application error occurs. An error appears in the heroku logs: 2021-10-13T07:44:14.143374+00:00 heroku[web.1]: Starting process with command `daphne Quiz.asgi:application --port 22236 --bind 0.0.0.0 -v2` 2021-10-13T07:44:16.405529+00:00 app[web.1]: Traceback (most recent call last): 2021-10-13T07:44:16.405551+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2021-10-13T07:44:16.405640+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2021-10-13T07:44:16.405651+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 170, in entrypoint 2021-10-13T07:44:16.405777+00:00 app[web.1]: cls().run(sys.argv[1:]) 2021-10-13T07:44:16.405779+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 232, in run 2021-10-13T07:44:16.405911+00:00 app[web.1]: application = import_by_path(args.application) 2021-10-13T07:44:16.405911+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/utils.py", lin e 12, in import_by_path 2021-10-13T07:44:16.405982+00:00 app[web.1]: target = importlib.import_module(module_path) 2021-10-13T07:44:16.405992+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, i n import_module 2021-10-13T07:44:16.406091+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-10-13T07:44:16.406101+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-10-13T07:44:16.406200+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-10-13T07:44:16.406262+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-10-13T07:44:16.406325+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-10-13T07:44:16.406387+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 855, in exec_module 2021-10-13T07:44:16.406469+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_remove d 2021-10-13T07:44:16.406527+00:00 app[web.1]: File "/app/./Quiz/asgi.py", line 9, in <module> 2021-10-13T07:44:16.406642+00:00 app[web.1]: from quiz_app.routing import ws_urlpatterns 2021-10-13T07:44:16.406642+00:00 app[web.1]: File "/app/./quiz_app/routing.py", line 3, in <module> 2021-10-13T07:44:16.406724+00:00 app[web.1]: from .consumers import … -
Django permissions using too much the database
We started investigation on our database as it is the less scalable component in our infrastructure. I checked the table pg_stat_statements of our Postgresql database with the following query: SELECT userid, calls, total_time, rows, 100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0) AS hit_percent, query FROM pg_stat_statements ORDER BY total_time DESC LIMIT 5; Everytime, the same query is first in the list: 16386 | 21564 | 4077324.749363 | 1423094 | 99.9960264252721535 | SELECT DISTINCT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" LEFT OUTER JOIN "auth_user_groups" ON ("auth_user"."id" = "auth_user_groups"."user_id") LEFT OUTER JOIN "auth_group" ON ("auth_user_groups"."group_id" = "auth_group"."id") LEFT OUTER JOIN "auth_group_permissions" ON ("auth_group"."id" = "auth_group_permissions"."group_id") LEFT OUTER JOIN "auth_user_user_permissions" ON ("auth_user"."id" = "auth_user_user_permissions"."user_id") WHERE ("auth_group_permissions"."permission_id" = $1 OR "auth_user_user_permissions"."permission_id" = $2) This sounds like a permission check and as I understand, it is cached at request level. I wonder if someone did a package to cache them into memcached for instance, or found a solution to reduce the amount of requests done to check those permissions? I checked all indices and they seem correct. The request is a bit slow mostly because we have a lot of permissions but still, the amount of calls … -
django multiplechoice field wont get saved
I have a simple form which has a checkbox for the users to choose some choices from.therefore, I created a model called InterestedField and connected my main model to it with manytomany method. this my main model: class PersonalInfo(models.Model): id = models.AutoField(primary_key=True) isCompleted = models.BooleanField(default=False) interested_field = models.ManyToManyField(InterestedField) and this the InterestedField itself: class InterestedField(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) simple enough. then, I created this form like this: class InterestedFieldChoiceForm(forms.Form): InterestedFieldChoice = forms.ChoiceField() and these are my views and html template code: class PersonalView(View): template_name = 'reg/personal.html' def get(self, request, *args, **kwargs): context = {} interested_field = InterestedField.objects.all() context['interested_field'] = interested_field return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): user = request.user form = InterestedFieldChoiceForm() if form.is_valid(): interested_field = request.POST.getlist('InterestedFieldChoice') user.personalInfo.interested_field = interested_field[0] user.personalInfo.save() user.personalInfo.isCompleted = True user.personalInfo.save() user.save() return render(request, 'reg/done.html', context={'info_type': 'اطلاعات فردی'}) my html: <form id="personal-form" method="POST" action="{% url 'personal' %}" autocomplete="off" class="ant-form ant-form-horizontal"> <div class="ant-descriptions"> <div class="ant-descriptions-view"> {% for field in interested_field %} <label class="ant-col ant-col-md-6 ant-col-xs-8 ant-checkbox-wrapper {% if field in user.personalInfo.interested_field.all %} ant-checkbox-wrapper-checked {%endif%}" style="margin-left: 0; float: right;"> <span class="ant-checkbox {% if field in user.personalInfo.interested_field.all %} ant-checkbox-checked {%endif%}"> <input type="checkbox" name="InterestedFieldChoice" class="ant-checkbox-input" value="{{field.id}}"> <span class="ant-checkbox-inner"></span> </span> <span>{{field.title}}</span> …