Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0: Display a Select widget as HTML in the List View table
I have a Django 2.0 app. One class in the admin interface ("list" view, not "change"!) needs a column with a select dropdown with numbers from 1:10, and a Submit button. From the docs I understood that I should use a "Select" widget and define a form. I am curious if it's possible to do with just admin.py and my model, without involving forms.py, templates, etc. So I tried this: class MyClassAdmin(SuperAdmin): list_display = ["inline_mycolumn", "other_field1", "etc"] def mycolumn(self, my_object): from django import forms MY_CHOICES= [tuple([x,x]) for x in range(1,11)] return mark_safe(forms.Select(choices=MY_CHOICES)) .....the rest of the class code.... This below of course does not render the widget as select dropdown, in the source of the table it comes as: <th class="field-column"><a href="/admin/<myapp>/<my_model_name>/<record id>/change/"><django.forms.widgets.select object="" at="" 0x7f4fea267828=""></django.forms.widgets.select></a></th> and the cell stays empty. The rest of the table is rendered as it should. And without mark_safe it just prints the object's name in the cell: format_html (I had to try!) gives 'Select' object has no attribute 'format' Maybe there's a way to cast that widget object into HTML representation with just admin.py code? Thanks -
Azure Nginx splitted frontend and backend - proxy
Need some help with Microsoft Azure and Docker and Nginx. I got an website where backend and frontend are splitted (django and react) with docker. They are working on Microsoft Azure Virtual machine and they are working without nginx but now i am trying to use nginx to proxy urls to the right ports. With below links i can access two parts of my website and i want to change it to: mywebsite.northeurope.cloudapp.azure.com:8000 < this is backend of my website mywebsite.northeurope.cloudapp.azure.com:3000 < this is frontend of my website And below are the options which i would like to have mywebsite.northeurope.cloudapp.azure.com\back < this is backend of my website mywebsite.northeurope.cloudapp.azure.com\front < this is frontend of my website Below are my files: docker-compose version: '3' services: db: image: postgres:9.6-alpine environment: POSTGRES_DB: db POSTGRES_USER: me POSTGRES_PASSWORD: mypassword volumes: - ./data/postgres:/var/lib/postgresql/data my_django_web: image: my_image_backend build: ./backend/django_dashboard command: > bash -c " source ./env.sh && gunicorn django_dashboard.wsgi:application --bind 0.0.0.0:8000 --chdir ./backend/django_dashboard/" volumes: - .:/code expose: - 8000 depends_on: - db restart: "on-failure" nginx: build: ./nginx ports: - 1337:80 depends_on: - my_django_web frontend: image: my_image_frontend build: ./frontend/dashboard volumes: - ./frontend/dashboard:/code/frontend/dashboard ports: - "3000:3000" Dockerfile for nginx that changes my website from localhost:8000 to localhost:1337 FROM nginx:1.17.4-alpine RUN … -
How to set default value to None for Django choices form field
The below Django form works, but for the life of me I can't figure out how to make the ModelChoiceField for operator blank or set to None by default. I would like the user to have the option of just leaving this choices field set to None. This autopopulates with the first user in the user list. Model class Build(models.Model): PSScustomer = models.ForeignKey(Customer, on_delete=models.CASCADE) author = models.ForeignKey(get_user_model(),related_name='+',on_delete=models.CASCADE,blank=True, null= True,) plannedAuthor = models.ForeignKey(CustomUser,related_name='+',blank=True, null= True, on_delete=models.CASCADE) status = models.CharField(max_length=100,blank=True,) operator = models.ForeignKey(CustomUser,related_name='+',blank=True, null= True, on_delete=models.CASCADE, default=None) View class queuedBuild_CreateView(LoginRequiredMixin,CreateView): model = Build form_class = queuedBuild_Creation_Form template_name = 'addQueuedBuild.html' login_url = 'login' success_url = reverse_lazy('equipmentdashboard') def get_form(self, form_class=None): form = super().get_form(form_class) customer = self.request.user.PSScustomer form.fields['operator'].choices = [(item.id, item.first_name) for item in CustomUser.objects.filter(isDevice=False, PSScustomer = customer)] return form Form class queuedBuild_Creation_Form(forms.ModelForm): buildDescrip = forms.ModelChoiceField(initial='Your name') def __init__(self, *args, **kwargs): super(queuedBuild_Creation_Form, self).__init__(*args, **kwargs) self.fields['status'].required = True class Meta: model = Build fields = ['status', 'operator',] -
Not able to start `django` project in local as well as in docker
I am using Docker to deploy Python2.7 application with Django1.8. I am facing some issue from last two days and I found error as below. Error: root@64f8c580dd0a:/code# python manage.py runserver read completed! read completed! Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/lib/python2.7/site-packages/imagekit/__init__.py", line 2, in <module> from . import conf File "/usr/local/lib/python2.7/site-packages/imagekit/conf.py", line 1, in <module> from appconf import AppConf File "/usr/local/lib/python2.7/site-packages/appconf/__init__.py", line 1, in <module> from .base import AppConf # noqa File "/usr/local/lib/python2.7/site-packages/appconf/base.py", line 107 class AppConf(metaclass=AppConfMetaClass): ^ SyntaxError: invalid syntax uwsgi configuration: [uwsgi] wsgi-file = /code/config/wsgi.py callable = application uid = nginx gid = nginx socket = /tmp/uwsgi.sock chown-socket = nginx:nginx chmod-socket = 664 master = true cheaper = 5 processes = 15 vacuum = true I have installed below dependencies: Babel==2.8.0 beautifulsoup4==4.4.1 boto==2.38.0 boto3==1.4.4 botocore==1.5.95 cffi==1.14.0 contextlib2==0.6.0.post1 copyleaks==2.5.1 cryptography==2.8 dce-lti-py==0.7.4 Django==1.8 django-admin-honeypot==1.0.0 django-allauth==0.31.0 django-appconf==1.0.4 django-ckeditor==5.2.2 django-colorful==1.0.1 django-common-helpers==0.9.2 django-cors-headers==1.0.0 django-cron==0.5.0 django-debug-toolbar==1.6 django-environ==0.4.3 django-extensions==1.5.0 django-filter==1.1.0 django-hosts==2.0 django-imagekit==4.0.1 … -
django-elasticsearch-dsl with a nested field
I'm trying to use django-elasticsearch-dsl with AWS ElasticSearch service 7.4 and I'm trying to implement a NestedField. I cannot get the queries to work on the nested field So my model is defined as class MyModel (models.Model): name = models.CharField(max_length=101) ... my_other_model = models.ManyToManyField( 'MyOtherModel', blank=True, ) my_third_model = models.ManyToManyField( 'MyThirdModel', blank=True, ) class MyOtherModel(models.Model): name = models.CharField(max_length=101) class MyThirdModel(models.Model): name = models.CharField(max_length=101) My ES document is defined @search_index.document class MyModelDocument(Document): name = fields.TextField() my_other_model = fields.NestedField(properties={ 'name': fields.TextField() }) my_third_model = fields.NestedField(properties={ 'name': fields.TextField() }) I then try to search on this s = MyModelDocument.search() This works s.query( 'nested', path='my_other_model', query=Q('match', my_other_model__name='ABC') ) BUT I need to search a list, so I'm trying the following, but it returns nothing s.query( 'nested', path='my_other_model', query=Q('terms', my_other_model__name=['ABC','DEF']) ) How to I achieve this? -
How to make a query to get column difference between two followed rows
I'm trying to get the difference between a row column and the next row column. For example: pk | hour | ts ----+-------+---- 1 | 10:30 | 0 2 | 10:50 | 20 3 | 11:00 | 10 Where ts is the difference between hour column between next element and current I don't want to get all objects and then do this using python because in production there will be a lot of rows and I heard it becomes inefficient. So I've tried several ways. Option 1 - Using raw sql with LAG: Computer.objects.raw(''' SELECT id, hostname, date, date - LAG (date) OVER (ORDER BY date) AS lagged FROM hub_computer ''') When accessing an element, it gives the following error: Traceback (most recent call last): File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near "(": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1461, in __getitem__ return list(self)[k] File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1421, in __iter__ self._fetch_all() File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1408, in _fetch_all … -
Django Betterforms: how to pass initial values to FilterForm
Doc of django-betterforms: https://github.com/fusionbox/django-betterforms I've tried three different strategies, none works: 1) in the field definition: date_from = DateTimeField(label=_('Date from'), initial='{:%Y-%m-%d}'.format(datetime.date.today()), required=True ) 2) In the form init: def __init__(self, *args, **kwargs): updated_initial = {} updated_initial['date_from'] = '{:%Y-%m-%d}'.format(datetime.date.today()) kwargs.update(initial=updated_initial) super().__init__(*args, **kwargs) 3) In the get_initial of the BrowseView that uses this form: def get_initial(self): initial = super().get_initial() initial['date_from'] = '{:%Y-%m-%d}'.format(datetime.date.today()) return initial None of them works. Any ideas on how to populate the FilterForm of the BrowseView with initial values? -
How to assign value of field of one model to field of another model?
Say, I have a view function that creates a Vacancy object on saving the form, and it has the field company that, if the form is valid, has to be assigned with value of field name, that is on the other model named EmployerProfile, how can I do that? I have company as a foreign key on my model. My models class EmployerProfile(models.Model): name = models.CharField(max_length = 64) description = models.TextField() username = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) class Vacancy(models.Model): name = models.CharField(max_length = 64) competences = models.CharField(max_length = 32) salary = models.DecimalField(decimal_places = 2, max_digits = 10) description = models.TextField(null = True) company = models.ForeignKey(EmployerProfile, on_delete = models.CASCADE) featured = models.BooleanField(default = False) My view @login_required(login_url = 'login') def vacancyAddView(request): if request.method == 'POST': form = VacancyAddForm(request.POST) if form.is_valid(): form.save() return redirect('profile') else: form = VacancyAddForm() context = { 'form':form } return render(request, "addVacancy.html", context) My form class VacancyAddForm(forms.ModelForm): class Meta: model = Vacancy fields = [ 'name', 'competences', 'description', 'salary', ] P.S. I have tried adding this piece of code to my view, rigth after form.is_valid(): obj = EmployerProfile.objects.get(username = request.user) form.instance.company = obj.name but it didn't work, it returned the ValueError with text "Vacancy.company" must be a "EmployerProfile" … -
Django Bootstrap Dropdown Menu not working
Building my first Django app from a tutorial, following the instructions pretty much verbatim but my navbar dropdown menu is not working no matter what I try, so unable to log out or change password from the navbar. I am very new to js, but some things I have tried: Experimenting w different browsers (doesn't work for Safari or Chrome) Have looked at similar questions and implemented those techniques but it's still not working (linking to js in the head, making sure to link to js/popper/bootstrap in the correct order, etc.): django bootstrap dropdown not working Have also attempted to create static folders in pages/static/js and pages/static/css but that looks like it may be for more advanced styling than what we're going for here. Bootstrap template not working correctly Django Template file/directory below. Issue is between lines 55 and 68 (div class="collapse navbar-collapse") Thanks in advance for the help. <!-- templates/base.html --> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/\ 1.14.3/ umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAKl8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/\ js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ\ 6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <!-- Bootstrap … -
Factory Boy test with Wagtail fails: TypeError: Field 'id' expected a number but got {}
I'm trying to set up Factory Boy for a Wagtail site. In order for that to work, the _create method must be able to establish a parent-child-relationship between pages. I override the _create method as described in the docs: https://factoryboy.readthedocs.io/en/latest/reference.html#attributes-and-methods. But the addition of the 'parent' key causes the error. Have been looking at it for ages, dug into the source files. I suspect it has to do with the way the model_class method passes the kwargs, but I guess I'm blind for any obvious mistakes by now. Any help would greatly be appreciated! models.py: from wagtail.core.models import Page class HomePage(Page): pass class SubjectPage(Page): pass tests.py: from .factories import HomePageFactory, SubjectPageFactory from django.test import TestCase class TestModels(TestCase): @classmethod def setUpTestData(cls): cls.homepage = HomePageFactory(title='Test page') cls.subjectpage = SubjectPageFactory(parent=cls.homepage) def test_dummy(self): self.assertTrue(True) factories.py: import factory from .models import HomePage, SubjectPage from wagtail.core.models import Page class PageFactory(factory.django.DjangoModelFactory): class Meta: abstract = True @classmethod def _create(cls, model_class, *args, **kwargs): try: parent = kwargs.pop('parent') page = model_class(*args, kwargs) except KeyError: parent = Page.get_first_root_node() page = model_class(*args, **kwargs) parent.add_child(instance=page) return page class HomePageFactory(PageFactory): class Meta: model = HomePage class SubjectPageFactory(PageFactory): class Meta: model = SubjectPage -
[Django} Is there a way for a user to create a group and add other users?
I've tried to find resources on this but it all directs me to groups in admin. Like I want to be able for a user to create a group and add fellow users to that group. This group will then have permissons of editing a "to-do list". -
Django - can't refresh page - browser fine - there must be a cache. How do I stop it?
I have a site with a webhost which has a Django set up and I can't see the changes on a template for a variable which is hard-coded in a view. I've stripped the view right down and all I have now is:- @never_cache def test_pie_view(request): color1="blue" context={ "colour": color1 } return render(request, "_testing/pie.html", {'context': context}) and my template "_testing/pie.html" stripped down also:- <body> <p> {{ context.colour }} </p> </body> But the template shows "red" which was the last value of color1 before I changed it. The work in this case was to pass some JSON to a template, have JS pick it up and draw a pie-chart. Ultimately all the segment values and probably the colours will come from my models but the object for testing was to get something looking decent before making it dynamic. And then I tried to change a colour... My webhost has an app page from which I can reset the python application, after which the page will display the correct value. I have other pages sourcing data from my models via their respective views which are displaying just fine. It's not an issue with the browser - the old variable shows on different … -
No Virtual Host when trying to deploy Django rest-framework API using WAMP and mod_wsgi
I am trying to deploy a Django rest-framework API using WAMP and mod_wsgi. I have tested the API by running 'python manage.py runserver' command and it's working as expected. To setup and configure Django, WAMP and mod_wsgi, I used the below link for refrence: https://medium.com/@ahmadalsajid/serve-django-applications-with-mode-wsgi-and-apache-on-windows-server-4d35ab2ac6b6 below are the changes made to 'httpd.conf' and 'httpd-vhosts.conf' files httpd.conf Listen 127.0.0.1:8081 Listen 127.0.0.1:8089 ServerName localhost:8081 LoadModule wsgi_module "c:/python376/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" LoadFile "c:/python376/python37.dll" WSGIPythonHome "c:/python376" WSGIPythonPath "C:/C4U/Predictor" WSGIPassAuthorization On httpd-vhosts.conf # Virtual Hosts # <VirtualHost 127.0.0.1:8089> WSGIPassAuthorization On ErrorLog "C:/C4U/Predictor/Predictor.error.log" CustomLog "C:/C4U/Predictor/Predictor.access.log" combined WSGIScriptAlias / "C:/C4U/Predictor/Predictor/wsgi_windows.py" DocumentRoot "C:/C4U/Predictor" <Directory "C:/C4U/Predictor/Predictor"> <Files wsgi_windows.py> AllowOverride All Require all Granted </Files> </Directory> Alias /static "C:/C4U/Predictor/static" <Directory "C:/C4U/Predictor/static"> Require all granted </Directory> </VirtualHost> After this, I started WAMP service and I am able to reach 'localhost:8081' but it's saying no VirtualHost -
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use searches.set() instead
I've set up my models and viewsets in my Django REST API to assign a search record to a particular user, and to associate all the relevant user's searches to their record in the User model. It was all working fine, but I'm now getting the TypeError error message (in the subject line of this question) when I try to create a new user. I've listed the relevant models, serializers and viewsets below. Please could anyone take a look and let me know where I'm going wrong? Any help would be very much appreciated. User serializer: class UserSerializer(serializers.ModelSerializer): searches = serializers.PrimaryKeyRelatedField(many=True, queryset=SearchHistoryModel.objects.all()) class Meta: model = User fields = ('id', 'username', 'email', 'password', 'searches') extra_kwargs = {'email': { 'required': True, 'validators': [UniqueValidator(queryset=User.objects.all())] }} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user User viewset: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny] Search model: class SearchHistoryModel(models.Model): """ Stores each user's search submission """ created_date = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, related_name='searches', on_delete=models.CASCADE) cpu_component_name = models.CharField(max_length=10, blank=False) cpu_subcomponent_name = models.CharField(max_length=50, blank=False) motherboard_name = models.CharField(max_length=20, blank=False) gpu_component_name = models.CharField(max_length=10, blank=True, null=True) gpu_subcomponent_name = models.CharField(max_length=50, blank=True, null=True) gpu_subcomponent_quantity = models.PositiveIntegerField(default=0) ram_component_name = models.CharField(max_length=15, blank=True, null=True) ram_component_quantity = models.PositiveIntegerField(default=0) ssd_component_name = models.CharField(max_length=15, … -
Django REST Framework: custom serializer variables
I am using a model serializer (many=True) in Django Rest Framework where I want to return booking_color and text_color properties in JSON in order to display a booking instance on a calendar plugin. Both properties depend on job_type and job_status variables that are calculated (using foreign keys, etc.). I want to run a calculation for those variables when a particular instance gets initialized (in the init method) so that both calculated values then become available for both method fields (booking_color and text_color). The init method, however, passes entire queryset as 'inst' and so I can't do instance-specific calculations. What would be the best way around this? I have previously ran those calculations in the first method in the list ('get_booking_color' in this case) and it works, but it isn't very elegant and I am not sure if I am supposed to do it. class CalendarView(serializers.ModelSerializer): booking_color = serializers.SerializerMethodField() text_color = serializers.SerializerMethodField() def __init__(self, inst): self.job_type = [complicated calculation that depends on inst values] self.invoice_status = [complicated calculation that depends on inst values] def get_booking_color(self, inst): if self.invoice_status == 1: if self.job_type == 1: return "#000000" elif self.job_type == 2: return "#f1c40f" elif self.job_type == 3: return "#FFFFF" else: return '#faase4' … -
invoke data from view after database operation in django
I have a model named "Routing_Dest_Area", i need to get the destinationId from that table and using that value I need to write another query in the same view function itself.I have written the query but don't know how to pass this value to the next query as argument.Pleaae help me to solve . ...models.py....... class Routing_Dest_Area(models.Model): areaDigit = models.IntegerField(primary_key=True) destinationId = models.IntegerField() destinationName=models.CharField(max_length=30) def __str__(self): return '%d' % (self.destinationId) class Routing_Point(models.Model): destinationId = models.IntegerField() productId=models.CharField(max_length=30) routingPointId= models.IntegerField() routingPointName=models.CharField(max_length=30) ...view.py..... def get_route_list(request): data={} if request.method == "POST": areaDigit = request.POST['areaDigit'] destination_id=Routing_Dest_Area.objects.get(areaDigit=areaDigit) data={'test1':Routing_Point.objects.get(destinationId=destination_id)} else: data = '' return render(request, 'routing/test.html',{'data':data}) -
Add custom fields to Django Rest
I am subclassing Django's rest framework APIException class to create my custom API exceptions. For example, one of my exceptions look like this: class Unauthorized(APIException): status_code = 401 default_detail = 'You have to login first.' default_code = 'ERR_UNAUTHORIZED' And I've written a custom exception handler to modify key names. This is the part in my exception handler that deals with these kinds of exceptions: def custom_exception_handler(exc, context): response.data['code'] = response.data['detail'].code response.data['message'] = response.data['detail'] print(response.data) del response.data['detail'] return response As a result, the output for my exceptions looks like this : { "code": "ERR_UNAUTHORIZED", "message": "You have to login first." } What I want to do now is that I want to add a new field to my exceptions so that my exception output looks like this: { "code": "ERR_UNAUTHORIZED", "message": "You have to login first.", "another field" : "extra data" } I'm quite new to Django and I've searched about this and also tried to add the "another field" to my custom exception class fields but that couldn't solve my problem. Are there any ways to do something like this? -
Using the Django authentication system within a React SPA
I'm currently developing an application based on React and Django. I'm using Django rest Framework to create REST APIs that are consumed in the React frontend. This works pretty well. I'm now willing to implement authentication using Django session authentication system for the application. I could create authentication APIs. However I would prefer using Django authentication system. How can I use Django authentication views and forms in a React SPA? A code snippet describing the overall architecture would be much appreciated. I can't figure out how to have the React app "calling Django code" (apart from DRF APIs)! My question is about authentication, but I could reuse the same mechanism for other Django views. -
Django channels consumer freezes
I'm trying to create a Django Channels consumer which receives some data in real time from a RabbitMQ queue and then sends this data to a frontend. Here is my consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='Test') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume( queue='Test', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') await self.send({ "type": "websocket.accept" }) await channel.start_consuming() async def websocket_receive(self, event): print("received", event) # Echo the same received payload async def websocket_disconnect(self, event): print("disconnected", event) And here is my Javascript code: <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) if (loc.protocol == 'https:'){ wsStart = 'wss://' } socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("message", e) } socket.onerror = function(e){ console.log("message", e) } socket.onclose = function(e){ console.log("message", e) } </script> The problem with this code is that, altough in my console i will see the queue waiting for data, on my HTML page i won't see any message appear when the connection is opened; even more, … -
In Django, how do I aggregate one annotation result by another?
Here's a tricky operation that I've been working on. I have the following: users.values('first_name').annotate(demo=F('demo_responses__demographic__display'), response=F('demo_responses__option__display')) When I run this, I get something like the following for results: [ {'first_name': 'Bob', 'demo': 'Business Category', 'response': 'Engineering'}, {'first_name': 'Bob', 'demo': 'Job Function', 'response': 'Training'} {'first_name': 'Joe', 'demo': 'Business Category', 'response': 'Restaurant'}, {'first_name': 'Joe', 'demo': 'Job Function', 'response': 'Server'} ] What I would like to do is compress these into the following: [ {'first_name': 'Bob', 'Business Category': 'Engineering', 'Job Function': 'Training'}, {'first_name': 'Joe', 'Business Category': 'Restaurant', 'Job Function': 'Server'}, ] Having it in this format would be helpful for some of the reports I'm generating. I know that I can do this programmatically, but I didn't know if there was some Django query magic that I could use to get there faster. Any ideas? -
Django - Filtering Related Sets in Templates
I have two models; class Customer(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() class WorkOrder(models.Model): date_created = models.DateField('Date', default=datetime.now) due_date = models.DateField('Due Date') customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name='Customer') STATUS_CHOICES = [ ('pending', 'Pending'), ('approved', 'Approved'), ('completed', 'Completed'), ('cancelled', 'Cancelled'), ] status = models.CharField('Status of the work order', max_length=10, choices=STATUS_CHOICES, default='pending') description = models.TextField('Description of the work') I wrote a class based list view to make a customer list: class ReportCustomerListView(ListView): model = CustomUser template_name = 'reports/customer_report.html' def get_queryset(self): return CustomUser.objects.filter(is_staff=False).filter(is_superuser=False) I would like to prepare a report for the user about its customers so I wanted to show how many pending, approved and completed work orders a customer have. My list template is; <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Company</th> <th scope="col">Pending Work Orders</th> <th scope="col">Active Work Orders</th> <th scope="col">Completed Work Orders</th> <th scope="col">Draft Bills</th> </tr> </thead> <tbody> {% for customer in object_list %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ customer.first_name }}</td> <td>{{ customer.last_name }}</td> <td>{{ customer.company.company_name }}</td> ... ... ... // the part where I am stuck But I am lost after that after 4 hours of reading I am more confused. I know I can access work orders … -
OSError: [Errno 30] Read-only file system: '/[Path to project]' on mac
I am trying to set up django-silk in my django project and I keep running into this issue when I run python manage.py collectstatic. I have tried creating a new virtual environment and trying again but I get the same error. But if I were to create a new django project with only Dango Rest Framework and Silk everything works fine. I have been stuck on this issue for several days. Can anyone help? -
Count CheckBox in Django-tables2 table and Rendering
I want display the actual sum of checked box with a table by django-tables2. Table Structure class GeneralTable(tables.Table): """ GeneralTable Class """ id = "" s = tables.CheckBoxColumn(accessor="id", attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False) column_default_show = ['s'] export_formats = ['csv', 'xls'] class Meta: """ Meta Class """ attrs = {'class': 'table table-sm table-hover table-bordered table-striped table-condensed'} Table Generate table = GeneralTable(data) print(table.as_html(request)) Table html <table class="table table-sm table-hover table-bordered table-striped table-condensed"> <thead > <tr> <th class="s"> <input type="checkbox" onclick="toggle(this)"/> </th> </tr> </thead> <tbody > <tr class="even"> <td class="s"><input type="checkbox" name="s" value="386"/></td> </tr> </tbody> </table> HTML code I try to build a javascript function but the function render the count of the checked box (as excepted) but when i count all the checkboxs with the checkbox in the header columns, it's not working like in the image below. <p id="result"><p> {% block table%} <div class="row" style=" white-space: nowrap;"> {% load django_tables2 %} {% render_table table %} <br/> </div> <script> showChecked(); function showChecked(){ document.getElementById("result").textContent = "Total Number Selected = " + document.querySelectorAll("input:checked").length; } document.querySelectorAll("input[name=s]").forEach(i=>{ i.onclick = function(){ showChecked(); } }); </script> -
ModelBackend authenticate doesn't receive credentials when using Admin Panel
I've setup a custom backend with the following configuration: Settings.py; REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'users.backends.CustomUserBackend', 'django.contrib.auth.backends.ModelBackend', ), } AUTHENTICATION_BACKENDS = ('users.backends.CustomUserBackend',) backends.py class CustomUserBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = request.data.get("username") if password is None: password = request.data.get("password") .... return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None When submitting a request via my API this works as expected and authenticates the user correctly etc. My problem comes when I try and log into the admin panel. The stack trace I'm getting when trying to login is caused by an exception when trying to access request.data which is because it's not the correct type to look at, which is correct to how my logic works. The problem is the authenticate method in here; def authenticate(request=None, **credentials): """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backends(return_tuples=True): print(backend) try: inspect.getcallargs(backend.authenticate, request, **credentials) except TypeError: # This backend doesn't accept these credentials as arguments. Try the next one. continue try: user = backend.authenticate(request, ) except PermissionDenied: # This backend says to stop in our tracks - this user should not be allowed in at … -
How do you pass model data to a template using Django?
I am trying to pass data from a Django model into an HTML template using a class based view. urls.py from django.urls import path from app import views urlpatterns = [ path('review/', views.ReviewRecord.as_view(template_name='review.html'), name='review') ] models.py from django.db import models class MyModel(models.model): RegNumber = models.TextField(primary_key=True) Description = models.TextField(null=True) views.py from app.models import MyModel from django.views.generic import TemplateView class ReviewRecord(TemplateView) template_name = 'review.html' model = myModel def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['description'] = self.model.description return context html <textarea readonly>{{ description }}</textarea> The above code inserts the following into the html textarea: <django.db.models.query_utils.DeferredAttribute object at 0x0000024C449B9F88> I need to display the stored field data from the model, not the object data as stated above. I am trying to create a queryset based on a field in the model, for example, for a particular RegNumber. Eventually I would like to retrieve several records and be able to increment through them, however I am currently just trying to get one to work. I have also tried using a DetailView using the primary key in the url, however I keep getting errors, therefore the provided example code is from what appears to be my closest attempt to my goal.