Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WebSocket HANDSHAKING /ws/play/testroomcode [127.0.0.1:57522] Exception inside application: __call__() missing 1 required positional argument: 'send'
When I was trying to connect my websocket then it is showing this error: Error: WebSocket HANDSHAKING /ws/play/testroomcode [127.0.0.1:57522] Exception inside application: call() missing 1 required positional argument: 'send' The code inside my asgi.py : import os from django.urls import path from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from tictactoe.consumers import GameRoom from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'advancesource.settings') application = get_asgi_application() ws_pattern = [ path('ws/play/<room_code>', GameRoom) ] application= ProtocolTypeRouter( { 'websocket': AuthMiddlewareStack(URLRouter( ws_pattern )) } ) The code inside my consumer.py : from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class GameRoom(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = 'room_%s' % self.room_name print(self.room_group_name) async_to_sync(self.channel_layer.groups_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.groups_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): print(text_data) async_to_sync(self.channel_layer.groups_send)( self.room_group_name,{ 'type' : 'run_game', 'payload': text_data } ) In websocketking it is showing: Could not connect to "ws://127.0.0.1:8000/ws/tictactoe/play/testroomcode". You may be able to find more information using Inspector/Dev Tools on this page. -
Django - How to create multiselect checkbox dropdown in django forms
I wanted to created a multiselect check in the dropdown. I have created model with choices and passed it to the form and it renders to the template with the dropdown. I have tried out multiselect choice field in the form as well but not getting the expected result. I have 3 fields which needs to be in multiple select dropdown. Thanks in advance. models.py class Userbase(models.Model): Payment_Term = models.CharField(max_length=255) Netdue_Date = models.DateField(null=True) Predicted_Paid_days = models.DateField(verbose_name=('Predicted paid days')) company_code = models.CharField('company code',choices=CHOICES,max_length=10) Area = models.CharField(choices=AREACHOICES, max_length=155) country = models.CharField(choices=AREACHOICES, max_length=155) forms.py class Userform(forms.ModelForm): # CHOICES = (("address1","address1"), ("address2","address2")) # country=forms.MultipleChoiceField(choices=CHOICES,widget=forms.CheckboxSelectMultiple()) def __init__(self, *args, **kwargs): super(Userform, self).__init__(*args, **kwargs) self.fields['Payment_Term'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder': 'Payment_Term','id': 'id_Payment_Term'}) self.fields['Netdue_Date'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder': 'Netdue_Date', 'name': 'email', 'id': 'Netdue_Date'}) self.fields['Predicted_Paid_days'].widget.attrs.update( {'class': 'form-control mb-3', 'name': 'Predicted_Paid_days', 'id': 'Predicted_Paid_days', 'placeholder':'Predicted_Paid_days'}) self.fields['company_code'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder':'Select company_code','name': 'company_code', 'id': 'id_my_date'}) self.fields['Area'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder':'Select Area','name': 'Area', 'id': 'id_Area'}) self.fields['country'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder':'Select Country','name': 'country', 'id': 'id_country'}) class Meta: model =Userbase # fields = '__all__' fields = ('country','Payment_Term','Netdue_Date','Predicted_Paid_days', 'PBK_Desc','Vendor_Name','Reference','company_code','Area') widgets={ 'Netdue_Date':DateInput() } home.html <div>Company Code</div> <div class="row" id='id_row'> {{ form.company_code}} </div> <div>Area</div> <div class="row" id='id_row'> {{ form.Area}} </div> <div>Country</div> <div class="row" id='id_row'> {{ form.country}} </div> <div>Payment Term</div> … -
openpyxl ValueError : didn't return an HttpResponse object. It returned None instead
I am currently trying to change my code from creating a CSV file to creating an xlsx file. My code for some reason returns the following error when I click the button which is supposed to download the file: ValueError at /accConnect/AgeAnalysisCSV/12 The view main.views.AgeAnalysisCSV didn't return an HttpResponse object. It returned None instead. Please see the below code, I don't think that the problem is that I had returned the save function through response? Is there any other way for me to save it while closing off the function with a return? Views.py # Starting CSV book = Workbook() sheet = book.create_sheet("Sheet1") sheet['A1'] = 'Prepared By : Atout(PTY) ltd' sheet['A2'] = 'Customer Age Analysis for Monthly Customers as at 31/10/21' sheet['A3'] = 'Account' sheet['B3'] = '' sheet['C3'] = '' sheet['D3'] = '120+ Days' sheet['E3'] = '90 Days' sheet['F3'] = '60 Days' sheet['G3'] = '30 Days' sheet['H3'] = 'Current' sheet['I3'] = 'Total' sheet['J3'] = '' sheet['K3'] = 'Name' sheet['L3'] = 'E-mail' for x in ageSelect: rows = ( (x["Account"], '*' , ' ','0','0 ','0','0', x["Balance"], x["Balance"],'',x["Name"], x["E-mail"]), ) for row in rows: sheet.append(row) for x in XtotalCurent: lastrow = ( ('Totals :',' ', ' ','120 Days', '90 Days', '60 Days', … -
Testing a view that uses TemporaryUploadedFile
I have a view that does this: import pandas as pd def ingest(request): for temp_file in request.FILES.values(): # There only ever is one use next(gen) if you prefer path = temp_file.temporary_file_path() break df = pd.read_csv( path, encoding="UTF-16-le", header=None ) ... And I'd like to test this view. I can't actually change the view logic as it is designed to be the endpoint fpr an external service that I have no control over. I've added FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler',] to the settings to avoid nasty surprises, but I can't make the tests work. My test.py : from django.core.files.uploadedfile import TemporaryUploadedFile from django.test import TestCase class InputTest(TestCase): def test_extract_csv(self): form_data = { 'upload_file': TemporaryUploadedFile("data/test.csv", "csv", 88614, "utf-16-le") } self.client.post("/ingest", form_data) but that results in empty data in the view. -
Is it poostible to convert a python method to djagno database method?
I want to ordery my query by total value, total is forigen key to items i use method bellow to calculte total amount . models.py function def total(self): total=0 for item in self.items.all(): if item.taxed==True: total = total + item.amount + (item.amount*(self.tax)/(100)) else: total = total + item.amount return total my query lookslike : nvoices = Invoices.objects.all().order_by() -
How can I substitute django conditional template tags in a string of html code
I'm using django-ajax-datatable to render data tables in my django project In doing so I would like to customize what one row called actions renders an example of doing so is as follows def customize_row(self, row, obj): # 'row' is a dictionary representing the current row, and 'obj' is the current object. row['code'] = '<a class="client-status client-status-%s" href="%s">%s</a>' % ( obj.status, reverse('frontend:client-detail', args=(obj.id,)), obj.code ) if obj.recipe is not None: row['recipe'] = obj.recipe.display_as_tile() + ' ' + str(obj.recipe) return take note of this line of code row['code'] = '<a class="client-status client-status-%s" href="%s">%s</a>' % ( the HTML to be rendered to the row is written in a string as you can see. For my own specific case I would like to render the following HTML inclusive of the django template tags (batch to be replaced with obj) <a class="btn btn-sm btn-alt-secondary" href="{% url 'batch_detail' batch.pk %}" data-bs-toggle="tooltip" title="View"> <i class="fa fa-fw fa-eye"></i> </a> {% if batch.approve == False %} <a class="btn btn-sm btn-alt-secondary" href="{% url 'approve_manufacturing_batch' batch.pk %}" data-bs-toggle="tooltip" title="Approve"> <i class="fa fa-fw fa-check-circle"></i> </a> {% else %} <a class="btn btn-sm btn-alt-secondary" href="{% url 'approve_manufacturing_batch' batch.pk %}" data-bs-toggle="tooltip" title="Disapprove"> <i class="si si-close"></i> </a> {% endif %} I tried out multiple string … -
Django changes the spaces to underscores how to avoid that or change it to download with the original name?
Remove underscores by reverting to original name -
Two different django apps with different authentications in the same project
Please I want to create two different apps in django with two different authentications. I have Personal Assistant app and Accountant app. I want the Personal Assistant page to be different from Accountant Page. Please how should I go about creating different authentication for Accountant app? Login for personal assistant ''' from django.contrib.auth import authenticate, login, logout def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'app/login.html', context) ''' Because I don't want -
python django newline not working with replace in richtextfield
models.py description = RichTextField(blank=True, null=True) admin.py description = "*text1/*text2/*text3" desired_output = "*text1 *text2 *text3" #I Tried to do with replace but it dont work - description.replace("/", "\n") #replace dont work to get newline in RichTextField Any Solutions? -
How do i use kepler.gl with Django backend
Is there a kepler library i can install in my django project to use kepler.gl in my frontend, like in leaflet-django. If not, how do i use Kepler.gl maps as frontend for django backend? -
Django filter using Q and multiple fields with different values
I am trying to generate a result that satisfies with the filter query below: indicators = request.GET.getlist('indicators[]') fmrprofiles = FMRPriority.objects.all() q_objects = Q() obj_filters = [] for indicator in indicators: split_i = indicator.split('_') if len(split_i) == 5: if not any(d['indicator'] == split_i[1] for d in obj_filters): obj_filters.append({ 'indicator': split_i[1], 'scores': [] }) for o in obj_filters: if split_i[1] == o['indicator']: o['scores'].append(int(split_i[4])) for obj in obj_filters: print (obj['scores']) q_objects.add(Q(pcindicator__id = int(obj['indicator'])) & Q(score__in=obj['scores']), Q.AND) print (q_objects) fmrprofiles = fmrprofiles.values('fmr__id','fmr__road_name').filter(q_objects).order_by('-fmr__date_validated') print (fmrprofiles.query) Basically, indicators is a list e.g. ['indicator_1_scoring_1_5', 'indicator_1_scoring_1_4', 'indicator_2_scoring_2_5'] I wanted to filter FMRPriority with these following fields: pcindicator score e.g. pcindicator is equal 1 and scores selected are 5,4..another selection pcindicator is equal to 2 and scores selected are 3. The query q_objects.add(Q(pcindicator__id = int(obj['indicator'])) & Q(score__in=obj['scores']), Q.AND) returns empty set..i have tried also the raw sql, same result. Model: class FMRPriority(models.Model): fmr = models.ForeignKey(FMRProfile, verbose_name=_("FMR Project"), on_delete=models.CASCADE) pcindicator = models.ForeignKey(PCIndicator, verbose_name=_("Priority Indicator"), on_delete=models.PROTECT) score = models.FloatField(_("Score")) -
Hi My problem is with the terminal VS app
PS E:\learning\project\django\env\scripts> activate activate : The term 'activate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 activate + CategoryInfo : ObjectNotFound: (activate:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Can we blindly trust Django ERROR "you may need to add xxx to ALLOWED_HOSTS"?
Regularly I receive from my server these kind of errors: Invalid HTTP_HOST header: '139.162.113.11'. You may need to add '139.162.113.11' to ALLOWED_HOSTS. The problem is that my server works fine and I don't know where do these IP addresses are comming from. If I try to localize the one in example, it appears to be in Tokyo, which is weird to me, having a server based in France for mainly european customers. Can it be a suspicious attempt to the server security? I'm not keen to allow this IP. What is the correct attitude toward this kind of error. -
Do we need to use runserver command in production to start our django project?
Do we need to use runserver command in production to start our project? If yes, then how to do it, and If No then how does out project server starts? -
How to add model with multiple services and prices for them in Python/Django
I've just started learning Python/Django and I have a question for you guys:) I want to create a model in Django that will allow me to create a service with prices for each user. For example, Users can open a form that will allow them to put there their services, and prices for each services. But I don't know how to create an appropriate model. Please help. -
getting error while parsing json ein django using SSE
Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data I am sending implement SSE using js , but some of my js code is throwing errors on JSON.parse wonder where I am going wrong about this def somefunc(): face_attributes = { "quality_issue": False, <----------- this is what I am sending to client "more_faces": False, "no_face": False, "face_absence": False } for face in faces: x1, y1 = face.left(), face.top() x2, y2 = face.right(), face.bottom() imgOriginal = cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2) moreFaceCount = 0 noFaceCount = 0 # cv2.imshow('frame', imgOriginal) if cv2.waitKey(1) & 0xFF == ord('q'): break time.sleep(3) yield "\ndata: {}\n\n".format([face_attributes]) error spot eventSource.onmessage = function(e) { console.log(e) final_data = e console.log(JSON.parse(final_data)) $('.toast').toast('show') } -
many2many to same model but not itself and not multiple times
hej! I have a model referring to the same model via "self", this does work in general but I want that it is not connected with 'itself'. So let's say topic1 can not be connected to topic1 (which wouldn't make any sense) and I don't want it to be possible to connect topic1 multiple times to topic2. It should just be once topic1-topic2 in the data base. # views.py related_topic = models.ManyToManyField( "self", # TODO: constraint in m2m! not with itself, not in both directions. verbose_name="Related Topic", blank=True, related_name="related_topic" ) I found symmetric=False to not have the connection in both directions which is helpfull but not enough. Does anyone knows how to achieve that? Many thanks! -
How to clear the table by signal in django?
I have the following temporary model: from django.db import models class TempModel(models.Model): backup = False operation_type = models.CharField(max_length=128, verbose_name='operation type') device_type = models.BigIntegerField(verbose_name='device type') operation_datetime = models.DateTimeField(verbose_name='date and time of the payment') transaction_sum = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='sum of transactions') ... file = models.ForeignKey(to='core.RegistryFile', on_delete=models.CASCADE) reg_date = models.DateField(verbose_name='Date of register') operday = models.ForeignKey(to='OperDay', on_delete=models.SET_NULL, null=True) class Meta: app_label = 'core' I'd like to populate it with the temp data we need to compare with our internal table and truncate all the contents AFTER we use it every time we run the comparison. What Django signal can I use to trigger data removal after every comparison? How may it look like? -
Python Ternary Operations
I have the following code: from django_app.models import Model def func_name(): name = "name" if Model.objects.filter(name=name).count() > 1: raise ValidationError("This name already exists.") else: return name Now I want to turn it into a one-liner. This is what I did: from django_app.models import Model def func_name(): name = "name" raise ValidationError("This name already exists") if Model.objects.filter(name=name).count() > 1 else return name But this gives me a syntax error. Is such an implementation possible in Python? -
In CreateWithInlinesView save all 7 extra forms from database value as default (formset) Django
How to save all 7 extra forms which all of their's value are default? this inline formset class CompanySchedulePerDaysgraphInlineFormSetFactory(InlineFormSetFactory): model = models.CompanySchedulePerDaysgraph exclude = ('is_work_day',) form_class = CompanySchedulePerDaysgraphModelForm factory_kwargs = { 'can_delete': False, 'widgets': {'is_work_day': forms.CheckboxInput(attrs={'class': 'form-control'}), 'start_work': forms.TimeInput(attrs={'class': 'form-control', 'type': 'time'}), 'end_work': forms.TimeInput(attrs={'class': 'form-control', 'type': 'time'}), }, 'extra': 7 } *view.py* class CompanyScheduleCreateView(LoginRequiredMixin, CreateWithInlinesView): model = models.CompanyScheduleFreeGraph inlines = [forms.CompanySchedulePerDaysgraphInlineFormSetFactory] form_class = forms.CompanyScheduleFreeModelForm template_name = 'backoffice/pages/company-schedule/create.html' success_url = reverse_lazy('company_schedule') def forms_valid(self, form, inlines): response = self.form_valid(form) for formset in inlines: formset.instance = self.object formset.save() return response def form_valid(self, form): self.company = form.save(commit=False) self.company.company = self.request.user.company self.company.save() return super().form_valid(form) models.py class CompanySchedulePerDaysgraph(models.Model): import datetime days_graph = models.ForeignKey(CompanyScheduleFreeGraph, on_delete=models.CASCADE) is_work_day = models.BooleanField(default=True) start_work = models.TimeField(default=datetime.time(9, 00)) end_work = models.TimeField(default=datetime.time(18, 00)) created_at = models.DateTimeField(auto_now_add=True) -
How to filter list with Remaining days of date of birth in Django
I want to display an upcoming birthday list with the remaining days of 30 days. Example: Name Date Of Birth Remaining Days John Die 2050-10-25 4 Days Left John Snow 2050-10-26 5 Days Left I dont know how to calculate remaining days but i try this code but i got error "can't subtract offset-naive and offset-aware datetimes" customer=Customer.objects.filter()[:10] for i in customer: remaining = i.dateOfBirth - datetime.today() print(remaining) -
Django JQuery Autocomplete for two forms on one page
Found this autocomplete code on the web, but it works for one form on the page. How to make it work for two forms with different data for each one? views.py from django.http import JsonResponse from django.shortcuts import render # Create your views here. from core.models import Product def autocomplete(request): if 'term' in request.GET: qs = Product.objects.filter(title__icontains=request.GET.get('term')) titles = list() for product in qs: titles.append(product.title) return JsonResponse(titles, safe=False) return render(request, 'core/home.html') models.py class Product(models.Model): title = models.CharField(max_length=124) qty = models.IntegerField() def __str__(self): return self.title home.html <form> <label for="product">Product</label> <input type="text" name="product" id="product"> </form> <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 () { $("#product").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 2 }); }); </script> urls.py urlpatterns = [ path('', views.autocomplete, name='autocomplete'), ] -
django Create lazy queryset method
I want to create lazy method in QuerySet class: I want from this method to make extra filtering accordings to fileds in the querysets: class CustomQuerySet(Queryset): def extra_filter(self): fields = self._fields: lookup =getattr(self._query,"_lookup_joins",[]) #processing and return the custom queryset when I user the extra_filter before django filter then the the values of fields and lookups is empty. MyModel.objecs.extra_filter().filter(....) # doesn't workd the values of "fields" and "lookup" is empty MyModel.objects.filter(...).extra_filter() # it work So, how to extra_filter lazy to excute in all cases? -
Docker : Alpine : Django - Error installing python mysqlclient library
I am building an Alpine based image of a Django application to connect with a MySQL db. For connecting with the database, I am using mysqlclient. For building the image, I am using docker-compose. When I do docker-compose build I get the respective error: #15 7.366 Downloading mysqlclient-1.3.0.tar.gz (76 kB) #15 7.403 Preparing metadata (setup.py): started #15 7.545 Preparing metadata (setup.py): finished with status 'error' #15 7.545 ERROR: Command errored out with exit status 1: #15 7.545 command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup.py'"'"'; __file__='"'"'/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-wh30qihi #15 7.545 cwd: /tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/ #15 7.545 Complete output (10 lines): #15 7.545 /bin/sh: mysql_config: not found #15 7.545 Traceback (most recent call last): #15 7.545 File "<string>", line 1, in <module> #15 7.545 File "/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup.py", line 17, in <module> #15 7.545 metadata, options = get_config() #15 7.545 File "/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup_posix.py", line 47, in get_config #15 7.545 libs = mysql_config("libs_r") #15 7.545 File "/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup_posix.py", line 29, in mysql_config #15 7.545 raise EnvironmentError("%s not found" % (mysql_config.path,)) #15 7.545 OSError: mysql_config not found #15 7.545 ---------------------------------------- #15 7.545 WARNING: Discarding https://files.pythonhosted.org/packages/6a/91/bdfe808fb5dc99a5f65833b370818161b77ef6d1e19b488e4c146ab615aa/mysqlclient-1.3.0.tar.gz#sha256=06eb5664e3738b283ea2262ee60ed83192e898f019cc7ff251f4d05a564ab3b7 (from https://pypi.org/simple/mysqlclient/). … -
Django - Passing a json or an array in URL for an API call
I want to pass a number off variables (either as a JSON or Array) via an API, such as: {'age': 35, 'gender':'female', ...etc} I am not sure how to pass this information into the Djano URL. I could set up individual parameters in the URL, but I got quite a few to pass. there must be an easier way of doing it