Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to represent django QUERY as table in html page with table heading same as django field name. How can I implement this?
I would like to find a way to represent on HTML table a recordset obtained through a SQL query. I consulted a previous post that spoke of a similar problem to mine but in that post refer to a model and I couldn't adapt it to my needs. I would like to adapt the solution of that post so that it works even when I use SQL query. It would be possible? The post is this: I want to represent django model as table in html page with table heading same as django field name. How can I implement this? Here my view: def posts_discussione(request,pk): discussione = Discussione.objects.get(pk=pk) posts = Post.objects.raw(f'SELECT * from forum_post where discussione_id = {pk} order by dataCreazione ASC') context = {'posts':posts,'discussione':discussione} return render(request,'posts-discussione.html',context) Here my HTML code: <table> <thead> <th>Autore</th> <th>Data</th> <th>Contenuto</th> </thead> <tbody> {% for post in posts %} <tr> <td>{{post.autorePost}}</td> <td>{{post.dataCreazione}}</td> <td>{{post.contenuto}}</td> {% endfor %} </tbody> </table> -
I keep getting path error when i input in the django app
this is my views.py, when i input in anything i get error i tried changing the path to /fo still there is error.............................................. from django.shortcuts import render import requests import sys from subprocess import run, PIPE def button(request): return render(request, 'home.html') def button(request): return render(request, 'home.html') def output(request): data = requests.get("https://www.google.com/") print(data.text) data = data.text return render(request, 'home.html', {'data': data}) def external(request): inp = request.POST.get('param') out = run([sys.executable, 'buttonpython/buttonpython/test.py', inp], shell=False, stdout=PIPE) print(out) return render(request, 'home.html', {'data1': out.stdout}) -
Getting the error 'ClassAssignment' object has no attribute 'assignmentfileupload'
The models that I am using are as followed class ClassAssignment(models.Model) : classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE) title = models.CharField(max_length=300, blank=False, null=False) instructions = models.TextField(blank=True, null=True) completed = models.ManyToManyField(User) due_date = models.DateTimeField(blank=True, null=True) created_on = models.DateTimeField(default=datetime.now()) def __str__(self) -> str : return self.title class AssignmentFileUpload(models.Model) : assignment = models.ForeignKey(ClassAssignment, on_delete=models.CASCADE) attachment = models.FileField(upload_to="assignment_uploads/") created_on = models.DateTimeField(default=datetime.now()) def __str__(self) -> str : return self.assignment.title def delete(self, *args, **kwargs) : self.attachment.delete(save=False) return super().delete(*args, **kwargs) The code for the serializer class AssignmentSerializer(serializers.ModelSerializer) : assignmentfileupload = serializers.HyperlinkedRelatedField( view_name='file_uploads', many=True, read_only = True ) class Meta : model = ClassAssignment fields = ( 'id', 'classroom', 'title', 'instructions', 'due_date', 'created_on', 'assignmentfileupload' ) I am not able to understand where I am doing wrong. Even the documentation says the same thing and I followed it but it is not working as expected. -
How to display child row information using jQuery DataTables plugin with Django
I am referring to https://www.geeksforgeeks.org/how-to-display-child-row-information-using-jquery-datatables-plugin/ and I want to display datatable with child rows. The problem I faced now is to pass the view function I created. I want to pass the django url on the line: "ajax": "nestedData.txt", instead of a file as it is here $(document).ready(function () { /* Initialization of datatables */ var table = $('#tableID').DataTable({ "ajax": "nestedData.txt", "columns": [{ "className": 'details-control', "orderable": true, "data": null, "defaultContent": '' }, { "data": "name" }, { "data": "designation" }, { "data": "city" }, { "data": "salary" } ], "order": [[1, 'asc']] }); Kindl assist -
model methods returning empty strings
I am getting empty in return (from my model methods), I don't get where I am wrong , we can model using self class SocialLinks(models.Model): alias_name = models.CharField(max_length=10,) name = models.CharField(max_length=30) url_link = models.URLField() def get_fb_link(self): try: fb = self.objects.get(alias_name='fb') return fb.url_link except: return "" def get_linkdin_link(self): try: linkdin = self.objects.get(alias_name='linkedin') return linkdin except: return "" def get_insta_link(self): try: insta = self.objects.get(alias_name='insta') return insta.url_link except: -
Not Found The requested resource was not found on this server. python
I try to upload my project to cpanel, but when i try error like this Not Found The requested resource was not found on this server. i try to edit my wsgi file many times, but still not working i try to install django with virtualenv and upgrade pip with virtualenv, but still not working, i try to reset my cpanel and do it again still not working, i try to ask with the customer service but there is no answer this is my project directory enter image description here and this is my python app enter image description here this is my passanger_wsgi file and this is my requirements.txt file asgiref==3.4.1 certifi==2021.10.8 charset-normalizer==2.0.7 Django==3.2.8 idna==3.3 Pillow==6.2.2 pytz==2021.3 requests==2.26.0 sqlparse==0.4.2 urllib3==1.26.7 app an this is my settings """ Django settings for web_test project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
How do you install npm for Windows?
I am trying to install tailwind CSS, and one of the codes I need to write is the following: $ npm init -y && npm install tailwindcss autoprefixer clean-css-cli && npx tailwindcss init -p However, this is obviously for the macOS. Is there another way to do this for the windows system? Thank you, and please ask me any questions you have. -
drf create manytomany fields
models class CreatorRawArtwork(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=500) descripton = models.TextField() editions = models.IntegerField(null=True, blank=True) price = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) medias = models.FileField(null=True, blank=True, upload_to="raw-medias") user = models.ForeignKey( to=Login, on_delete=models.CASCADE, related_name="creatorrawartwork", null=True, blank=True ) collection = models.ForeignKey( to=DesignerCollection, on_delete=models.CASCADE, related_name="creatorrawartwork", null=True, blank=True ) categories = models.ManyToManyField(DesignerCategories, related_name='creatorrawartwork') def __str__(self): return self.title serializer class CreatorRawArtworkSerializer(serializers.ModelSerializer): categories = serializers.PrimaryKeyRelatedField(queryset=DesignerCategories.objects.all(), many=True) class Meta: model = CreatorRawArtwork fields = "__all__" depth=1 views class CreatorRawArtworkView(viewsets.ModelViewSet): queryset = CreatorRawArtwork.objects.all() serializer_class = CreatorRawArtworkSerializer Here i am trying to create manytomany fields using drf serialier it is showing some error plese check the screenshot for parameter and responses What can be the issue please take a look -
how to redirect to another page in django without refreshing?
how to redirect to another page in Django without refreshing? how to redirect to another page in Django without refreshing? how to redirect to another page in Django without refreshing? -
Error running Django application on IIS with HttpPlatformHandler
I'm deploying a Django app on a windows machine. The app works correctly when running "python manage.py runserver" with a virtual environment. I also have granted permissions to IIS_IUSRS and IUSR to the virtualenv folder and the django project folder. I'm getting an error when trying to run it on IIS with HttpPlatformHandler (https://docs.microsoft.com/en-us/visualstudio/python/configure-web-apps-for-iis-windows?view=vs-2017). The error is Error HTTP 502.3 - Bad Gateway, and i'm getting an error log that reads No Python at 'C:\Users\APP_USER\AppData\Local\Programs\Python\Python39\python.exe', but that's no the processPath defined on web.config. Here's the web.config contents: ` <system.webServer> <handlers accessPolicy="Read, Script"> <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" /> </handlers> <httpPlatform startupTimeLimit="1" startupRetryCount="0" stdoutLogEnabled="true" processPath="C:\PROJECT\venv\Scripts\python.exe" arguments="manage.py runserver"> <environmentVariables> <environmentVariable name="foo" value="bar" /> </environmentVariables> </httpPlatform> </system.webServer> ` Seems any time I attempt to load the page, another log with the same "No python at ..." is generated. I tried restarting the IIS service but the error persists. -
Django Integrate existing code into generic class based view from two factor auth
I have the following login view: @axes_dispatch @check_recaptcha_login def loginpage(request, credentials: dict = None): form = RegisterForm() attempts_list = get_user_attempts(request, credentials) attempt_count = max( ( attempts.aggregate(Sum("failures_since_start"))[ "failures_since_start__sum" ] or 0 ) for attempts in attempts_list ) #print(attempt_count) attempt_count = attempt_count context = {'attempt_count': attempt_count} 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: if user.is_active and attempt_count < 3: login(request, user) return redirect('home') elif user.is_active and request.recaptcha_is_valid: login(request, user) return redirect('home') if not user.is_active: messages.error(request, 'Account for this User has not been Activated.') else: messages.error(request, 'Username or Password is Incorrect.') #print(context) return render(request, 'login.html', context) But am now using django two factor auth views, and would like to integrate the decorators and attempt count code and context and if statement login attempts (under if user is not None:) in my above code with the LoginView class based view from the following link: https://github.com/Bouke/django-two-factor-auth/blob/master/two_factor/views/core.py I believe I need to change my own login view to call loginView thats in link above and add my decorators and my custom code mentioned above into the view but not sure how to do this. Help is much appreciated. Thanks -
django cookiecutter media/ location for testing
Problem: I have an ImageField in a model. The TestCase isn’t able to find the default image file to perform a image resize on it (a @receiver(pre_save, sender=UserProfile) decorator thing) class UserProfile(Model): user = ForeignKey(AUTH_USER_MODEL ...) ... photo = ImageField( verbose_name=_("Photo"), upload_to="media", null=True, blank=True, help_text=_("a photo will spark recognition from others."), default="default.png") Overview: I’m running tests locally from pycharm to a docker container. This project is based on a django cookiecutter project. I did a search for the target file in the presave hook and the file was found in these 2 directories ['/app/media/default.png', '/opt/project/media/default.png'] I am getting a FileNotFound error on '/app/<my_project_name>/media/default.png' How do I get the media file to look in these directories? @receiver(pre_save, sender=UserProfile) def user_profile_face_photo_reduction(sender, instance, *args, **kwargs): """ This creates the thumbnail photo for a concept """ test_image_size(instance) # this is the function that gives problems. it's below. im = generic_resize_image(size=face_dimensions, image=instance.photo) save_images_as_filename( filename=Path(instance.photo.path).with_suffix(".png"), image=im, instance=instance, ) def test_image_size(instance=None, size_limit=None): """ size_limit is a namedtuple with a height and width that is too large to save. instance needs to have a photo attribute to work """ if instance and instance.photo: print([x.absolute() for x in sorted(Path("/").rglob("default.png"))]) # this is where I got the actual location info … -
Error in custom Django admin page on csv uploads (object has no attribute 'model')
I have been trying to create a custom upload button in my Django admin page, but I keep getting an error pointing to my CsvUploader.py file: object has no attribute 'model' I have a very simple model: class Link(models.Model): name = models.CharField(db_column='Name', max_length=50) url = models.URLField(db_column="URL", max_length=500) def __str__(self): return f"{self.name}: {self.url}" I also have my admin template modified, as follows: #Extend Admin portal use class CsvUploadAdmin(admin.ModelAdmin): change_list_template = "custom_admin/csv_form.html" def get_urls(self): urls = super().get_urls() additional_urls = [ path("upload-csv/", self.upload_csv), ] return additional_urls + urls urls = property(get_urls) def changelist_view(self, request, extra_context=None): extra = extra_context or {} extra["csv_upload_form"] = CsvUploadForm() return super(CsvUploadAdmin, self).changelist_view(request, extra_context=extra) def upload_csv(self, request): if request.method == "POST": form = CsvUploadForm(request.POST, request.FILES) if form.is_valid(): if request.FILES['csv_file'].name.endswith('csv'): try: decoded_file = request.FILES['csv_file'].read().decode('utf-8') except UnicodeDecodeError as e: self.message_user( request, "There was an error decoding the file:{}".format(e), level=messages.ERROR ) return redirect("..") # Here we will call our class method io_string = io.StringIO(decoded_file) uploader = CsvUploader(io_string, self.model, SecurityArchitecturePortal) result = uploader.create_records() else: self.message_user( request, "Incorrect file type: {}".format( request.FILES['csv_file'].name.split(".")[1] ), level=messages.ERROR ) else: self.message_user( request, "There was an error in the form {}".format(form.errors), level=messages.ERROR ) return redirect("..") @admin.register(Link) class LinkAdmin(CsvUploadAdmin): pass Finally, here is my CsvUploader.py file: import csv from SecurityArchitecturePortal.models import … -
Unable to apply migrations to Heroku postgres database
The database is postgres and framework is django. Running migrations works fine on localhost but not on Heroku server. I cannot drop or reset the database because it contains important data. I backed up the database, reset it and all migrations worked, but when I restored the backup, it reverted back to the old migration state and the problem persisted. I don't know how to transfer only the data from the backup into a reset database instead of also transferring the old database structure. When I run heroku run python manage.py migrate I get this error: No migrations to apply. Your models in app(s): 'app1', 'app2', 'app3', 'app4', 'users' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Using heroku run python manage.py makemigrations app-name does not help either. Is there a way to map and transfer just the user data from the old database into the new one? Or is there a way to brute force the old database to accept the new migration structure? I would be glad if I get some help. Thanks. -
Django is not sending email to admins on error 500 (but email settings to work with send_mail!)
I know, there are plenty of similar questions about this, but none of them helped. When I set the EMAIL_BACKEND to django.core.mail.backends.console.EmailBackend, I do see the email when I trigger a 500. When I set EMAIL_BACKEND to django.core.mail.backends.smtp.EmailBackend, I don't receive the email.. but email manually sent using the send_mail function gets delivered just fine, so the email settings do work. I just don't understand this. DEBUG = False EMAIL_BACKEND = env("EMAIL_BACKEND") EMAIL_HOST = "smtp.sendgrid.net" EMAIL_HOST_USER = "apikey" EMAIL_HOST_PASSWORD = env("SENDGRID_API_KEY") EMAIL_PORT = 587 EMAIL_USE_TLS = True SERVER_EMAIL = "{my email}" ADMINS = [ ("Kevin Renskers", "{my email}"), ] MANAGERS = ADMINS I don't have any custom LOGGING set, and like I said with django.core.mail.backends.console.EmailBackend I do see the email in my console. So how can it be that I can send email using send_mail, yet errors are not sent to me using the exact same email settings? I've looked in my sendgrid account activity, and yeah they are not sent at all. -
django when user is change,message doesn't come from web socket
I am using web sockets(channels) in my django project.Firstly when the page is reloading everything is fine,but when I want to chat another user so I click other user (running runChatUser function of javascript which is located in app.js) after that message is going web socket and receiving web socket fine but in app.js chatSocket.onmessage operation console.log(data) doesn't appear in javascript console.So I didn't add message html to conversation .I am trying fix that days.But I didn't .Can anyone help me ?? app.js var roomName = JSON.parse(document.getElementById('room-name').textContent); var conversation=document.getElementById("conversation"); var sendButton = document.getElementById("sendMessage"); var inputField = document.getElementById("message-input-chat"); var chatSocket = ""; function webSocketConnect(roomName){ // var roomName = document.getElementById('room-name').textContent; chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ) inputField.focus(); }; //roomName is changing when the user click other user to chat window.onload=webSocketConnect(roomName); chatSocket.onmessage = function(e) { inputField.focus(); var data = JSON.parse(e.data); console.log(data); var message=`<li class="media sent"> <div class="media-body"> <div class="msg-box"> <div> <p>${data.message}</p> <ul class="chat-msg-info"> <li> <div class="chat-time"> <span>8:30 AM</span> </div> </li> </ul> </div> </div> </div> </li>` conversation.innerHTML+=message }; chatSocket.onclose=function(e){ console.error("Socket closed"); }; inputField.focus(); inputField.onkeyup = function(e) { if (e.keyCode === 13) { // enter, return sendButton.click(); } }; sendButton.onclick = function(e) { var message = inputField.value; … -
Django SAML2 idp saml2.response.IncorrectlySigned Internal Server Error: /idp/login/process/
I am implementing SSO with SAML2 but i am going through trouble. I am using these lib: https://github.com/OTA-Insight/djangosaml2idp https://github.com/IdentityPython/djangosaml2 The SP is working well, there issue with the idp This is the error i am getting: raise IncorrectlySigned() saml2.response.IncorrectlySigned Internal Server Error: /idp/login/process/ and this is my url pattern urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')), path('idp/', include('djangosaml2idp.urls')), path('', TemplateView.as_view(template_name="index.html")), ] and this is my settings.py file import saml2 import os from saml2.saml import NAMEID_FORMAT_EMAILADDRESS, NAMEID_FORMAT_UNSPECIFIED from saml2.sigver import get_xmlsec_binary LOGIN_URL = '/accounts/login/' BASE_URL = 'http://localhost:8000/idp' SAML_IDP_CONFIG = { 'debug' : DEBUG, 'xmlsec_binary': get_xmlsec_binary(['/opt/local/bin', '/usr/bin']), 'entityid': '%s/metadata' % BASE_URL, # 'entityid': os.path.join(BASE_DIR, 'metadata'), 'description': 'Example IdP setup', 'service': { 'idp': { 'name': 'Django localhost IdP', 'endpoints': { 'single_sign_on_service': [ ('http://localhost:8000/idp/sso/post/', saml2.BINDING_HTTP_POST), ('http://localhost:8000/idp/sso/redirect/', saml2.BINDING_HTTP_REDIRECT), ], "single_logout_service": [ ("http://localhost:8000/idp/slo/post/", saml2.BINDING_HTTP_POST), ("http://localhost:8000/idp/slo/redirect/", saml2.BINDING_HTTP_REDIRECT) ], }, 'name_id_format': [NAMEID_FORMAT_EMAILADDRESS, NAMEID_FORMAT_UNSPECIFIED], 'sign_response': True, 'sign_assertion': True, 'want_authn_requests_signed': True, }, }, # Signing 'key_file': os.path.join(BASE_DIR, 'certificates/private.key'), 'cert_file': os.path.join(BASE_DIR, 'certificates/public.cert'), # Encryption 'encryption_keypairs': [{ 'key_file': os.path.join(BASE_DIR, 'certificates/private.key'), 'cert_file': os.path.join(BASE_DIR, 'certificates/public.cert'), }], 'valid_for': 365 * 24, "metadata": { "local": [ os.path.join(BASE_DIR, 'metadata') ], }, } # Each key in this dictionary is a SP our IDP will talk to SAML_IDP_SPCONFIG = { 'http://localhost:8000/saml2/metadata': { 'processor': 'djangosaml2idp.processors.BaseProcessor', 'attribute_mapping': { 'email': 'email', 'first_name': 'first_name', … -
Verifying in external Django REST API if a Wordpress user is a paid subscriber or not
I have been working on a program in python that I want to make available to paid subscribers via REST. I'm currently thinking of having the frontend made in Wordpress and then host the backend somewhere else. In wordpress there are a bunch of plugins to handle paid subscribers and so on and everything seems great but my concern is how do I verify this on the backend that is hosted somewhere else? If I use Django, is there any way I can make some kind of call to the Wordpress server(?) and verify that the user that is trying to fetch items are an paid subscriber? I made a Diagram to kind of show what I mean. Basically B should only answer back with items if the caller A is a paid subscriber. I've read that it is possible to generate an API key that will be needed in order to fetch data from the API, I've also read ways of hiding this call from the frontend to the backend from the user by using some kind of relay on wordpress. Might be wrong here. Is there any preferred way of doing this? Is Django REST & Wordpress suitable … -
Django url path with question mark
I have got a question that I could not find an answer to. Is it possible in Django to create an URL path in urls.py that looks like the following? path('article?date={some value here}/', article.site.urls) -
DJango healthcheck for url [closed]
how can I display the health status of different urls(302,200 etc.) in an html page in my django project? for example; https://i.stack.imgur.com/rO6cs.png -
User searching system in Django
I am trying to make user searching system. The idea is to show users in dropbox under the searching field and make them link to their profile. But django template engine can't parse dynamically created tags, so links are incorrect. Hope on you, thanks main.js $.ajax({ type: 'POST', url: '{% url "instagram:search" %}', data: { name: $('#isearch').val(), csrfmiddlewaretoken: getCookie('csrftoken'), action: 'post' }, success: (json) => { search = document.querySelector('#drp') $(search).empty(); // TODO разобраться с поиском json['users'].forEach(element => { arr = ['<li role="presentation"><a role="menuitem" tabindex="-1" href="{% url ', "'instagram:home' username=", element, ' %}">', element, '</a></li>' ] search.insertAdjacentHTML( 'beforeend', arr.join("") ); }); }, error: function (xhr, errmsg, err) { } }); } -
Django why does @action decorator ignore *_classes overrides in some circumstances
I cannot consistently recreate this issue since I cannot pinpoint what causes this. In a few ViewSets we have extra views using the @action decorator. About half of them properly override *_classes arguments (such as permission_classes, renderer_classes, parser_classes), and the other half, just don't. Which can be seen by debugging, or simple setting these arguments to garbage. In half of them, setting permission_classes to the string 'hello world' will blow Django up upon hitting that endpoint since it tries to instantiate an object from the string. Doing the same for the other half, nothing happens. Django doesn't complain or blow up, and in debugging in the view, the *_classes are still set to the parent ViewSet's (either when garbage or validly set to a different list). Haven't been able to find anything in common between the viewsets with @action decorators that don't properly override *_classes arguments. Is there any bit of code that I should look through to figure this out? -
Bootstrap dropdown wont appear
Hey so my bootstrap dropdown menu wont work by clicking on it. Heres my code: <div class="dragArea row fake_input"> <div class="col-md col-12 form-group" data-for="name"> <p class="fake_input_text">{{ password }}</p> </div> <div class="dropdown"> <button class="btn btn-success display-4 dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Choose Length </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#">2</a> <a class="dropdown-item" href="#">4</a> <a class="dropdown-item" href="#">6</a> </div> </div> <div class="mbr-section-btn col-12 col-md-auto"><a href="{% url 'home:passwordgenerator' %}" class="btn btn-success display-4">Generate</a></div> </div> -
ODBC Driver 17 for SQL Server: Client unable to establish connection, macOS, django, odbc
Everything was working until I restarted my laptop. I have this setup: python 3.8.9 django 3.1.1 pyodbc 4.0.30 pyodbc.drivers() shows this: ['ODBC Driver 17 for SQL Server'] SQLServer openssl version shows this: OpenSSL 1.1.1l 24 Aug 2021 isql -v -k "DRIVER=ODBC Driver 17 for SQL Server;SERVER=<my server>,<my port>;UID=<my username>;PWD=<my password>" connects to the database with no issues servername, port, user, and password seems correct also because the jdbc driver works without any issues with them. cat /etc/odbcinst.ini and cat /etc/odbc.ini - both return this: [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/usr/local/lib/libmsodbcsql.17.dylib UsageCount=10 odbcinst -j returns this: unixODBC 2.3.9 DRIVERS............: /usr/local/etc/odbcinst.ini SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources USER DATA SOURCES..: /Users/sgalich/.odbc.ini SQLULEN Size.......: 8 SQLLEN Size........: 8 SQLSETPOSIROW Size.: 8 in the django settings: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } cat ~/.bash_profile shows this: export PATH="/usr/local/opt/openssl@1.1/bin:$PATH" export CPATH="/usr/local/opt/openssl@1.1/include" export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib" export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include" export LIBRARY_PATH="/usr/local/opt/openssl@1.1/lib" export DYLD_LIBRARY_PATH="/usr/local/opt/openssl@1.1/lib" export DYLD_FALLBACK_LIBRARY_PATH="/usr/local/opt/openssl@1.1/lib" I reinstalled the ODBC Driver with this official Microsoft instruction. But it didn't help. I'm still failing to start the django … -
Django-Dramatiq - How to configure dramatiq_abort
I am running: Windows 10 Django 4+ Python 3.9.x Newest version of dramatiq Newest version of dramatiq_abort Newest version of django_dramatiq settings.py ### ### For dramatiq tasks! ### import urllib.parse import dramatiq import dramatiq_abort REDIS_USER = "myuser" REDIS_PASS = "mypassword" REDIS_URL = "redis://%s:%s@localhost:6379/0" % (urllib.parse.quote(REDIS_USER, safe=''), urllib.parse.quote(REDIS_PASS, safe='')) # Frontend DRAMATIQ_BROKER = { "BROKER": "dramatiq.brokers.redis.RedisBroker", "OPTIONS": { "url": REDIS_URL, }, "MIDDLEWARE": [ "dramatiq.middleware.Prometheus", "dramatiq.middleware.AgeLimit", "dramatiq.middleware.TimeLimit", "dramatiq.middleware.Callbacks", "dramatiq.middleware.Retries", "dramatiq_abort.middleware.Abort", #I import Abort "dramatiq_abort.middleware.Abortable", # I import Abortable "django_dramatiq.middleware.DbConnectionsMiddleware", "django_dramatiq.middleware.AdminMiddleware", ], # When I put this here, I get the error __init__() missing 1 required keyword-only argument: 'backend' #"BACKEND": "dramatiq_abort.backends.RedisBackend(client=None).from_url(" + REDIS_URL + ")" } # Defines which database should be used to persist Task objects when the # AdminMiddleware is enabled. The default value is "default". DRAMATIQ_TASKS_DATABASE = "default" # Backend DRAMATIQ_RESULT_BACKEND = { "BACKEND": "dramatiq.results.backends.redis.RedisBackend", "BACKEND_OPTIONS": { "url": REDIS_URL, }, "MIDDLEWARE_OPTIONS": { "result_ttl": 60000 }, #"BACKEND": "dramatiq_abort.backends.RedisBackend(" + REDIS_URL + ")", # When I put it here, I get No module named 'dramatiq_abort.backends.RedisBackend(client=None) "BACKEND": "dramatiq_abort.backends.RedisBackend(client=None).from_url(" + REDIS_URL + ")" } ### ### End of dramatiq tasks! ### I have django_dramatiq configured correctly, consequentially dramatiq configured correctly. The question is how do I configure dramatiq_abort in conjunction with django_dramatiq?