Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django list all projects [duplicate]
I have a directory with multiple projects. How can I list all the Django projects in a directory with a command possibly like django-admin? -
Append JWT as the "x-my-jwt" header to the upstream post request
Go a specific solution looking like this In Django as as you can see from my previous effort, got a specific endpoint #urls.py path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain'), #views.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer When I POST with an existing user like I get a response where it's possible to see an access token similar to this eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTE0MTk4LCJqdGkiOiJhZDZmNzZhZjFmOGU0ZWJlOGI2Y2Y5YjQ4MGQzZjY2MiIsInVzZXJfaWQiOjExLCJpYXQiOjE1OTA5MTc0OTgsInVzZXIiOiJ0aWFnbyIsImRhdGUiOiIyMDIwLTA1LTMxIn0.-5U9P-WWmhlOenzCvc6b7_71Tz17LyNxe_DOMwwqH4RqrNsilVukEcZWFRGupLHRZjIvPya2QJGpiju9ujzQuw How can I append the JWT as the "x-my-jwt" header to the upstream POST request? -
Deserializing array from ajax get()
I am trying to send two arrays with ajax: var pressIdList = []; var imprintArray = []; function getPressList(){ for (i = 0; i < pressList.length; i++) { pressIdList.push(parseInt(pressList[i].getAttribute("press"))); var pr = pressList[i] var prid = pr.getAttribute("press"); var prx = pr.getAttribute("x"); var pry = pr.getAttribute("y"); var imprint = { press_id : prid, x : prx, y : pry, }; imprintArray.push(imprint); }; }; $.ajax({ method: "GET", url: endpoint, data: { "pressIdList" : pressIdList, "imprintArray" : imprintArray, }, success: function(data){ console.log(data) } }); request.GET looks like this: <QueryDict: {'pressIdList[]': ['42', '43', '44', '129', '71'], 'imprintArray[0][press_id]': ['42'], 'imprintArray[0][x]': ['2.3069764e-07'], 'imprintArray[0][y]': ['-4.4408921e-16'], 'imprintArray[0][width]': ['13.229166'], 'imprintArray[0][height]': ['13.229166'], 'imprintArray[1][press_id]': ['43'], 'imprintArray[1][x]': ['18.52083'], 'imprintArray[1][y]': ['-7.1525574e-07'], 'imprintArray[1][width]': ['13.229167'], 'imprintArray[1][height]': ['13.229167']} So i can get first array out of it with request.GET.getlist('pressIdList[]'). But how do i get the second one out. And why isn't it wrapped inside imprintArray[]:[] if i declared it as array[]? -
psycopg2 not detected by postgres django
I am using PyCharm and using Python 3.8 - 64 bit and Django 2.2. pip install psycopg2 successfully installed psycopg2-2.8.5. My database settings are as follows: settings.py, DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'my-database', 'USER': 'my-user', 'PASSWORD': 'my-password', 'HOST': 'localhost', 'PORT': '', } } my-user is the user that I am using and my-password is my password. However, python manage.py makemigrations causes a few errors as follows: Traceback (most recent call last): File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 20, in <module> import psycopg2 as Database File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
Django channels load previous messages
I am in the process of building a simple chat application and have already managed to make a functioning chat that stores sent messages in a model. However, I am struggling to retrieve previous messages. consumers.py def old_messages(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] room = ChatRoom.objects.get(room_name=self.room_name) messages = ChatMessage.objects.filter(room=room) content = { 'command': 'old' } return content room.html chatSocket.onopen = function(e) { console.log("open",e) old_messages() }; function old_messages() { chatSocket.send(JSON.stringify({ 'command': 'old_messages' })); }; Whenever I call old_messages() I get the error message = text_data_json['message'] KeyError: 'message' which refers to this chunk of code def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] -
list indices must be integers or slices, not str Django
I m getting this error. I am new in django. I am trying so send mail with django. Tracke Back : response = self.process_exception_by_middleware(e, request) File "/home/bari/Desktop/email_send/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/bari/Desktop/email_send/Simple_Email_Send_Project/email_app/views.py", line 36, in send_mail message_body = form.changed_data["message_body"] TypeError: list indices must be integers or slices, not str [05/Jun/2020 17:55:22] "POST / HTTP/1.1" 500 69463 my views.py def send_mail(request): form = SendMailForm(request.POST) template = 'send_mail.html' if form.is_valid(): subject = form.cleaned_data["subject"] message_body = form.changed_data["message_body"] email_address = form.cleaned_data["email_address"] try: mail = EmailMessage(subject, message_body, settings.EMAIL_HOST_USER, [email_address]) mail.send() return render(request, template, {'email_form': form, 'error_message': 'Sent mail to {}'.format(email_address)}) except: return render(request, template, {'email_form': form, 'error_message': 'Email Send failed. Please try again later'}) How can I solve this ??? help will be highly appreciated... -
Multiple levels of lookups in a Django queryset
With these models: class Work(models.Model): creator = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name = 'creator') class dateEvent(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) class Event(models.Model): repertoire = models.ManyToManyField(Work, blank=True) how can I get the dateEvents in whose repertoire feature works by a specific creator? dateEvent.objects.filter(event__repertoire__creator=1) returns an empty queryset. What am I doing wrong? -
nested annotation with OuterRef not working
I want to annotate a field to an annotated field of a parent Model. My code : user_enrolments = UserEnrolment.objects.filter( enrolment__enrollable__id__in=course_ids_taught_by_teacher).annotate( not_graded_attempt=Exists( AssignmentModuleProgress.objects .annotate(user_enrolment=OuterRef('id')) .filter(user_enrolment__id=OuterRef('id'), module_progress__module=instance, score=None) )) This particular querycall is made in a serializer method field . Im annotating a field not_graded_Attempt as a boolean field. For this im checking Exists of AssignmentModulePRogress. I want to query this table with the current user_enrolment in annotation , so i want to annotate the id of the current user enrolment in the ASsignmentModuleProgress queryset since its not directly preset in the Model. For this im using OuterRef . Im getting error as : AttributeError: 'ResolvedOuterRef' object has no attribute 'get_lookup' -
Open image file, save it as a string and convert it to base64
I am doing a Django project that needs to receive an image and store it into the database as a TextField. To accomplish that I am doing something similar to this: In my models.py: class Template(models.Model): image = models.TextField(null=True, blank=True) The equivalent code is: with open('logo.png', 'wb') as file: image = str(file.read()) Template.objects.create(id=1, image=image) Later, when I need to get back the file and convert it to base64 to insert in an HTML file, I am doing the following: import base64 from django.template import Template as DjangoTemplate from django.template import Context from weasyprint import HTML from .models import Template template = Template.objects.get(id=1) data = {'logo': base64.b64encode(str.encode(template.image)).decode('utf-8')} html_template = DjangoTemplate(template.html_code) html_content = html_template.render(Context(data))) file = open('my_file.pdf', 'wb') file.write(HTML(string=html_content, encoding='utf8').write_pdf()) file.close() But the problem is that the image is not showing in the pdf file. I've also tried to copy the decoded data and open it with another site, but I got a broken file. How can I fix my code to convert the image properly? -
how to run Django web app locally in Heroku
I am following this instruction to run my django project locally https://devcenter.heroku.com/articles/getting-started-with-python#run-the-app-locally When I type heroku local web, it says "[FAIL] No Procfile and no package.json file found in Current Directory - See run-foreman.js --help". However, my project is a Django/python app and I don't have package.json. But my project does have requirements.txt and Procfile in the root directory of my web application. What should I do? Thanks -
Django: Static Image Not Loading
I'm having issues getting an image to load on my Django web application. I have used the online documentation and tried peoples suggestions that I found on Stackoverflow but I am still not having any luck getting it to load. Here is what I have: Settings.py: STATIC_DIR = os.path.join(BASE_DIR,'static') INSTALLED_APPS = [ ... 'django.contrib.staticfiles' ] STATIC_URL = '/static/' STATIC_ROOT = [STATIC_DIR,] Urls.py: from django.urls import path from dir_app import views from django.conf import settings from django.conf.urls.static import static app_name = 'dir_app' urlpatterns=[ path('', views.tradesmen, name='tradesmen'), path('register', views.register,name='register'), path('user_login', views.user_login,name='user_login') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Index.html: (Gist) <!DOCTYPE html> {% load static %} <html> <head> </head> <body> <img src="{% static 'dir_app/tools.png' %}"> </body> </html> Here is where the image is stored: -
unable to download video created using moviepy in django
I am trying to import a video, add a watermark and then download the processed video in django using moviepy. The problem is that I am able to save the processed video to my computer by specifying an absolute path to the computer drive. However, I have not been able to download this processed video. I have tried researching on the internet. However, no luck till now. below is my code: views.py from django.shortcuts import render import numpy as np from .forms import UploadFileForm import tempfile import os from django.core.files.storage import default_storage from django.http import HttpResponse from django.core.files.storage import FileSystemStorage import sys import moviepy.editor as mp from .utils import CFEVideoConf, image_resize # Create your views here. def watermark(request): if request.method=="GET": form = UploadFileForm() return render(request, 'video_et.html', {'form':form}) else: if request.method=="POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): fs = FileSystemStorage(location='/media') x = bytes() #arr=cv2.VideoWriter() image = request.FILES['Watermark_Image'] video = request.FILES['Video_File'] print("Name of the Watermark Image: ", image.temporary_file_path()) print("Name of the Video: ", video.name) file_name1 = default_storage.save(video.name, video) file1 = default_storage.open(file_name1) file_url1 = default_storage.url(file_name1) print("file url= ",file_url1) url_now1 = "http://127.0.0.1:8000/"+file_url1 #image = request.FILES['Watermark_Image'].read() file_name2 = default_storage.save(image.name, image) file2 = default_storage.open(file_name2) file_url2 = default_storage.url(file_name2) print("file url= ",file_url2) url_now2 = "http://127.0.0.1:8000/"+file_url2 video = mp.VideoFileClip(url_now1) … -
Cart Item Update(add or Remove) throwing Type Error
TypeError("'%s' instance expected, got %r" % ( TypeError: 'CartItem' instance expected, got I am getting this error when I tried to add or remove the product obj from cartItem. Help me to overcome this error. CartUpdate view def cart_update(request): product_id = request.POST.get('product_id') print(product_id) try: qty = request.POST.get('qty') update_qty = True except: qty = None update_qty = False if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect("cart:cart") cart_obj, new_obj = Cart.objects.new_or_get(request) cart_item, created = CartItem.objects.get_or_create(cart=cart_obj, product=product_obj) if created: print("created") if update_qty and qty: if int(qty) == 0: cart_item.delete() else: cart_item.quantity = qty cart_item.save() else: pass if product_obj in cart_obj.cartitem_set.all(): cart_obj.cartitem_set.remove(product_obj) added = False else: cart_obj.cartitem_set.add(product_obj) added = True new_total = 0.0 for x in cart_obj.cartitem_set.all(): line_item = float(x.product.price) * x.quantity new_total += line_item request.session['cart_items'] = cart_obj.cartitem_set.count() cart_obj.subtotal = new_total if cart_obj.subtotal > 0: cart_obj.total = Decimal(cart_obj.subtotal) * Decimal(1.08) else : cart_obj.total = 0.00 cart_obj.save() -
Django Retrieve Data From Two Tables By Join
Hi I have two tables which are Employee(eid,eName,contact_num,e-mail,adress,salary) and Nurse(nurse_id,e_id) and the "e_id" column of Nurse model has foreign key on 'eid' of Employee model.I know how to filter by specific id, however all of them as list so that, I want to return all nurses from Employee table.You can find my models below. I am new to Django that is why any help or hint is appreciated. Thanks in advance. class Employee(models.Model): eid = models.IntegerField(primary_key=True) ename = models.CharField(db_column='eName', max_length=25) # Field name made lowercase. contact_num = models.DecimalField(max_digits=12, decimal_places=0) e_mail = models.CharField(max_length=30) adress = models.CharField(max_length=250, blank=True, null=True) salary = models.IntegerField() class Nurse(models.Model): nurse_id = models.IntegerField(primary_key=True) e = models.ForeignKey(Employee, models.DO_NOTHING) -
Django - Signal receiver not being called
I am working on a project utilizing Django All Auth. Inside the package, there is an account.signals file that contains a signal. email_confirmed = Signal(providing_args=["request", "email_address"]). It is used inside of a model for EmailConfirmationHMAC. ef confirm(self, request): if not self.email_address.verified: email_address = self.email_address get_adapter(request).confirm_email(request, email_address) signals.email_confirmed.send(sender=self.__class__, request=request, email_address=email_address) return email_address Adding a stack trace in here, I can see it is getting to this part. Inside my project, I have a python file receivers.py from allauth.account.signals import email_confirmed from django.dispatch import receiver @receiver(email_confirmed) def custom_logic(sender, **kwargs): a = 0 import ipdb; ipdb.set_trace() if a: pass However, whenever I confirm an email verification my custom logic debugger is not being hit, the email is being confirmed and the page is being re-routed. How do I ensure that my custom_logic function can be ran, after the signal is sent? signals.email_confirmed.send(sender=self.__class__, request=request, email_address=email_address) Thanks! -
Cannot assign SimpleLazyObject for CustomUser Model in django
hey everyone i created a blogpost so whenever i want to add a new blogpost i get this error ValueError at /pages/blog/new/ Cannot assign ">": "Blog.doctor" must be a "Doctor" instance. here is my views.py class BlogCreateView(CreateView): model = Blog fields = ['title', 'categories', 'overview'] def form_valid(self, form): form.instance.doctor = self.request.user return super().form_valid(form) -
django slice filter breaks template for tinymce safe content
I have contents which were published using tinymce editor. Now, I want to show my content, that's why I have to use safe filter. But, whenever I'm trying to use slice or truncate filter, the template breaks. this is my HTML code. {% extends 'blog/frontend/layouts/base.html' %} {% block content %} <div class="card border-primary"> {% for post in posts %} <div class="card my-2 mx-1"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'post-detail' post.permalink %}" class="text-primary">{{ post.title }}</a></h5> <hr> <img src="{{ post.image.url }}" alt="Card image" width="85%" class="mx-auto d-block"> <p class="card-text mt-1"> {{ post.content|truncatewords:50|safe}} </p> <hr> <div class="d-flex"> <div class="px-2 py-0 my-auto"> <h6><i class="fas fa-user-edit"></i>&nbsp;<a href="#">{{ post.author.username }}</a></h6> </div> <div class="px-2 py-0 my-auto"> <h6>Date posted: <span class="text-info">{{ post.date_posted|date:"d M, Y" }}</span></h6> </div> <div class="ml-auto px-2 my-auto "> <a href="{% url 'post-detail' post.permalink %}" class="btn btn-primary">Read more</a> </div> </div> </div> </div> {% endfor %} </div> {% endblock content %} These are the image, first one without sliceor turncate filter, 2nd and 3rd one are with them. -
Making a topic public to all users in Django
I've got a project where users can enter topics and have the option to make the topic public or private. I want all public topics to be visible to everyone, and private topics to only be visible by the owner of that topic (Project is from Python Crash Course exercise 20-5). I'm not getting any errors when I click through my project, but when I create a new topic and select the "public" option, it is still not showing up for public viewing. I've researched similar problems and followed all the suggestions here How to make a topic public to all users in django? and here Django - How to make the topics, that you create public? Learning Log Project with no luck. I'm guessing my queryset is not rendering data correctly? I've read the Django documentation on querysets as well, but nothing I've tried has worked. I'm really new to programming so any help would be appreciated. Thank you! Here's my models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) public = models.BooleanField(default=False) def __str__(self): … -
Build a complicated Django query for SQLite or MySQL
I have a Django application with a database. Currently in SQLite, which will be earlier or later transferred to MySQL This table contains approx. 100.000 records of competition product names. class CrossRefTable(models.Model): all_bez = models.CharField('All Bezeichnung', max_length=30, default="", unique=True, blank=True, null=True) uid_nr_f = models.ForeignKey(UidTable, on_delete=models.CASCADE, related_name='uid_nr' This table contains 10.000 records with replacement products for products from CrossRefTable class xx_Table(models.Model): xx_idnr = models.CharField('xx Id.Nr', max_length=10, default="", blank=True ) xx_bez = models.CharField('XX Bezeichnung', max_length=30, default="", unique=True) pgroup_f = models.ForeignKey(product_group, on_delete=models.PROTECT, related_name='P_Group_XX', \ verbose_name='Product Group_FG', default="", blank=True, null=True) uid_nr_f = models.ForeignKey(UidTable, on_delete=models.PROTECT, related_name='Uid_F', verbose_name='Uid_F', default="", blank=True, null=True) price = models.DecimalField('List Price', max_digits=8, decimal_places=2, default=0, blank=True, null=True) This table is used as a connecting table of foreign keys for CrossRefTable and xx_Table. Contains approx. 8.000 records. class UidTable(models.Model): uid_nr_1= models.IntegerField('uid_nr_1', default=0, null=True, unique=True) uid_bez = models.CharField('Uid Bezeichnung', max_length=30, default="", unique=True, null=True,) This table contains discount rate for different product groups in xx_table. class product_group(models.Model): value = models.CharField('Product Code: ', max_length=15, default="") cust_price = models.DecimalField('Customer d.factor: ', max_digits=5, decimal_places=2, default=0, blank=True, null=True) I need to build a query, which connects all four tables as follows: THe customer chooses a product from CrossRefTable, e.g. all_bez = "ABCDEFG" It must be connected via foreign field to … -
Django/Wagtail - Custom form widget CSS/JS not being rendered with template file
I have a base Address model with a formatted_address field, which uses a custom LocationPicker widget (essentially an autocomplete for searching addresses). A couple of classes inherit from Address, including my Place class below. models.py class Address(models.Model): formatted_address = models.CharField(max_length=500, verbose_name='address') ... class Place(ClusterableModel, Address) ... panels = [ MultiFieldPanel([ FieldPanel('formatted_address, widget=LocationPicker(), FieldPanel('some_other_field') ], heading='My field group') widgets.py class LocationPicker(WidgetWithScript, TextInput): template_name = 'places/forms/widgets/location_picker.html' @property def media(self): print('get media') return Media( css={'screen': ('places/css/location-picker.css',)}, js=('places/js/location-picker.js',), ) This widget appears fine in the Wagtail admin, where I have registered a ModelAdmin instance for it. However, the problem I have is that I cannot get the widget to appear properly in my vanilla Django ModelForm. The widget template file is rendered, but the associated media is not included. I have created the form as follows: forms.py class PlaceForm(ModelForm): class Meta: model = Place fields = '__all__' widgets = { 'formatted_address': LocationPicker() } No matter what I've tried, the widget's media is not included when the form is rendered. The 'get media' printout doesn't even appear. I'm certain this can be done but I don't know what obvious thing I'm missing here. -
Django , need to set default value to a models field by calling a method . Th
Model X(Models.Model): Somefield=models.Charfield(..., default=SomeMethode} def SomeMethode(self): var= X.objects.filter() ... Problem is order issue! I got either function undefined or Model undefined if I declare the method outside-befor the model . I am stuck. Any help would be so nice. -
Http to Https Redirect in htaccess when FCGI Deployment (django)
I have deployed django project using fcgi. this is my .htaccess file <IfModule mod_fcgid.c> AddHandler fcgid-script .fcgi <Files ~ (\.fcgi)> SetHandler fcgid-script Options +FollowSymLinks +ExecCGI </Files> </IfModule> <IfModule mod_rewrite.c> Options +FollowSymlinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] </IfModule> I received SSL and I don't know how to do redirect http to https. I tried but getting too many redirect errors. help me to write redirect. thanks in advance. -
Serializer method field takes too many queries
I have an Assignment module Model . Im using a serializer method field to display the submitted count and to grade count . For an assignment to be submitted , it should have another table entry and a boolean of that table will be set to true .Im using a Model Serializer and the serializer method field takes too much time to return the result . I need help to optimize the query. My serializer method field: def __submitted_count(self, instance): user = self.context["request"].user assigned_course_share_items = instance.course_share_item.all() assigned_courses = Course.objects.filter( course_share_item__in=assigned_course_share_items, tenant=user.tenant) right = PMRight.objects.get(short_name="teach") entity_items = RoleManager().get_all_secondary_role_entity_items_with_right( user, right, "COURSE") course_ids_taught_by_teacher = [ item.entity_item_id for item in entity_items] user_enrolments = UserEnrolment.objects.filter( enrolment__enrollable__id__in=course_ids_taught_by_teacher).only("id", "enrolment").select_related("enrolment", "enrolment__enrollable").annotate(is_submitted=) submitted_count = 0 for user_enrolment in user_enrolments: existing_attempt = None try: existing_attempt = ModuleProgressInit().get_existing_attempt( user_enrolment.id, user_enrolment.enrolment.enrollable.id, instance.id) except: pass if existing_attempt is not None and existing_attempt.is_submitted: submitted_count = submitted_count + 1 return submitted_count def __to_grade_count(self, instance): user = self.context["request"].user assigned_course_share_items = instance.course_share_item.all() assigned_courses = Course.objects.filter( course_share_item__in=assigned_course_share_items, tenant=user.tenant) right = PMRight.objects.get(short_name="teach") entity_items = RoleManager().get_all_secondary_role_entity_items_with_right( user, right, "COURSE") course_ids_taught_by_teacher = [ item.entity_item_id for item in entity_items] user_enrolments = UserEnrolment.objects.filter( enrolment__enrollable__id__in=course_ids_taught_by_teacher).only("id", "enrolment").select_related("enrolment", "enrolment__enrollable") to_grade_count = 0 for user_enrolment in user_enrolments: existing_attempt = None try: existing_attempt = ModuleProgressInit().get_existing_attempt( user_enrolment.id, user_enrolment.enrolment.enrollable.id, … -
Disable choices in multiselect Django widget
Is it possible to disable a few select choices in a Django multiselect widget? I can do something like this in the view: id_roles = (10, 2, 1, 3, 11) self.fields['role'].queryset = Role.objects.filter(id__in=id_roles) But this would throw an error when saving bound forms with values outside that list. Can I have all the roles there, just disabled? -
Django REST JSON API: how to include nested compound documents?
Using Django REST JSON Api, i.e. djangorestframework-jsonapi==3.1.0 and having the following data structure: parent, singleChild, manyGrandChildren (all just dummy names, singleChild means one-to-one relation, manyGrandChildren means one-to-many nested relation). ... class Parent(serializers.HyperlinkedModelSerializer): included_serializers = { 'singleChild': singleChildSerializer, 'manyGrandChildren': manyGrandChildrenSerializer, } class Meta: model = models.Parent fields = [ 'field1', 'field2', 'url', ] class JSONAPIMeta: included_resources = ['singleChild', 'manyGrandChildren'] ... My code does not work, because I cannot access manyGrandshildren on my response, which is something like http://host.com/api/parents/1/?include=singleChild,singleChild.manyGrandChildren also please correct me if my url ?include= statement is not correct. How do I accomplish that?