Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF follies when trying to log in to Django with Python requests/sessions
I'm trying to log in to Django using Python requests. There are old questions about this, but none of them are answered due to inadequate details. There are two CSRF tokens involved in this. One is the cookie, and the other is part of the login form. I've verified that Chrome returns the cookie token in the cookies and the form token in the body, and my url encoded body matches the format of one my browser passes back. And yet I still get "Forbidden (CSRF token missing or incorrect.)" as my response. Can any one suggest what I might be doing wrong? My Python looks like this: def login(url, username, password): session = requests.Session() response = session.get(f"{url}/accounts/login/") print(f"First headers: {response.headers}") header_csrftoken = session.cookies['csrftoken'] print(f"Header csrftoken: {header_csrftoken}") soup = BeautifulSoup(response.text, "html.parser") form = soup.find("form", {"id":"login-form"}) found = form.find("input", {"name":"csrfmiddlewaretoken"}) form_csrftoken = found['value'] print(f"csrftoken2: {form_csrftoken}") data = {'csrfmiddlewaretoken': form_csrftoken, 'username': username, 'password': password, 'next': '/'} response2 = session.post(f"{url}/accounts/login/", data=data, headers={'content-type': 'x-www-form-urlencoded'}) print(f"outgoing: {response2.request.body}") print(f"Headers: {response2.request.headers}") First headers: {'Date': 'Mon, 20 Sep 2021 03:37:17 GMT', 'Server': 'WSGIServer/0.2 CPython/3.8.12', 'Content-Type': 'text/html; charset=utf-8', 'Expires': 'Mon, 20 Sep 2021 03:37:17 GMT', 'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate, private', 'Vary': 'Cookie, Origin', 'X-Frame-Options': 'DENY', 'Content-Length': '20609', 'X-Content-Type-Options': … -
Can anyone help me with this issue - Django View (Passing of keys)
I have the following views: def device_port(request): devices = Device.objects.all() if request.method == "POST": selected=request.POST.get('device') devices = Device.objects.get(pk=selected) tablename = 'dev_interface_'+selected print("tablename: " +tablename) cursor=connection.cursor() cursor.execute(f"SELECT interface FROM {tablename} WHERE id >=2") righttable = cursor.fetchall() return redirect('/device/port/selected',{'devices':devices, 'selected': selected, 'righttable':righttable} ) return render(request, 'interface/device_port.html',{'devices':devices}) def device_port_selected(request, pk): if request.method == "POST": job = JobForm(request.POST) device = devices.hostname print(devices) #job.associateddevice = devices.hostname try: selection=request.POST.get('portrange') except: selection = "" messages.warning(request, "Please select the ports") print(selection) #job.associatedinterface = selection return render(request, 'interface/device/port/selected/'+device+'.html',{'devices':devices, 'righttable':righttable} ) return render(request, 'interface/device_port_selected.html',{'devices':devices, 'selected': selected, 'righttable':righttable} ) urls.py urlpatterns = [ path('', views.home, name='interface-home'), path('device/', DeviceListView.as_view(), name='interface-device'), path('device_edit/<int:pk>/', views.device_edit, name='device-edit'), path('device_delete/<int:pk>/', views.device_delete, name = 'device-delete'), path('device_add/', views.device_add, name='device-add'), path('device/port/', views.device_port, name='device-port'), path('device/port/selected/', views.device_port_selected, name='device-port-selected'), path('device/routeport/', views.device_routeport, name='device-routeport'), path('interface/', views.interface_list, name='interface-list') ] device_port.html <form method="POST"> <div class="form-row align-items-center"> <div class="col-md-5 my-1"> {% csrf_token %} <label for="Hostname">Hostname</label> <div class="input-group"> <select id = "list" class="custom-select mr-sm-2" onchange="getSelectValue();"> <option selected>Select</option> {% for device in devices %} <option value={{device.id}}>{{device.hostname}}</option> {%endfor%} </select> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="submit">Go</button> </div> </div> </div> </div> <input type ="text" name="device" id= "txtvalues" style="display:none"> </form> So there are 2 page I am dealing with over here. (/device/port and /device/port/selected). In this first page /device/port, user is required to pick a … -
Object creation assigns proxy class based on base model field(s)
I'm hoping to be able to create an object using a base model but have that object actually be created as a proxy class depending on the object's field(s). So for example, for the following models: class Animal(models.Model): species = models.CharField() class Cat(Animal): class Meta: proxy = True class Dog(Animal): class Meta: proxy = True How can I set it up so that cat = Animal.objects.create(species="cat") dog = Animal.objects.create(species="dog") Animal.objects.all() # Returns queryset of [cat, dog] Cat.objects.all() # Returns queryset of [cat] Dog.objects.all() # Returns queryset of [dog] -
Story object doesn't expire when User post a story feed
How do i set time for a story to expire at a certain time when users post a story, I been working on this project where i want users to be able to post a story feed for a period of time then it get deleted. Here is my story model. actually i don't really understand the way to make the post story of users to expired at a certain time like after 48 hours the post should be deleted from the story feed. class StoryManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( expire__lt=Now() ) class Story(models.Model): title = models.CharField(max_length=250) story = models.FileField(upload_to="stories",blank=True,null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) images = models.ImageField(upload_to="ImageStorie", blank=True,null=True) created = models.DateTimeField(auto_now_add=True) expire = models.DateTimeField(db_index=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name="like") image_thumbnail = ImageSpecField(source='images', processors=[ResizeToFill(500, 300)], format="JPEG", options={'quality':100}) objects = StoryManager() This my view for the story model, but the story doesn't delete after 48 hours when its been post? can someone kindly help me with this! def storie(request): context = {} videos = Story.objects.filter(expire__lt=Now()).delete() context['video'] = videos return render(request,'feed/feed.html', context) -
convert MYSQL four-table join query to Django ORM query
I have a web app, backend using Django. I want to convert a MYSQL four-table join query to the corresponding Django ORM query. The four-table join query is: 'SELECT distinct t.id, t.title as Textbook, GROUP_CONCAT(concat(ci.discipline_code, ci.code, " (" , ci.type , ")") SEPARATOR ', ') as CourseCode FROM TMS_UAT.bms_material m, TMS_UAT.bms_title t, TMS_UAT.bms_course c,TMS_UAT.bms_courseinfo ci where t.id = m.book_id and c.id = m.course_id and ci.id = c.id and isbn != "NA" GROUP BY t.id;' I want to convert it to Django ORM query and use with other filter in view.py: @csrf_exempt def Browse_and_adopt(request): Title_list = Title.objects.filter(Q(Format_issued="eText") | Q(Format_issued="Print")).select_related('publisher') //the four-table join query should be added to this , so the Title_list both have publisher and the column selected by the four-table join query -
Is there a way to seperate the description for the first image and the second image using django?
so for my website is there is 2 part to uploading an images, one is to upload images for the box and the other is to upload an images of the equipment but when it is uploaded the first image description is together with the second image description. Example shown below. Picture of what happens when it is uploaded (not I wanted) picture of what I wanted in my database. views.py @login_required() def ReceptionUnserviceable(request): descriptionbox = Photo.objects.all() if request.method == 'POST': data = request.POST images = request.FILES.getlist('images') for image in images: photo = Photo.objects.create( descriptionbox=data['descriptionbox'], image=image, serialno=data['serialno'], partno=data['partno'], reception=data['reception'], customername=data['customername'], descriptionequipment=data['descriptionequipment'], ) return redirect('success') context = {} return render(request, 'ReceptionUnserviceable.html', context) models.py class Photo(models.Model): class Meta: verbose_name = 'Photo' verbose_name_plural = 'Photos' image = models.ImageField(null=False, blank=False) descriptionbox = models.TextField() serialno = models.TextField() partno = models.TextField() reception = models.TextField() customername = models.TextField() descriptionequipment = models.TextField() def __str__(self): return self.descriptionbox Receptionunservicable.html <form method='POST' action="" enctype="multipart/form-data"> {% csrf_token %} <div> <label>Description Of The Box</label> <input required name="descriptionbox" type="text" placeholder="Enter a description" style="width:300px" class="form-control"> </div> <br> <div> <label>Upload Box Photo</label> <input required name="images" type="file" multiple class="form-control-file"> </div> <br> <div> <label>Part Number</label> <input required name="partno" type="text" placeholder="Enter part number" style="width:300px" class="form-control"> </div> <br> <div> <label>Serial … -
Why is my upload directory relative to the project directory but Django is trying to get it from an app related path?
I am building a Dev-blog to store and refer to project I've coded for my portfolio, and I've been trying to add a media upload capability to my post text boxes. I started off by using a standard RichTextField, which had a built-in function to add Images through URL(No uploading). It worked fine, but I wanted the ability to upload photos from my machine. The blog is fully operational (on a local server for development), so all irrelevant code was disregarded. The only problem is with setting the paths to my image files. models.py from django.db import models from django.utils import timezone from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): author=models.ForeignKey('auth.User',on_delete=models.CASCADE) title= models.CharField(max_length=40) text = RichTextUploadingField() create_date = models.DateTimeField(default=timezone.now()) publication_date = models.DateTimeField(blank=True,null=True) def publish(self): self.publication_date=timezone.now() self.save() def approve_comment(self): return self.comments.filter(approved_comment=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'pk':self.pk}) def ckeditor_upload(self): return reverse('post_detail', kwargs={'pk':self.pk}) urls.py from django.contrib import admin from django.urls import path,include,re_path from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), path('accounts/login/',views.LoginView.as_view(template_name='registration/login.html'),name='login'), path('accounts/logout/',views.LogoutView.as_view(),name='logout',kwargs={'next_page':'/'}), #{'next_page':'/'} makes it go back to homepage re_path(r'^ckeditor/', include('ckeditor_uploader.urls')), ] **settings.py** <pre> INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader', 'blog' ] # # # CKEDITOR_UPLOAD_PATH = 'media/uploads' The file … -
Django manytomany field automatically populates with all objects of related Model
I just added two manytomany fields to a django model; however, when I create a new instance of the model with the manytomany fields, the fields automatically contain all instances of the models they are related to. Here is the model: class Thread(models.Model): title = models.CharField(max_length=250, unique=True) owner = models.ForeignKey(AuthorUser, null=True, on_delete=models.SET_NULL, related_name='+') articles = models.ManyToManyField(Article, null=True) authors = models.ManyToManyField(AuthorUser, null=True) date_created = models.DateTimeField(default=timezone.now) And after creating a new instance of a Thread, it automatically contains all articles and authors currently in the database. Is there a way to fix this so that it starts with nothing in it and I can add authors and articles? -
Configure logger Django
I have the following code: logging.config.dictConfig( { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} - {message}', 'style': '{', }, 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'simple' } }, 'loggers': { 'django': { 'handlers': ['mail_admins'], 'level': 'INFO', 'propagate': True, }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', }, }) The problem basically exists only at the "logger". Whenever i set any of the handlers at the root key it always works, but it never reaches any of the config loggers. Any guesses? -
Python Sockets: Socket not closing when connected = False
When the disconnect message is received from my client(A django site sending the data), my socket isn't closing and this is preventing the rest of the code in my python file from running. If anybody knows what is causing this, help would be great. My Code: HEADER = 64 PORT = 6060 SERVER = '0.0.0.0' ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" my_queue = queue.Queue() print(SERVER) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): print(f"[NEW CONNECTION] {addr} connected") connected = True while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) if msg == DISCONNECT_MESSAGE: connected = False else: my_queue.put(msg) print(f"[{ADDR}] {msg}") conn.send("MSG Received".encode(FORMAT)) conn.close() def start(): server.listen() print(f"[LISTENING] Server Is Listening On {SERVER}") while True: conn, addr = server.accept() thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start() print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}") print("[Starting] Server") start() msg = my_queue.get() print(msg) -
Django MySQL Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535
I am currently migrating my tables to a new MySQL database from SQLite. There were no issues when I migrate to SQLite but when I try to migrate on to MySQL, I get the error above. I think it was due to my textfields taking up much of the space so I added a max_length=500 attribute to all of them but the error persists. This is the error: Is there a way to resize the textfield, or resize the maximum row size? Thanks in advance. -
Django URL Not Matching with Intended View
I'm having trouble figuring out why tag pages for my blog are trying to pass to a different view than the one I intend. My /tag/ url's should go to TagsListView, but instead are going to PostDetail. My url structure: app_name = 'blog' urlpatterns = [ path('', views.home, name='home'), path('search/', SearchResultsView.as_view(), name='search_results'), path('tag/<slug:slug>', views.TagsListView.as_view(), name='blog_tag'), path('<slug:slug>/', views.CategoriesDetail.as_view(), name='categories_detail'), path('<slug:categories_detail>/<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('<slug:categories_detail>/<slug:slug>/comment', views.CommentCreateView.as_view(), name='post_comment_create'), ] View: class TagsListView(ListView): model = Tag template_name = 'blog/tags.html' Template (implementation has to be dynamic): <a href="/{{ tag.slug }}"><h4><span class="badge badge-primary">{{ tag }}</span></h4></a> For some reason the url, domain.com/tag/tagname will try to match and run through the PostDetail view and 404, instead of the TagListView. Everything seems like it should match, so I'm not sure why it's skipping that over. Also, I believe I should have the model for the TagListView set to Post (blog posts), and create a custom queryset that filters based on the slug for the requested tag. Correct? Or is it the other way around? I haven't gotten to that point to test yet and wondering the best approach there. Thanks. -
Axios is sending OPTIONS instead of POST to Django
I'm using Django Rest Framework with a front-end in Vue. I'm using axios to make POST requests to Django, but the Django server is receiving OPTIONS requests, as you can see in the server log. "OPTIONS /save/ HTTP/1.1" 200 0 Broken pipe from ('127.0.0.1', 59396) The problem doesn't appear to be in the server, since CORS is configured correctly and I can send a POST request with Postman. Here's the javascript code async save() { let data = { "name": this.name, "title": this.title, } let config = { header : { "Content-Type": "application/json", } } response = await axios.post( 'http://127.0.0.1:8000/save/', data, config ) } -
Django: ModuleNotFoundError: No module named (django unable to import modules?)
When attempting to debug a file named "formulas.py", I got the following error: ModuleNotFoundError: No module named 'ingredients'. This was strange, as yesterday I debugged the file and it worked perfectly. To my knowledge, I didn't change anything that should have impeded django's ability to load my module. My file structure is the following: Blocky_alchemists blocky_alchemists ingredients media playground database manage.py In playground there are (among others) my formulas.py and views.py, and in ingredients I have my models.py which contains the model called "Ingredient". I am trying to use this model to create a queryset, so I used the following line of code in formulas.py: from ingredients.models import Ingredient When running the file formulas.py however, it runs until the above line of code, and then returns: Traceback (most recent call last): esktop\blocky_alchemists'; & 'C:\Users\ticov.virtualenvs\blocky_alchemists-KNju3Ys9\Scripts\python.exe' 'c:\Users\ticov.vscode\extension File "c:\Users\ticov\desktop\blocky_alchemists\playground\formulas.puncher' '54184' '--' 'c:\Users\ticov\desktop\blocky_alchemists\playground\formulas.py' y", line 3, in from ingredients.models import Ingredient y", line 3, in ModuleNotFoundError: No module named 'ingredients' In my main settings.py I have added 'ingredients' to the installed apps, but it is still unable to find it. Does anyone know how to fix this? Thanks in advance! -
post_save fails to create instance for OneToOneField
In attempting to use signals for the first time, I'm testing the scenario where once a User instance is created a Profile is created and is attached to the User. However, the test is not passing. I've read similar questions, but two signals are used. Django create profile for user signal Create a post_save signal that creates a profile object for me Why are two signals being used in those cases? How can I get a profile created in my case? from django.test import TestCase from ..forms import CreateProfileForm class TestNewUserProfileCreated(TestCase): '''Verify that a user profile is created once a user has registered with a username and password.''' @classmethod def setUpTestData(cls): user_submitted_data = { "username": "MockUser", "password1": "#hf7*3k", "password2": "#hf7*3k" } cls.form = CreateProfileForm(**user_submitted_data) cls.user = cls.form.save() def test_new_user_profile_form_pass(self): self.assertTrue(hasattr(self.user, 'profile')) forms.py class CreateProfileForm(UserCreationForm): def __init__(self, *args, **kwargs): pass def save(self, *args, **kwargs): pass class Meta: pass models.py class Profile(Model): user = OneToOneField( settings.AUTH_USER_MODEL, on_delete=CASCADE, related_name="profile" ) favorite_images = ManyToManyField( FavoriteImage, related_name="favorites" ) follows = ManyToManyField("self", related_name="followers") following = ManyToManyField("self", related_name="following") receivers.py from .models import Profile def create_profile_receiver(sender, instance, created, **kwargs): if created: profile = Profile.objects.create(user=instance) instance.profile = profile app.py from django.apps import AppConfig from django.conf import settings from django.db.models.signals … -
Listen for notification on React Native app from Django server
I'm currently developing a programme that will need app developers to listen out for a (ideally) silent notification from my Django server. Right now, I'm testing with a React Native app I've made but I don't know how to implement something like this. Basically, when something happens in relation to a certain app on the server end of things, I want to send a notification to that client app to react accordingly. Almost like a webhook but for mobile. It's important to know that in practice, I won't be the owner and developer of both the client-side app and the server-side software, just the server-side. If anyone knows how to do it natively on either Android or iOS that would be appreciated too. -
Django: How to add next to manual login redirect?
I have a view: def create_something(request): ... I want to redirect to login if a person isn't logged in. Normally I'd use: @login_required def create_something(request): ... but 🍑.... I want to add a message before the redirect. I wanted to do it like this: def create_something(request): if not request.user.is_authenticated: messages.info(request, 'You must be logged in to create a thing 👀.') return redirect('login') ... However, that doesn't include a ?next in the url to go back to the page I was going to. So my question is: How would you manually redirect back to the login page WITH a manually added ?next query? -
Spanning multi-valued relationships
I read the django documentation and I found something confusing! https://docs.djangoproject.com/en/3.2/topics/db/queries/#spanning-multi-valued-relationships. It is stated that "When you are filtering an object based on a ManyToManyField or a reverse ForeignKey, there are two different sorts of filter you may be interested in" "To select all blogs that contain entries with both “Lennon” in the headline and that were published in 2008 (the same entry satisfying both conditions), we would write:" Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008) "To select all blogs that contain an entry with “Lennon” in the headline as well as an entry that was published in 2008, we would write:" Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008) "Suppose there is only one blog that had both entries containing “Lennon” and entries from 2008, but that none of the entries from 2008 contained “Lennon”. The first query would not return any blogs, but the second query would return that one blog" So, by reading this guide, multiple questions have been created in my mind: 1- What is difference between these two types of filtering? what I know is that both of them must return blogs that contain both 'Lennon' in headline and was published in 2008. I can't find out the point. 2- The Document says this rule is just … -
why i am getting TypeError: create_superuser() missing 1 required positional argument: 'username' in AbstractUser?
I am have written a custom User model and when trying to create superuser got the following error**:-** TypeError: create_superuser() missing 1 required positional argument: 'username' when i run the command for creating superuser, django did't asked me to enter username field. Model Class:- class CustomUser(AbstractUser): email = models.EmailField(max_length=250, null=False, unique=True) name = models.CharField(max_length=50, null=False) username = models.CharField(max_length=50, null=False) password = models.CharField(max_length=15, null=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] this is all what i have written, and i am new django unable to figure out what i am doing wrong. Thanks in advance. Hope to here from you soon. -
Django: how apply uuid django.contrib.auth migration
I create a project Django with Postgres. I only apply to User model. But I want to use uuid for field primary key id in all models in app django.contrib.auth such as User, Permission, Group ... Beside, I want to apply uuid for all migrations of my project How can I do that, please help me. -
Django API path restrict
I am pretty new to Django REST framework and have made an app with React/Django REST by following a tutorial. I am including an example on how it's done urls.py urlpatterns = [ path('', TemplateView.as_view(template_name='index.html')), path('api/register/', RegisterAPI.as_view(), name='register'), ] views.py class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): ... and then let's say index.html contains registration form that generates JSON request and sends it to the register url included above and then it obviously gets processed by the view and response is generated. This is all cool and simple. However, now let's say that some user goes to the url http://127.0.0.1:8000/api/register/. He/she will then access my auto built django rest page with the form that doesn't look very "production-ready". I was wondering if there was a way to allow this page to be accessed by the react, but when we try accessing this url physically, I want the page to redirect us to some other page, or show 404 error. Is there a way to do this? Thanks for the help! -
Django form not rendering widget
I can't figure out, why the django form widget is not rendered in the browser. This is my form: from django import forms from .models import RealEstateTax class CreateRealEstateForm(forms.ModelForm): class Meta: model = RealEstateTax fields = ['invoice_number',] widget = { 'invoice_number': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Text goes here'}), } Just for testing purposes, I reattributed the field as a Textarea and gave it a class where the text should appear red. This is the template: {% extends 'main.html' %} {% load static %} {% block title %} Create Realestate Tax {% endblock %} {% block content %} <style> .form-control { color: red; } </style> <form method="post"> <div class="form-group"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-info">Send</button> </div> </form> {% endblock %} When I inspect the element in the browser, there is no class, it is not a Textarea and the text is not red: This is what I specified in the view: from realestate.models import RealEstate from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from django.db.models import Sum from realestate.models import RealEstate from .forms import CreateRealEstateForm def create_real_tax(request): form = CreateRealEstateForm if request.method == 'POST': form = CreateRealEstateForm(request.POST) if form.is_valid(): form.save() print(form.base_fields) context = … -
Django: Query database from Channels consumers
I had a Django app which had live chat working. Now I am trying to add a query to the database within the connect method. I am following the Channels documentation, and tried the solution in this other StackOverflow question but nothing is working. Below is my code. The error I'm seeing in the Javascript console is WebSocket connection to 'ws://localhost:9008/ws/chat/334/' failed: WebSocket is closed before the connection is established. I do have redis-server running on localhost and that was working before, so that's not a problem. async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name valid_connection = await database_sync_to_async(self.verify_chat_room_key)() # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def verify_chat_room_key(self): trans = database_sync_to_async(Transaction.objects.get)(id=self.room_name) return True -
Django view filter count
I want to get to know the number 'tasks' (Pendentes) for each 'Customer' (Cliente) I have this models in my models.py: class Cliente(models.Model): id = models.IntegerField(primary_key=True) nome = models.CharField(max_length=200, help_text="Nome") localidade = models.CharField(max_length=100, help_text="Localidade") [...] class Pendente(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ID Unico") cliente = models.ForeignKey('Cliente', on_delete=models.RESTRICT, blank=True, null=True) memo = models.TextField(null=True, blank=True, help_text="Memória Descritiva", max_length=200) criado = models.DateField(default=date.today, null=True, blank=True, help_text="Data registo ") concluir = models.DateField(null=True, blank=True, help_text="Data de execução máxima ") tecnico = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) tecnicoatribuido = models.ForeignKey('TecnicoAtribuido', on_delete=models.SET_NULL, blank=True, null=True) Basicly i want to run this sql: "select A.id, A.nome, A.localidade, count(B.id) as tarefas from todolist_pendente B LEFT JOIN todolist_cliente A ON A.id = B.cliente_id GROUP by A.id;" Can't seem to figure out how it would work on a view. I'm able to get the count per cliente with : resultado = Pendente.objects.values('cliente').order_by('cliente').annotate(count=Count('id')) But this doesn't render the name of each customer on the template. On my template I'm using : <ul> {% for obj in resultado %} <li>{{ obj.cliente}} : {{ obj.count}}</li> {% endfor %} </ul> This is rendering: 6 : 2 35 : 1 40 : 1 92 : 1 106 : 1 105 : 1 is there a way to get the … -
django-compressor "Settings has no attribute"
I included django-compressor in version 2.4.1 to my django-project to compile scss-files. I followed the quickstart guide at https://django-compressor.readthedocs.io/en/stable/quickstart/ When I am now open the page where I included the css-file I got an error with regarding to this line {% compress css %} The error: 'Settings' object has no attribute 'COMPRESS_DEBUG_TOGGLE' When I add the value manually it comes to the next attribute which is not set and so on for all attributes. Regarding to the documentation the attributes should have a standard value. Why is my project not recognizing that there are default values set to the variables?