Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project deployment on Versel
I was deploying my Django Project where I got error 500, how can I resolve this error and is there any better platform to deploy Django project. I expected that project would be easily deployed but it gave error 500 on vercel. -
relation "account_emailaddress" does not exist
I am trying to make a Google Sign In for my app but when I try to migrate it gives me the error: **django.db.utils.ProgrammingError: relation "account_emailaddress" does not exist ** Here is My Settings.py: ``INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'rest_framework', 'rest_framework_simplejwt', 'videos', 'embed_video', 'users', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ]` `SOCIALACCOUNT_PROVIDERS = { 'google': { "SCOPE":[ 'profile', 'email' ], 'AUTH_PARAMS': {'access_type': 'online'} } }` `TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR.joinpath('templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # Required by allauth template tags "django.core.context_processors.request", # allauth specific context processors "allauth.account.context_processors.account", "allauth.socialaccount.context_processors.socialaccount", ], }, }, ]` `AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' )` `LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' I saw this and tried doing this : I figured out what the problem was. the allauth uses account app which doesn't support migrations as yet. Initially I had run python manage.py migrate allauth.socialaccount python manage.py migrate allauth.socialaccount.providers.facebook Along with this we need to run the syncdb to complete the puzzle. But it did not work and it gave me another error. CommandError: No installed app with label 'allauth.socialaccount.providers.google'. Did you mean 'google'? this error so when I do that it … -
Python - Cannot Reach Module With Relative Import
I have a file called views.py that imports a class from another file stored in the same folder. The other file is called models.py and the needed class is called Docgen. I'm using the following code to import. from .models import Docgen But I keep getting the following error. ImportError: attempted relative import with no known parent package No error is shown when I write the line from .models import Docgen but it still won't work for some reason I can't figure out. -
Google Cloud Storage Authentication Issue with Django using google-auth
I am facing an authentication issue while trying to use Google Cloud Storage with Django. I have set up my Django project to use google-auth library for authentication with other Google APIs, but when I try to use Google Cloud Storage, I get the following error: This library only supports credentials from google-auth-library-python. See https://google-auth.readthedocs.io/en/latest/ for help on authentication with this library. Steps Taken: I have set up my Django project with the necessary configurations, including installing google-auth library. I have defined the GS_CREDENTIALS variable in my Django settings to store the path to the service account JSON file. I am using the storages.backends.gcloud.GoogleCloudStorage storage backend in Django settings to handle media and static files storage on Google Cloud Storage. Django settings.py GS_CREDENTIALS = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS') STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' Expected Behavior: I expect the google-auth library to handle the authentication with Google Cloud Storage, just as it does with other Google APIs in my Django project. Actual Behavior: When trying to use Google Cloud Storage, the mentioned error is raised, indicating that the library only supports credentials from google-auth-library-python, even though I have google-auth installed and working correctly with other APIs. Additional Information: I have verified that google-auth … -
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 …