Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
presentationUploadExternalUrl in BigBlueButton Api
I am using BigBlueButton Api to create meetings but they have added some new fields in the 2.6 version like presentationUploadExternalUrl the official documentations description describes the field as {Pass a URL to a specific page in external application to select files for inserting documents into a live presentation. Only works if presentationUploadExternalDescription is also set.}. I am not sure what kind of url they are talking about is it a url to specific website if it is then what kind of websites?? I have tried adding the fields to the code and passed the google drive url but no change has been observed by me. -
How to put selection fields in django given multiple sub parts inside a class
class Resume(models.Models): CATEGORY = ( ('Summary', 'Summary'), ('Education', 'Education'), ('Projects', 'Projects'), ('Open Source', 'Open Source'), ('Certifications', 'Certifications'), ) # view different fields according to the category category = models.BooleanField(choices=CATEGORY, default='Summary') # for each catergory according to the category field, there will be specific fields # 1 Summary option will have title , description and address, phone, emailid summary_title = models.CharField(max_length=100) summary_description = models.TextField() summary_address = models.CharField(max_length=200) summary_phone = models.CharField(max_length=20) summary_email = models.EmailField() # 2 Education option will have title, course, start_date, end_date, GPA edu_title = models.CharField(max_length=100) edu_course = models.CharField(max_length=100) edu_date = models.CharField(max_length=100) # it holds the start and end year of the course edu_where = models.CharField(max_length=200) # college or school name edu_gpa = models.FloatField() as you can see here my highly inefficient code ... given this Resume class the thing here is there are 5 different fields here and then each have their own fields in turn is there a way to efficiently write this piece of code where in the admin page i can choose the category .. and wrt to that the thing pops up asking for the input ... is it possible and also there are few global filed like title and stuff ... so how to … -
Issue with querying the database after a table is deleted
I had a table table_one and another table table_two. I had designed table_two somewhat like this: class TableTwo(models.Model): sample_content_type = models.ForeignKey( ContentType, blank=True, null=True, on_delete=models.CASCADE ) sample_content_type_id = models.CharField( max_length=255, blank=True, null=True ) sample_object = GenericForeignKey( 'sample_content_type', 'sample_content_type_id' ) I had rows in table_two which had GenericForeignKey relation with table_two content types. Later I had to delete table_one. Now whenever I tried to query table_two I was facing errors and fixed that by deleting all the rows which had relation with table_one. I was expecting once the table is deleted all the data related with that table in table_two would also be deleted. I want to know how django handles such situations. FYI: This is the error I got 'NoneType' object has no attribute '_base_manager' -
What is the best format way to separate django-admin access to different parties or people
The Admin I am planning a django school portal project If we want teachers to have their own set of privileges other than that which the django offers url/admin which is reserved for the head and school technician I tried to have the same platform url/admin with separate credentials but realized every superuser has access to same models -
saving checkbox values in django form
I'm trying to make a boards function, where you select the clothes you want (in checkboxes), but i'm not being able to save the checked items into my django model because the form is invalid my html (with checkboxes for each item): <form method='POST' action="{% url 'create-boards' %}"> <div class="select-display"> <h3 id="select-text">Select</h3> <div class="select-container"> {% for item in clothes %} <div class="column stacked featured"> <input class="checkbox" id="mycheckbox" type="checkbox" name="selected_clothes"> <label for="mycheckbox"> <img class="gallery column__img" src="{{ item.image.url }}"> </label> </div> {% endfor %} </div> </div> </div> </form> models.py class Clothes(models.Model): title = models.CharField(max_length=50) image = models.ImageField(default='', upload_to='wardrobe/') category = models.CharField(max_length=200, null=True, blank=True) brand = models.CharField(max_length=200, null=True, blank=True) color = models.CharField(max_length=200, null=True, blank=True) time = models.DateTimeField(default=datetime.datetime.now()) deleted = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Clothes' def __str__(self): return f'{self.color} {self.title} from {self.brand}' class Boards(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=500) selected_clothes = models.ManyToManyField('Clothes', null=True) forms.py from django import forms from .models import User, Clothes, Boards class BoardsForm(forms.ModelForm): forms.ModelMultipleChoiceField( queryset=Clothes.objects.all(), widget=forms.CheckboxSelectMultiple(), required=True) class Meta: model = Boards fields = ('title','description','selected_clothes') views.py def create_board(request): if request.method == 'POST': form = BoardsForm(request.POST or None) if form.is_valid(): title = request.POST['title'] description = request.POST['description'] selected_clothes = form.save(commit=True) create_boards = Boards(title=title, description=description, selected_clothes=selected_clothes) create_boards.save() return HttpResponseRedirect(reverse(boards)) else: return HttpResponse('the … -
Django Headers and Middleware
I've created a middleware which it checks for api_key when interacting with my api class APIKeyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Allow access to Django admin without an API key if request.path.startswith(reverse('admin:index')): return self.get_response(request) # Allow access to Swagger documentation without an API key if request.path.startswith('/api/docs/'): return self.get_response(request) api_key = request.META.get('HTTP_API_KEY') # Assuming the API key is sent in the 'API_KEY' header if api_key: try: api_key_obj = APIKey.objects.get(key=api_key, is_active=True) request.user = api_key_obj.user except APIKey.DoesNotExist: return JsonResponse({'error': 'Invalid API key.'}, status=401) else: return JsonResponse({'error': 'API key is missing.'}, status=401) response = self.get_response(request) return response However when debugging my META I cannot find any API_KEY that was passed in the headers there. I know it has to do with some other middleware which might get rid of my API_KEY and therefore not appearing in my META. Can anyone help here ?? My middleware : 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'users.middleware.APIKeyMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', -
Django-filter with a paginate_by param selected by user in the template: how to keep pagination param and filter params together?
I'm using Django 4.1 and Python 3.10. I have a ListView that uses django-filter. I succeed in applying filters and get the pagination work together. Then I had to make paginate_by a param that each user can select from the template. So I have created a form with a GET method and I update paginate_by variable in the view with self.request.GET.get('paginate_by', self.paginate_by). The problem is when a user select paginate_by and some filters in the template. When the filter form is submitted, it reloads the page without taking into account the paginate_by param selected by user. I tried to rewrite the class get_paginate_by in the view to pass paginate_by variable but the queryset generated with django-filter doesn't take it into account. Is it possible to append paginate_by param in the filter? Is there a better way to do that? I hope my message is clear. Many thanks in advance for your help 🙏 -
How to update 'Allow' headers to match an OPTIONS request's permissions?
I am using Django Rest Framework 3.14 with ModelViewsets and a settings-wide DjangoModelOrAnonReadOnly permission class. Given this config, out of the box my JSON API seems to respond to OPTIONS requests in a misleading way, i.e. sending unauthenticated OPTIONS requests to /api/collections/collectionA/items is replied with Allow: GET, POST, HEAD, OPTIONS in the headers (correct would be: GET, HEAD, OPTIONS). However if I define my own metadataclass and do something like: def options(self, request, *args, **kwargs) -> response.Response: allowed_actions = self.metadata_class().determine_actions(request, self) allowed_actions = ", ".join(allowed_actions.keys()) # ^ allowed_actions is correct data = self.metadata_class().determine_metadata(request, self) return response.Response(data, headers={"Allow": allowed_actions}) I am able to get the correct allowed_actions (GET, OPTIONS, HEAD). However, and that is my issue, headers are unmodified by the last statement in the snipper above. How can I update my headers to ensure that the "Allow" headers correctly reflect the state of my API? -
Web push notification token changes in Safari on macOS (16.5.2)
I have successfully implemented web push notifications on my website using Firebase Admin SDK. The notifications work flawlessly on Windows and Chrome on macOS. However, I encountered an issue with Safari on macOS 16.5.2. The problem is that every time I quit Safari, the notification token changes, and as a result, users do not receive new notifications when they reopen the browser. Strangely, this behavior doesn't occur in Chrome on macOS. Does anyone have any insights into why this might be happening? This is my getToken code, I extracted it from the docs. const token = localStorage.getItem('firebaseToken') const messaging = getMessaging(firebaseApp); getToken(messaging, { vapidKey: 'my vapid key'}) .then((currentToken) => { if (currentToken != token) { console.log(currentToken) sendTokenToServer(currentToken) else { console.log('Already saved'); }).catch((err) => { console.log('An error occurred while retrieving token. ', err); }); -
Can I use FastApi instead of drf to make APIs for my Django projects?
For example, I want to make e-commerce website which I am using Django for backend and I need to make API for connecting backend with front-end. Can I use Fast-API instead of DRF to do it? Or is it better to use DRF? I want to use Fast-API because it is much faster than Django Rest Framework -
Multi-Tenant Django application using MSSQL as database
I'm trying to create a multi-tenant Django application using MSSQL server. which should support per-tenant db isolation. For PostgreSQL there are packages like django-multitenant and django-tenant-schemas. But I cannot find any library for the same using MSSQL db. What's the best approach to solving this problem? Any help on this is much appreciated. Requirement: Database MSSQL (must). Tenant and Db creation on the fly. db routing. Celery support for the same. Applying Migration for all the databases. -
Python Django: TypeError: cannot unpack non-iterable MatchAll object
I am facing below error when try to query using 'Q' in a viewset. It will work without any issues if I use this in a management command file. My view. @permission_classes((AllowAny,)) class ClipartViewSet(viewsets.GenericViewSet): serializer_class = ClipartSerializer queryset = Clipart.objects.filter(is_active=True).all() def list(self, request, **kwargs): # Some extra logic # qs = Clipart.objects.filter(name="Apes") #This line will work without any issues qs = Clipart.objects.filter(Q(name="Apes") | Q(name="Dog")) # This line will show error print(qs) return super(ClipartViewSet, self).list(self, request, **kwargs) Error: Internal Server Error: /api/s/configurator/cliparts backend_1 | Traceback (most recent call last): backend_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner backend_1 | response = get_response(request) backend_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response backend_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) backend_1 | File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view backend_1 | return view_func(*args, **kwargs) backend_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/viewsets.py", line 125, in view backend_1 | return self.dispatch(request, *args, **kwargs) backend_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch backend_1 | response = self.handle_exception(exc) backend_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception backend_1 | self.raise_uncaught_exception(exc) backend_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception backend_1 | raise exc backend_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch backend_1 | response = handler(request, *args, **kwargs) backend_1 | File "/backend/mycomp/apps/ecommerce/configurator/views/design_views.py", line 109, … -
Django post save signal timing issue?
**Model.py ** class Store(models.Model): status_type = ( ("y",'Yes'), ("n","No") ) branch = models.ManyToManyField(Branch) asset = models.ForeignKey(AssetTag,on_delete=models.CASCADE) asset_code = models.CharField(max_length=100, null=True, blank=True, unique = True) model = models.CharField(max_length=250) serial_no = models.CharField(max_length=200) vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE) invoice_code = models.ForeignKey(Invoice, on_delete=models.CASCADE) purchase_date = models.DateField() store_status = models.CharField(max_length=1, choices = status_type, default = "y", blank = True) store_date = models.DateTimeField(auto_now=True) store_remark = models.TextField(max_length=100, null=True, blank=True, default=None) start_warrany = models.DateField(default=None) end_warrany = models.DateField(default=None) emp_id= models.ForeignKey(Employee,on_delete=models.CASCADE, null=True ,blank=True, default=None) assige = models.CharField(max_length=1, choices = status_type, default = "n", blank = True) assige_date = models.DateField(auto_now=True) assige_remark = models.TextField(max_length=100, null=True, blank=True, default=None) scrap = models.CharField(max_length=1, choices = status_type, default = "n", blank = True) scrap_date = models.DateTimeField(auto_now=True) scrap_remark = models.TextField(max_length=100, null=True, blank=True, default=None) created_by = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def AssetCodeGenerator(sender, instance, created, *args, **kwargs): if created: id = instance model_obj = Store.objects.get(id = int(id.id)) print(model_obj.branch) post_save.connect(AssetCodeGenerator, sender = Store) View.py def Add_Store(request): # for Asset add if request.method == "POST": try: form = StoreForm(request.POST) if form.is_valid: store_add = form.save(commit=False) store_add.created_by = request.user store_add.save() form.save_m2m() # for m to m field save return redirect('store_page') **Problem is that when run store_add.save() while directly signal is called and then after run form.save_m2m() that's reason signal don't know … -
Django Search Product feature issue
I was trying to create a search functionality in Django, I have some data stored in my Django database and I am searching product name and I am getting it: Please make sure to enter relevant search query Please check my code and let me know where I am Mistaking. Here is my urls.py file: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="ShopHome"), path("about/", views.about, name="AboutUs"), path("contact/", views.contact, name="ContactUs"), path("tracker/", views.tracker, name="TrackingStatus"), path("search/", views.search, name="Search"), path("products/<int:myid>", views.productView, name="ProductView"), path("checkout/", views.checkout, name="Checkout"), ] here is my views.py file: from django.shortcuts import render from .models import Product, Contact, Orders, OrderUpdate from math import ceil import json from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse def searchMatch(query, item): '''return true only if query matches the item''' if query in item.desc.lower() or query in item.product_name.lower() or query in item.category.lower(): return True else: return False def search(request): query = request.GET.get('search') allProds = [] catprods = Product.objects.values('category', 'id') cats = {item['category'] for item in catprods} for cat in cats: prodtemp = Product.objects.filter(category=cat) prod = [item for item in prodtemp if searchMatch(query, item)] n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) if len(prod) … -
drf-spectacular swagger authentication
I'm digging google for 3 hours right now, and can't find solution for my problem. I moved in my project from drf-yasg to drf-spectacular because openapi +3.0 isn't supported in yasg. I want to have an authentication to swagger page. I had a solution like this for yasg: schema_view = get_schema_view( openapi.Info( title="API", default_version="v2", description="api description", terms_of_service="", contact=openapi.Contact(email=""), license=openapi.License(name=""), ), public=True, patterns=swagger_urls, authentication_classes=(isStaffPermission,), ) The problem is I can't add a similar solution to drf-spectacular. Right now I have this piece of code which ofc doesn't work. My goal is to run a popup for login before swagger page is rendered: class MySchemaView(SpectacularAPIView): urlconf=swagger_urls class CustomSpectacularSwaggerView(SpectacularSwaggerView): authentication_classes=(isStaffPermission,) urlpatterns += [ path("api/v3/schema/", MySchemaView.as_view(api_version="v3"), name="schema"), path('api/v3/swagger-ui/', CustomSpectacularSwaggerView.as_view(), name='swagger-ui') ] I want to authenticate with my custom class: class isStaffPermission(authentication.BasicAuthentication): """Custom authentication class to check if the user is staff.""" def authenticate(self, request) -> Optional[User]: """Authenticate the user""" user: Optional[User, bool] = super().authenticate(request) if user and user[0] and user[0].is_staff: return user return None Does anyone know how to fix it? -
How to show name instead of id with foreighkey
I have a django application. And a foreign relationship. But the api calls shows the id instead of the name. But I want to show the name instead of the id. So this is the property: category = models.ForeignKey(Category, related_name='animals', on_delete=models.CASCADE, verbose_name="test") and serializer: class SubAnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = ['id', 'name', 'description',"category","pet_list", 'images' ] read_only_fields = ['id'] so this is part of the api call: "animals": [ { "id": 3, "name": "Vicuña", "description": "kjhkkhkhkjhjkhj Hello", "category": 6, "pet_list": "D", "images": "http://192.168.1.135:8000/media/media/photos/animals/mammal.jpg" }, { "id": 5, "name": "Goudhamster", "description": "khkjh", "category": 6, "pet_list": "C", "images": "http://192.168.1.135:8000/media/media/photos/animals/imgbin_dog-grooming-puppy-cat-pet-png_I7rLPen.png" } ], And I googled something ofcourse. So I found this: How to show name instad of id in django ForeignKey? But it doesn't exactly fit what I am looking for. Question: how to show name instead of id in api call -
Data Vanish from Mongo DB on next day
I have created a django Project with Postgres and mongodb as my database.i'm connecting mongodb using the django module called djongo. with this settings: 'mongo': { 'ENGINE': 'djongo', 'NAME': 'caracaldb', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'localhost', 'port': 27017, }, } In local mongodb works fine. While I deployed my project in aws server,mongodb data stays for a day.Next day data gets vanished. May I know what exactly happening in server. I'm using Mongodb communityserver and mongocompass interface. Kindly provide me solution.Thanks I want a solution to avoid vanish of my data in mongodb -
DJANGO - "SMTPNotSupportedError: SMTP AUTH extension not supported by server" - error
I have an app where I'm testing email sending with django. The django project is still and development and I'm using the default sqlite3 as database. I have configured the EMAIL_BACKEND, EMAIL_HOST, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD, EMAIL_PORT, EMAIL_USE_TSL and EMAIL_USE_SSLfields in my app_name/settings.py. I am trying to send the email with a default personal gmail.com EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '<username@gmail.com>' EMAIL_HOST_PASSWORD = '<app_password>' EMAIL_PORT = 587 EMAIL_USE_TSL = True EMAIL_USE_SSL = False And I'm trying to send the email in the python powershell like this: In [1]: from django.conf import settings In [2]: from django.core.mail import send_mail In [3]: send_mail(subject='Add an eye-catching subject', message='Write an amazing message', from_email=settings.EMAIL_HOST_USER, fail_silently=False, ...: recipient_list=['<username@gmail.com>']) --------------------------------------------------------------------------- SMTPNotSupportedError Traceback (most recent call last) Cell In[3], line 1 ----> 1 send_mail(subject='Add an eye-catching subject', message='Write an amazing message', from_email=settings.EMAIL_HOST_USER, fail_silently=False, recipient_list=['<username@gmail.com>']) File C:\PATH\lib\site-packages\django\core\mail\__init__.py:87, in send_mail(subject, message, from_email, recipient_list, fail_silently, auth_user, auth_password, connection, html_message) 84 if html_message: 85 mail.attach_alternative(html_message, "text/html") ---> 87 return mail.send() File C:\PATH\lib\site-packages\django\core\mail\message.py:298, in EmailMessage.send(self, fail_silently) 294 if not self.recipients(): 295 # Don't bother creating the network connection if there's nobody to 296 # send to. 297 return 0 --> 298 return self.get_connection(fail_silently).send_messages([self]) File C:\PATH\lib\site-packages\django\core\mail\backends\smtp.py:127, in EmailBackend.send_messages(self, email_messages) 125 return 0 126 … -
Error when using manage.py loaddata to load Django JSON file created with dumpdata
I am using ./manage.py loaddata file.json to load a JSON file created with ./manage.py dumpdata > ../directory/file.json, and I get the following error: matching_chars: 6 Traceback (most recent call last): File "/opt/venv/djangoEnv/lib/python3.8/site-packages/django/core/serializers/json.py", line 69, in Deserializer objects = json.loads(stream_or_string) File "/usr/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/usr/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/venv/djangoEnv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/venv/djangoEnv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/venv/djangoEnv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/venv/djangoEnv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/opt/venv/djangoEnv/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 78, in handle self.loaddata(fixture_labels) File "/opt/venv/djangoEnv/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 123, in loaddata self.load_label(fixture_label) File "/opt/venv/djangoEnv/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 181, in load_label for obj in objects: File "/opt/venv/djangoEnv/lib/python3.8/site-packages/django/core/serializers/json.py", line 74, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture '/home/example/rep/file.json': I don't understand how there can be an error — if the file is both created and read … -
How to access request.session.get[] variable value in forms.py in Django
I want populate using request.session.get[] model choice field in forms.py form.py file class AssetTagForm(ModelForm): assets = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-control'}) ,queryset=Asset.objects.filter(branch = self.session['branch'])) class Meta: model = AssetTag fields = '__all__' labels = { 'tag':'Asset Tag', } exclude = ['created_by',] widgets = { 'branch':forms.CheckboxSelectMultiple(attrs={}), 'code':forms.TextInput(attrs={'class':'form-control', 'placeholder':'Code','readonly':'readonly'}), 'tag':forms.TextInput(attrs={'class':'form-control', 'placeholder':'Asset Tag'}), 'status':forms.Select(attrs={'class':'form-control'}), } **I don't know how to use request.session.get[] variable in form.py file ** -
One to many join using django-tables2
I'm trying to join two tables together (Question and Choice) and visualize the output with django-tables2. Between Question and Choice exists a one-to-many relationship. My goal is to get this join working while specifying the Questions table as starting point / as a model in the views.py There are 2 quizzes, each quiz has 2 questions and each question has 2 answers. models.py class Quiz(models.Model): quiz_identifier = models.IntegerField(primary_key=True) quiz_name = models.CharField(max_length=200) class Question(models.Model): question_identifier = models.IntegerField(primary_key=True) quiz_identifier = models.ForeignKey(Quiz, db_column='quiz_identifier', on_delete=models.CASCADE) question_text = models.CharField(max_length=200) class Choice(models.Model): choice_identifier = models.IntegerField(primary_key=True) question_identifier = models.ForeignKey(Question, db_column='question_identifier', on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) tables.py class QuestionTable(tables.Table): quiz_name = tables.Column(accessor='quiz_identifier__quiz_name', verbose_name='Quiz Name') choice_text = tables.Column(accessor='choice__choice_text', verbose_name='Choice Text') class Meta: model = Question fields = ("question_identifier", "choice_text", 'quiz_name',) views.py class QuestionListView(SingleTableView): model = Question table_class = QuestionTable template_name = 'polls/question.html' Versions: django==4.2.3 django-tables2==2.5.3 Running this code yields a table output where the choice_text column is always none. The values in the quiz_name are all there. I tried to specify a render function for choice_text, but it was never called. def render_choice_text(self, value, record): LOG.info(f"render function called") return "something" Moreover I expected to get 8 rows (4 questions * 2 choices), but I only got 4. Manually specifying a … -
Django filter parent on base of child
i have invoice model class Invoice(models.Model): name = models.ForeignKey('Patient', on_delete=models.CASCADE) i have another invoice amount model which have FK of invoice class InvoiceAmount(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) amount = models.IntegerField(default=0) is_paid = models.BooleanField(default=False) i want to get invoices which have is_paid = True invoice amounts i am using this query but it's not working Invoice.objects.annotate(all_paid=Exists(InvoiceAmount.objects.filter(is_paid=True, id=OuterRef('pk')))).filter(all_paid=True) -
Output in jinja loop two parameters
I'm developing with Django. The output data is passed to the html page as follows: def page(request): data = { 'name':[ 'nameOne', 'nameTwo', 'nameThree' ], 'id':[ '1', '2', '3' ] } return render( request, "mainpageapp/page.html", data) I would like to see a link with text name and value id <a href="/{{id}}">{{name}}</a> At the moment I can only output one element in the for loop {% for el in name %} <a href="/{{el}}">{{el}}</a><br> {% endfor %} Is it possible to display two dictionary elements in one forloop? Or some other way to implement this? -
Django search in Postgresql db_collation field
I'm using Django and DRF searchFilter, which allows me to add fields to the view's 'search_fields' to allow searching in them. Django version is 3.2 (will probably upgrade to 4.2) and DRF version 3.12.2. Lately I've added a new field of type CharField with a db_collation of case_insensitive. I need that field to be case-insensitive and I understood that Postgres will stop supporting CI field and the recommendation is using db_collation. It did work until I wanted to support searching in that field. After adding that new field to the 'search_fields' of the view and trying searching, I got this error message - File ".../lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.NotSupportedError: nondeterministic collations are not supported for LIKE Is there a pre-prepared solution for that? I couldn't find any and I find it weird that Postgres enforce using db_collation but doesn't support LIKE in it. This is the field definition in the model - custom_field = models.CharField(db_collation="case_insensitive", db_index=True, max_length=100, null=True) This is the collation definition - [ CreateCollation( "case_insensitive", provider="icu", locale="und-u-ks-level2-kn-true", deterministic=False, ), ] -
How do I use foreign keys in Django?
from django.db import models # Create your models here. class ParentDeck(models.Model): deck_name = models.CharField(max_length=300, primary_key=True) def __str__(self): return self.deck_name class Flashcard(models.Model): cardID = models.AutoField(primary_key=True) question = models.CharField(max_length=300) answer = models.CharField(max_length=300) due_date = models.DateField() parent_deck = models.ForeignKey(ParentDeck, null=True, on_delete=models.CASCADE) def __str__(self): return self.name This has been killing me for a while now. Any help would be massively appreciated! I'm still a beginner :) I tried looking up solutions and used ChatGPT [I've learnt that ChatGPT isn't great for these tasks], yet nothing seems to be working.