Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django automatic file-upload: [WinError 123] The filename, directory name, or volume label syntax is incorrect C:\\path\to\folder\C:
I'm pretty new to Django and I'm working on a project in which I have to automate PDF file uploads from a given folder to a model in Django and these files will undergo a text extraction process. I wrote a script to monitor the folder and upload new files to database. The django model looks like this: class Version(models.Model): id = models.AutoField(primary_key = True) file = models.FileField(upload_to = history_directory_path, db_column = 'file', max_length = 500) filename = models.CharField(default = '', max_length = 100, db_column = 'filename') date = models.DateTimeField(auto_now_add = True, db_column = 'date) version_num = models.IntegerField(null = True, blank = True) history_directory_path is a function which creates the folder using the filename and its version number. A piece of my automatic upload script (in this example only for 1 file, I will put it in a loop when it starts working) is the following: from django.core.files import File from myapp.models import Version import os import glob BASE_PATH = r'C:\path\to\folder_to_be_monitored' files = [os.path.basename(x) for x in glob.glob(BASE_PATH + '/*.pdf')] filename = files[0] f = open(os.path.join(BASE_PATH, filename), 'rb') my_file = File(f) version = Version(file = my_file, filename = filename, version_num = 1) version.save() executing the last command I get OSError: … -
How to save matplotlib animations as BytesIO and embed them in a Django website?
I want to save my Matplotlib animation (gif file) as BytesIO. I want to then call the gif onto my HTML webpage in my Django project. For static images (static Matplotlib graphs), what I do is bytesio = io.BytesIO() fig.savefig(bytesio,format='png') bytesio.seek(0) string = base64.b64encode(string) uri = urllib.parse.quote(string) I shall have in my views.py return render(request, 'index.html',{data:uri}) and in my HTML page I have <imag src = "data:image/png;base64,{{data}}"> But I don't know how to implement a similar strategy for animations (gif files). My animations are generated using Matplotlib FuncAnimation. Thanks in advance for any/all responses! -
passing querystring in DRF action
I am trying to fetch some data from a url that (optionally)contains a query string. Here's a snippet of my code: class MyViewSet(ModelViewSet): queryset = models.Me.objects ... ... @action(detail=False, methods=['get'], url_path='someurl(?:/(?P<colour>[^/]+))?')) def some_url(self, request, id): colour = request.GET.get('colour') obj = self.get_object() url = settings.MY_URL if colour: url = url + f'?{colour}' result = requests.get(url) return Response(status=result.status_code) This throws an error that the serializer can not understand colour as a field. Ofcourse, it's not supposed to be a field, it's a query string. How do I handle it correctly to use it for the url request only? Finally, the get url should look something like "www.abc.com/?colour=blue" -
How to use django inlineformset_factory to allow users to create course in a function base view
Okay am really having a hard time figuring out how to use django inlineformset_factory as a form in a function base view to allow users to create their own course, I keep coming against this error (ModelForm has no model class specified) when i try to create a course, is there any better practice to use an inlnineformset in a function base view? or is it only possible with class base view? below is my form for creating course and module. from django.forms.models import inlineformset_factory from .models import Course, Module class CreateCourse(forms.ModelForm): ModuleFormSet = inlineformset_factory(Course, Module, fields=['title', 'description'], extra=2, can_delete=True) Here is my function base view for creating a course def course_create(request): if request.method == "POST": form = CreateCourse(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('courses:main') else: form = CreateCourse(request.POST,request.FILES) context={'form':form} return render(request,'manage/module/formset.html',context) -
Django boundfields auto naming: changing the form part
I can't seem to find if/how this is possible. But say I have a form: class Detform(ModelForm): class Meta: model = Ap_detcmd fields = ["foo"] Formset = inlineformset_factory(ParentModel, ChildModel, form=Detform, can_delete=False, extra=0) Then in the template this gets renders, for instance in the management form (or any field): <input type="hidden" name="ap_detcmd-TOTAL_FORMS" value="0" id="id_ap_detcmd-TOTAL_FORMS"> Since the model of the form is "Ap_detcmd", then I get #id_ap_detcmd-.... as a prefix for all fields. Is there a way to specify that prefix? -
Django template's include not sharing static files
I have a large Django project with multiple templates which are merged later on to construct pages dynamically, I am facing a weird issue as follows: I have a base.html which includes all the needed imports, including JS and CSS. I have sub-folders for both CSS/JS in the assets, which are usually imported at the end of base.html. Now, as my project got bigger, I decided I'd rather have the scripts imports, e.g: <script type="text/javascript" src="{% static "js/base.js" %}"></script> <script type="text/javascript" src="{% static "js/menus/projects.js" %}"></script> <script type="text/javascript" src="{% static "js/menus/sensors.js" %}"></script> included in each individual HTML file, instead of all being in the base.html, I expected to have no issues, since as far as I know include statements should also transfer context, for reference sake, those are the include statements of interest: in base.html: {% include "applications/Devices/deviceDashboard.html" %} in deviceDashboard.html: {% include "applications/Devices/deviceDashboard/listCard.html" %} {% include "applications/Devices/deviceDashboard/editCard.html" %} {% include "applications/Devices/deviceDashboard/graphCard.html" %} In all of those, if I try to run it as-is I get the following: TemplateSyntaxError at / Invalid block tag on line 25: 'static'. Did you forget to register or load this tag? When I try to use the same script import tags as before, and this … -
How to provide voice synthesis on my website?
I have a python program which can take as an input a text file and some parameters, and give as output a file mp3. I would like to let people try the system on my website, for small sentences. I thought I could put the python program on a cloud server and create a API with Flask-Restful, and then call this API with my website which is made with Django Framework. I can't afford a GPU server, so it will take a few seconds/minutes to generate the mp3 file. I can't make a POST request that long, can I? The thing is, I don't know if this is an appropriate method, is there an easier way to do this ? I just want to install my tts system on a web server, and be able to call it from my website. I didn't found any documentation or tutorial that helped me... Tell me if my problem is not clear enough, Thank you for your help -
get and dispaly and open image from s3 bucket to django admin template
I have a folder on amazon s3 bucket which contains multiple images. I want to display those images on django admin panel also the images should be clickable. I am able to display image on admin template but when I have created its href to open image it gives me blank. my current code looks like this: admin.py class ImagesAdmin(admin.ModelAdmin): def image_from_S3(self, obj): image_obj = client.get_object(Bucket=bucketName, Key='folder_name/'+str(obj.image_name) ) body = image_obj['Body'].read() return format_html('<a target="_blank" href="data: image/png; base64,'+b64encode(body).decode('utf8')+'"><img src = "data: image/png; base64, {}" width="100" height="100"></a>'.format( b64encode(body).decode('utf8') )) using this code I have successfully displayed image on django admin template but when trying to hit image then image is unable to load . -
React and Django website not loading on Heroku
Homepage doesn't load properly I have successfully build and deployed my code in Heroku. It works fine locally but react doesn't render the index.html The backend API works properly here but the homepage here doesn't load - using ReactJS. My all GitHub codes are here inside the develop branch. -
How to change File type from CSV to XLSX
My current code prints my file data to a CSV perfectly, however, I need this data to be in an XLSX format instead. Does anyone know how I could do this without changing my code too much, here is what I have currently got : Views.py # Starting CSV response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="' + complexName + '"Age Analysis.csv"' writer = csv.writer(response) writer.writerow(['Prepared By : Atout(PTY) ltd']) writer.writerow(['Customer Age Analysis for Monthly Customers as at 31/10/21']) writer.writerow( ['Account', ' ', ' ', '120+ Days', '90 Days', '60 Days', '30 days', 'Current', 'Total', '', 'Name', 'E-mail']) for x in ageSelect: writer.writerow([ x["Account"], '*', ' ', '0', '0 ', '0', '0', x["Balance"], x["Balance"], '', x["Name"], x["E-mail"] ]) for x in XtotalCurent: writer.writerow(['Totals:', ' ', ' ', '120 Days', '90 Days', '60 Days', '30 days', x, x]) writer.writerow(['PERCENTAGE :', ' ', ' ', '120 Days', '90 Days', '60 Days', '30 days', 'Current', '100%']) writer.writerow(['GRAND TOTAL :', ' ', ' ', '', '', '', '', '', x]) return response -
Django Filter Duplicated Obj in Queryset
I have Product and ProductPrices Model. class ProductPrice(BaseModel): product = models.ForeignKey( to="Product", related_name="prices", on_delete=models.CASCADE, verbose_name=_("prices"), null=True, blank=True ) When ı try order by price model field some objects duplicated. What ı doing? if order_by in [order_choices[HIGH_TO_LOW_PRICE], order_choices[LOW_TO_HIGH_PRICE]]: outer_price = ProductPrice.objects.filter(end_user__isnull=False, product_id=OuterRef("pk")) qs = qs.annotate(has_price=Exists(outer_price)).order_by("-has_price", order_by).distinct() return qs -
Are there any existing universal Python post code validation packages?
I know how to make post codes (zip codes) validations for specific countries. I know how to check to see the number of characters the user has entered and whether he has included numbers, letters or both. But is there a package I can install that already has post code (zip code) validations for every country. I want the form to apply different validations based on the country the user selects. For example I only want the user to be able to enter letters in the post code if they have chosen one of these countries - Argentina, Brunei, Canada, Eswatini, Ireland, Kazakhstan, Malta, Netherlands, Peru, Somalia or United Kingdom. -
How to setup Django + RabbitMQ + Celery with Docker?
I'm trying to setup my Django app to have push notification functionality. For scheduling notifications I'm trying to use Celery, for the message broker I chose RabbitMQ. My app is running in Docker containers and I'm struggling to get the RabbitMQ to work. I get an error message Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. when running docker-compose up. Here are my celery and rabbitmq3 services from my docker-compose.yml: celery: restart: always build: context: . command: celery -A test_celery worker -l info volumes: - .:/test_celery env_file: - ./.env depends_on: - app - rabbitmq3 rabbitmq3: container_name: "rabbitmq" image: rabbitmq:3-management-alpine ports: - 5672:5672 - 15672:15672 In my test_celery -app I have a file called celery.py which contains the following: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_celery.settings') app = Celery('test_celery') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() And finally, in my settings.py I have this: CELERY_BROKER_URL = 'amqp://localhost'. Should I define the CELERY_BROKER_URL somehow different? Is there something wrong with my docker-compose file? Would appreciate any help with this, what is wrong with my setup? -
Unable to connect to Sql Server from Docker Django
i'm trying to connect my Django to en existing legacy MS SQL database. When im trying to run a sql on the database works fine: sql = 'SELECT * FROM ' + db_name + '.INFORMATION_SCHEMA.TABLES' connection_string = "driver=FreeTDS;server={};PORT={} database={};UID={};PWD={};TDS_Version=8.0;".format(db_host, db_port, db_name, db_user, db_password) conn = pyodbc.connect(connection_string, autocommit=True) for row in cursor.fetchall(): print(row) And i can see all the tables but when try to generate model from database running this command: python manage.py inspectdb --database pirineos > pirineos_models.py I get the error: django.db.utils.Error: ('08001', '[08001] [FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)') This are my project files. Dockerfile: FROM python:3.8-slim-buster ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update -y && apt-get install -y unixodbc unixodbc-dev tdsodbc freetds-common freetds-bin freetds-dev && apt-get clean && rm -rf /var/lib/apt/lists/* RUN mkdir /djangonoguero COPY ./project /djangonoguero/ COPY ./requirements.txt /djangonoguero/ ADD odbcinst.ini /etc/ WORKDIR /djangonoguero RUN pip install --no-cache-dir -r requirements.txt EXPOSE 8000 requirements.txt: pyodbc==3.0.10 django-mssql-backend==2.8.1 settings.py: DATABASES = { 'pirineos': { 'ENGINE': 'sql_server.pyodbc', 'NAME': DB_PIRINEOS_NAME, 'USER': DB_PIRINEOS_USER, 'PASSWORD': DB_PIRINEOS_PASSWORD, 'HOST': DB_PIRINEOS_HOST, 'PORT': DB_PIRINEOS_PORT, 'OPTIONS': { 'driver': 'FreeTDS', 'unicode_results': True, 'driver_supports_utf8' : True, 'extra_params': 'tds_version=8.0;', }, }, } odbcinst.ini: [FreeTDS] Description=FreeTDS Driver for Linux & MSSQL on Win32 Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so UsageCount=1 -
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"))