Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best practices of implementing a computationally intensive task on a socket connection [closed]
The context is as follows: I am working on a specific widget on the dashboard of a SAAS product. The backend is in Django. The widget displays a line graph of certain measurements updated real time. This part is implemented using Django channels. Among the various buttons at the bottom of the widget is one that initiates a time consuming calculation, the result of which is another line graph overlaid on the same figure. Note: The dashboard has other widgets on their own socket connections. So unless I am mistaken this seems to be both a CPU bound as well as an IO bound problem. Initially I had decided to use celery to offload the calculation on a different process but after a bit of research it seems that one normally uses celery for fire-and-forget tasks where the end result of the process doesn't have to be returned to the user which doesn't fit my use-case since I have to feed the result of my computation back to the user. In my research I have also found a few libraries that may help but I am unclear about whether they are the way to go or too much for my … -
Saving formset related models by multi-room relationships in Django
Please tell me how to save a formset with two models related to the manytomanyfield relationship, it turns out while two forms are displayed when the page is opened, after filling in and clicking on the "Add" button, the "phone" and "client_name" fields are cleared and the form is not sent. In view class OrderCreateView(CreateView), checking client_formset.is_valid() returns False. Here is the code: models.py from django.db import models from django.contrib.auth.models import User class Client(models.Model): phone = models.CharField(max_length=20, verbose_name='Телефон') client_name = models.CharField(max_length=100, verbose_name='ФИО клиента') def __str__(self): return '%s %s' % (self.phone, self.client_name) class Meta: verbose_name = 'Клиент' verbose_name_plural = 'Клиенты' class Order(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name='Принял', blank=True) date_of_creation = models.DateTimeField(auto_now=True, verbose_name='Дата создания') execution_date = models.DateField(verbose_name='Дата исполнения') address = models.CharField(max_length=200, verbose_name='Адрес') service = models.CharField(max_length=100, verbose_name='Услуга') master = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='master', null=True, verbose_name='Мастер', blank=True) client = models.ManyToManyField(Client, verbose_name='Клиент', blank=True) def __str__(self): return '%s %s %s' % (self.execution_date, self.address, self.service) class Meta: verbose_name = 'Заявка' verbose_name_plural = 'Заявки' forms.py from django import forms # from .models import Orders, Person, Phone from .models import Order, Client from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.forms import modelformset_factory class UserFullnameChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.get_full_name() class OrderForm(forms.ModelForm): master = UserFullnameChoiceField(queryset=User.objects.all(), label='Мастер') class Meta: … -
Investigating Slow Performance in Adding Products to Django Oscar Basket via REST API
I'm currently facing performance issues when adding products to the shopping cart in a Django Oscar-based e-commerce application. The problem becomes particularly noticeable when the basket contains around 50 items. I'm using Django Oscar's REST API for adding products to the basket, which is called by JavaScript. The challenge is to identify the root cause of the slowdown and explore possible solutions. Observations: Adding products through product list views is slow. Adding products through the product detail page remains fast even with a considerable number of products in the cart. Details: API Endpoint: http://localhost:8000/en/api/basket/add-product/ Direct Adding via Detail Page: http://localhost:8000/en/basket/add/12787/ Offer Calculations: Offers are a significant concern, as adding a line to the basket triggers the calculation of all available offer conditions for each row. Investigation So Far: Middleware Approach: For direct adding via the detail page, offer calculations are handled in Django Oscar's BasketMiddleware during the redirect page load. This code might be better optimized compared to the custom code in the API. Offer Calculation in API: The problem intensifies when the basket consists of 30+ basket lines with different products. The query count increases linearly with the basket line count during API calls. Request for Help: I'm seeking … -
CreateView template not found
I am trying to create a CreateView in Django, but am facing a 'template not found' error (shown below) Currently, I have the following code: views.py: from django.shortcuts import render from django.views.generic import ( ListView, DetailView, CreateView, DeleteView ) from .models import EventPost class EventPostListView(ListView): model = EventPost template_name = "event_blog/home.html" context_object_name = "event_posts" ordering = ['-date_posted'] class EventPostDetailView(DetailView): model = EventPost class EventPostCreateView(CreateView): model = EventPost fields = ['name', 'location', 'locked', 'description', 'image'] urls.py: from django.urls import path from .views import * urlpatterns = [ path("", EventPostListView.as_view(), name="event-blog-home"), path("event/<int:pk>/", EventPostDetailView.as_view(), name="post-detail"), path("event/new/", EventPostCreateView.as_view(), name="post-create"), ] You can see I have already used a ListView and DetailView which has worked fine. The code from these views also extends 'event_blog/base.html' so I do not expect this to be the issue. Here is the directory for the files: And the HTML code for the template if you needed it: {% extends "event_blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Event</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-secondary mt-3 mb-3" type="submit">Post</button> </div> </form> </div> {% endblock content %} Also the model: class EventPost(models.Model): name = models.CharField(max_length=100) location = … -
Building Issue When Deploying Django Project To Railway
When I upload my django project online to railway the following error appears: Dockerfile:20 18 | ENV NIXPACKS_PATH /opt/venv/bin:$NIXPACKS_PATH 19 | COPY . /app/. 20 | >>> RUN --mount=type=cache,id=s/585223ec-cc75-4dcd-9f98-7ab08bb3e77f-/root/cache/pip,target=/root/.cache/pip python -m venv --copies /opt/venv && . /opt/venv/bin/activate && pip install -r requirements.txt 21 | 22 | ERROR: failed to solve: process "/bin/bash -ol pipefail -c python -m venv --copies /opt/venv && . /opt/venv/bin/activate && pip install -r requirements.txt" did not complete successfully: exit code: 1 Error: Docker build failed **My Settings.py** """ Django settings for django2 project. Generated by 'django-admin startproject' using Django 4.2.6. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'bootstrap4', 'stdimage', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django2.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django2', 'USER': 'root', 'PASSWORD': 'django2023', 'HOST': 'localhost', 'PORT': '3306', } } # Static files (CSS, … -
Django Rest - Redirect Password Form?
I recently upgraded to Django 4.0 and upgraded django-allauth with alongside django-rest-auth. When a user fills out the password reset form under http://localhost:8000/api/dj-rest-auth/password/reset/ they get a link in the console that goes to: http://localhost:8000/users/reset/2n/bxggn2-05019c81f9d6dfda6a10b7cfec09e839/ The link provided gets me to this old form: How can I get this message in the console to point to accounts/password/reset/key/1-set-password/? That form looks like this: That’s where my allauth form lives and I’m not fully sure if this is the correct approach. Below is some of my settings and urls. Any help is gladly appreciated. Thanks! settings.py INSTALLED_APPS = [ # Local, 'api.apps.ApiConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', 'users', # 3rd Party 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth', 'dj_rest_auth.registration', 'corsheaders', 'drf_yasg', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } urls.py from django.urls import path, include from allauth.account.views import ConfirmEmailView, EmailVerificationSentView urlpatterns = [ path('accounts/', include('allauth.urls')), path('', include('users.urls')), path('api/', include('api.urls')), path('api-auth/', include('rest_framework.urls')), path('api/dj-rest-auth/registration/account-confirm-email/<str:key>/', ConfirmEmailView.as_view()), # Needs to be defined before the registration path path('api/dj-rest-auth/', include('dj_rest_auth.urls')), path('api/dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('api/rest-auth/registration/account-confirm-email/', EmailVerificationSentView.as_view(), name='account_email_verification_sent'), path('', include('django.contrib.auth.urls')), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), ] -
Django app cannot delete AWS S3 bucket items
DISCLAIMER: (I'll put it at the top so people don't just skip and not read) I just recently started using AWS so I still don't understand a lot of things and yes, I already did the research on this subject and every post I found said to "make the bucket publicly available" which is something I would like to avoid and that should not be the correct answer since, in the tutorial I was following, the guy used it as private blocking all outside access. The upload of an Images works without issues, so I would roule out any problem with the connection itself, but when I try to delete one I get the error An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied I was following a tutorial about how to connect the bucket to django. The steps I took: Created a bucket (not public like it said in the tutorial) Created a User Group with "AmazonS3FullAccess" policy Created a User inside the group with both the S3 full access and the "AWSCompromisedKeyQuarantineV2" policy Generated the necessary keys (secret and access) The S3FullAccess policy should be this one: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": … -
Django Model Inheritance: Every
In Django, I want to have several models of the same type: ANode, BNode, CNode are all of type "Node". In the database, you can look up a "Node" by id, then quickly get what kind of Node it is (ANode, BNode, CNode), and then reference that node. Every node is only of one specific node type, and there are node "Nodes", only "ANodes", "BNodes", "CNodes". There may be many kinds of Nodes (A-Z) each with different fields. I can picture the underlying SQL: there is a "Node" table with an ID column and an enum field keeping track of which type of Node it is. How can I implement that? -
How to let Django serve images when hosting on Vercel
I deployed a Django project on Vercel. The app is responsible for serving data to a Next.js frontend. However, the images don't get served while other data do. GET request to the images return NOT FOUND error after deploying to Vercel. I have studied all similar questions on this platform but none seems to solve my problem. I have this in my settings.py file: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles_build', 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/article_photos') I'm serving only the article_photos. I have this in my project urls.py file: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is the structure of my media folder: I have struggled with this problem throughout the whole day. Any help will be appreciated. Update: This is my vercel.json file: { "builds": [{ "src": "core/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } }], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "core/wsgi.py" } ] } This is my my build_files.sh echo "BUILD START" python3.9 -m pip install -r requirements.txt python3.9 manage.py collectstatic --noinput --clear echo "BUILD END" Update 2: Below is the error returned: … -
Python Django and parallel process
I'm making a delayed messaging service in Django. I reached the task manager. In theory, it should be launched in parallel with Django, its task is to “read the database” and send messages. I used "multiprocessing Pool", the code was entered into manage.py. It confuses me that when starting, one of the processes fires twice, “ok” in the screenshot. Using a parallel process, the site is assembled and works properly. why is that? Are there any better practices? Result: не ok не ok Performing system checks... Watching for file changes with StatReloader System check identified no issues (0 silenced). November 10, 2023 - 16:55:45 Django version 4.2.6, using settings 'WhiteRabbit.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ok 2023-11-10 16:56:44.743514 ok 2023-11-10 16:56:45.275028 manage.py: import os import sys from multiprocessing import Pool from automation.task_messanger import task_messanger def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WhiteRabbit.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': with Pool(processes=2) as pool: pool.apply_async(task_messanger, ) pool.apply_async(main(), ) # main() … -
How to generate ID card or certificate in Django with any kind of template as MS Word or PPT or PDF?
I need help to make a ID card or document in django to provide user their ID card or any dynamic documents such as certificates. And provide as PDF I tried, Python docx library. with that it is possible to create a docx file and even add an image. but if i use a template and when i want to replace a text in the docx and the text is in text-box in word then its not replacing. Btw, I solved that. but now i can't replate a image in appropriate place in word. SEE THE TEMPLATE IMAGE . Here if i want to add an image and the image i want to place is in the center Top. but i can't do it. So Please if you can help with this that's fine else , Please give a way that how can i edit a document template with python Just need to generate dynamic document. CODE : def myreplace(file, regex, replace): for p in file.paragraphs: if regex.search(p.text): inline=p.runs for i in range(len(inline)): if regex.search(inline[i].text): text=regex.sub(replace, inline[i].text) inline[i].text=text for table in file.tables: for row in table.rows: for cell in row.cells: myreplace(cell, regex, replace) def ReadingTextDocuments(fileName): doc = Document (fileName) completedText … -
Django Filter a Queryset based on Prefetched FK Relationsship
I have 2 models below, and I am trying to run a query on JournalLineItems that filters out entries that have no associated GeneralLedger entry. My queries are not able to find the right items as I am querying wrong. class JournalLineItem(SafeDeleteModel, UUID, TimestampModel): id = models.AutoField(primary_key=True) ... class GeneralLedger(SafeDeleteModel, UUID, TimestampModel): id = models.AutoField(primary_key=True) journal_line_item = models.ForeignKey('accounting.JournalLineItem', null=True, on_delete=models.CASCADE, related_name='general_ledger', db_index=True) Overall I can do this, but I want it done on the DB level with a queryset filter: for line_item in JournalLineItem.objects.filter().prefetch_related('general_ledger').using(client_url).order_by('-accounting_period', '-pk'): # only deal with ones that are not in the GL if not line_item.general_ledger.exists(): ... When I try this, the query is not right: JournalLineItem.objects.filter(general_ledger=None).prefetch_related('general_ledger') or JournalLineItem.objects.filter(general_ledger__is_null=True).prefetch_related('general_ledger') -
Not Logging the supplier when suppplier has more then 1 product in his list
this project is about supplier and client management system when we login to client it is working perfect but when I log in to supplier it is throwing error... if we add more than one product in supplier list then it's not logging in that account again. only allowing 1 order . this is the model of my code. # models.py from django.contrib.auth.models import User from django.db import models from django.shortcuts import render, redirect,HttpResponse from django.contrib.auth.models import User from .models import * from django.contrib.auth import authenticate, login,logout from django.contrib.auth.decorators import login_required from django.contrib import messages from django.contrib.auth import authenticate, login class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=15) address = models.CharField(max_length=255) class Supplier(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_name = models.CharField(max_length=255) product_price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='products/') from here views.py start of start of the code def signup(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') Confirm_Password = request.POST.get('Confirm_Password') user_type = request.POST.get('role') if password != Confirm_Password: return HttpResponse("Your password and confirm password are not the same!!") elif User.objects.filter(email=email).exists(): return HttpResponse("Email Already Exist") # Create the user elif user_type == 'client': # ... existing code for client registration ... mobile = request.POST.get('mobile') address = request.POST.get('address') … -
Make dynamic imports of ts module absolute path in js using Webpack
I'm using Webpack as a bundler. My project contains .ts files with dynamic imports. And everything works just fine. But It is Django project and compressor doesn't see modules to which path is build dynamically. Is there a way to make webpack not build path to module but put it as full string in .js file? This is how it looks now: const obj = await import('../components/MyComponent/MyComponent'); In bundled js: const e = await r.e(3802).then(r.bind(r, 73802)); It is building a path to this module. And I would like to have it as an absolute path. Is there a way to do so? -
Django increment string value without race condition
On save I want to receive names like name, name(1), name(2). I implemented the following code: with transaction.atomic(): same_name_count = Folder.objects.filter( owner=validated_data["owner"], name__iregex=r"%s(\s\(\d+\))?" % validated_data["name"], ).count() if same_name_count: validated_data["name"] = f"{validated_data['name']} ({same_name_count+1})" folder = Folder.objects.create(**validated_data) But I still receive race condition and receive same names when I run this code in celery task. I also tried select_to_update to lock all rows somehow and get correct count -
How to use Accessors in Django, in which django-tables2 is connected, to display links to pages with data about each field in the table?
It is necessary in Django, in which django-tables2 is connected, to output a field with a link to a page with data about this field by get_absolute_url(). To do this, I need to use Accessors, but how??? class GostTable(tables.Table): # get_absolute_url() I need on field 'name'! class Meta: model = Gost template_name = "django_tables2/bootstrap.html" fields = ('name', 'short_name') I haven't any ideas about using Accessors... -
Making Request to django restframework from a deployed django project
I have a project that was created using django and drf along with jquery's ajax for sending post and get request to my django server url. But I am having an issue when I deploy the project on railway. If I run my project on my localhost or 127.0.0.1:8000 it works totally fine but when I try to make request to my server after deploying it fails and shows a CORs error on my browser dev panel. I tried adding my domain to CORS_ALLOWED_ORIGINS in my settings.py file but that does not fix the problem. I also added my domain to CORS_ORIGIN_WHITELIST still yet no progress. Please how do I fix this error. #settings.py CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://127.0.0.1:3000', 'https://my-domain.com', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'https://my-domain.com', ] ALLOWED_HOSTS = ['*'] CSRF_TRUSTED_ORIGINS = ['https://my-domain.com', 'http://127.0.0.1'] #main.js $.ajax({ url: https://my-domain.com/api/blogview, type: "GET", dataType: "json", I tried those codes in my settings.py file yet no progress. And that is how I am making my ajax requests. I also tried order drf endpoints but I still get the same errors on my browser dev panel. These are the errors I got when I run the following command to mimmick a non local server. -----> … -
How to display multiple video streams in django from streamlit?
I have a code that should show a video on a django page. I’m trying to convert it from streamlit to django, but without success. Please tell me how to implement this? Multiple threads arrive and all of them need to be shown on one page in Django like video-wall. Code in streamlit: video_placeholders = [st.empty() for _ in range(3)] for i, result in enumerate(results): image = result.orig_img detection_results = model(image)[0] detections = sv.Detections.from_ultralytics(detection_results) detections = tracker.update_with_detections(detections) annotated_frame = process_frame(image) resized_image = cv2.resize(annotated_frame, (1024, 768)) video_placeholders[i % 3].image(resized_image, channels="BGR", use_column_width=True, caption=f"Video {i + 1}") The Django code I’m trying shows images from all cameras in one place, but each thread should have its own display: def video_stream(request): def generate_frames(): for i, result in enumerate(results): image = result.orig_img detection_results = model(image)[0] detections = sv.Detections.from_ultralytics(detection_results) detections = tracker.update_with_detections(detections) annotated_frame = process_frame(image, stream_index=i) # Pass stream_index to process_frame resized_image = cv2.resize(annotated_frame, (1024, 768)) _, frame = cv2.imencode('.jpg', resized_image) frame = frame.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') return StreamingHttpResponse(generate_frames(), content_type='multipart/x-mixed-replace; boundary=frame') I just recently started learning Django and have not yet fully understood the processing logic. My html template: {% for stream_name in stream_names %} <h2>{{ stream_name }}</h2> <img src="{% url … -
Request data Modifiy in django
I have a class with APIView, which accept request. from there, I pass the request to 2 different methods, but when I print data from 2nd function, it is modified by first method. Sample class events(APIView): def post(self, request): data = request.data self.tinybird(data) self.events(data) I was expecting to have same copy of data in both method, but tinyBird method changes one line as del product['options'] and due to this I am not able to get product['options'] in events() method. As I am passing data separately to both functions, how data modification of 1st function affect data of 2nd function. Tried I tried to send copy of request to each function or one function but still same issue. data1 = request.copy() data2 = request.copy() self.tinybird(data1) self.events(data2) still data2 throw keyerror on data2['options'] -
Django tables2: Table reverts to previous value
I have a view where i display 2 tables and I have a form to create a new filter in my template. Using my code I would expect that the filter table to update and stay that way. However, after creating a new filter, it displays in the table but if i refresh the page or create a new filter, it reverts to the "original" table i.e. if i have 1 filter and I create one but i refresh the page or create a new filter afterwards, the table displayed will show just one filter. To illustrate in a more concrete way: original: [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d3bc70>] [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d3bc70>] 172.19.0.3 - - [10/Nov/2023:10:33:00 +0000] "POST /trendyqc/dashboard/ HTTP/1.0" 302 0 "http://localhost:8000/trendyqc/dashboard/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OPR/106.0.0.0 (Edition developer)" original: [<trend_monitoring.tables.ReportTable object at 0x7f01e4d45670>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d45bb0>] [<trend_monitoring.tables.ReportTable object at 0x7f01e4d45670>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d45bb0>] 172.19.0.3 - - [10/Nov/2023:10:33:01 +0000] "GET /trendyqc/dashboard/ HTTP/1.0" 200 233735 "http://localhost:8000/trendyqc/dashboard/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OPR/106.0.0.0 (Edition developer)" original: [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d3bc70>] [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at … -
Use Absolute URLs for wagtail richtext
I have the following field defined on my model: email_body = RichTextField( verbose_name=_("Email Body"), help_text=_("Body of the email to send when you are out of office."), features=[ "bold", "italic", "ol", "ul", "hr", "h2", "h3", "h4", "h5", "h6", "code", "superscript", "subscript", ], max_length=2048, blank=True, null=True, ) However; when including links, images or documents in the features; the urls generated are all relative: <p data-block-key="e0dv1"><a href="/documents/14/Kunststof_Catalogus_F1204.pdf">Kunststof Catalogus (F1204)</a></p> <img alt="" class="richtext-image right" height="498" src="/media/images/aluminium-catalogus-f2204-page4_1.width-500.jpg" width="500"> <p data-block-key="5nssj"><a href="/nl/producten/">Producten</a></p> <p data-block-key="aa12u">Het <a href="/nl/"><b><i>(REDACTED)</i></b></a> team, 2023</p> As implied by the field name; this is used in emails; thus I cannot use relative URLs. The HTML is generated like so: (It is designed for template injection. Only to be used by admins.) template = util.template_from("from_string", self.email_body) body = richtext(template.render(context, request=request)) context["body"] = body context["email_body"] = body is_file = True as_html = True template_name = "office/emails/closed_email.html" How can I make the richtext editor always generate full (absolute) URLs? -
`channel_layer.group_send` won't call method in `AsyncWebsocketConsumer`
I wrote a WebSocket connection in a Django app, using Django Channels and I'm testing in my local environment with Daphne (I will use uvicorn for production) Here's a function that will be called in the save method of UserNotification model, to send title and message of notification, through user WebSocket connection. from typing import Type from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from django.conf import settings def send_user_notification( user_id: int | Type[int], title: str, message: str ): channel_layer = get_channel_layer() channel_name = settings.NOTIFICATION_WEBSOCKET_CHANNEL_NAME.format(user_id=user_id) group_name = settings.NOTIFICATION_WEBSOCKET_GROUP_NAME.format(channel_name=channel_name) async_to_sync(channel_layer.group_send)( group_name, { "type": "user_notify", "message": { "title": title, "message": message }, }, ) class UserNotification(models.Model): user = models.ForeignKey("users.User", on_delete=models.CASCADE) notification = models.ForeignKey( to="notification.Notification", on_delete=models.CASCADE ) def save(self, **kwargs): send_user_notification( user_id=self.user_id, title=self.notification.title, message=self.notification.message, message_type=self.notification.message_type, ) super().save(**kwargs) And here's my AsyncWebsocketConsumer: import json import logging from channels.generic.websocket import AsyncWebsocketConsumer from channels.layers import get_channel_layer from django.conf import settings class UserNotificationConsumer(AsyncWebsocketConsumer): async def connect(self): if self.scope["user"].is_anonymous: await self.close() self.channel_name = settings.NOTIFICATION_WEBSOCKET_CHANNEL_NAME.format( user_id=self.scope["user"].pk ) self.group_name = settings.NOTIFICATION_WEBSOCKET_GROUP_NAME.format( channel_name=self.channel_name ) self.channel_layer = get_channel_layer() await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.group_name, self.channel_name) async def user_notify(self, event): print("Event: ", event) data = event["message"] await self.send(text_data=json.dumps(data)) And here's the asgi.py file: import os from channels.routing import … -
Change Model data after form submission in Django
Im writing a Booking System in Django with ModelForms, I Want to change value of a Boolean field in a ForeginKey model when form saves. models.py class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates, null=True, blank=True,on_delete=models.CASCADE) free_hours_from = models.CharField(max_length=10,null=True, blank=True) free_hours_to = models.CharField(max_length=10,null=True, blank=True) status = models.BooleanField(null=True,default=True) class Bookings(models.Model): ... booked_time = models.ForeignKey(AvailableHours, on_delete=models.CASCADE,related_name='booked_time') views.py @login_required() def booking_form(request): form = forms.BookingForm() if request.method == 'POST': form = forms.BookingForm(request.POST) if form.is_valid(): book = form.save(commit=False) book.user = request.user form.save() return HttpResponseRedirect(reverse('creator:login')) return render(request, 'account/book.html', {'form': form}) forms.py class BookingForm(forms.ModelForm): class Meta: model = Bookings exclude = ('user','booking_code','confirmed',) Since I want each AvailableHours be able to get booked only once , I need the form to change value of AvailableHours status to False so I can filter it in templates. Can anyone suggest an approach to this issue ? I Tried something like form.booked_time.status = False in my views but it didnt work -
How can i work AJAX update JSON with Datatable (Datatable.JS) - Django?
I have tried to work ajax update from Django to Datatable templates like this code template [shipment.html] <table id="example"> <thead> <tr> <th>User</th> <th>Author</th> </tr> </thead> <tbody> </tbody> </table> i'm use this to got a json data and then now show this already. views.py def getlist(request): if request.method == "GET": data = serializers.serialize("json", Editors.objects.all()) respon = json.loads(data) return HttpResponse(json.dumps(respon, ensure_ascii=False), content_type="application/json") json (getlist) [{"model": "tracking.editors", "pk": 1, "fields": {"editor_name": "This AA", "num_users": 10}}, {"model": "tracking.editors", "pk": 2, "fields": {"editor_name": "This BB", "num_users": 20}}, {"model": "tracking.editors", "pk": 3, "fields": {"editor_name": "This CC", "num_users": 30}}, {"model": "tracking.editors", "pk": 4, "fields": {"editor_name": "This DD", "num_users": 40}}] Javascript <script type="text/javascript" language="javascript" class="init"> $(document).ready(function () { $('#example').DataTable({ ajax: { url: "{% url 'getlist' %}", type: 'GET', dataSrc: "", }, columns: [ {data: "fields.editor_name"}, {data: "fields.num_users"}, ], }); }); </script> Now it's data is already show on my Table but not Real-time update. How can i do it's to Real-time update when have a new record in my Database? i need someone to help for clear of this can be used like my method or need use by our method, Thanks -
dlopen symbol not found in flat namespace '_ffi_prep_closure'
I am getting the following error with the traceback. I have tried install reinstalling cryptography. Went through this as well https://github.com/ffi/ffi/issues/946 as well with no solution and a few other solution but nothing worked. ImportError: dlopen(/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/_cffi_backend.cpython-37m-darwin.so, 0x0002): symbol not found in flat namespace '_ffi_prep_closure' thread '<unnamed>' panicked at /Users/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pyo3-0.18.3/src/err/mod.rs:790:5: Python API call failed note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Users/rj/.pyenv/versions/3.7.17/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/rj/vogo/consumer-api/api/accounts/models.py", line 2, in <module> from .users.models import ( File "/Users/rj/vogo/consumer-api/api/accounts/users/models.py", line 23, in <module> from libs.clients import paytm_client, redis_consumer_client, ola_client, amazonpay_client File "/Users/rj/vogo/consumer-api/api/libs/clients/__init__.py", line 35, in …