Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i change translation values in Django wagtail?
How can I change some of the translations in wagtail which I don't like (or add new ones)? My first attempt was to change values in the wagtail/locale/{language-code}/django.po files, then to recompile them in .mo files, hoping to change translations, but this didn't work. Image -
Django library upload
not taking the created module and shows error enter image description here I am creating a website through django but when i tried to push data in the database it shows error in taking the module. And when i changed the name in module then it shows duplicate names mot allowed. enter image description here Github Repo link: https://github.com/Prakhar2706/Django_first_project -
Python and Django: How do I dynamically create a dynamic URL with employee ID
I have a specific template that can filter an activity logs of an Employee. This is my view: @login_required def activity_filter(request, buyer_id): """Returns activities based on the filter options sent by an (AJAX) POST.""" template_name = 'buyer/activity/activities.html' activities = _compile_activities(request.user.cached_buyer, request.user.cached_buyer_role.privacy_filter) year_range = list(range(activities[0].date_created.year, activities[len(activities) - 1].date_created.year - 1, -1)) form = _ActivitiesFilterForm( buyer_id=buyer_id, data=request.POST, user_choices=_compile_activity_users(activities), from_date=activities[len(activities) - 1].date_created, to_date=activities[0].date_created, from_to_year_range=year_range, ) if not form.is_valid(): _logger.debug("Filter validation errors: %r", form.errors) return render(request, template_name, status=400) query_params = getattr(request, request.method) # either the request.GET or request.POST dict from_date = query_params.get('from_date', None) if from_date: from_date = datetime.combine(from_date, datetime.min.time()) # first second of the day activities = activities.filter(date_created__gte=from_date) to_date = query_params.get('to_date', None) if to_date: to_date = datetime.combine(to_date, datetime.max.time()) # last second of the day activities = activities.filter(date_created__lte=to_date) selected_users = query_params.getlist('users', None) if selected_users: user_role_ids, user_role_types = _get_selected_user_role_details(selected_users) if user_role_types and user_role_ids: activities = activities.filter(user_role_type__in=user_role_types).filter(user_role_id__in=user_role_ids) if ( query_params.getlist('users') ): print("===selected_users===\n", query_params, "\n===selected_users===\n") context = { 'activities': activities[:MAX_NO_OF_ACTIVITIES], 'activities_search_form': form, } if is_ajax(request): return render(request, 'buyer/activity/activities_table.html', context) return render(request, template_name, context) <a href="{% url 'buyer:activity' employee.buyer_id %}"> {% svg_icon "Activity" "w-6 h-6 dui-stroke-primary" None "Latest Activity" %} </a> But I need this icon(URL) <a> tag once clicked it will redirect and automatically filtered on my Latest … -
NotFittedError at /classify/ Vocabulary not fitted or provided
I am trying to build a spam classifier. However, when sending a POST request, I am getting the error "NotFittedError: Vocabulary not fitted or provided". How can I solve this issue? My POST request looks: { "email":"Get free v-bucks. For that click on link https:/rk%jgqk@$bjg&kjraekj/youRickRolledXD" } Here my code in models.py file nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') nltk.download('punkt') try: wordnet.ensure_loaded() except LookupError: nltk.download('wordnet') class LogisticRegression(nn.Module): def __init__(self): super(LogisticRegression, self).__init__() self.linear1 = nn.Linear(10000, 100) self.linear2 = nn.Linear(100, 10) self.linear3 = nn.Linear(10, 2) def forward(self, x): x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x def classify_spam(message): model = LogisticRegression() model.load_state_dict(torch.load('W:/SpamOrHamProject/SpamOrHamBack/api/AIModel/SpamClassification.pth')) model.eval() cv = CountVectorizer(max_features=10000, stop_words='english') processed_message = preprocess_message(message) vectorized_message = cv.transform([processed_message]).toarray() with torch.no_grad(): tensor_message = Variable(torch.from_numpy(vectorized_message)).float() output = model(tensor_message) _, predicted_label = torch.max(output, 1) return 'Spam' if predicted_label.items() == 1 else 'Not Spam' def preprocess_message(message): remove_non_alphabets = lambda x: re.sub(r'[^a-zA-Z]', ' ', x) tokenize = lambda x: word_tokenize(x) ps = PorterStemmer() stem = lambda w: [ps.stem(x) for x in w] lemmatizer = WordNetLemmatizer() leammtizer = lambda x: [lemmatizer.lemmatize(word) for word in x] processed_message = remove_non_alphabets(message) processed_message = tokenize(processed_message) processed_message = stem(processed_message) processed_message = leammtizer(processed_message) processed_message = ' '.join(processed_message) return processed_message And there code for my trained model: nltk.download("wordnet", "W:/SpamOrHamProject/SpamOrHamModel/nltk_data") os.listdir(r"W:/SpamOrHamProject/SpamOrHamModel/input/") data = … -
Django threading behind IIS and wfastcgi
I have a Django application that executes a lengthy task, that is controlled by Ajax on one of the app's pages. The first Ajax call creates an entry in a task table in the db, and then creates a thread that executes that task, by calling a Java app via Py4J. This sends a command to a legacy server and then regularly queries it for status and updates the task table until the task is complete. The code is as follows: # Get a PyFJ command def getMCLCmd(): gateway = JavaGateway() try: cmd = gateway.entry_point.getMCLCmd() return cmd except Py4JNetworkError as e: # maybe server not started logger.info('Py4J not started, starting it') pyserver = py4JVM() pyserver.start() # try again try: cmd = gateway.entry_point.getMCLCmd() return cmd except Py4JNetworkError as e: logger.debug('Py4J error' + e) return None class py4JVM(threading.Thread): def __init__(self): threading.Thread.__init__(self, daemon=True) self.error = None def run(self): try: process = subprocess.run(MCL_CMD, shell=True, check=True, stdout=subprocess.PIPE, universal_newlines=True) output = process.stdout logger.info(f'Py4J output: {output}') except subprocess.CalledProcessError as e: self.error = f"command return with error (code {e.returncode}): {e.output}" logger.error(self.error) # the thread class class FirstInitThread(threading.Thread): def __init__(self, task: ClientTask): self.task = task threading.Thread.__init__(self) def run(self): cmd = getMCLCmd() if cmd is None: self.task.status = 0 self.task.status_msg … -
Why is my Bootstrap checkbox always checked?
I'm using django-bootstrap for my Django project. A user of the website can create/update his posts, where one of the fields is Boolean field(is_public). The problem is, even when the user saved Boolean field as False, when he enters the update page the checkbox is checked. I first thought the data is not properly saved or passed to template, but it turns out it's not the case. Nothing is wrong with the backend logic. I checked this in my template. {{form.is_public}} Can be public. {{form.is_public.value}} <!-- Gives "False" which is correct --> So to wrap up, the value is passed correctly, but the checkbox is always checked by default. How do I solve this problem? -
Django SQLITE database showing wrong column names
from django.db import models class Players(models.Model): name = models.TextField() role = models.TextField(default="role") salary = models.DecimalField(decimal_places=2,max_digits=4) team = models.TextField() Actual CSV FILE SQLITE Table created on Django I am importing a csv file into a SQLITE table on Django, which I have attached below. This is the code I have written in the models.py fil to create the table. However, the SQLITE table created (attached below) has the column names in the wrong order. -
Django showing incorrect url but displaying the correct content
I am having an issue with some Django code; I have a form at mysite/edit_home, which updates some content which will be displayed on the index page at the root of mysite/. When the form correctly submits, it renders the index template, and all content is correctly displayed, but the url does not change, and instead shows /mysite/edit_home still despite showing a different page. I'm wondering if there's any reason why this will not change? I have tried to remove as much information from the below as it is a pretty large site already so don't want to clutter the issue. There are no issues other than this across all the other pages and databasing, etc, and this issue only is showing the wrong url and does not affect the content of the page. Thanks for all the help. I have tried most combinations of changing urls files, and changing the method of rendering, ie using a reverse etc but it won't say anything besides /mysite/edit_home rather than /mysite/ or /. Below is the code: mysite/project/urls.py urlpatterns = [ path('mysite/', include('mysite.urls')), path('admin/', admin.site.urls), path('', views.index, name='index') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) mysite/urls.py from django.urls import path ... app_name = 'mysite' urlpatterns … -
countdown timer Django
need to implement a timer with the following idea: the user has a form to submit their data to the Answer database, which is handled by the QuizTake class. This class contains views that perform various functions such as validation, user authentication, data submission to the server, and data saving. The functionality you want to implement is as follows: create a countdown function where, while the timer is running, the answer submission form is enabled and the user can use it. When the timer expires, the form saves its content and forcefully saves it to the Answer database, and input into the form is no longer accessible. How can this be implemented? view class QuizTake(FormView): form_class = QuestionForm template_name = 'cansole/question.html' result_template_name = 'result.html' single_complete_template_name = 'single_complete.html' timer_duration = 3600 def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied self.logged_in_user = self.request.user.is_authenticated if self.logged_in_user: self.sitting = Sitting.objects.user_sitting(request.user, self.quiz) else: self.sitting = self.anon_load_sitting() ##сделать редирект на логин if self.sitting is False: return render(request, self.single_complete_template_name) self.start_time = datetime.now() self.timer_expired = False return super().dispatch(request, *args, **kwargs) def check_timer_expired(self): elapsed_time = (datetime.now() - self.start_time).total_seconds() return elapsed_time >= self.timer_duration def get_form(self, *args, **kwargs): if self.logged_in_user: self.question = self.sitting.get_first_question() … -
<a> tag concatonates current url to href value in django
Im building an app where users can enter their twitter, fb and ig account links to their profiles. After they have submitted these urls to the profile form my django app save them to db and later on these values should be populated in the profile page as tags as such. <div class="gap-3 mt-3 icons d-flex flex-row justify-content-center align-items-center"> {% if object.twitter_link %} <a href="{{ object.twitter_link }}"><span><i class="fa fa-twitter"></i></span></a> {% endif %} {% if object.fb_link %} <a href="{{ object.fb_link }}"><span><i class="fa fa-facebook-f"></i></span></a> {% endif %} {% if object.ig_link %} <a href="{{ object.ig_link }}"><span><i class="fa fa-instagram"></i></span></a> {% endif %} </div> I noticed that the tag values are not the same as in the href attribute. For example these are the actual values of the href attribute and the corresponding tag values. {{ object.twitter_link }} = 'weeeee' --> https://currentpageurl.com/weeeee {{ object.fb_link }} = 'www.facebook.com' --> https://currentpageurl.com/www.facebook.com {{ object.ig_link }} = 'https://www.instagram.com/instagram/' --> https://www.instagram.com/instagram/ The tag generated the value that is inside href attribute only in case when the link had an https prefix. In all other cases it concatenated the current page url with the value inside the href attribute. How can I avoid this behaviour and make the tag show only … -
Django test cases: Not able to call execute function from GraphQL Client
i am creating test cases to validate graphql api calls using graphene-django library and while trying to execute query i am getting Client obj has no attr execute where as the dir method is showing execute method, i am very confused any help is much appreciated: here is what i have tried: from django.test import TestCase from graphene.test import Client from app.graphql.schema import schema from app.graphql.tests import constants def generate_token(user): from app.serializers import TwoFactorAuthenticationSerializer return TwoFactorAuthenticationSerializer().get_token(user).access_token class AssetGraphQLTestCase(TestCase): client = Client(schema) print("outside------------------", type(client)) print("outside------------------", dir(client)) @classmethod def setUpTestData(cls): print("Setting up test data-------------------------------") cls.client = Client(schema) cls.user = constants.TEST_USER cls.organization = constants.TEST_ORGANIZATION cls.asset_1 = constants.TEST_ASSET_1 cls.headers = { "Content-Type": "application/json", "HTTP_AUTHORIZATION":generate_token(cls.user) } print("--------------------------------",type(cls.client)) print("--------------------------------",dir(cls.client)) def test_all_asset(self): print("Testing-------------------------------------------") response_data = self.client.execute(query=constants.GRAPHQL_ASSET_QUERY, varaibles=constants.QUERY_VARIABLES, headers=self.headers) print(response_data) print(response_data['data']) self.assertEqual(response_data.status_code, 200) self.assertEqual(response_data['data'], 'Expected value')` here is the output: Setting up test data------------------------------- -------------------------------- <class 'graphene.test.Client'> -------------------------------- ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'execute', 'execute_async', 'execute_options', 'format_error', 'format_result', 'schema'] Testing------------------------------------------- E ====================================================================== ERROR: test_all_asset (app.graphql.tests.test_assets_graphql_fix.AssetGraphQLTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/graphql/tests/test_assets_graphql_fix.py", line 41, in test_all_asset response_data = self.client.execute(query=constants.GRAPHQL_ASSET_QUERY, varaibles=constants.QUERY_VARIABLES, headers=self.headers) AttributeError: 'Client' object has no … -
User creation using the microsoft MSAL lib
when I am using the MSAL lib and giving all the parameters that are required , i have created some users in the tenant and when i am trying to access the same users then there is a issue it throws a error as selected user does not exsit in the tenenat , but in acutal the user exists in that tenant please help me out this is my code <!DOCTYPE html> <html> <head> <title>Azure AD B2C Authentication</title> <script src="https://cdn.jsdelivr.net/npm/msal@1.4.4/dist/msal.min.js"></script> </head> <body> <h1>Azure AD B2C Authentication</h1> <button onclick="login()">Login</button> <button onclick="logout()">Logout</button> <script> // MSAL client configuration const msalConfig = { auth: { clientId: **** authority:********, redirectUri: '*****/', }, }; const msalClient = new Msal.UserAgentApplication(msalConfig); // Login function function login() { msalClient.loginPopup() .then(response => { // Login successful console.log('Login successful'); console.log(response); }) .catch(error => { // Login failed console.error('Login failed'); console.error(error); }); } // Logout function function logout() { msalClient.logout(); } // Handle redirect callback msalClient.handleRedirectCallback((error, response) => { if (error) { console.error('Redirect callback error'); console.error(error); } else { // Access token and user information available in the response const accessToken = response.accessToken; const user = response.account; // Use the access token for authenticated API calls or other operations console.log('Redirect callback successful'); … -
Face recognition with django
import os, sys import cv2 import numpy as np import math import face_recognition # Helper class FaceRecognition: face_locations = [] face_encodings = [] face_names = [] known_face_encodings = [] known_face_names = [] process_current_frame = True recognized=" " detected =" " def __init__(self): self.encode_faces() @staticmethod def calculate_confidence(face_distance, face_match_threshold=0.6): range = (1.0 - face_match_threshold) linear_val = (1.0 - face_distance) / (range * 2.0) if face_distance > face_match_threshold: return str(round(linear_val * 100, 2)) + '%' else: value = (linear_val + ((1.0 - linear_val) * math.pow((linear_val - 0.5) * 2, 0.2))) * 100 return str(round(value, 2)) + '%' def encode_faces(self): for image in os.listdir('/home/wissal/stage/smart_authentication_dashboard/dashboard/faces'): face_image = face_recognition.load_image_file(f"/home/wissal/stage/smart_authentication_dashboard/dashboard/faces/{image}") face_encodings = face_recognition.face_encodings(face_image) if len(face_encodings) > 0: face_encoding = face_encodings[0] self.known_face_encodings.append(face_encoding) self.known_face_names.append(image) else: print(f"No faces found in image {image}") print(self.known_face_names) def run_recognition(self): # Get a reference to webcam #0 (the default one) video_capture = cv2.VideoCapture(0) while True: ret, frame = video_capture.read() # Only process every other frame of video to save time if self.process_current_frame: # Resize frame of video to 1/4 size for faster face recognition processing small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_small_frame = small_frame[:, :, ::-1] # Find … -
"June 8 2023, 02:00 pm" change to "8 June 2023, 14:00"
please help me figure this out. I made a project on django on Windows OS, transferred it to debian server, everything works, but there is a problem with displaying the date: I use updated_at = models.DateTimeField(auto_now=True), on Windows OS it is displayed as: 8 June 2023, 14:00, but on debian for some reason it is displayed as: June 8 2023, 02:00 pm. What could be the problem? How to fix? -
How to remove trailing slash in the URL for API created using Django Rest Framework
I have created a django web-app and created rest apis for the same. Here is the project structure main_project | |___api | |___product this is the urls.py in the main_project. urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/", include("api.urls")) ] There is urls.py inside the api folder like this urlpatterns = [ path("product/", include("api.product.urls"))] Now inside the product folder I have created a urls.py file urlpatterns = [ path("<str:id>", ProductView.as_view(), name="product") ] Now when I run these apis on Postman I do get a trailing slash and the urls look like this localhost:8000/api/v1/product/xyz123 also when I have to query something the urls look like this localhost:8000/api/v1/product/?sorting_field_name = product_name/ Now as per the convention this is an incorrect way of naming urls, I want to remove those unnecessary trailing slashes. How do I solve this? -
Connection Error While Synchronizing Permission for Keycloak Realm in Django
When I try to synchronize permission for a realm from Keycloak in Django, I got the following error. Ayone knows the way of it? -
Why can't I use inspectdb command with terms table in Django project?
I'm trying to create a model for terms table in models.py file using inspectdb command in Django project. The terms table contains information about students and their GPA for three grades. I'm using Oracle 18 database and Django 3.2. When I try to execute this command: python3 manage.py inspectdb terms > models.py I get this message: Unable to inspect table 'terms' The error was: 'STU_ID' I don't know what is the error with STU_ID column, it exists in the database and has a valid data type and constraints. I tried to use --exclude option to exclude the column from inspection, but it didn't work. I got this message: manage.py inspectdb: error: unrecognized arguments: --exclude I also tried to use --table-filter option to inspect only terms table, but it also didn't work. I got the same message: manage.py inspectdb: error: unrecognized arguments: --table-filter I don't understand why these options are not available in Django 3.2, they are mentioned in the official documentation. Is there a solution for this problem? How can I create a model for terms table in models.py file? Thank you. -
Docker compose up -d can not see new files
I'm using docker compose to up my django app on server And for some reason if i using git pull to get new files from github command up -d can not see new files I need to use up -d --build but i dont want to build docker everytime when i update my app Thats what im using docker-compose down --remove-orphans git pull docker-compose -f docker.compose.yml up -d This is only way this works docker-compose -f docker.compose.yml up -d --build I'm using django and nginx -
script not working as expected in django_elastic_dsl,
model shop class Shop(models.Model): name = models.CharField(max_length=100) lat = models.DecimalField( null=True, blank=True, decimal_places=15, max_digits=19, default=0 ) long = models.DecimalField( null=True, blank=True, decimal_places=15, max_digits=19, default=0 ) radius = models.FloatField(default=5) address = models.CharField(max_length=100) city = models.CharField(max_length=50) @property def location_field_indexing(self): return { "lat": self.lat, "lon": self.long, } document @registry.register_document class ShopDocument(Document): location = fields.GeoPointField(attr="location_field_indexing") id = fields.TextField(attr="id") name = fields.TextField(attr="name") radius = fields.FloatField(attr="radius") class Index: name = "shops" settings = {"number_of_shards": 1, "number_of_replicas": 0} class Meta: # parallel_indexing = True # queryset_pagination = 50exit fields = ["id", "name"] class Django: model = Shop my lookup lat = 10.943198385746596 lon = 76.66936405971812 distance = 1 shops = ( ShopDocument.search() .filter( Q( "script_score", query={"match_all": {}}, script={ "source": """ def distance = doc['location'].arcDistance(params.lat, params.lon); def radius = doc['radius'].value; def total_distance = params.dis.value + radius; if (distance <= total_distance) { return distance; } else { return 0; } """, "params": { "lat": lat, "lon": lon, "dis": { "value": distance }, }, }, ) ) .sort( { "_geo_distance": { "location": { "lat": lat, "lon": lon, }, "order": "asc", "unit": "km", "distance_type": "plane", } } ) .extra(size=10, from_=0) ) my requirement: get the shops list from the Elastic document that does not fare more than the value of the … -
Uncaught TypeError: Cannot read properties of undefined (reading 'install')
What does this error mean and why does it sometimes happen? VM3327 vue.esm.js:5829 Uncaught TypeError: Cannot read properties of undefined (reading 'install') at Vue.use (VM3327 vue.esm.js:5829:31) at eval (VM3493 index.js:10:45) at ./src/router/index.js (VM3317 chat.js:173:1) at webpack_require (VM3317 chat.js:1973:42) at eval (VM3326 main.js:5:65) at ./src/main.js (VM3317 chat.js:162:1) at webpack_require (VM3317 chat.js:1973:42) at VM3317 chat.js:2037:37 at VM3317 chat.js:2039:12 Vue.use @ VM3327 vue.esm.js:5829 eval @ VM3493 index.js:10 ./src/router/index.js @ VM3317 chat.js:173 webpack_require @ VM3317 chat.js:1973 eval @ VM3326 main.js:5 ./src/main.js @ VM3317 chat.js:162 webpack_require @ VM3317 chat.js:1973 (anonymous) @ VM3317 chat.js:2037 (anonymous) @ VM3317 chat.js:2039 I'm using vuejs in a django project. package.json { "name": "vue-chat-app-two", "version": "0.1.0", "private": true, "description": "## Project setup ``` yarn install ```", "author": "", "scripts": { "serve": "vue-cli-service serve", "build": "webpack --mode production", "lint": "vue-cli-service lint", "dev": "webpack-dev-server --mode development --hot", "start": "concurrently \"python3 manage.py runserver\" \"npm run dev\"" }, "main": "babel.config.js", "dependencies": { "axios": "^1.4.0", "core-js": "^3.30.2", "vue": "^3.3.4", "vue-native-websocket": "^2.0.15", "vue-router": "^4.2.2", "vue-scrollto": "^2.20.0" }, "devDependencies": { "@babel/core": "^7.22.1", "@babel/eslint-parser": "^7.21.8", "@babel/preset-env": "^7.22.4", "@vue/cli-plugin-babel": "~5.0.0", "@vue/cli-plugin-eslint": "~5.0.0", "@vue/cli-service": "~5.0.0", "babel-loader": "^9.1.2", "concurrently": "^8.1.0", "css-loader": "^6.8.1", "eslint": "^7.32.0", "eslint-plugin-vue": "^8.7.1", "file-loader": "^6.2.0", "sass": "^1.63.2", "sass-loader": "^10.4.1", "style-loader": "^3.3.3", "vue-cli-plugin-vuetify": "~2.5.8", "vue-loader": "^15.10.1", "vue-template-compiler": "^2.7.14", "webpack": "^5.86.0", … -
Error while install MySQLClient package cPanel terminal please
((project:3.8)) [shriyamc@callisto project]$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [40 lines of output] mysql_config --version ['10.5.20'] mysql_config --libs ['-L/usr/lib64', '-lmariadb', '-pthread', '-ldl', '-lm', '-lpthread', '-lssl', '-lcrypto', '-lz'] mysql_config --cflags ['-I/usr/include/mysql', '-I/usr/include/mysql/..'] ext_options: library_dirs: ['/usr/lib64'] libraries: ['mariadb', 'dl', 'm', 'pthread'] extra_compile_args: ['-std=c99'] extra_link_args: ['-pthread'] include_dirs: ['/usr/include/mysql', '/usr/include/mysql/..'] extra_objects: [] define_macros: [('version_info', "(2,1,1,'final',0)"), ('version', '2.1.1')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-38 creating build/lib.linux-x86_64-cpython-38/MySQLdb copying MySQLdb/init.py -> build/lib.linux-x86_64-cpython-38/MySQLdb copying MySQLdb/exceptions.py -> build/lib.linux-x86_64-cpython-38/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-cpython-38/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-cpython-38/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-cpython-38/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-cpython-38/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-cpython-38/MySQLdb creating build/lib.linux-x86_64-cpython-38/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.linux-x86_64-cpython-38/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-cpython-38/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-cpython-38/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-cpython-38/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-cpython-38/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-cpython-38/MySQLdb/constants running build_ext building 'MySQLdb.mysql' extension creating build/temp.linux-x86_64-cpython-38 creating build/temp.linux-x86_64-cpython-38/MySQLdb gcc -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE -fPIC -fwrapv -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE … -
AttributeError: 'NoneType' object has no attribute '_meta' for inner import
I try to code a unit test for a method: def my_method(): from path import MyModel items = MyModel.filter(some_functionality) return self.annotate(items).some_more_functionality When I try to call my_method from unit test, I get the following error: AttributeError: 'NoneType' object has no attribute '_meta' I know that this is related with importing MyModel within the method. But I'm not able to refactor that method at this point, it's very risky. I can only develop unit tests. How can I go around this problem? -
ASGI development server is not starting in django app
Issue: ASGI Server Not Starting I'm experiencing a problem with my ASGI server not starting properly. I've checked my code and configuration, but I can't seem to figure out the issue. Here are the relevant files: I have channels==4.0.0 channels-redis==4.1.0 charset-normalizer==3.1.0 colorama==0.4.6 constantly==15.1.0 cryptography==41.0.1 daphne==3.0.2 Django==4.2.2 asgi.py: import os from django.core.asgi import get_asgi_application from channels import URLRouter, ProtocolTypeRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack from .routing import ws_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") application = ProtocolTypeRouter( { "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(ws_application)) ) } ) routing.py: from django.urls import path from channels.routing import URLRouter from WS.consumers import ( CodeConsumer, WhiteboardConsumer, ChatConsumer, ) ws_application = URLRouter( [ path("ws/code/", CodeConsumer.as_asgi()), path("ws/whiteboard/", WhiteboardConsumer.as_asgi()), path("ws/chat/", ChatConsumer.as_asgi()), ] ) settings.py: # Relevant settings configuration... ASGI_APPLICATION = "core.routing.ws_application" I've ensured that the necessary packages (aioredis, asgiref, etc.) are installed. However, when I try to start the ASGI server, it fails to start without any error messages. Thank you! I expect the ASGI server to start successfully without any errors or exceptions. Upon starting the server, I should see output indicating that the server is running and ready to accept WebSocket connections. I should be able to establish WebSocket connections to the specified endpoints (/ws/code/, /ws/whiteboard/, /ws/chat/) and interact with … -
How to break the loop in if statement in django template?
Following is the code, {% if question.custom_user != user %} {% if question.flagged_user.exists %} {% for flagged_user in question.flagged_user.all %} {% if flagged_user == user %} <span style="border: 2px solid #00000012;padding-left: 15px;padding-right: 15px;background-color: red; color: grey;" onclick="flag(this.querySelector('i'), event);">Flag <i id="{{question.id}}" class="fa fa-flag" aria-hidden="true"></i></span> {% else %} <span style="border: 2px solid #00000012;padding-left: 15px;padding-right: 15px;background-color: beige;" onclick="flag(this.querySelector('i'), event);">Flag <i id="{{question.id}}" class="fa fa-flag" aria-hidden="true"></i></span> {% endif %} {% endfor %} {% else %} <span style="border: 2px solid #00000012;padding-left: 15px;padding-right: 15px;background-color: beige;" onclick="flag(this.querySelector('i'), event);">Flag <i id="{{question.id}}" class="fa fa-flag" aria-hidden="true"></i></span> {% endif %} {% endif %} I want to stop executing else statement when the if statement is already executed! Thanks. -
Django Keycloak Integration
I am trying to integrate Keycloak (single sign on) in Django framework. There are couple of packages I found online, however, none of them are working as per the expectation. Is there any documentation or example source codes from which I can get the help? Thanks in advance.