Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How can I create code to show the question with follow levels as easy until hard
enter image description here enter image description here my system can show question have save in the table, but just random way. create code that categorizes questions by difficulty level (easy, medium, hard), and displays them in ascending order of difficulty. -
Unexpected " [] " Characters on Django Admin Log in Page
I have a Django App running on a local server. I am using the default admin features and rendering with collected static files. However, I am seeing " [] " inserted into the main content of the login form. Why is this and how do I ensure this doesn't occur? -
django 5.1 email [WinError 10061]
хочу отправить письмо с джанго вроде все настроил верно но выходит ошибка: ConnectionRefusedError: [WinError 10061] Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение. помогите пжл. вот мои настройки: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.yandex.ru' EMAIL_PORT = 465 EMAIL_USE_TLS = False EMAIL_USE_SSL = True EMAIL_HOST_USER = \['Vlad.Olegov750@yandex.ru'\] EMAIL_HOST_PASSWORD = 'пароль' RECIPIENTS_EMAIL = \['Vlad.Olegov750@yandex.ru'\] DEFAULT_FROM_EMAIL = \['Vlad.Olegov750@yandex.ru'\] SERVER_EMAIL = \['Vlad.Olegov750@yandex.ru'\] EMAIL_ADMIN = \['Vlad.Olegov750@yandex.ru'\] пробовал менять порт на 587. но без успешно -
How to use REST API in flowable-ui docker image
I have a Django Website, on this Website is a form and if I click on Submit, it should start a workflow in flowable(flowable-ui docker container). But I can't reach the API. curl 'http://admin:password@localhost:8080/flowable-ui/process-api/repository/deployments' does work, but everything else does not. It's always a 404 Error and I can't find the right URL to make this work. Can somebody please give advise on how to get this work? Greetings curl 'http://admin:passwort@localhost:8080/flowable-ui/process-api/repository/deployments' -> does work every other api call does not -
Image upload problem in django-ckeditor-5
I use django-ckeditor-5 in my Django project These are my ckeditor settings in settings.py CKEDITOR_5_CONFIGS = { 'extends': { 'blockToolbar': [ 'paragraph', 'heading1', 'heading2', 'heading3', '|', 'bulletedList', 'numberedList', '|', 'blockQuote', ], 'toolbar': { 'items': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough', 'subscript', 'superscript', 'highlight', '|', 'insertImage', 'fileUpload', 'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', '|', 'fontSize', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat', 'insertTable'], 'shouldNotGroupWhenFull': True }, 'image': { 'toolbar': [ "imageTextAlternative", "|", "imageStyle:alignLeft", "imageStyle:alignRight", "imageStyle:alignCenter", "imageStyle:side", "|", "toggleImageCaption", "|" ], 'styles': [ 'full', 'side', 'alignLeft', 'alignRight', 'alignCenter', ] }, 'table': { 'contentToolbar': ['tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties'], 'tableProperties': { 'borderColors': customColorPalette, 'backgroundColors': customColorPalette }, 'tableCellProperties': { 'borderColors': customColorPalette, 'backgroundColors': customColorPalette } }, 'heading': { 'options': [ {'model': 'paragraph', 'title': 'Paragraph', 'class': 'ck-heading_paragraph'}, {'model': 'heading1', 'view': 'h1', 'title': 'Heading 1', 'class': 'ck-heading_heading1'}, {'model': 'heading2', 'view': 'h2', 'title': 'Heading 2', 'class': 'ck-heading_heading2'}, {'model': 'heading3', 'view': 'h3', 'title': 'Heading 3', 'class': 'ck-heading_heading3'} ] }, }, } CKEDITOR_5_ALLOW_ALL_FILE_TYPES = True CKEDITOR_5_FILE_UPLOAD_PERMISSION = "authenticated" This is the field where I used ckeditor: CKEditor5Field('content', config_name='news') But when I upload an image from my PC through admin panel, I get this error: This problem exists for all files, not just images Can you please advise what the problem … -
Retryable write with txnNumber 4 is prohibited on session | Django and MongoDB
How to do atomic update in below code following line of code throws an error: self._large_results.replace(json_result, encoding='utf-8', content_type='application/json') Application Code: class MyWrapper(EmbeddedDocument): # Set the maximum size to 12 MB MAXIMUM_MONGO_DOCUMENT_SIZE = 12582912 # Lock object to lock while updating the _large_result lock = threading.Lock() # The default location to save results results = DictField() # When the results are very large (> 16M mongo will not save it in # a single document. We will use a file field to store these) _large_results = FileField(required=True) def large_results(self): try: self._large_results.seek(0) return json.load(self._large_results) except: return {} # Whether we are using the _large_results field using_large_results = BooleanField(default=False) def __get_true_result(self): if self.using_large_results: self._large_results.seek(0) try: return json.loads(self._large_results.read() or '{}') except: logger.exception("Error while json converting from _large_result") raise InvalidResultError else: return self.results def __set_true_result(self, result, result_class, update=False): class_name = result_class.__name__ valid_result = self.__get_true_result() with self.lock: try: current = valid_result[class_name] if update else {} except: current = {} if update: current.update(result) else: current = result valid_result.update({class_name: current}) json_result = json.dumps(valid_result) self.using_large_results = len(json_result) >= self.MAXIMUM_MONGO_DOCUMENT_SIZE if self.using_large_results: self._large_results.replace(json_result, encoding='utf-8', content_type='application/json') self.results = {} self._large_results.seek(0) else: self.results = valid_result self._large_results.replace('{}', encoding='utf-8', content_type='application/json') Using Django with Mongo deployed in cluster and Celery to run these statements. getting … -
ATTRIBUTEERROR: module 'mysqldb.constants.er' has no attribute 'constraint_failed' [duplicate]
im trying to connect Mysql database with my django project. i get this after running my project: Traceback (most recent call last): File "C:\python\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\python\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\core\management\commands\runserver.py", line 126, in inner_run autoreload.raise_last_exception() File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\contrib\auth\models.py", line 5, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\contrib\auth\base_user.py", line 40, in <module> class AbstractBaseUser(models.Model): File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\db\models\base.py", line 143, in __new__ new_class.add_to_class("_meta", Options(meta, app_label)) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\db\models\base.py", line 371, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\db\models\options.py", line 231, in contribute_to_class self.db_table, connection.ops.max_name_length() File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\utils\connection.py", line 15, in __getattr__ … -
Why css is not updating in my django project?
I was working on django project and apparently css is not updating. It sticked to the css that I wrote last time. Help me to find solution! I tried to refresh in chrome with Ctrl+R, Ctrl+Shift+R. I tried to use it on different browser like Safari. And I also tried to make css inline in html. Nothing has worked. I want to write css in my django project and it should immediately reflect in the browser. -
how do i solve django pip dependency conflict error
I am currenlty working to integrate azureSQL to my website, but i am encountering this error that some of my packages require django version more than 4, others require version 2 what should i do. this is the error i am getting : ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. djangorestframework 3.15.2 requires django>=4.2, but you have django 2.1.15 which is incompatible. django-cors-headers 4.4.0 requires django>=3.2, but you have django 2.1.15 which is incompatible. i tried downgrading django version but that gave me the same problem but for other packages -
Can't "test" amazon alexa custom skill in the developer console
I'm trying to develop a simple notification custom skill served on a web service using "django-ask-sdk". On the "build" tab, all the "Building Your Skill" categories are green: Invocation Name: OK Intents, Samples, and Slots: OK Build Model: OK Endpoint: OK On the "test" tab, "skill testing is enabled in" is set to "Development". On the "test" tab, in the "Alexa Simulator", it appears that I can issue a request, but the response is, "The requested skill can't be accessed". I'm using "HTTPS" endpoint type, and the endpoint set for the "Default Region" is correct. I'm not seeing any request being sent to my endpoint. Am I missing some configuration, or am I not understanding how the test tab works? How can I get a test request sent to my web skill? -
Looking for budget friendly hosting options for Django backend
I live in Turkey and plan to use Django for my backend. I’ve never rented hosting before and am looking for an affordable option that works well with Django. If you have any recommendations for reliable and budget-friendly hosting providers, I’d really appreciate your suggestions. I looked into hosting providers that support Django and compared their plans, but I haven’t been able to find a suitable and affordable option yet. -
Django Management Command Not Triggering API Update in Frontend: Debugging Connection Issues Between Django Backend and React Frontend
from django.core.management.base import BaseCommand from myapi.models import StrengthWknes, CustomUser import pandas as pd from sklearn.neighbors import NearestNeighbors from sklearn.linear_model import LinearRegression import numpy as np class Command(BaseCommand): help = 'Create study groups based on normalized percentages using k-NN and predict target score for the weakest subject' def add_arguments(self, parser): parser.add_argument('grade', type=str, help='Grade for which to create study groups') parser.add_argument('current_user_id', type=int, help='ID of the current user') parser.add_argument('n_neighbors', type=int, default=5, help='Number of neighbors to find') def handle(self, *args, **kwargs): grade = kwargs['grade'] current_user_id = kwargs['current_user_id'] n_neighbors = kwargs['n_neighbors'] user_data = self.fetch_user_data(grade) group_usernames, group_df = self.create_study_group(user_data, current_user_id, n_neighbors) if len(group_usernames) < 3: self.stdout.write(self.style.WARNING('Group is too small. Select group manually.')) else: self.stdout.write(self.style.SUCCESS(f'Created group: {group_usernames}')) # Predict target score for the weakest subject if not group_df.empty: target_scores = self.predict_target_score(group_df, current_user_id) self.stdout.write(self.style.SUCCESS(f'Target scores for the weakest subject: {target_scores}')) def fetch_user_data(self, grade): records = StrengthWknes.objects.filter(grade__grade=grade) data = [] for record in records: user = CustomUser.objects.get(pk=record.id.id) data.append({ 'user_id': user.id, 'username': user.username, 'normalized_percentage': record.normalized_percentage, 'strgth_wkness': record.strgth_wkness }) df = pd.DataFrame(data) self.stdout.write(self.style.SUCCESS(f'Fetched user data:\n{df}')) return df def create_study_group(self, df, current_user_id, n_neighbors): TOLERANCE = 10 # Tolerance percentage range for neighbor selection MAX_DIFF = 10 # Maximum allowed difference within the group if len(df) < n_neighbors: return [], pd.DataFrame() # Return … -
Can't access the Django endpoints
Can't access the various Django endpoints. Tried accessing the endpoints such as http://127.0.0.1:8000/api/line-chart-data/ http://127.0.0.1:8000/api/candlestick-data/ and etc, but got a 404. urls.py """ URL configuration for mysite project. The `urlpatterns` list routes URLs to For more information please see: https://docs.djangoproject.com/en/5.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ # mysite/urls.py from django.contrib import admin from django.urls import path from .views import line_chart_data, candlestick_data, bar_chart_data, pie_chart_data from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('charts.urls')), path('api/candlestick-data/', candlestick_data), path('api/line-chart-data/', line_chart_data), path('api/bar-chart-data/', bar_chart_data), path('api/pie-chart-data/', pie_chart_data), ] views.py # mysite/views.py from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def candlestick_data(request): data = { "data": [ {"x": "2023-01-01", "open": 30, "high": 40, "low": 25, "close": 35}, {"x": "2023-01-02", "open": 35, "high": 45, "low": 30, "close": 40}, ] } return Response(data) @api_view(['GET']) def line_chart_data(request): data = { "labels": ["Jan", "Feb", "Mar", "Apr"], "data": [10, 20, 30, 40] } return Response(data) … -
TypeError: ‘NoneType’ object is not iterable
when testing a site using pytest, I get an error in the test, and I can’t figure out what is causing the error, please tell me where exactly the problem is in my code, and how to fix it (Files with tests cannot be changed - pytest). My code views.py: from django.views.generic import ( CreateView, DeleteView, DetailView, ListView, UpdateView ) from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.contrib.auth.forms import PasswordChangeForm from django.urls import reverse_lazy from django.contrib.auth import update_session_auth_hash from django.contrib.auth.mixins import UserPassesTestMixin from blog.models import Category, Post from .models import Comment from .forms import CommentForm from .forms import PostForm from .forms import UserProfileForm User = get_user_model() class OnlyAuthorMixin(UserPassesTestMixin): def test_func(self): object = self.get_object() return object.author == self.request.user class PostListView(ListView): model = Post queryset = ( Post.published .order_by('-pub_date') ) paginate_by = 10 template_name = 'blog/index.html' class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm template_name = 'blog/create.html' def get_success_url(self): return reverse_lazy( 'blog:profile', kwargs={'username': self.request.user.username} ) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostDetailView(DetailView): model = Post template_name = 'blog/detail.html' context_object_name = 'post' def get_object(self, queryset=None): post_id = self.kwargs.get("post_id") return get_object_or_404(Post, pk=post_id) def get_context_data(self, … -
change_form.html cannot display any drop-down select fields for the ModelForm
I'm working on implementing a drop-down menu for the "add" page of Product_to_Stock_Proxy_Admin function in the Django admin interface. The options for the drop-down menu are from the Distributor model, which is a foreign key for the Product model. The output only shows the drop-down menu itself, and there are no values from the Distributor model, not even the default value "---------". I don't understand why this is happening. Sincerely thank you for your help and suggestions. The reason why I use change_form is because I use Ajax to display other columns immediately when the user fills in the barcode_number. Therefore, I need to implement the drop-down menu on my own. models.py class Product(models.Model): name = models.CharField(max_length=20, blank=True, null=True) distributor = models.ForeignKey('Distributor', on_delete=models.CASCADE) barcode_number = models.CharField(max_length=20, blank=True, null=True) total_amount = models.IntegerField(blank=True, null=True) class Distributor(models.Model): name = models.CharField(max_length=10) admin.py class Product_to_Stock_Proxy_Admin(admin.ModelAdmin): form = Product_to_Stock_Proxy_Form change_form_template = 'admin/change_form.html' fields = ["distributor", "name", "total_amount"] admin/change_form.html This code only displays the drop-down item itself without any options, not even the default value "-------": {% block content %} <form method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row field-barcode_number"> <div> <div class="flex-container"> <label for="id_barcode_number">條碼號碼:</label> <input type="text" id="id_barcode_number" name="barcode_number" value="{{ form.barcode_number.value }}" /> </div> </div> </div> … -
Angular proxy not working with Django allauth
I have an angular + django project and mostly everything is working. I've setup a proxy.conf as mentioned in the documenation - example here: { "/api": { "target": "http://localhost:8000", "secure": false, "logLevel": "debug", "changeOrigin": true } } but for some reason I cannot make api calls to any django allauth endpoints. The proxy is working because i can make a request to /api/accounts/profile which is a custom view i created to fetch a users information. However, what I'm trying to do is use allauths pre-created endpoints such as /accounts/login or /accounts/logout. If I make a request to http://localhost:4200/accounts/login I get 404 errors that the page/view isn't found. If I remove the domain name so that the proxy kicks in - example: /accounts/login its the same thing. If I change the url to be http://localhost:8000/accounts/login I suddenly get cross origins errors, which means the url is recognized as existing but is not accessable. I have already added all of the cross origins settings to my settings.py and added crf token validation to eliminate some possibilities. Has anyone else experienced this and if so what have you done to fix it? I don't want to create views in Django, that would be … -
Razorpay integration error on python django
Unrecognized feature: 'otp-credentials'. error occured in browser console while razorpay integration and Method Not Allowed (POST): /checkout/ in terminal [TerminalBrowser Console](https://i.sstatic.net/Kn6QfxTG.png) HTML script and button already loaded above <script> var options = { "key": "rzp_test_THuJCWTGTSyCOm", // Enter the Key ID generated from the Dashboard "amount": "{{ razoramount }}", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Anasulfiros", //your business name "description": "Purchase Product", "order_id": "{{ order_id }}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "handler": function(response){ console.log("success") var form = document.getElementById("myform"); // alert(form.elements["custid"].value); // alert(response.razorpay_payment_id); // alert(response.razorpay_order_id); // alert(response.razorpay_signature); window.location.href = "http://localhost:8000/paymentdone?order_id=${response.razorpay_order_id}&payment_id=${response.razorpay_payment_id}&cust_id=${form.elements["custid"].value}" }, "theme": { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed',function(response){ alert(response.error.description); }); document.getElementById('rzp-button1').onclick = function(e){ console.log("button click"); rzp1.open(); e.preventDefault(); } </script> {% endblock payment-gateway %} views class checkout(View): def get(self,request): user = request.user add = Customer.objects.filter(user=user) cart_items=Cart.objects.filter(user=user) famount = 0 for p in cart_items: value = p.quantity * p.product.discounted_price famount = famount + value totalamount = famount + 40 razoramount = int(totalamount * 100) client = razorpay.Client(auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) data = {"amount":razoramount,"currency":"INR","receipt":"order_rcptid_12"} client.set_app_details({"title" : "Django", "version" : "1.8.17"}) payment_response = client.order.create(data=data) print(payment_response) order_id = payment_response['id'] order_status … -
Hello, can you tell me I'm writing a website on django 4
[enter image description here](https://i.sstatic.net/OmSFrl18.jpg) Вот так у меня [enter image description here](https://i.sstatic.net/ml9pLrDs.jpg) hello, you can tell me I'm writing a site on django 4 that gives the search bar select debugger in Run and Debug with the choice of only one single action, this is Python Debugger instead of the Debug Configuration search bar with a single choice of Django. Can you tell me how to solve this problem?? That's how the person I'm using to make the launch site.Our json is completely different. I don't understand how to solve this problem -
Django password reset with front end UI
I'm working on a project that uses Django as the backend and next.js/react.js on the front end. The issue I'm running into is trying to reset the password using the UI of my front end. All of the solutions I've found involve creating the UI on the backend server with templates which I would prefer not to do. I'm able to get the following email from Django(dj_rest_auth) that provides a link with the server domain. Hello from MyApp! You're receiving this email because you or someone else has requested a password reset for your user account. It can be safely ignored if you did not request a password reset. Click the link below to reset your password. http://localhost:8000/password-reset-confirm/k/cd01t1-dfsdfdfwer2/ I've tried to override the PasswordResetSerializer like so but it doesn't work. from dj_rest_auth.serializers import PasswordResetSerializer class MyPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self) : return { 'email_template_name': 'http://localhost:3000/new-password' } And in my settings.py file I have ... REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'myapp.serializers.MyPasswordResetSerializer' } ... How can I change the link in the reset password email to one that sends the user to the client to create their new password? -
Internal Server Error by uploading django project to apache server
Try to upload my djnago project to apache2 server and at the begging hadn't an access(error 403). After somehow solved problem got new one Internal Server Error. /var/log/apache2/error.log: [Sat Sep 07 22:05:50.292291 2024] [core:warn] [pid 74852:tid 129319697659776] AH00045: child process 74853 still did not exit, sending a SIGTERM [Sat Sep 07 22:05:50.292335 2024] [core:warn] [pid 74852:tid 129319697659776] AH00045: child process 74854 still did not exit, sending a SIGTERM [Sat Sep 07 22:05:52.294434 2024] [core:error] [pid 74852:tid 129319697659776] AH00046: child process 74853 still did not exit, sending a SIGKILL [Sat Sep 07 22:05:52.294476 2024] [core:error] [pid 74852:tid 129319697659776] AH00046: child process 74854 still did not exit, sending a SIGKILL [Sat Sep 07 22:05:53.295592 2024] [mpm_event:notice] [pid 74852:tid 129319697659776] AH00491: caught SIGTERM, shutting down [Sat Sep 07 22:08:55.562107 2024] [mpm_event:notice] [pid 76122:tid 129486358599552] AH00489: Apache/2.4.52 (Ubuntu) mod_wsgi/4.9.0 Python/3.10 configured -- resuming normal operations [Sat Sep 07 22:08:55.562464 2024] [core:notice] [pid 76122:tid 129486358599552] AH00094: Command line: '/usr/sbin/apache2' /etc/apache2/sites-available/mysite.conf <VirtualHost *:80> ServerName myip WSGIScriptAlias / /my/directory/my_project/wsgi.py <Directory /my/directory/my_project> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /my/directory/my_project <Directory /my/directory/my_project> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/mysite_error.log CustomLog ${APACHE_LOG_DIR}/mysite_access.log combined </VirtualHost> If anyone needs more information, I'll be happy to provide it I've already tried … -
django-ckeditor-5 media embed config for youtube shorts
I am having django project with django-ckeditor-5 package. The default media providers of ckeditor-5 has youtube. However, I could find from the original source that the regex for youtube do not include shorts url. So, I had to add extraProviders. I tried various ways, but none of them worked. "mediaEmbed": { "previewsInData": "true", "extraProviders": [ { "name": "youtube-shorts", "url": [ r"^(https?:\/\/)?(www\.)?youtube\.com\/shorts\/([a-zA-Z0-9_-]+)$", r"/^(?:m\.)?youtube\.com\/shorts\/(.+)/", ], "html": ( '<div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 56.2493%;">' '<iframe src="https://www.youtube.com/embed/{matched}" ' 'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' 'frameborder="0" allow="autoplay; encrypted-media" allowfullscreen>' "</iframe>" "</div>" ), }, ], }, this is one of the method I tried, and it gives the below error. If I use like below for allowing all it works without the preview image like the screenshot below though. mediaEmbed": { "previewsInData": "true", "extraProviders": [ { "name": "all", "url": r"/^.+/", }, ], }, Anyone had experience make this work? -
Webpack Getting Variables
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Django Webpack template</title> </head> <body> <div id="root"></div> <p id="message">Template Data</p> <script id="templateDataScript" type="application/json"> {{ template_data|safe }} </script> <script src="{% static 'data.bundle.js' %}"></script> </body> </html> This seems to work file when I run it locally... However, if I Webpack this and use my bundle file online it does not recognize the Django template_data. Trying to find out is it possible to somehow incorporate my variables and data into the Webpack itself. Just searching for any insight. -
Django, how can I follow a http redirect?
I have 2 different views that seem to work on their own. But when I try to use them together with a http redirect then that fails. The context is pretty straightforward, I have a view that creates an object and another view that updates this object, both with the same form. The only thing that is a bit different is that we use multiple sites. So we check if the site that wants to update the object is the site that created it. If yes then it does a normal update of the object. If no (that's the part that does not work here) then I http redirect the update view to the create view and I pass along the object so the new site can create a new object based on those initial values. Here is the test to create a new resource (passes successfully) : @pytest.mark.resource_create @pytest.mark.django_db def test_create_new_resource_and_redirect(client): data = { "title": "a title", "subtitle": "a sub title", "status": 0, "summary": "a summary", "tags": "#tag", "content": "this is some updated content", } with login(client, groups=["example_com_staff"]): response = client.post(reverse("resources-resource-create"), data=data) resource = models.Resource.on_site.all()[0] assert resource.content == data["content"] assert response.status_code == 302 Here is the test to create … -
Prefetching complex query that does a Union
I'm trying to prefetch a related object to optimize performance. The code I'm trying to Prefetch is this; class Product(models.Model): ... def get_attribute_values(self): # ToDo: Implement this prefetch. if hasattr(self, "_prefetched_attribute_values"): return self._prefetched_attribute_values if not self.pk: return self.attribute_values.model.objects.none() attribute_values = self.attribute_values.all() if self.is_child: parent_attribute_values = self.parent.attribute_values.exclude( attribute__code__in=attribute_values.values("attribute__code") ) return attribute_values | parent_attribute_values return attribute_values What this does is the following; Get all attribute_values of itself, attribute_values is a related model ProductAttributeValue If it's a child, also get the parent attribute_values, but exclude attribute_values with attribute__codes that are already present in the child attribute_values result Do a union that combines them together. Currently, I have this prefetch; Prefetch( "attribute_values", queryset=ProductAttributeValueModel.objects.select_related( "attribute", "value_option" ) ), This works for the non child scenario, but unfortunately, there are a lot of child products and thus the performance isn't as great. So ideally, I can prefetch the combined attributes to '_prefetched_attribute_values', though I would be fine with doing two prefetches as well; For the product itself For the parent, but still needs to exclude attributes that the child itself had I have tried doing it with a Subquery & OuterRef, but no luck yet. -
How to wrap a search function in a class that inherits from wagtail Page?
Is there a way to make a search form using a wagtail template inheriting from Page? Instead of using a simple view. And how can I render it in the template? I find it more enriching to be able to use the wagtail page attributes to better style the search page, add more fields and make it translatable into multiple languages using for example wagtail localyze. class SearchPage(Page): # Database fields heading = models.CharField(default="Search", max_length=60) intro = models.CharField(default="Search Page", max_length=275) placeholder = models.CharField(default="Enter your search", max_length=100) results_text = models.CharField(default="Search results for", max_length=100) cover_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) # Editor panels configuration content_panels = Page.content_panels + [ FieldPanel('cover_image'), FieldPanel('heading'), FieldPanel('intro'), FieldPanel('placeholder'), FieldPanel('results_text'), ] def search(self, request): search_query = request.GET.get("query", None) page = request.GET.get("page", 1) active_lang = Locale.get_active() # Search if search_query: search_results = Page.objects.filter(locale_id=active_lang.id, live=True).search(search_query) # To log this query for use with the "Promoted search results" module: # query = Query.get(search_query) # query.add_hit() else: search_results = Page.objects.none() # Pagination paginator = Paginator(search_results, 10) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return TemplateResponse( request, "search/search_page.html", { "search_query": search_query, "search_results": search_results, }, ) My layout.html file: {% block content %} {% …