Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest api and axios post request don't work
I am trying to make a simple api where a user writes something in an input, presses a button and a new instance is added in a database. To do this I am using react and django rest framework. App.js const [name,setName] = useState('') const handleChange = (e) => { setName(e.target.value) } function handleClick(e) { e.preventDefault() axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" axios.post('http://127.0.0.1:8000/post/', { headers: { "Content-Type": "application/x-www-form-urlencoded", 'X-CSRFToken': 'csrftoken' }, data:{ title: name, name: name } }) } return ( <> <form> <input type='text' value={name} onChange={handleChange} /> <button onClick={handleClick}>OK</button> </form> </> ); views.py @api_view(['POST']) def home2(request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) urls.py from django.urls import path from . import views urlpatterns = [ path('api/',views.home,name='home'), path('post/',views.home2,name='home2'), path('a/',views.home3,name='home3') ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'main', 'corsheaders' ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True But when I press the button I get manifest.json:1 GET http://127.0.0.1:8000/manifest.json 404 (Not Found) and manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. in javascript. In django I get "POST /post/ HTTP/1.1" 200 0 Also I am using npm run build for javascript and manifest.json is in public folder. React is inside django and the structure looks like this: … -
csrftoken is null in React-rendered form
I am using purely React for the frontend, with Django on the backend. I am using React to render a form & not using the Django form. I am currently unable to make a POST request from my React front end (http://localhost:3001/) to my Django backend (http://127.0.0.1:8000) because of the Forbidden (CSRF cookie not set.): /createListing error. This is what my POST request code looks like async function createListing(listing) { let csrftoken = getCookie('csrftoken'); const response = await fetch( "http://127.0.0.1:8000/createListing/", { method: "POST", body: JSON.stringify(listing), headers: { "Content-Type": "application/json", "X-CSRFToken": csrftoken }, } ); const data = await response.json(); return data; } // The following function are copying from // https://docs.djangoproject.com/en/dev/ref/csrf/#ajax function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } I got this snippet from a SO answer. This is my Django API endpoint def createListing(request): # Creating a new Listing must be via … -
"empty_value_display" doesn't work for an empty value on "change list" page in Django Admin
I defined name field which accepts an empty string in Person model as shown below: # "models.py" class Person(models.Model): name = models.CharField(max_length=20, blank=True) def __str__(self): return self.name Then, I set "-empty-" to AdminSite.empty_value_display, ModelAdmin.empty_value_display, @admin.display()'s empty_value or view_name.empty_value_display as shown below: # "admin.py" admin.site.empty_value_display = "-empty-" # Or @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ("view_name",) empty_value_display = "-empty-" # Or @admin.display(empty_value="-empty-") # Or def view_name(self, obj): return obj.name view_name.empty_value_display = '-empty-' # Or But, -empty- is not shown even though I saved an empty string as shown below: So, how can I show -empty- when I save an empty string? -
Host the django on https in ec2 for production with a free SSL certificate for it. Without a domain
I have a django deployed on aws and i have a frontned react js running on a https endpoint server. The frontend allows only https requests to be made. But when i run the django python manage.py runserver in my "production" of django app on ec2 i only get to use http not https. So, is there any way to get a free SSL certificate for that django app running on ec2 public ip without a domain. -
Template doesn't exist at /users/login while creating a login page using Django
TemplateDoesNotExist at /users/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/users/login/ Django Version: 4.2.2 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: C:\Users\shubh\OneDrive\Desktop\django-app\main-app\env\Lib\site-packages\django\template\loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: C:\Users\shubh\OneDrive\Desktop\django-app\main-app\env\Scripts\python.exe Python Version: 3.11.4 Python Path: ['C:\Users\shubh\OneDrive\Desktop\django-app\main-app\ablog', 'C:\Users\shubh\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\shubh\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\shubh\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\shubh\AppData\Local\Programs\Python\Python311', 'C:\Users\shubh\OneDrive\Desktop\django-app\main-app\env', 'C:\Users\shubh\OneDrive\Desktop\django-app\main-app\env\Lib\site-packages'] Server time: Mon, 19 Jun 2023 15:46:25 +0000 I should be able to get a Login Page I should have gotten a login page but the template file can't be fetched -
why django celery beat worker not relaying expected tasks data
hello everyone i'm trying to perform a task like an APY(annual percentage yield) kind of funtionality, where my user savings will increase by a certain percentage at an interval(monthly or by seconds). my beat scheduler is working but the worker is not returning the expected output in the terminal, nor is it altering the value MODELS.PY def save(self,*args,**kwargs): if self.funds == '' or self.funds is None: self.funds=0 if self.referrer_bonus== '' or self.referrer_bonus is None: self.referrer_bonus=0 if self.total== '' or self.total is None: self.total=0 if self.bonus== '' or self.total is None: self.bonus=0 self.bonus=int(self.referrer_bonus)*15/100 if self.withdrawn == False: # self.total=(int(self.funds)*15/100 * int(self.funds))+self.bonus self.total=int(self.funds)+self.bonus interval=IntervalSchedule.objects.get(every=20,period='seconds') if self.total != 0 and self.funds!=0: PeriodicTask.objects.create( interval=interval, name=f'{self.user.email} investment increment', task='increment_user_funds', start_time=self.timestamp, args=json.dumps([self.total,self.funds]), ) # increment_user_funds(self) super().save(*args,**kwargs) CELERY.PY from __future__ import absolute_import,unicode_literals from celery import Celery import os from celery import shared_task from django.conf import settings from celery.schedules import crontab # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rawfx.settings') app = Celery('rawfx') app.config_from_object('django.conf:settings', namespace='CELERY') # app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.autodiscover_tasks() TASK.PY from __future__ import absolute_import,unicode_literals from celery import Celery from celery import shared_task from rawfx.celery import app @app.task def increment_user_funds(total,funds): total=int(total)+int(funds)*15 print(total) return total below is the picture of both my worker and beat [![beat][2]][2] … -
Django unable to get Environment Variables from Vercel
I am hosting a Django application with Vercel. To help improve the security of the app I attempted establishing the environment variables within Vercel and retrieving them in the settings.py file. The app no longer works, and when I tried to revert the changes and start using the .env file again, the app is still completely down. When Vercel builds the new deployment the entire site is down because Django cannot connect to the db. My code is as follows: #settings.py import os.path import os from django.contrib.messages import constants as messages from pathlib import Path import pymysql DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": os.environ.get('DB_NAME'), "HOST": os.environ.get('DB_HOST'), "PORT": os.environ.get('DB_PORT'), "USER": os.environ.get('DB_USER'), "PASSWORD": os.environ.get('DB_PASSWORD'), "OPTIONS": {'ssl': {'ca': os.environ.get('MYSQL_ATTR_SSL_CA')}} } } #.env/Vercel environment variables DB_NAME=xxxxxx DB_USER=xxxxxxxxxxxxxxx DB_PASSWORD=xxxxxxxxxxxxxxxxxxxxxxxxxx DB_HOST=xxxxxxxxxxxxxxxxxxxxxx DB_PORT=xxxx MYSQL_ATTR_SSL_CA=xxxxxxxxxxxxxxxxxxxxxxx I have no idea why the .env wont even work now as no changes were made to the code other than the removal, then replacement of the .env file. Any direction on this would be greatly appreciated. -
How do I output only the last form submission in for a form. Using React and javascript here. Thank you
Currently, I have a form on a page. I wish to display the latest form submission below the form, but it will display all the form submissions till date. I am wondering how to approach this issue. I have no idea how to approach this issue. I tried several methods, such as using data filter, or using an if else statement to see if the input value is same as the latest logged value. However, I have no idea what to pass in as the argument and I keep getting errors.. Hope I can receive tips on how to tackle this issue. Thank you so much. This is the frontend render of the website This is an example of the backend database. Please let me know if you guys require any extra information. Thank you so much! -
CSRF Token issue in Django app deployed in Railway, "CSRF verification failed. Request aborted."
The error I get is "CSRF verification failed. Request aborted." Error Image The site works fine and there are no issues on localhost I tried adding this base domain in my settings.py but I am still getting the same error: enter image description here I also tried this fix, and reloaded the requirements.txt but to no avail: enter image description here Any help would be appreciated. -
How to change link in Django admin backend "Webseite anzeigen"
I am developing a Django app and using both the admin backend and the developed website, which I refer to as the frontend, for the user. In the admin backend, there is a button "Webseite anzeigen" (Django German version) located at the top right corner. The code for this button is provided by Django. This button leads to the website or the frontend. I want to modify this button but I am not sure where to find it. For example, I want to increase the font size and change the color. -
Django app sending jwt token and refresh token to browser cookie but why my frontend app couldn't verify it?
I am using jwt authentication on my Django app. When user login to my website my server sends jwt token and refresh token to the browser cookie but I am getting "User is not authenticated." error and not getting any profile data for my user_profile/ api endpoint. Even I can see jwt token and refresh token also avaiable on the browser cookie after user login and aslo {withCredentials:true} in my axois post. here is my login code: @api_view(['POST']) def user_login(request): if request.method == 'POST': ...others code refresh = RefreshToken.for_user(user) response = Response({'message': 'Login successful.'}, status=status.HTTP_200_OK) response.set_cookie('jwt_token', str(refresh.access_token)) response.set_cookie('refresh_token', str(refresh)) return response else: return Response({'error': 'Invalid credentials.'}, status=status.HTTP_401_UNAUTHORIZED) here is my api for get user profile @api_view(['GET']) def get_user_profile(request): if request.user.is_anonymous: return Response({'error': 'User is not authenticated.'}, status=status.HTTP_401_UNAUTHORIZED) user = request.user profile = Profile.objects.get(user=user) data = { 'username': user.username, } return Response(data, status=status.HTTP_200_OK) my settings.py REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), } my frontend code: axios.get(`${CustomDomain}/user_profile/`,{withCredentials:true}) .then((res) => { console.log(res); }) .catch((error) => { console.error(error); }); }) ; -
How to show items in dropdown based on alphabet search from Model in Django?
Just like Stackoverflow Tags auto-complete dropdown, I have a model of name Tags which contains 68311 name of Tags and key which contains the first alphabet it starts with. **Note ** : There are few words which starts with dot (.) for example, (.post) in that case, we will consider the second alphabet. class Tags(models.Model): name = models.CharField(max_length=255) key = models.CharField(max_length=1, null=True, default='') def __str__(self): return self.name def save(self, *args, **kwargs): if not self.key: if self.name.startswith('.'): self.key = self.name[1].upper() else: self.key = self.name[0].upper() super().save(*args, **kwargs) class Meta: indexes = [ models.Index(fields=['name']) Following is the view I am using to search the possible words starts with the user specified alphabet. def tag_search(request): search_term = request.GET.get('search', '') print("search_term", search_term) if search_term.startswith('.'): search_term = search_term[1].upper() else: search_term = search_term[0].upper() tags = Tags.objects.filter(name__istartswith=search_term).values_list('name', flat=True) return JsonResponse({'tags': list(tags)}) When I try to input any character from frontend on the auto=-complete dropdown, It executes tag_search only once and provide the words which contains first character that the user provider. What I required is when the user delete the first character and delete and type another one, then it should not show the result of previous written character. For example, I refreshed the page, and in auto-complete … -
Why date from data base dont show on home.html Python Django
The problem is that date from database that i have created doesnt show on my html page and i dont understand what is the problem maybe i connected something wrong models.py from django.db import models class table_1(models.Model): datetime = models.DateField() machine_1 = models.IntegerField() machine_2 = models.IntegerField() dryer = models.IntegerField() machine_1_time = models.TimeField() machine_2_time = models.TimeField() dryer_time = models.TimeField() def __int__(self): return self.title settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'data', 'USER': 'postgres', 'PASSWORD': '1221', 'HOST': 'localhost', 'PORT': '5432', } } home.html <h2>1{{ tablet.machine_1_time }}</h2> {{ mytable.machine_1 }} {% for item in tablet %} <h3>{{ item.datetime }}</h3> <!-- Выведите другие поля модели --> {% endfor %} views.py from django.shortcuts import render from .models import table_1 def home(request): tablet = table_1.objects.all() return render(request, 'table/home.html', {' tablet': tablet}) When i runserver there is no data shown at all machine_data.sql create table machine_dara ( datetime DATE, machine_1 INT, machine_2 INT, dryer INT, machine_1_time INT, machine_2_time INT, dryer_time INT ); insert into machine_dara (datetime, machine_1, machine_2, dryer, machine_1_time, machine_2_time, dryer_time) values ('2022-12-31', 55, 77, 35, 84, 91, 63); insert into machine_dara (datetime, machine_1, machine_2, dryer, machine_1_time, machine_2_time, dryer_time) values ('2023-01-14', 67, 69, 79, 80, 50, 64); insert into machine_dara (datetime, machine_1, machine_2, dryer, … -
Django chunked upload
I have a Django app in which the user can upload a tdms file. When I deploy it, this does not work for large files, which is why I want to implement chunked upload through the django-chunked-upload library. I gave it a go, but I really need help. I get this feedback in my terminal: "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 <QueryDict: {'resumableChunkNumber': ['5'], 'resumableChunkSize': ['1048576'], 'resumableCurrentChunkSize': ['1339055'], 'resumableTotalSize': ['5533359'], 'resumableType': [''], 'resumableIdentifier': ['5533359-VibrationLog_2023-05 -05-084134tdms'], 'resumableFilename': ['Vibration Log_2023-05-05 - 084134.tdms'], 'resumableRelativePath': ['Vibration Log_2023-05-05 - 084134.tdms'], 'resumableTotalChunks': ['5']}> [19/Jun/2023 14:50:44] "POST /tdms/api/chunked_upload/?resumableChunkNumber=5&resumableChunkSize=1048576&resumableCurrentChunkSize=1339055&resumableTotalSize=5533359&resumableType=&resumableIdentifier=5533359-VibrationLog_2023-05-05 -084134tdms&resumableFilename=Vibration%20Log_2023-05-05%20-%20084134.tdms&resumableRelativePath=Vibration%20Log_2023-05-05%20-%20084134.tdms&resumableTotalChunks=5 HTTP/1.1" 302 0 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 <QueryDict: {}> [19/Jun/2023 14:50:44] "POST /tdms/api/chunked_upload_complete/ HTTP/1.1" 302 0 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 which seems okay, but the file does not get saved anywhere. This is my models.py: from django.db import models from nptdms import TdmsFile import json import pytdms from chunked_upload.models import ChunkedUpload # Create your models here. class VibrationLogChunkedUpload(ChunkedUpload): name = models.CharField(max_length=100, blank=True, null=True) notes = models.TextField(blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) data = models.JSONField(blank=True, null=True) sample_frequency = models.FloatField(blank=True, null=True, default=8533.33) tdms_file = models.FileField(upload_to='tdms') … -
Custom submit button's name isn't added to request.POST when I add the record in Django admin
Let's say I have model Record with the approved flag class Record(models.Model): approved = models.BooleanField(default=False) I want to add Save and approve button in Record's admin near the Save button. For that I added new imput tag in the submit_line.html: {% extends 'admin/submit_line.html' %} {% load i18n admin_urls %} {% block submit-row %} {{ block.super }} {% if show_save %} <input type="submit" value="Save & approve" name="_save_and_approve"/> {% endif %} {% endblock %} Now I see this button and _save_and_approve appears in the request.POST when I edit the created record, but this name doesn't exist in the request.POST when I try to add a new one. So, the custom button works only when I edit the record. What I'm doing wrong? I use Django 4.1 P.S. Things I've tried so far: tried overriding the change_form.html with adding change_form_template to admin.Model class tried using both templates: change_form.html and submit_line.html tried adding add_form_template to admin.Model class with relation to change_form.html checked all relateed topics -
Displaying images from an EPUB file along with text using ITEM_DOCUMENT in Python
I'm currently working on a Python project where I need to extract text and images from EPUB files and display them together. I'm using the ITEM_DOCUMENT method from the epublib library to extract the text successfully. However, I'm facing difficulties in extracting and displaying images alongside the text. Here's a simplified version of my code: class PDFtoBookCreateView(CreateView): template_name = 'pdf_viewer.html' model = EBook def get_context_data(self, **kwargs): context={} book = epub.read_epub("H:/Hexcoder/sellzzy/new2_developer02/tshirtbundle/static/epub/9781408855713.epub") epub.EpubBook.get_template = new_get_template epubObj= book.get_items_of_type(ebooklib.ITEM_DOCUMENT) epubObjList= list(epubObj) context['finalTextList'] = [xhtml_to_html(i.content) for i in epubObjList] return context I'm able to retrieve the text content using the ITEM_DOCUMENT method, but I'm unsure how to extract and incorporate the images into the display. I've tried exploring the EPub library's documentation, but I couldn't find specific guidance on this matter. Could someone please provide guidance on how I can extract images from the EPUB file using Python, and integrate them into my display alongside the extracted text? Any example code or pointers to relevant resources would be greatly appreciated. Thank you! -
How can I Mock OpenSearch Client in Django unit test
I'm trying to mock OpenSearch client for writing unit tests for those methods using OpenSearch operations i.e. index, delete, etc. I have tried openmock library's decorator but in git workflow test it couldn't connect to OpenSearch client. -
giving user's ip address and display it in admin.py of a django project
how can i give ip address of users and display it in admin.py of django project? I created view of it but i don't know how to display it in admin panel this is my view function : `def get_ip_address(request): user_ip_address = request.META.get('HTTP_X_FORWARDED_FOR') if user_ip_address: ip = user_ip_address.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def show_ip_address(request): user_ip = get_ip_address(request) return render(request, "output.html", {"user_ip":user_ip})` ...................................................................................................... -
Django App for azure authentication python 3.7
I have a Django web app that runs on Python 3.7 and I want to integrate user authentication with Azure Active Directory in my web app. There is a Django app "django-azure-auth" & "django-azure-auth 1.1.0" but it requires Python >=3.8. Can anyone please suggest to me a Django app that supports Python 3.7? -
how to connect an existing mongdb database which has collection and fields to a website in django frame work
Is there a solution or approach to reuse an existing MongoDB database for a website instead of creating a new one, given that both have the same structure? I want to avoid the hassle of setting up a new database and ensure efficient utilization of resources. The objective is to leverage the existing MongoDB database, which already has the desired structure, for my website. By reusing the database, I can avoid duplicating efforts and maintain consistency in data management. I'm seeking guidance on the logic or code required to accomplish this task. Ideally, I would like to establish a connection to the existing MongoDB database, ensuring that the website can interact with it seamlessly. I want to perform CRUD operations, such as retrieving data, updating records, and executing queries, based on the needs of my website. Furthermore, I need to adapt the retrieved data from the database to suit the requirements of my website. This may involve transforming the data into a format compatible with web pages or other components of the website. Ultimately, I aim to integrate the existing MongoDB database with my website, allowing it to serve as the backend data storage solution. By reusing the database, I … -
How can I create mock a manytomany field for django pytest?
I am trying to create mock data for test in django. I have team model like this: class Team(TimeStampedModel): id: int created: datetime name = models.CharField(max_length=100) members = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="teams", through="Membership" ) And here is the part of test file: class TestTeamListViews: def test_team_list( self, client: Client, mocker, site_admin_user: User, team_with_members: Team ): admin1 = team_with_members.members.get(email="admin1@example.com") mock_teams = [ Team( id=1, name="Test Team", members=admin1, created=datetime.datetime.now(), ) ] This case, I get error: def __set__(self, instance, value): > raise TypeError( "Direct assignment to the %s is prohibited. Use %s.set() instead." % self._get_set_deprecation_msg_params(), ) E TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use members.set() instead. So, I tried class TestTeamListViews: def test_team_list( self, client: Client, mocker, site_admin_user: User, team_with_members: Team ): admin1 = team_with_members.members.get(email="admin1@example.com") mock_teams = [ Team( id=1, name="Test Team", members=Team.members.set(admin1), created=datetime.datetime.now(), ) ] Then, I get error: AttributeError: 'ManyToManyDescriptor' object has no attribute 'set' I googled a lot, but there is no solutions I could found other than using add instead of set. Using add gives same error. Please help me. -
How do i make custom api calls in Ant design's filters/Search in a table columns?
I have a React application where I'm implementing a filter feature for the columns of my table. The goal is to make the search in the back and get an updated datasource that fit the search criteria or filter criteria. However, I'm facing an issue where the API requests continue endlessly, even after implementing a timeout mechanism. here is one of the columns : { title: "Project visibility", dataIndex: "projectVisibility", filters: filterLists.projectVisibilityFilters, onFilter: (value) => { console.log("onfilter method", value); dispatch(setColumnSearchValues("projectVisibility", "filter", value)); if (timeoutId > 500) { clearTimeout(timeoutId); } else { console.log("how many times i am in the else !!"); timeoutId = setTimeout( dispatch( RequestSearchColumns( advancedSearchForm, quickFiltersForm, columnsFiltersForm, currentPage, pageSize ) ), 500 ); } console.log("time taken to reach the back !!", timeoutId); }, onFilterDropdownOpenChange: (visible) => { if (visible) { setTimeout(() => searchInput.current?.select(), 500); } }, render: (value, row, index) => { isUnavailableValue(value); switch (value) { case "Confidential": return ( <div className="custom-width-column w-120"> <div className="blur-layer"></div> <Badge color="red" text={value} /> </div> ); case "Visible": return ( <div className="custom-width-column w-120"> <div className="blur-layer"></div> <Badge color="#52C41A" text={value} /> </div> ); default: if (isUnavailableValue(value)) { return unavailableValue(value); } else { return ( <div className={ row.isConfidential ? "blur-content custom-width-column w-120" : "custom-width-column w-120" }> <div … -
How to not escape a character in a Django ORM?
I use Django, ORM. I don't want the character '%' to be escaped. name='' author='' annotation = 'harry%magic%school' criterion_name = Q(name__contains=cleaned_data['name']) criterion_author = Q(name__contains=cleaned_data['author']) criterion_annotation = Q(name__contains=cleaned_data['annotation']) Book.objects.filter(criterion_name, criterion_author, criterion_annotation) I get '%harry\%magic\%school%': select name, author, annotation from books where name LIKE '%%' AND author LIKE '%%' AND annotation LIKE '%harry\%magic\%school%' I want to get '%harry%magic%school%': select name, author, annotation from books where name LIKE '%%' AND author LIKE '%%' AND annotation LIKE '%harry%magic%school%' How to fix it? -
I am unable to Add to Cart as Anonymous User using session key
I am developing a ecommerce website using Python Django framework. Code is proper and actively working when user login but not working as a guest. I am unable to Add to Cart as Anonymous User using session key. models.py class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) product_qty = models.IntegerField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) session_key = models.CharField(max_length=140, null=True) cart.py from django.http import JsonResponse from django.shortcuts import render, redirect from django.contrib import messages from buyjoi.models import Product, Cart from django.contrib.auth.decorators import login_required def addtocart(request): if request.method == 'POST': if request.user.is_authenticated: prod_id = int(request.POST.get('product_id')) product_check = Product.objects.get(id=prod_id) if (product_check): if (Cart.objects.filter(user=request.user.id, product_id=prod_id)): return JsonResponse({'status': "Product Already in Cart"}) else: prod_qty = int(request.POST.get('product_qty')) if product_check.quantity >= prod_qty: Cart.objects.create( user=request.user, product_id=prod_id, product_qty=prod_qty) return JsonResponse({'status': "Product added successfully"}) else: return JsonResponse({'status': "Only " + str(product_check.quantity) + " quantity available"}) else: return JsonResponse({'status': "No such product found"}) else: request.session['product_id'] prod_id = int(request.POST.get('product_id')) product_check = Product.objects.get(id=prod_id) if (product_check): if (Cart.objects.filter(product_id=prod_id, session_key=request.session.session_key)): return JsonResponse({'status': "Product Already in Cart"}) else: prod_qty = int(request.POST.get('product_qty')) if product_check.quantity >= prod_qty: Cart.objects.create( product_id=prod_id, product_qty=prod_qty, session_key=request.session.session_key) return JsonResponse({'status': "Product added successfully"}) else: return JsonResponse({'status': "Only " + str(product_check.quantity) + " quantity available"}) else: return JsonResponse({'status': "No such product found"}) return redirect("/") def … -
Django and Docker: ModuleNotFoundError: No module named 'widget_tweaks'
I'm trying to use django-widget-tweaks in my web application (using Django and Docker), but it is not being recognized as an installed package. My DockerFile: # Pull base image FROM python:3.10.2-slim-bullseye # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt RUN pip3 install django-widget-tweaks # Copy project COPY . . My settings.py: INSTALLED_APPS = [ 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'openai', ] INSTALLED_APPS += [ 'widget_tweaks', ] The error: Exception in thread django-main-thread: project-web-1 | Traceback (most recent call last): ... project-web-1 | ModuleNotFoundError: No module named 'widget_tweaks'