Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Cannot auto focus on this form but can on forms
I have a login, register and password reset pages both login and register pages auto focus on the username field however on my password reset page auto focus is not working. I have tried widget_tweaks within my template but to no avail like so: {{ fieldValues.email|attr:"autofocus" }} and {{ form.email|attr:"autofocus" }} I just cannot get my head around why auto focus works on my other forms but not on password reset. My code is as follows: View class RequestPasswordResetEmail(View): @method_decorator(check_recaptcha_form) def get(self, request): return render(request, 'password/reset-password.html') @method_decorator(check_recaptcha_form) def post(self, request): email = request.POST['email'] context = { 'values': request.POST } current_site = get_current_site(request) user = User.objects.filter(email=email) user_by_email = User.objects.filter(email=email).first() if not user.exists(): messages.error(request, 'Please supply a valid email') return render(request, 'password/reset-password.html', context) if user.exists() and request.recaptcha_is_valid: uid = urlsafe_base64_encode(force_bytes(user_by_email.pk)) token = PasswordResetTokenGenerator().make_token(user_by_email) email_subject = 'WFI Workflow System - Password Reset' email_body = 'password/password_reset_email.html' to_email = [user_by_email.email] send_email(user, request, email_subject, email_body, uid, token, to_email) messages.success( request, mark_safe( 'We’ve emailed you instructions for setting your password, if an account exists with the email you entered. You should receive them shortly.' '<br class="brmedium"> If you don’t receive an email, please make sure you’ve entered the address you registered with, and check your spam folder.</br>')) … -
Use CreateView and ListView in the same template and use form.instance correctly
In my project my user should be able to submit an appointment (class UserAppointment) based on the disponibility given by the staff (class StaffDuty). So I'd ike to use the CreateView Class of the UserAppointment model and ListViewClass for the StaffDuty model in the same template. With my code I can access the data from the StaffDuty model but I'm not able to submit the form for UserAppointment model, since the submit button does nothing. Also I'd like to automatically assign the staff and event foreing key and pass data from StaffDuty to complete form.instance.date_appointment with the date given in the staff model and form.instance.event_name with the name of the event that is found in the Event model. But my code is not working at all models.py class Event(models.Model): name = models.CharField(max_length=255) staff_needed = models.PositiveIntegerField() date = models.DateField() spots_total = models.PositiveIntegerField() venue = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('event_details', args=[str(self.id)]) class StaffDuty(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) date_work = models.DateField() shift = models.CharField(max_length=255) def __str__(self): return self.event.name | str(self.date_work) class UserAppointment(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) staff = models.ForeignKey(StaffDuty, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) event_name = models.CharField(max_length=255) date_appointment = models.DateField(null=True) morning_hour = models.CharField(max_length=255) afternoon_hour = … -
HEROKU: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)')
I am having an issue trying to use mssqlserver with pyobdc in django on heroku. I'm getting this error:('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)') -
NoReverseMatch at /create_blog/ Reverse for 'update_blog' with no arguments not found. 1 pattern(s) tried: ['update_blog/(?P<id>[0-9]+)$']
ERROR views.py urls.py link_to_update PLEASE TYPE THE CODE DOWN AND TELL THE REASON AND PLEASE SEND IT -
how to use group by in django with TruncDay
I'm trying to show profit and loss of a company using group by for each day here is what i tried : class InvoiceItem(models.Model): item = models.ForeignKey(Item,on_delete=models.CASCADE) invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE) quantity = models.IntegerField) price = models.DecimalField(max_digits=20,decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) class Item(models.Model): item = models.ForeignKey(Information,on_delete=models.CASCADE) quantity = models.IntegerField() buying_price = models.DecimalField(max_digits=30,decimal_places=2) cost = models.DecimalField(max_digits=30,decimal_places=2,blank=True,null=True) i have to show daily profit with daily loss , something like this total_price = 1000 , total_main_price = 900 , profit = 100 but if we have sell something for example its main_price is 100 but we sell it for 90 , then our profit will change to 90 and we dont have loss because still we have profit , but i want to show its loss as well even if we have profit in most of invoices but in one invoice we have loss , i have to show the loss of that invoice ! i dont want to show the average i just want to show summation of profit invoices and loss of invoices separately class DailyInvoiceIncomeView(LoginRequiredMixin,ListView): template_name = 'invoiceapp/dmyincomes/dailyinvoice.html' model = InvoiceItem def get_queryset(self): return InvoiceItem.objects.annotate(day=TruncDay('created_at')).values('day').annotate( paid_price=Sum( (F('price') * F('quantity')) - F('discount'),output_field=DecimalField(max_digits=20,decimal_places=3)), storage_price=Sum( (F('item__buying_price')+F('item__cost')) * F('quantity'),output_field=DecimalField(max_digits=20,decimal_places=3)), income=Case( When(paid_price__gte=F('storage_price'),then=F('paid_price')-F('storage_price')),default=0,output_field=DecimalField(max_digits=20,decimal_places=3)), ).annotate( loss=Case( When( storage_price__gt=F('paid_price'),then=F('storage_price') - … -
'NoneType' object is not subscriptable . When using the django admin
I am trying to create an ecommerce website and when working to make the cart order for non authenticated users and then save it and send it to the backend I just get this error in every view when I log in the django admin panel. It works well when I am not logged as an admin although it does not save the order once the order is set to completed. The error is 'NoneType' object is not subscriptable. and mentions this variable as empty: cartItems = data['cartItems'] views.py from django.shortcuts import render from .models import * from django.http import JsonResponse import json import datetime from .utils import cartData, cookieCart def store(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products':products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems': cartItems} return render(request, 'store/cart.html', context) def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems': cartItems} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('ProductId:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, … -
Queryset filter() in Django with ForeignKey
I'm having trouble with Django queryset. First of all, what I want to do is to receive from the customer which discount coupons (dc for short) he/she used and then compare with the ones already in the system. And I did manage to do it with 1 my view: @login_required(login_url='login') def cupons(request): produtos = Produto.objects.all() cliente = Cliente.objects.get(user=request.user) pedido = Pedido.objects.all().get(cliente=cliente) return render(request, 'cupons.html', {'lista': produtos, 'venda': pedido.produto.cupom}) The succesfull result P.S: There are 2 Usado (Used) because they have the same "dc" The problem starts when the user used 2 or more "dc", it says that get() received more than 1 result and after some research I found that I need to use filter, but someone can explain me how can achieve the same result using filter ? My classes are Cliente (Client), Produto (Product) and Pedido (Order). my model: class Cliente(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... class Produto(models.Model): STATUS = ( ('Novo', 'Novo'), ('Expirado', 'Expirado'), ('Usado', 'Usado'), ) ... ... cupom = models.CharField(max_length=200, null=True) ... class Pedido(models.Model): cliente = models.ForeignKey(Cliente, null=True, on_delete=models.SET_NULL) produto = models.ForeignKey(Produto, null=True, on_delete=models.SET_NULL) ... Just for sure my html: {% for i in lista %} <tr> <td ><img src="{{i.lojista.imagem}}" class="logo_lojista"> </td> <td> {{i.nome}}</td> <td><a … -
How can I use a Local SQLite3 DB for Testing and a MSSQL DB for Production in Django?
So I have a project I'm currently working on where my DB user does not have the ability to create and destroy databases on the server where my production DB is stored. So I have decided to try and locate my test databases within sqlite3 database much like is shipped with Django. I tried doing this which I think I read about somewhere in the Django documentation, but it is not working and keeps giving me the error: AttributeError: 'PosixPath' object has no attribute 'startswith' Code: DATABASES = { # C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\DATA 'default': { 'ENGINE': 'engine', 'NAME': 'db', 'HOST': '1.1.1.1', 'PORT': '1', 'USER': 'username', 'PASSWORD': 'password', 'OPTIONS': { 'driver': 'driver', 'connection_timeout': 15 }, 'TEST': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'testdb.sqlite3', 'HOST': 'localhost' } }, } I feel like I'm close and so I tried removing the BASE_DIR and just going with the file name but that still sends me messages saying that the user does not have the ability to create DB in master which means it's still connecting to the same PRODUCTION server. -
trying to migrate a date of birth field and i keep getting column "date_of_birth" of relation "Occupier_occupier" does not exist
class OccupierManager(BaseUserManager): def create_user(self,email,username,date_of_birth,occupations,password=None): if not email: raise ValueError('Users must have email address') if not username: raise ValueError('Users must have username') if not occupations: raise ValueError('Occupiers must have occupation') if not date_of_birth: raise ValueError('Users must enter date_of_birth') user = self.model( email = self.normalize_email(email), username =username, occupations = occupations, date_of_birth = date_of_birth ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email = self.normalize_email(email), password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user #Occupier model class Occupier(AbstractBaseUser): email = models.EmailField(verbose_name='email',max_length=59, unique=True) username = models.CharField(max_length=30,unique=True) occupations = models.CharField(max_length=200,null=False) #amount of occupations user does #cliques = models.ForeignKey(Clique,null=True,on_delete=models.CASCADE) #cliques user is in date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) date_of_birth = models.DateField(default=None,null=False) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) password = models.CharField(max_length=255,unique=True) objects = OccupierManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','occupations','password'] def str_(self): return self.username def has_perm(self,perm, obj=None): return self.is_admin def has_module_perms(self,app_label): return True -
failing to install a package in virtual enviroment
Im trying to install django in my virtual environments but files always get install in the python main direction (im using python latest version (3.10) and pip (21.3.1) and visual studio code) too and also when iim trying to work with my new venv i have issues with imports django -
Lack of correct display of Persian in PDF format in Django
I used reportlab in Django to make a pdf of Persian words in Django as follows: from reportlab.pdfgen import canvas from reportlab.lib.units import inch from reportlab.lib.pagesizes import letter import io from django.http import FileResponse from django.conf import settings import reportlab def pdf(request): reportlab.rl_config.TTFSearchPath.append(str(settings.BASE_DIR) +'/static') pdfmetrics.registerFont(TTFont('Samim','Samim.ttf')) buf=io.BytesIO() c=canvas.Canvas(buf,pagesize=letter) txt=c.beginText() txt.setTextOrigin(inch,inch) txt.setFont('Samim',14) lines=[ 'سلام', 'خوبی', 'چه خبر' ] for l in lines: txt.textLine(l) c.drawText(txt) c.showPage() c.save() buf.seek(0) return FileResponse(buf,as_attachment=True,filename='me.pdf') But the output is as follows: I also used other fonts like Nazanin but the result did not change and I even used the xhtml2pdf library but the result was still in this format. In fact, there is a problem with the output format, which must be right to left, which is left to right, unfortunately! How should I solve this problem? -
Error while deploying Django to Heroku using GitHub
I am trying to deploy my GitHub repository on Heroku, the build is successful but when I am going to the domain it is showing an Application Error and the logs are showing this. What I think: I am sure that the problem is in INSTALLED_APPS setting in settings.py. Heroku isn't recognising my 'app_name', may be some namespace problem. GitHub - https://github.com/vivekthedev/savetheearth Heroku Logs File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-10-29T18:52:58.335358+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-10-29T18:52:58.335358+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2021-10-29T18:52:58.335358+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-10-29T18:52:58.335359+00:00 app[web.1]: File "/app/core/core/wsgi.py", line 16, in <module> 2021-10-29T18:52:58.335359+00:00 app[web.1]: application = get_wsgi_application() 2021-10-29T18:52:58.335359+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-10-29T18:52:58.335359+00:00 app[web.1]: django.setup(set_prefix=False) 2021-10-29T18:52:58.335360+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup 2021-10-29T18:52:58.335360+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2021-10-29T18:52:58.335360+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate 2021-10-29T18:52:58.335360+00:00 app[web.1]: app_config = AppConfig.create(entry) 2021-10-29T18:52:58.335360+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 90, in create 2021-10-29T18:52:58.335361+00:00 app[web.1]: module = import_module(entry) 2021-10-29T18:52:58.335361+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-10-29T18:52:58.335361+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-10-29T18:52:58.335361+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-10-29T18:52:58.335361+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-10-29T18:52:58.335361+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked … -
fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error
have tried everything in the forum, but nothing works for me, I am a nube please if you provide the explanation I would like a detailed explanation. Please help to find the problem. I have tried to upload wheels enter image description here I tried to implement MariaDB in \Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb and \Program Files (x86)\MySQL\MySQL Connector C 6.1\lib\mariadb But nothing works form me. PS C:\Users\info\Desktop\storefront> pipenv install mysqlclient Installing mysqlclient... Error: An error occurred while installing mysqlclient! Error text: Collecting mysqlclient Using cached mysqlclient-2.0.3.tar.gz (88 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py): started Building wheel for mysqlclient (setup.py): finished with status 'error' Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient: started Running setup.py install for mysqlclient: finished with status 'error' ERROR: Command errored out with exit status 1: command: 'C:\Users\info\.virtualenvs\storefront-ncd4CFf2\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\info\\AppData\\Local\\Temp\\pip-install- teckkm52\\mysqlclient_916f3b56813c4e1c90eea8491caf2c2c\\setup.py'"'"'; __file__='"'"'C:\\Users\\info\\AppData\\Local\\Temp\\pip-install- teckkm52\\mysqlclient_916f3b56813c4e1c90eea8491caf2c2c\\setup.py'"'"';f = getattr(tokenized, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\info\AppData\Local\Temp\pip-wheel-x6tij91j' cwd: C:\Users\info\AppData\Local\Temp\pip-install- teckkm52\mysqlclient_916f3b56813c4e1c90eea8491caf2c2c\ Complete output (31 … -
Django generic.ListVIew: display list item's details on the same page (~ combine ListView and DetailView)
Roughly speaking, what I want is combine generic.ListView with generic.DetailView, but display the clicked ListView item's details on the same page. What I've done is: generic.ListView of Contacts: from .models import Contact from django.views import generic class ContactList(generic.ListView): model = Contact context_object_name = 'contacts' template_name = 'contacts/list.html' The contacts/list.html template includes a JS Fetch request (GET) to get the clicked item: {% block content %} {% if contacts %} <ul> {% for contact in contacts %} <li><a id="{{ contact.id }}" onClick="showDetails(this.id)">{{ contact.first_name }}</a></li> {% endfor %} </ul> {% else %} No contacts. {% endif %} <div id='contactDetail'></div> <script type="text/javascript"> function showDetails(contactId){ console.log(contactId); fetch(`http://127.0.0.1:8080/contacts/${contactId}`, { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', }, }) .then(response => { // should 500 be processed? return response.json(); }) .then(data => { //Perform actions with the response data from the view window.onload = function() { // build html markup next document.getElementById("contactDetail").innerHTML= ...; } }) } </script> {% endblock content %} The Django view that handles this Fetch-GET request is: from django.shortcuts import get_object_or_404 from django.forms.models import model_to_dict def contact_details(request, contact_id): contact = get_object_or_404(Contact, pk=contact_id) contact = {k: v for k, v in model_to_dict(contact).items() if v} return JsonResponse(contact) Is it the correct way? -
Django returns 301 even with slash appended to URL
I'm trying to test my viewset with APIClient, but it returns HTTP 301 even when I send a request with the slash appended. This is my router for the viewset. from rest_framework.routers import SimpleRouter from .views import ( ReturnLabelTicketViewSet ) app_name = "ticket_submission" router = SimpleRouter() router.register(r'return_label_tickets/', ReturnLabelTicketViewSet) urlpatterns = router.urls This is the app urls. urlpatterns = [path("", include("ticket_submission.urls"), name="root")] And my test case. client = APIClient() response = client.post('/return_label_tickets/', ticket) # ticket data is not relevant here self.assertEqual(response.status_code, 200) -
python3 ModuleNotFoundError: No module named 'rest_framework_jwt'
i want to import from jwt but got an error line 12, in from rest_framework_jwt.settings import api_settings ModuleNotFoundError: No module named 'rest_framework_jwt' -
Return monthly sales value in Django
I've got some simple models below class Stamping(models.Model): created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Product(Stamping): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_product') name = models.CharField(max_length=300, unique=True) price = models.FloatField() class GroupProductOrder(Stamping): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='group_product_orders') product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField() class Order(Stamping): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') fulfilled = models.BooleanField(default=False) products = models.ManyToManyField(GroupProductOrder, blank=True) @property def total_price(self): cost = 0 for product in self.products.all(): cost += product.total_price return cost Now I want to query the database and return some details on a monthly basis. Details like total number of sales for each month and sum of sales for each month. I've tried using annotate but it seems can't pass model property in it. What is the best way to tackle this problem? Example of expected output is {'month': 'October', 'count': 5, 'total': 15} -
Exchanging data between django apps in the same project
I would like to exchange data between two django apps that are coming from a single big app that due to the increasing size and functionalities we decided to split. Specifically I need to retrive only a string in one app from the other. Litterally a 10 character string. The only thing that I found at the moment that satisfies me, since I would like to avoid import stuff from the other app (to me it seems not a clean way to do it, in the other case please change my mind), is making an http request from one app to the other. Anyway I found it overkill. Is there a clean way to achive this without using http request or imports? -
no such table: operational error in django
I run makemigrations followed by migrate but still I get the error when I try to populate DB with dummy values that no such table exists. This happens for one single table. Here is my models.py file for the table: class G(models.Model): desc = models.CharField(max_length=charLen256) points = models.IntegerField(default=0) add = models.BooleanField(default= False) complete = models.BooleanField(default=False) Here is what I try to do in my populate script: def add_goal(item): g = G.objects.get_or_create(desc=item['description'], points=item['points_earned'])[0] g.save() Can anybody spot the problem or error. I happen to have researched a lot but did not find any suggestion other than running makemigrations and migrate. Here is the error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: myapp_goal -
I want to multiple user authentication with django social oauth2 and simpleJWT(Normal register form and social auth together)
I want to use two types of user login in my django project. One of them is the form that asks for information such as email and password, which is the traditional method, and the other is the login process using social media accounts. However, in the video I watched, he first deletes the simpleJWT module he had made before, and then only uses the oauht2 module. I am very confused at this point. I want both types of user input, how can I do that? Here is the video And here is the doc. of oauth2 module -
Create a form with specific changed_data in django for testing purposes
I've overridden ModelAdmin.save_model in order to trigger a task if a certain field was changed. Basically something like: def save_model(self, request, obj, form, change): obj.save() if "field_name" in form: transaction.on_commit(lambda: trigger_task()) Now I'm trying to write a unit test that checks whether this task will be triggered in response to the field change. Only I'm having a hard time creating a form whose changed_data will contain that field. My test is currently something like: @patch(...) def test_task_should_trigger_if_field_changed(self, mocked_task): admin = MyAdmin(model=MyModel, admin_site=AdminSite()) form = MyForm({"field_name": "changed"}, initial={"field_name": "initial"}) ... admin.save_model(request=MagicMock(), obj=my_model, form=form, change=False) The test above won't create a form whose changed_data contains field_name and the task will never be triggered. At this point, I'm considering creating a mocked object that will return that famed form.changed_data["field_name"] but I'm wondering if I'm missing something or is there a simpler way of doing this. -
Channels group_send method doesn't send data until method ends
I am developing the app with private chat between 2 users. There are 2 consumers: chat consumer for receiving/sending messages and chats consumer for receiving messages from all chats of the user. When the consumer receives a message, it should broadcast data into all clients that are connected to websocket, so I use self.channel_layer.group_send method. After that, I have to do some data checks and transformation and send new data into all clients from another websocket (chats websocket). The problem is that data transformations can take some time (DB calls, services, etc), but the first group_send call won't send any data until method receive ends. For example, if I put asyncio.sleep(10) between group_send calls - the data won't be received by clients for 10 seconds. async def receive(self, text_data): await self.channel_layer.group_send(f"chat_{self.sender}_{self.receiver}", text_data) ... #some data transformation or checks await self.channel_layer.group_send(f"all_chats_{self.sender}", transformed_data) -
Connecting flutter with Django API in localhost, but CORS issue keeps blocking connection
I want to connect Djnago API with flutter app, but I have lots of problem. I'll show flutter and django code both. Settings.py """ Django settings for crawler project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)4%#q5&d3^5=0!bauz62wxmc9csk*_c09k!jl2g1a-0rxsa--j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawling_data', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'crawler.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'crawler.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': … -
Is there a way to annotate a related field in django?
Is something like this possible? m = Message.objects.annotate(room__something=Value('DOH', output_field=CharField())).select_related('room') m.room.something == 'DOH' # is true -
Request help for webscraping issues
I have been trying to webscrape two websites for data but facing issues. I will be extremely glad if anyone can help in resolving the problem 1.https://online.capitalcube.com/ The website requires one to login. I came up with the following code after watching tutorials on youtube for the last 2 days. from bs4 import BeautifulSoup import pandas as pd import requests URL = 'https://online.capitalcube.com/' LOGIN_ROUTE = '/login' import requests headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:93.0) Gecko/20100101 Firefox/93.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Sec-Fetch-Dest': 'document', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Site': 'none', 'Sec-Fetch-User': '?1', 'TE': 'trailers', } s = requests.session() login_payload = { 'email': '<intentionally removed it>', 'password': '<intentionally removed it>' } login_req = s.post(URL + LOGIN_ROUTE, headers = headers, data = login_payload) print(login_req.status_code) The error i am getting is as follows *Traceback (most recent call last): File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connectionpool.py", line 382, in _make_request self._validate_conn(conn) File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connectionpool.py", line 1010, in validate_conn conn.connect() File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connection.py", line 416, in connect self.sock = ssl_wrap_socket( File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/util/ssl.py", line 449, in ssl_wrap_socket ssl_sock = ssl_wrap_socket_impl( File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/util/ssl.py", line 493, in _ssl_wrap_socket_impl return ssl_context.wrap_socket(sock, server_hostname=server_hostname) File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/ssl.py", line 500, in wrap_socket return self.sslsocket_class._create( File …