Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Why is my like function not working for my django code?
I'm currently doing the CS50 week 4 network problem and I keep having issue with my 'like' and 'unlike' button. It refuses to change even though I click and refresh it multiple times. I've been at it for days and cant seem to figure out what is wrong. Here is my code. Like handler function: function likeHandler(id, whoYouLiked){ if(whoYouLiked.index0f(id) >= 0){ var liked = true; } else { var liked = false; } if(liked === true){ fetch(`/remove_like/${id}`) .then(response => response.json) .then(result => { console.log(result) }) } else{`your text` fetch(`/add_like/${id}`) .then(response => response.json) .then( result => { console.log(result) }) } } Btn for liking in index: {% if post.id in whoYouLiked %} <button class = "btn btn-info fa fa-thumbs-down col-1" onclick="likeHandler({{ post.id }}), {{ whoYouLiked }}" id="{{ post.id }}" ></button> {% else %} button class = "btn btn-info fa fa-thumbs-up col-1" onclick="likeHandler({{ post.id }}), {{ whoYouLiked }}" id="{{ post.id }}" ></button> {% endif %} Like function in my views as well as my URL: def remove_like(request, post_id): post = Post.objects.get(pk=post_id) user = User.objects.get(pk=request.user.id) like = Like.objects.filter(user=user, post=post) like.delete() return JsonResponse({"message": "Like removed!"}) def add_like(request, post_id): post = Post.objects.get(pk=post_id) user = User.objects.get(pk=request.user.id) newLike = Like(user=user, post=post) newLike.save() return JsonResponse({"message": "Like added!"}) Please … -
user = authenticate(request,username=username) returns 'None'
I'm currently working on a Django app in which I'm trying to make a login page. I have used a custom db to store the input into. I have successfully been able to make a signup page, but for some reason I cant authenticate the user every time I try to login. the authenticate function returns None as a return every time and I don't know where I have made a mistake. There are many similar topics like this and I have searched most of them. they didn't seem to solve my problem. Here's my code: views.py def signin(request): if request.method == "POST": username = request.POST["username"] pass1 = request.POST["pass1"] token = ld.login_user(username, pass1)# This is a custom login function which i made for my db. This returns a token which i havent made a use of yet if User.is_active==False: messages.error(request, "User Inactive!") return redirect("home") user = authenticate(request,username=username) if user is not None : login(request,user) fname = user.first_name return render(request, "authentication/index.html", {"fname": fname}) else: messages.error(request, "Bad credentials!") return redirect("home") return render(request, "authentication/signin.html") models.py I don't know if this is a necessary piece of code. I just put it in in case if its necessary @staticmethod def login_user(username, password): """Authenticate a user … -
How to use ccextractor in a django website to extract subtitles in windows
I am unable to make ccextractor work with django website and if I do it how I will able to deploy the website while ccextractor work locally . I think I am missing something critical, anyone know about this or can suggest any docs . I am expecting to extract subtiles and not know how to do it. -
Django Model Validation: How to validate a model field based on the field value of an instance of a different model?
Background: I have a model Bid that implements "bids" on a specific instance of a Listing model. When a Bid is created, the current_bid field is set through a ModelForm and I want to validate that the current_bid field set via the ModelFormfor that Bid is greater than the current_bid field previously set for the Listing instance the Bid is being created for. For reference, here are the two models I have created in Models.py: from django.conf import settings from django.contrib.auth.models import AbstractUser from django.db import models from django.core.validators import MinValueValidator, DecimalValidator from decimal import Decimal from django.core.exceptions import ValidationError class User(AbstractUser): pass class Listing(models.Model): CATEGORY_CHOICES = [ ("APPAREL", "Apparel"), ("COLLECTIBLES", "Collectibles"), ("COMICS", "Comics"), ("MEMORABILIA", "Sports Memorabilia"), ("SNEAKERS", "Sneakers"), ("TRADING_CARDS", "Trading Cards"), ("OTHER", "Other") ] CONDITION_CHOICES = [ ("BRAND_NEW", "Brand New"), ("NEW_DEFECTS", "New with Defects"), ("LIKE_NEW", "Like New"), ("Good", "Good"), ("LIGHTLY_USED", "Lightly Used"), ("USED", "Used"), ("POOR", "Poor") ] author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="usernames") title = models.CharField(max_length=80) description = models.CharField(max_length=800) starting_bid = models.DecimalField(max_digits=11, decimal_places=2,validators=[MinValueValidator(Decimal('0.00'))]) current_bid = models.DecimalField(default=0, max_digits=11, decimal_places=2,validators=[MinValueValidator(Decimal('0.00'))]) image = models.URLField(blank=True) category = models.CharField(max_length=40, choices=CATEGORY_CHOICES, blank=True) condition = models.CharField(max_length=40, choices=CONDITION_CHOICES, default="Brand New") def __str__(self): return f"{self.title}" class Bid(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="owners") listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listings") current_bid = … -
My question is about bootstrap responsive grid system
Suppose i have two columns in a row each of them are col-6 in left side i have text and the right side i have an image i gave the text-end class to the 2nd column i want to change the class from text-end to text-center in the md , sm screen how to do that ? can anyone guide me ? i just want to use the bootstrap not the custom class of css and make it to the center through media query ? i have used media query to do my task but i just want the bootstrap class to do it without any type of custom css i am expecting that i will get my answer from this platform .. thanks -
Django - want to use inspectdb to get only one table. Using MS SQL Server
I've been testing the inspectdb with django 4.0. If I do "python manage.py inspectdb --database MSDatabase", it tries to bring all table info into the model. Is there a way to select only few or one tables? The DB server is MS SQL Server. The database is MSDatabase, the schema is MySchema, and the table name is MYTBL. I tried "python manage.py inspectdb --database MSDatabase MYTBL" and got the table not found error.