Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Decrement/increment for qty and the value field
I am trying to create a cart page with the ability to use the add or minus buttons to decrement or increment the value of the input but the eventlisteners don't seem to be working and I have tried many different solutions online for this and get it to work properly. {% extends "base.min.html" %} {% block body_block %} {% load static %} <div class='container'> <a class='back-link' href="/"> Back to Catalog</a> <h1 class='cart-h1'>Cart </h1> <div class='cart'> <div class='requests'> <div class='request'> <img src='https://developers.elementor.com/docs/assets/img/elementor-placeholder-image.png' alt='request image'> <div class='request-info'> <p class='request-name'>Request: {{ requestName }}</p> <p class='request-details'>Details: {{ requestDetails }}</p> <p class='request-qty'>Qty: {{ requestQty }} <div class='qty-container'> <input type='button' value='+' class='qtyplus' id='plus' field='quantity' /> <input type='text' name='quantity' value='0' class='qty' id='inputQty' /> <input type='button' value='-' class='qtyminus' id='minus' field='quantity' /> </div> </p> <p class='qty-remove'></p> <span class='remove'>Remove</span> </div> </div> </div> </div> </div> </br> <div class='hidden-container'> <p>Checkout Confirmation #: {{confirmNum}}</p> </div> <script type="module" src="{% static '\js\supplyshop\pageload\RequestManagementLoad.min.js' %} " type ="text/javascript"></script> {% endblock %} const plusBtn = document.querySelector('#plus') const minusBtn = document.querySelector('#minus') const inputQty = document.querySelector('#inputQty') // increment/decrement value on input field // add eventlisteners on +/- buttons to update the value field plusBtn.addEventListener('click', e => { e.preventDefault() inputQty.value = parseInt(inputQty.value) + 1 }) minusBtn.addEventListener('click', e => { e.preventDefault() … -
CSRF fails on Route 53 redirect
I have two EC2 instances, which one has main Django-based backend app and another one has separate React-based frontend app using some of backend data. The backend app has its own views and endpoints and some frontend separate from the app in another EC2 instance. I got a new domain in AWS Route 53 which redirects to the frontend app and its location is configured on nginx. The missing thing are session cookies and csrftoken from the backend to make use of database. What may be useful is the frontend app is already reachable from the redirect set up in Django view but from the base server. In the example code below I don't paste the whole config but just the concept what I want to reach. Is there a way to redirect domain traffic to frontend app but through the backend to retrieve the cookies required to reach the backend data? Or should I think about other solution to make use of the domain? server { ... some server data ... $backend = "aws-backend-dns"; $frontend = "aws-frontend-dns"; location @backend { proxy_pass http://$backend; return @frontend; # but with some magic to keep the cookies! } location @frontend { proxy_pass http://$frontend; … -
Install GDAL x86_64 version on M1Max
For a given Django Project (to which I'm new) I need to install GDAL version: x86_64 because whenever I try python manage.py migrate on my Django project I get the following error: OSError: dlopen(/Users/name/lib/libgdal.dylib, 0x0006): tried: '/Users/name/lib/libgdal.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')).... I tried to switch the architecture of the terminal from arm64 to i386 and download it with the that architecture but I get the same error. In my settings.py the libraries GDAL and GEOS variable are declared as follows: GDAL_LIBRARY_PATH = '/opt/homebrew/opt/gdal/lib/libgdal.dylib' GEOS_LIBRARY_PATH = '/opt/homebrew/opt/geos/lib/libgeos_c.dylib' I searched and tried a lot of things, but nothing worked - have anyone had the same problem? -
How to delete one of the items of a field in the model?
I am trying to delete one of the items of a field in the model. For example, I want to remove the 'hadi', shown in the image , from the table. models.py class Expense(models.Model): expenser = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) debtors = models.ManyToManyField( CustomUser, related_name='debtors', ) amount = models.PositiveIntegerField() text = models.TextField() date = models.DateField(null=True) time = models.TimeField(null=True) def get_debtors(self): return ", ".join([str(d) for d in self.debtors.all()]) def who_has_no_paid(self): return ", ".join([str(d) for d in self.debtors.all() if str(d) != str(self.expenser)]) def debt(self): return int(float(self.amount/self.debtors.all().count())) def get_absolute_url(self): return reverse('expense_detail', args=[self.id]) What is the query that should be used in view? -
Image is not showing on my html page, using but only a link (path to image)
I have created an HTML(dashboard.html) page containing a div to display newly registered users' names, registration dates, and the user's pictures. div shows user names, and registration dates, but not the user's picture. Here is just a link to the image: Here are the files and their contents: podcast_user.models.py: class PodcastUser(AbstractUser): user_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) username = models.CharField(max_length=30,unique=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',message="Phone number must be in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True, null=True, unique=True, default='+') date_of_birth = models.DateField(blank=True, null=True) date_of_join = models.DateField(blank=True, null=True,default=date.today) address = models.CharField(max_length=100,blank=True, null=True) country = models.ForeignKey(Country, on_delete=models.CASCADE,blank=True, null=True) image = models.ImageField(upload_to='user_images/', blank=True, null=True) city_name = models.CharField(max_length=30, blank=True, null=True) postal_code = models.CharField(max_length=10,blank=True, null=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) email = models.EmailField(max_length=30, validators=[RegexValidator(regex="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.["r"a-zA-Z0-9-.]+$", message='please enter the correct format')],unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name','username'] def create_superuser(self, email, password, **extra_fields): if self.filter(is_superuser=True).exists(): raise ValueError('Superuser already exists') # set some default values for the superuser extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) # create the superuser with the provided email and password return self._create_user(email=email, password=password, **extra_fields) def __str__(self): return f"{self.username} ({self.user_id})" podcast_user.views.py: def PodcastDashboard(request): thirty_days_ago = datetime.now() - timedelta(days=30) new_users = PodcastUser.objects.filter(date_of_join__gte=thirty_days_ago) return render(request, 'pages/podcast_dashboard.html', {'new_users': new_users}) … -
I want to connect to the silicon pay API but am not sure how to handle the callback URL to obtain the status of the transaction
am trying to connect silicon pay, a payment API but I have failed to under how to handle the callback URL to check if the transfer was successful or not in order to give value to my customers @login_required(login_url='accounts:login') def mobile_deposit(request): if request.method == 'POST': form = MobileDepositForm(request.POST or None) if form.is_valid(): pending_amount = form.cleaned_data.get('pending_amount') if pending_amount >= 37000: account = Account.objects.get(user=request.user) data_req = { "req": "mobile_money", "currency": "UGX", "phone": str(account.user.phone_number), "encryption_key": "", "amount": str(pending_amount), "emailAddress": str(account.user.email), 'call_back': "https://41ab-137-63-181-131.in.ngrok.io/callback", "txRef": generate_txRef() } account.txRef = data_req['txRef'] account.save() headers = { 'Content-Type': 'application/json' } response = requests.post('https://silicon-pay.com/process_payments', data=json.dumps(data_req), headers=headers) print(response.text) account.save() messages.success(request, "Please confirm your Transaction on your phone") return redirect("accounts:mobile-deposit") else: messages.warning(request, "Minimum deposit is UGX 37000") return redirect('accounts:mobile-deposit') else: messages.warning(request, "Form error") return redirect('accounts:mobile-deposit') else: form = MobileDepositForm(request.POST or None) context = { 'form':form } return render(request, "mobile_deposit.html", context) def generate_txRef(): return "CTF-"+str(random.randrange(111111,999999)) I have tried reading the documentation on silicon pay but its in PHP yet am implementing mine in python. My solution has crushed the site -
Brew install watchman on mac does run the service
I am on Mac ventura 13.0.1 (22A400) I am trying to install watchman however it is not getting installed as a service that can be run in service/daemon mode brew install watchman ==> Downloading https://formulae.brew.sh/api/cask.json Warning: watchman 2023.02.13.00 is already installed and up-to-date. To reinstall 2023.02.13.00, run: brew reinstall watchman However, it says that it cannot be run and loadable brew services info watchman watchman (homebrew.mxcl.watchman) Running: ✘ Loaded: ✘ Schedulable: ✘ Brew services list brew services list Name Status User File memcached started xxx ~/Library/LaunchAgents/homebrew.mxcl.memcached.plist rabbitmq started xxx ~/Library/LaunchAgents/homebrew.mxcl.rabbitmq.plist redis none stunnel none However I can use watchman in command line mode, but other programs that need to find watchman can't use it -
Best practices for storing encrypted data that needs to be decrypted
I have a use case where I need to store userIDs and passwords to access other systems in my DRF App with a PostgreSQL DB. I must be able to retrieve this information, but I don't want to store it in plain text in the data base. The credentials will be used to login to other systems to collect data. Hashing is not an option as I need to be able to decrypt the encrypted passwords as they will be used to log into other systems. I was thinking using a vault (hashicorp), but then I need to store the keys to access the vault. That seems just shifting the problem, but not a solution. I am looking for a encryption/decryption that has not more than 2 secrets (key and vector) that could be the same for all credentials and provides a single string per password that can be stored in the DB. No fancy PostgreSQL features that are not supported by Django/DRF. I am not looking for long explanations about that you should not store a userID/Password information in a DB! -
'POST' or 'PUT' or 'DELETE' is not working
Here the class WriteByAdminOnlyPermission is not working perfectly. This if request.method == 'GET': working but remaining condition is not working. My target is, only the admin can change information and the other people just can see. How can I do it? And where I did do wrong? please give me a relevant solution😥 views.py: class WriteByAdminOnlyPermission(BasePermission): def has_permission(self, request, view): user = request.user if request.method == 'GET': return True if request.method in['POST' or 'PUT' or 'DELETE'] and user.is_superuser: return True return False class ScenarioViewSet(ModelViewSet): permission_classes=[WriteByAdminOnlyPermission] serializer_class = ScenarioSerializer queryset = Scenario.objects.all() models.py: class Scenario(models.Model): id = models.CharField(primary_key=True, max_length=10, default=uuid.uuid4, editable=False) Title = models.CharField(max_length=350, null=True, blank=False) film_id = models.OneToOneField(Film, on_delete=models.CASCADE, related_name="ScenarioFilmID", null=True) serializer.py: class ScenarioSerializer(ModelSerializer): class Meta: model = Scenario fields = "__all__" urls.py: router.register(r"scenario", views.ScenarioViewSet , basename="scenario") -
Django Authentication to use both email and username in exiting app
I am struggling with adding custom AUTHENTICATION_BACKENDS for my exiting app. I have all done with my app but now want to login with username or EmailID. I am successfully able to login with username and password. now just want to add EmailID as well. I tried adding below code in my settings.py AUTHENTICATION_BACKENDS = ( 'authentication.backends.EmailOrUsernameModelBackend', 'django.contrib.auth.backends.ModelBackend', ) and in \authentication\backends.py I have from django.conf import settings from django.contrib.auth.models import User class EmailOrUsernameModelBackend(object): def authenticate(self, username=None, password=None): print("Inside EmailorUsernameModelBackend") if '@' in username: print("User with Email") kwargs = {'email': username} else: print("User with Username") kwargs = {'username': username} try: user = User.objects.get(**kwargs) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None where my \authentication\views.py def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) print("User=",user) if user is not None: login(request, user) return redirect("dashboard") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "/login.html", {"form": form, "msg": msg}) I am trying to print some statement if authenticate method call from EmailOrUsernameModelBackend but none printing, so I guess for some … -
JAVASCRIPT: After sending Item to Database (POST) the window.location.reload() does not work. How to refresh the Data in HTML-Template?
I recode a Tutorial on Youtube. Django, Python, HTML an Javascript. Everthing works fine exept the window.location.reload() function. I try some workarounds with windows.reload(true), window.href = window.href location = self.location and some more. I have a hunch that the reload is executed before or during the code before the reload. But I do not know. The goal is to send the data from the input to the database and only then refresh the page. This ist the Code from the tutorial: index.html (shortened) <body> <header> <h1>Shoppinglist</h1> <div id="input-field"> <label for="item-input">Was möchtest du einkaufen?</label> <input type="text" name="item" id="item-input"> </div> <button id="btn" onclick="addItem()">+</button> </header> <div id="item-table"> {% for row in all_items %} <div class="list-item"> <input type="checkbox"> {{row.name}} </div> {% endfor %} </div> <script> function addItem(){ let itemName = document.getElementById("item-input").value; let formData = new FormData(); let token = '{{csrf_token}}'; formData.append('itemName', itemName); formData.append('csrfmiddlewaretoken', token); fetch('/mylist/', { method: 'POST', body: formData }); window.location.reload(); }; </script> </body> </html> views.py from django.shortcuts import render from .models import ShoppingItem # Create your views here. def mylist(request): if request.method == 'POST': print('Received date: ', request.POST['itemName']) ShoppingItem.objects.create(name = request.POST['itemName']) all_items = ShoppingItem.objects.filter(done = 0) return render(request, 'index.html', {'all_items':all_items}) models.py from django.db import models from datetime import date #Create your models … -
Multiple signin in django
I want to multiple role in django. I also create default auther user. But i want add login in second database table. I try to authenticate(username='john', password='secret') function but it is working only django default author. I want to use second database table then how can i authenticate the second user and login to the site. Please advice currently working django 4.1 version. -
Django Rest Framework get filtered queryset in custom get function
So I have an APIView like this: from rest_framework.views import APIView class MyAPIView(APIView): queryset = MyObject.objects.all() filter_backends = [MyCustomFilterBackend, DjangoFilterBackend] filterset_fields = ["field1", "field2"] def get(self, request): s = StatManager(self.queryset) return Response(s.dashboard()) where I filter bunch of stuff using MyCustomFilterBackend and DjangoFilterBackend. My goal is to give the filtered queryset to StatManager so it generates stats for the dashboard. Currently, s = StatManager(self.queryset) does not take filters into account. How can I provide the filtered queryset in my get function? I read the DRF documentation. I was expecting for APIView to have some function like get_filtered_queryset(). I read Filters of Django REST Framework inside GET function? and DJango filter_queryset but they have no adequate answers. -
how to disable django page caching
is there a way to prevent page caching in django? Because I have 2 views. view2 is only accessible if a request.session['iv'] exists. This is only created within view1 of a post request and is also deleted at the beginning of view1, so that access to view2 is not possible for the time being. If I am then redirected from view1 to view2 I can easily go back with the browser and land on view1. The problem is I can then go back to "show next page" and end up on view2 although the request.sesion no longer exists. This must be because the browser opens a cached version of view2, which I want to prevent. -
Websocket connection failing
`The WebSocket connection to 'ws://localhost:3000/ws/api/stocks_prices/AAPL/' failed: WebSocket is closed before the connection is established. React frontend views.js `useEffect(() => { const socket = new WebSocket(`ws://${window.location.host}/ws/api/stocks_prices/${symbol}/`); console.log("socket",socket) socket.onmessage = event => { const data = JSON.parse(event.data); setStockPrices(prevStockPrices => ({ ...prevStockPrices, data: [data, ...prevStockPrices.data.slice(0, 4)], })); console.log("websocket data",data); }; return () => { socket.close(); console.log("WebSocket closed"); }; }, [symbol]);` Using Django for backend routing.py `from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/api/stocks_prices/(?P<symbol>\w+)/$', consumers.StockConsumer.as_asgi()), ]` consumer.py `from channels.generic.websocket import AsyncWebsocketConsumer import json import yfinance as yf class StockConsumer(AsyncWebsocketConsumer): async def connect(self): self.stock_name = self.scope['url_route']['kwargs']['stock_name'] self.stock_group_name = 'stocks_prices/%s' % self.stock_name # Join room group await self.channel_layer.group_add( self.stock_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.stock_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) stock_name = text_data_json['stock_name'] # Fetch real-time stock data ticker = yf.Ticker(stock_name) data = ticker.history(period='1d') stock_price = { 'stock_name': stock_name, 'price': data['Close'].iloc[-1], } # Send real-time stock data to the client await self.channel_layer.group_send( self.stock_group_name, { 'type': 'stock_price', 'price': stock_price } ) # Receive message from room group async def stock_price(self, event): stock_price = event['price'] # Send real-time stock data to the client await self.send(text_data=json.dumps({ 'stock_name': stock_price['stock_name'], 'price': stock_price['price'] })) views.py … -
Merging converted pdf files in aws lambda function
Trying to acheive below functionality Uploading multiple files to s3 bucket. Non pdf files needs to get converted to pdf and then merge into single pdf file. The folder structure will be folder1/2/3/4. under folder 4 the files gets uploaded. Below is my code(lambda function) but the issue is the files(only some) are merging before all the files gets converted. convert to pdf has to occur successfully before the merging starts. import os import io from io import BytesIO import tarfile import boto3 import subprocess import brotli from PyPDF2 import PdfMerger from time import sleep #Directory where libre office open source s/w will be saved lambda tmp directory LIBRE_OFFICE_INSTALL_DIR = '/tmp/instdir' s3_bucket = boto3.resource("s3").Bucket("bucketname") def load_libre_office(): if os.path.exists(LIBRE_OFFICE_INSTALL_DIR) and os.path.isdir(LIBRE_OFFICE_INSTALL_DIR): print("Have a cached copy of LibreOffice, Skipping Extraction") else: print("No Cached copy of Libre Office exists , extracting tar stream from brotli file") buffer = BytesIO() with open('/opt/lo.tar.br','rb') as brotli_file: decompressor = brotli.Decompressor() while True: chunk = brotli_file.read(1024) buffer.write(decompressor.decompress(chunk)) if len(chunk) < 1024: break buffer.seek(0) print('Extracting tar stream to /tmp for caching') with tarfile.open(fileobj=buffer) as tar: # TODO: write code... print('opening tar file') tar.extractall('/tmp') print('LibreOffice caching done!') return f'{LIBRE_OFFICE_INSTALL_DIR}/program/soffice.bin' def convert_word_to_pdf(soffice_path, word_file_path, output_dir): conv_cmd = f"{soffice_path} --headless --norestore --invisible --nodefault … -
django listview order by model property
I have a model called Lap with a property calculated using data from the table class Lap(models.Model): team=models.ForeignKey('Team', models.DO_NOTHING) timestamp=models.IntegerField() num=models.IntegerField() @property def laptime(self): endtime=self.timestamp starttime=Lap.objects.get(team=self.team, num=self.num-1).timestamp) return time.timedelta(seconds=endtime-starttime) I am trying to create a listview for the model class FastestLap(ListView): model=Lap template_name='fastestlaps.html' context_object_name='laps' I want to order the list view by the laptime property. sorting by a column can be done using the ordering variable or by creating a get_queryset method and doing queryset.order_by(fieldname) in that method but I cant find a way to order by the property. How do I order by laptime? -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/register.html
Working on *django * on a test app, while creating a subpage as register in index/homepage, facing an error as follows: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: [name='index'] admin/ accounts ^media/(?P.*)$ The current path, accounts/register.html, didn’t match any of these. views.py: from django.shortcuts import render def register(request): return render(request,'register.html') urls.py: from django.urls import path from . import views urlpatterns = [ path("register",views.register, name="register") ] mysite url.py: from django.contrib import admin from django.urls import include , path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('Sell.urls')), path('admin/', admin.site.urls), path('accounts', include('accounts.urls')) ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html: <div class="container"> <div class="header_section_top"> <div class="row"> <div class="col-sm-12"> <div class="custom_menu"> <ul> <li><a href="#">Best Sellers</a></li> <li><a href="#">Gift Ideas</a></li> <li><a href="#">New Releases</a></li> <li><a href="accounts\register.html">Register</a></li> <li><a href="#">Customer Service</a></li> </ul> </div> </div> </div> </div> </div> #Although the register.html is in a templates folder but i tried it too but still not working. Register.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv='X-UA-Compatible' content="IE=edge"> <title>Register</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="main.css"> <script src="main.js"></script> </head> <body> <form action='register' method='post'> {% csrf_token %} <input type="text" name="first_name" placeholder="First Name"><br/> <input type="text" name="last_name" placeholder="Last Name"><br/> <input type="text" name="username" placeholder="username"><br/> <input … -
how to make my css style apply on my pages
I've been using django for a while but I'm just a beginner in css, I don't know much. I put style on my style.css file which is in the static folder and I placed the link in my template base.html but when I launch the server, the css style does not apply. what to do? mon templates base.html {% load static %} <html> <head> <title>Lax blog</title> <link rel="stylesheet" href="{% static 'style.css' %}" /> </head> <body> <div class="sidebar"> <h1>Lax Blog</h1> {% if user.is_authenticated %} {% if user.profile_photo %} <img class="avatar" src="{{ user.profile_photo.url }}" /> {% else %} <img class="avatar" src="{% static 'images/default_profile.png'%}" /> {% endif %} <p><a href="{% url 'home' %}">Accueil</a></p> <p> Vous etes connecté entant que {{request.user }} <a href="{% url 'deconnexion' %}">Se déconnecter</a> </p> {% endif %} </div> <div class="main">{% block content %}{% endblock content %}</div> </body> </html> mon fichier style.css body { background-color: white; color: blue; } html { font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif; } .sidebar { height: 100%; /* Full-height: remove this if you want "auto" height */ width: 220px; /* Set the width of the sidebar */ position: fixed; /* Fixed Sidebar (stay in place on scroll) */ z-index: 1; /* Stay on top … -
How to create password reset in Django Rest Framework
I have an app called API where I want to create a "Forgot Password" button for the user to insert their email, and a password reset is sent to them. In the same Django project, I have an application called users which implements this process in the backend. How can Django Rest Framework be used to reset the password? Do I link the URLs of the users app or create new URLs in API app Here is the users app urls.py app_name = 'users' urlpatterns = [ path('password/', user_views.change_password, name='change_password'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html', success_url=reverse_lazy('users:password_reset_done')), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html',success_url=reverse_lazy('users:password_reset_complete')),name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'), ] here is the main urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), path('api/', include('api.urls'), ), path('users/', include('users.urls'), ), here is the api app urls.py app_name = 'api' router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='user') urlpatterns = [ path('', include(router.urls)), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] -
Django-channels: How to delete an object?
I'm making a real-time chat app using django channels. I want to delete an object from database using django channels(actually deleting a message from the group). How can this be done? This is my backend code: import json from django.contrib.auth.models import User from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from .models import Room, Message class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): data = json.loads(text_data) print(data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username, room, message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username': username })) @sync_to_async def save_message(self, username, room, message): user = User.objects.get(username=username) room = Room.objects.get(slug=room) Message.objects.create(user=user, room=room, content=message) Should i use javascript? I tried to delete some objects by using Ajax but it didn't work. -
Is it possible to return render request and json response together?
I got a little function for rendering an html and I also wanna return a JsonResponse in the same page, is it possible to return both at the same time? I'll leave mi little function Below def addObservation(request): reservations= Reservation.objects.all() return render(request, 'observations/registerObservation.html', {'reservations': reservations}) I wanna add a Json response to get the reserveations list in js Thanks for your help -
I get this error when I try to render some html files in django: NoReverseMatch at / Reverse for 'it_languages' not found
When I try to render a html file in django project, I get this error, and I can't see the localhost page 'cause of this. The error is: NoReverseMatch at / Reverse for 'it_languages' not found. 'it_languages' is not a valid view function or pattern name. and it languages is url for in html Then it bolds me with yellow this: Home About Me **IT-languages** Projects Contact I expect to see my offline page rendered by django project Should I keep it like the original html version: Home About Me IT-languages Projects Contact -
Unable to add image in django
I am unable to display the image from local storage to the html page using django HTML code: <!DOCTYPE html> <html> <head> <title>Display Image</title> </head> <body> <img src="{{ image_path }}" alt="Image"> </body> </html> view.py code: from django.shortcuts import render def display_image(request): image_path = 'templetes\media\image.png' context = {'image_path': image_path} return render(request, 'valid.html', context) setting.py code: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ -
Queryset ordered by must frequent values
I'm trying to order a simple queryset by the must frequent value in a column. For exemple, I have those models: class Keyword(models.Model): keyword = models.CharField(verbose_name='Keyword', null=False, blank=False, max_length=20) class BigText(models.Model): text = models.CharField(verbose_name='Big Text', null=False, blank=False, max_length=1000) class BigTextKeyword(models.Model): keyword = models.ForeignKey(Keyword, verbose_name='Keyword', null=False, on_delete=models.CASCADE) bigtext = models.ForeignKey(BigText, verbose_name='Big Text', null=False, on_delete=models.CASCADE) Then, I'm searching for the keywords passed on query params and returning the BigTextKeywords result found like this: class BigTextKeywordViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): queryset = BigTextKeyword.objects.all() serializer_class = BigTextKeywordSerializer def get_queryset(self): keyword_filter = Q() search_content = self.request.query_params.get('search_content', '') for term in search_content.split(' '): keyword_filter |= Q(keyword__icontains=term) keywords = Keyword.objects.filter(keyword_filter) result = BigTextKeyword.objects.filter(keyword__in=keywords) return result I want to order the result by the must frequent bigtext field. For example, if a bigtext occurs 3 times on the result, it should appears first than a bigtext that occurs 2 times.