Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
product.models.Products.DoesNotExist: Products matching query does not exist
product.models.Products.DoesNotExist: Products matching query does not exist. i have this problem in my site when i ran this url it show me this error please help in django and this is my views.py: class GetListProduct(APIView): def get(self, request): products = Products.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) class Getproduct(APIView): def get_object(self, brand): comment = Products.objects.get(brand=brand) serializer = ProductSerializer(comment) return Response(serializer.data) class Topsellsviews(APIView): def get(self, request): topsellsproduct = TopSells.objects.all() serializer = Topsellsserializer(topsellsproduct, many=True) return Response(serializer.data) class Getdetailproduct(APIView): def get(self, request, productid): detail = Products.objects.get(productid=productid) serializer = ProductSerializer(detail) return Response(serializer.data) and this is my url: from django.urls import path from.views import GetListProduct, Topsellsviews, Getdetailproduct, Getproduct urlpatterns = [ path('product/', GetListProduct.as_view()), path('topsells/', Topsellsviews.as_view()), path('product/<str:productid>/', Getdetailproduct.as_view()), path('product/<str:brand>/', Getproduct.as_view()), when i run /product/productid it worked but when i run /product/brand it not worked -
Using field in Trunc's kind property
I use PostgreSQL in my project and have three related models: class Timer(models.Model): start = models.DateTimeField() end = models.DateTimeField() task = models.ForeignKey( Task, models.CASCADE, related_name="timers", ) class Task(models.Model): name = models.CharField(max_length=64) wanted_duration = models.DurationField() frequency = models.ForeignKey( Frequency, models.CASCADE, related_name="tasks", ) class Frequency(models.Model): class TimeUnitChoices(models.TextChoices): DAY = "day", "day" WEEK = "week", "week" MONTH = "month", "month" QUARTER = "quarter", "quarter" YEAR = "year", "year" events_number = models.PositiveIntegerField() time_unit = models.CharField(max_length=32, choices=TimeUnitChoices.choices ) I want to get a start of timespan (day, week - a value of Frequency's time_unit) according to start date (field of Timer). I tried execute next code: task.timers.annotate(start_of=Trunc('start', kind='task__frequency__time_unit')) But Django doesn't accept field in kind argument of Trunc class. Error: psycopg.ProgrammingError: cannot adapt type 'F' using placeholder '%t' (format: TEXT) If I execute a following query in raw SQL: SELECT DATE_TRUNC(schedules_frequency.time_unit, timers_timer.start)::date as start_of FROM public.tasks_task INNER JOIN public.schedules_frequency ON tasks_task.frequency_id = schedules_frequency.id INNER JOIN public.timers_timer ON timers_timer.task_id = tasks_task.id; Everything works as wanted. Is there workaround without using raw SQL directly in the Django project? -
I/O Operation on closed file while using boto3 library for S3 file upload
Here is the traceback Internal Server Error: /api/v1/vehicle/ss-image-upload/ Traceback (most recent call last): File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\vehicle_management\views.py", line 462, in patch i.save() File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 814, in save self.save_base( File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 877, in save_base updated = self._save_table( ^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 981, in _save_table values = [ ^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 985, in <listcomp> (getattr(self, f.attname) if raw else f.pre_save(self, False)), ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\fields\files.py", line 317, in pre_save file.save(file.name, file.file, save=False) File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\fields\files.py", line 93, in save self.name = self.storage.save(name, content, max_length=self.field.max_length) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\core\files\storage\base.py", line 38, in save name = self._save(name, content) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\storages\backends\s3boto3.py", line 446, in _save content.seek(0, os.SEEK_SET) ValueError: I/O … -
Error after removing slug from Page.promote_panels [Django Wagtail]
I am getting the following error after removing the 'slug' field from Page.promote_panels. I am using wagtail 5.1. KeyError at /admin/pages/add/blog/blogdetailpage/10/ "Key 'slug' not found in 'BlogDetailPageForm'. Choices are: category, classes, comment_notifications, container_size, containerized, content, expire_at, go_live_at, publish_at, search_description, seo_title, site, title." I am autogenerating the slug with the following piece of code, so I do not see a need for keeping it around. def save(self, request=None, *args, **kwargs): ... slug = slugify(f"{self.title}-{self.created_at}") if not self.slug or self.slug != slug: self.slug = slug if not self.publish_at: self.publish_at = datetime.now() super().save(*args, **kwargs) Is anyone familiar with doing something along the lines of this? -
Connect a Reddit app to Django and get permission to make a post
As a developer, I'd like to create a Reddit app and use it in Django. I'd like to get authorization to get the posts that the user has authorized. Imagine: A user clicks a button on my website and goes directly to the authorization screen and then he will be able to see his Reddit posts on my website -
How reset the user password in django
I have make canteen invoice making app and also admin can create user, update user and change the user's password But admin can't change user password form.py class PasswordChange_Form(UserCreationForm): class Meta: model = User fields = ["username","password1","password2"] widgets = { "username":forms.TextInput(attrs={'class':'form-control','placeholder':'Username', 'readonly':'readonly'}), "password1":forms.TextInput(attrs={'class':'form-control',"placeholder":"Password"}), "password2":forms.TextInput(attrs={'class':'form-control','placeholder':'Confirm Password'}), } View.py @login_required(login_url='/') def UserChangePassword(request,pk): id = User.objects.get(id = pk) user_id =request.user heading_name = "user" rights, main_heading, page_menu, form_btn_data = RightLoader(user_id, heading_name) try: auth_check = rights.form_btn.get(heading_name = heading_name, btn_type = "Password")# fetch form btn right if request.method == 'POST': form = PasswordChange_Form(request.POST, instance=id) try: if form.is_valid(): form.save() form = PasswordChange_Form(instance=id) #update_session_auth_hash(request, ) # Important! messages.success(request, 'Your password was successfully updated!') except: messages.error(request,str(form.errors)) else: form = PasswordChange_Form(instance=id) context = { 'form':form, 'page_menu':page_menu, 'main_heading':main_heading, 'btn_type':'fa fa-regular fa-plus', 'title':'iCateen | User', 'page_title':'Password Change', 'tree_title_1':'User', 'tree_url':'user', 'tree_title_2':'Add Form', 'view':'yes', } return render(request, 'base/user/change_password.html',context) except: return HttpResponseRedirect("/") Admin user can change user's password ? -
PyCharm does not accept my Python interpreter
I'm working with Python framework Django. I used Pycharm's terminal created virtual environment. {.\venv\Scripts\activate} It was created, and i run the server with this python manage.py runserver But the system responds: No Python at "C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe But i installed and using Python 3.11.2 And i have file manage.py in project1 folder What should i do? The code PS D:\binkw32.dll\djangomorning> .\venv1\Scripts\activate (venv1) PS D:\binkw32.dll\djangomorning> cd project1 (venv1) PS D:\binkw32.dll\djangomorning\project1> python manage.py runserver No Python at 'C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe' (venv1) PS D:\binkw32.dll\djangomorning\project1> -
Web and Daphne always restarting and not working properly
I've checked all I've seen, yet nothing is working. Please, I'm trying to make use of docker and all for the first time. This is my docker-compose.yml services: cache: image: redis:7.0.4 restart: always volumes: - ./data/cache:/data db: image: postgres:15.0 restart: always volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=samuel - POSTGRES_USER=samuel - POSTGRES_PASSWORD=*** web: build: . command: ["./wait-for-it.sh", "db:5432", "--", "uwsgi", "--ini", "/code/config/uwsgi/uwsgi.ini"] restart: always volumes: - .:/code environment: - DJANGO_SETTINGS_MODULE=chollosite.settings.prod - POSTGRES_DB=samuel - POSTGRES_USER=samuel - POSTGRES_PASSWORD=samuel101 depends_on: - db - cache daphne: build: . working_dir: /code/chollosite/ command: ["../wait-for-it.sh", "db:5432", "--", "daphne", "-u", "/code/chollosite/daphne.sock", "chollosite.asgi:application"] restart: always volumes: - .:/code environment: - DJANGO_SETTINGS_MODULE=chollosite.settings.prod - POSTGRES_DB=samuel - POSTGRES_USER=samuel - POSTGRES_PASSWORD=samuel101 depends_on: - db - cache nginx: image: nginx:1.23.1 restart: always volumes: - ./config/nginx:/etc/nginx/templates - .:/code ports: - "80:80" - "443:443" this is my base.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pex0v$*b!kjl-bk2p%1y8rf!&jh+bqa!9t5e4@xnac-(nbi2wc' # Application definition INSTALLED_APPS = [ 'chollo_main.apps.CholloMainConfig', 'chollo_cart.apps.CholloCartConfig', 'orders.apps.OrderConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.postgres', 'channels', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', … -
Possible security risks for the following form submission in Django
I am trying to create the page for a livetime chat app using Django and some Ajax. I have always used django forms, since it is more secure and clean if you are not very familiar with javascript. The below html and views.py don't use django forms, but instead go with the traditional method of using javascript. However, I am concerned that there might be security leaks with this following form, which I copied from another website. I believe I added the csrf token correctly, but is there anything else I need to consider? Thank you, and please leave any comments. <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script> </head> <body> <h2>{{room}} - DjChat</h2> <div id="display"> </div> <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "/getMessages/{{room}}/", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.messages) { var temp="<div class='container darker'><b>"+response.messages[key].user+"</b><p>"+response.messages[key].value+"</p><span class='time-left'>"+response.messages[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occured') } }); },1000); }) </script> <div class="container"> <form id="post-form"> {% csrf_token %} <input type="hidden" name="username" id="username" value="{{username}}"/> <input type="hidden" name="room_id" id="room_id" value="{{room_details.id}}"/> <input type="text" name="message" id="message" width="100px" /> <input type="submit" value="Send"> </form> </div> </body> <script type="text/javascript"> $(document).on('submit','#post-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/send', data:{ username:$('#username').val(), room_id:$('#room_id').val(), message:$('#message').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, … -
Django daphne service service is not working while deploying on aws ec2 an error Requested setting INSTALLED_APPS, but settings are not configured
Aug 06 11:11:00 ip-172-31-12-99 python[92893]: File "/home/ubuntu/nextshelters/env/lib/python3.10/site-packages/django/conf/init.py", line 72, in _setup Aug 06 11:11:00 ip-172-31-12-99 python[92893]: raise ImproperlyConfigured( Aug 06 11:11:00 ip-172-31-12-99 python[92893]: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJ> Aug 06 11:11:00 ip-172-31-12-99 systemd[1]: daphne.service: Main process exited, code=exited, status=1/FAILURE Aug 06 11:11:00 ip-172-31-12-99 systemd[1]: daphne.service: Failed with result 'exit-code'. Aug 06 11:11:00 ip-172-31-12-99 systemd[1]: daphne.service: Scheduled restart job, restart counter is at 1. Aug 06 11:11:00 ip-172-31-12-99 systemd[1]: Stopped WebSocket Daphne Service. this is the error coming when i am trying to do this sudo journalctl -u daphne.service here is m asgi.py file import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Renter.settings') django.setup() from django.conf import settings settings.configure() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter, get_default_application from django.core.asgi import get_asgi_application from django.urls import path from home.consumers import ChatConsumer, NotificationsConsumer, TenantsConsumer application = get_asgi_application() application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( [ path("chat/<room_code>", ChatConsumer.as_asgi()), path("view_messages", NotificationsConsumer.as_asgi()), path("dashboard/tenant_details/<tenant_uid>", TenantsConsumer.as_asgi()) ] ) ), } ) -
Having problems with message tags
*trying to create dynamic responses depending on user input but no alert button even appears. but when i get rid of {% for message in messages%} an empty alert button appears. ** here are sections of the code views.py file from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate, login, logout def signup(request): if request.method == "POST": username = request.POST.get('username') email = request.POST.get('email') pass1 = request.POST.get('pass1') pass2 = request.POST.get('pass2') if pass1 != pass2: messages.info(request, "Password is not matching") return redirect('/authapp/signup/') try: if User.odjects.get(username=get_email): messages.warning(request, 'User with email already exist') return redirect('/authapp/signup/') except Exception as identifier: pass myuser = User.objects.create_user(username, email, pass1) myuser.save() messages.success(request, "Your Account has been successfully created, Login") return redirect('/authapp/signin/') return render(request, 'authapp/signup.html') signup.html {% for message in messages %} <div class="alert alert-{{message.tags}} alert-dismissible fade show" role="alert"> <strong> {{message}} </strong> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} settings.py MESSAGE_TAGS = { messages.ERROR:'alert-info' } -
how to access MsSql Database from Cpanel
i am using python django project hosted in c panel. Database used is MsSql but not Supporting. try to add MsSql databse in CPanel but got error- MsSql is not supported.how to add mssql databasein cpanel with free of cost -
How to get full history executed function inside parrent function in Python / Django
I have function like this def test_func_1(angka): angka = angka + 3 result = test_func_2(angka) return result def test_func_2(angka): angka = angka + 5 return test_func_3(angka) def test_func_3(angka): angka = angka * 2 return angka def wrapper_func(): return test_func_1(3) When I call wrapper_func() I want to have history function that executed like this : wrapper_func() test_func_1(3) test_func_2(angka) test_func_3(angka) is that possible ? I know it's possible if we put trace_back.print_stack() like this Getting a python traceback without an exception But what if I don't have access to change that code ? It's very useful when I run django shell in the production server, and debug intermittent issue. So I can just call that function and I input specific parameter, then I can know what actually that function did -
Django session id cookie not as expected when requesting from swift
When I use Postman to log a user in I get my csrftoken and sessionid cookies in the response as expected. When I make the same exact request but on my iOS app on the simulator, I get the csrftoken cookie from my response just fine as expected. But I do not get the same sessionid cookie. The cookie I'm getting is named "__cf_bm" with a much longer than expected value. The domain of the sessionid cookie on iOS is also now "cloudflare-ipfs.com", whereas on both Postman and iOS the csrftoken domain is just 127.0.0.1. On Postman the sessionid cookie's domain is also just local host. I never did anything with cloudflare. What could be causing this? -
asgi config in Django
I implemented a chat environment with Django chat channel and it works with asgi, messages are exchanged on my computer without any problem, but when I upload my project on host, it does not exchange messages, I am wondering should I config my passenger_wsgi or some configuration from my host? My asgi config: import os import chat.routing from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from chat.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) My wsgi import os from django.core.wsgi import get_wsgi_application from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zgalaxy.settings') aplication = get_wsgi_application() ` My passenger_wsgi from zgalaxy.asgi import application ` My settings.py ASGI_APPLICATION = 'zgalaxy.asgi.application' ` -
how to make a post request for a model with a foreign key in django-ninja using api
My models looks like this: from django.db import models class PRODUCT(models.Model): name = models.CharField(max_length=50) price = models.FloatField() def __str__(self): return f'{self.name}- {self.price}' class CUSTOMER(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=254) def __str__(self): return f'{self.name}-{self.email}' class ORDER(models.Model): productID = models.ForeignKey(PRODUCT, on_delete=models.CASCADE, null=True,blank=True) customerID = models.ForeignKey(CUSTOMER, on_delete=models.CASCADE,null=True,blank=True) quantity = models.IntegerField() price = models.FloatField() def __str__(self): return f'{CUSTOMER.pk}-{PRODUCT.pk}-{self.quantity}' The schemas I used are: class ORDERin(Schema): productID: int customerID: int quantity: int price: float class ORDERout(Schema): id: int productID: int customerID: int quantity: int price: float This is how I tried to do the post api from ninja import Router from myapp.models import ORDER from myapp.schemas import ORDERin,ORDERout from typing import List order_router = Router() @order_router.post('/post') def post_order(request, data: ORDERin): qs = ORDER.objects.create(**data.dict()) return {List[ORDERout]} When I tried to test this post request, I got this error: "ValueError: Cannot assign "1": "ORDER.productID" must be a "PRODUCT" instance." I don't know what I messed up here, probably my schemas but I don't know how to do it the right way. -
Django: Session data not updating
I'm building an ecommerce app on Django, and I'm trying to add a functioning cart app that can add, update, and delete items in it. However, I can't seem to get the session data to update when the user clicks the relevant button to add an item The template: {% extends "../main.html" %} {% load static %} {% block title %} {{ product.name }} {% endblock %} {% block content %} <div class = "container"> <main class = "pt-5"> <div class = "row g-3"> <div class = "col-md-5 col-lg-5 order-mg-first"> <img class = "img-fluid mx-auto d-block" width = "200px" alt = "Responsive image" src = "{{ product.image.url }}" /> </div> <div class = "col-md-7 col-lg-7 ps-md-3 ps-lg-5"> <h1 class="mb-0 h4">{{ product.title }}</h1> <p><span class="lead">{{ product.author }}</span> (Author)</p> <p>{{ product.description|slice:":355" }}...</p> <div class="border"> <div class="col border-bottom"> <div class="row p-3"> <div class="col-6">Hardback</div> <div class="col-6 text-end"><span class="h4 fw-bold">€{{ product.price }}</span></div> </div> </div> <div class="col"> <div class="row p-3"> <div class="col-6"> <label for="select">Qty</label> <select id="select"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> </div> <div class="col-6 text-end"> <button type="button" id = "add_button" value = "{{product.id}}" class="btn btn-secondary btn-sm"> Add to Cart </button> </div> </div> </div> </div> </div> </div> </main> </div> <script> $(document).on('click', '#add-button', function(e){ … -
Django "django-modeladmin-reorder" library does not work for side navigation/nav bar of admin
I have a django project, which contains several models with natural grouping, as well as some off-the-shelf models from install libraries. I am trying to have this natural grouping reflected in the admin hope page, as well as the side navigation (nav bar) of the admin panel. By using django-modeladmin-reorder library, the home page is properly grouped as I want. Though, the nav bar ordering is not working and the models appear in their original order (alphabetically, grouped by the library/file where they are fetched from). I have tried several complex (or more complex than just plugging a library) solutions, such as overriding the nav bar/app list html of django and create other templates and creating custom middlewares. -
How to keep django web session active in react-native-webview?
Based on this answer I tried to retain my session in IOS and even though I am passing the cookies back with the request, I am still coming back when I exit and re-open the app, the difference from the above link is I am using django and its sessions export default class App extends Component { constructor(props) { super(props); this.currentUrl = ''; this.myWebView = React.createRef(); this.state = { isReady: false, cookiesString: '', userAgent: '', }; } UNSAFE_componentWillMount() { // CookieManager.clearAll(); this.provideMeSavedCookies() .then(async (savedCookies) => { let cookiesString = this.jsonCookiesToCookieString(savedCookies); const sessionid = await AsyncStorage.getItem('sessionid'); if (sessionid) { cookiesString += `sessionid=${sessionid};`; } DeviceInfo.getUserAgent().then((userAgent) => { this.setState({userAgent: userAgent, cookiesString, isReady: true}); }); }) .catch((e) => { this.setState({isReady: true}); }); } onLoadEnd = () => { let successUrl = `${domain}`; if (this.currentUrl === successUrl) { CookieManager.getAll().then((res) => { console.log('RES'); console.log(res) AsyncStorage.setItem('savedCookies', JSON.stringify(res)); if (res.sessionid) { AsyncStorage.setItem('sessionid', res.sessionid.value); } }); } }; jsonCookiesToCookieString = (json) => { let cookiesString = ''; for (let [key, value] of Object.entries(json)) { cookiesString += `${key}=${value.value}; `; } return cookiesString; }; onNavigationStateChange = (navState) => { this.currentUrl = navState.url; }; provideMeSavedCookies = async () => { try { let value = await AsyncStorage.getItem('savedCookies'); if (value !== null) { … -
What is wrong with the Procfile I use in order to deploy my Django website to Heroku
I've been trying for days now to deploy my django website to heroku. I fixed problems with my requirement.txt file, but the Procfile stills gives me problems. The procfile contains this simple line : web: gunicorn myproject.wsgi Which corresponds to the name of my django project, as it is in my wsgi.py file : import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_wsgi_application() The structure of my project is basic : /django_learn /myproject /landing_page /myproject /staticfiles /db.sqlite3 /manage.py /venv310 Procfile requirements.txt runtime.txt The requirements.txt was generated with a pip freeze command, no problems when I push to heroku with git push heroku master. When I use herok open I end up with an application error message. The logs show this : 2023-08-11T20:58:01.720670+00:00 heroku[web.1]: State changed from crashed to starting 2023-08-11T20:58:04.042143+00:00 heroku[web.1]: Starting process with command `gunicorn myproject.wsgi` 2023-08-11T20:58:04.849914+00:00 app[web.1]: [2023-08-11 20:58:04 +0000] [2] [INFO] Starting gunicorn 21.2.0 2023-08-11T20:58:04.850170+00:00 app[web.1]: [2023-08-11 20:58:04 +0000] [2] [INFO] Listening at: http://0.0.0.0:11115 (2) 2023-08-11T20:58:04.850205+00:00 app[web.1]: [2023-08-11 20:58:04 +0000] [2] [INFO] Using worker: sync 2023-08-11T20:58:04.852505+00:00 app[web.1]: [2023-08-11 20:58:04 +0000] [7] [INFO] Booting worker with pid: 7 2023-08-11T20:58:04.854461+00:00 app[web.1]: [2023-08-11 20:58:04 +0000] [7] [ERROR] Exception in worker process 2023-08-11T20:58:04.854461+00:00 app[web.1]: Traceback (most recent call last): … -
Django gettext not working properly with django rest
I'm having some weird bug with gettext while using a ModelSerializer, I cannot get the translated charfield choice for all of the choices, some choices work but others don't I even tried to run another makemessages command but the same inconsistent result. this is the problematic field status= models.CharField( max_length=50, default="pending", choices=[ ('pending', _('Pending')), ('initiated', _('Initiated')), ('completed', _('Completed')) ] ) -
Get ElasticSearch suggestion based on filtered data in Django
I am using django-elasticsearch-dsl for integrating elastic search. I have an API that returns name suggestions using elastic search suggest feature. It's working as expected but the issue is I can't apply a specific filter. For example, I want to get suggestions for the published products only. #Document class ProductDocument(Document): status = fields.IntegerField() meta = fields.ObjectField( properties={ "is_published": fields.BooleanField(), "full_name": fields.TextField( analyzer=html_strip, fields={ "raw": fields.KeywordField(), "suggest": fields.Completion(), } ), }, ) search = ProductDocument.search() search = search.filter("match", meta__is_published=True) completion = { 'field': "meta.full_name.suggest", 'size': 10, 'fuzzy': {'fuzziness': "auto:4,8"}, } suggest = search.suggest("auto_complete","abc", completion=completion) But it return products with is_published=False. Is there any way to achieve this? -
Django And Windows 2016 IIS Server
I have at work a local Windows 2016 IIS Server. How can I configure it to recognize a live instance of my Django project? -
Django translation.activate not working in middleware
I'm attempting to implement an auto language switcher in Django based on the client's IP address. For testing purposes, I've created a middleware to set the language to French ('fr'). class SetFrenchLanguageMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user_language = 'fr' translation.activate(user_language) request.LANGUAGE_CODE = translation.get_language() response = self.get_response(request) response.set_cookie('django_language', user_language) print("language set to ", user_language) return response When I access a page, I see "language set to fr" printed in the console, indicating that the middleware is executed. However: The content is still displayed in English, the default language. The URL prefix doesn't change to "/fr/". Could someone help me understand why this isn't working as expected and guide me on how to resolve the issue? -
I need to create a button in html
Good time of day. I have a Field and a button that changes a record in the Database when clicked.I want to not have this field, and when I press the button, I go to the already filled field, and I can customize it, and then save it by pressing the button. Here is my code, I hope it will help in some way.I would also be grateful for help in improving the code, I'm a beginner. today.html <title>Todoist</title> <h1>Сегодня</h1> <h2>Задачи</h2> <form method="POST" action="{% url 'todoist:add' %}" >{% csrf_token %} <input type="text" name='tasks' pattern=".{2,}" required title='Минимум два символа!!!'> <button type="submit" class="save btn btn-default">Добавить задачу</button> </form> {% for todo in todos%} <div> <p> {{todo.tasks}}</p> <a href={% url 'todoist:delete' today_id=todo.id%}>Удалить</a> <form action="{% url 'todoist:update' today_id=todo.id%}" method="post"> {% csrf_token %} <input type="text" name='tasks'> <button type="submit" class="save btn btn-default">Изменить</button> </form> </div> {% endfor %} views.py from django.shortcuts import render,redirect from .models import Today from django.views.decorators.http import require_http_methods def index(request): todos = Today.objects.all() return render(request, 'today.html', {'todos':todos}) @require_http_methods(['POST']) def add(request): tasks = request.POST["tasks"] task = Today(tasks=tasks) task.save() return redirect('todoist:index') def delete(request, today_id): todo = Today.objects.get(id=today_id) todo.delete() return redirect('todoist:index') def update(request, today_id): todo = Today.objects.get(id=today_id) todo.tasks = request.POST.get('tasks') todo.save() return redirect('todoist:index')