Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
trouble in admin pages showing name in select for foreign key instead of id
I have two models Client and Master. Master has a foreign key to client. I am trying to get the select for the foreign key to display the name in the admin pages but getting an error. Here is the client model class Client(models.Model): id = models.BigAutoField(primary_key=True), name = models.CharField(max_length=200, blank=False, null=True) clientEmail = models.CharField(max_length=200, blank=False, null=True) clientPhone = models.CharField(max_length=200, blank=False, null=True) clientCompany = models.CharField(max_length=200, blank=False, null=True) def __str__(self): and here is an abbreviated Master class Master(models.Model): id = models.BigAutoField(primary_key = True) client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user_metadata = models.JSONField(max_length=500, null=True, blank=True) user_id = models.CharField(max_length=500, blank=False, null = True) user_name = models.CharField(max_length=500, blank=False, null = True) #abbreviated def __str__(self): return self.user_name def c_name(self): return self.client.name and the admin.py class MasterDataAdmin(admin.ModelAdmin): list_display = ( 'id', 'c_name','user_name', 'account_status') admin.site.register(Master, MasterDataAdmin) Now when I go to the Master in admin pages I get... OperationalError at /admin/kdconnector/master/ no such column: kdconnector_master.client_id Request Method: GET Request URL: http://localhost:8000/admin/kdconnector/master/ Django Version: 4.1.7 Exception Type: OperationalError Exception Value: no such column: kdconnector_master.client_id Exception Location: C:\Users\MikeOliver\KDConnectorSite\venv\Lib\site-packages\django\db\backends\sqlite3\base.py, line 357, in execute Raised during: django.contrib.admin.options.changelist_view Python Executable: C:\Users\MikeOliver\KDConnectorSite\venv\Scripts\python.exe Python Version: 3.11.3 I tried the following example that works. class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): … -
Profile() got unexpected keyword arguments: 'id_user'
I cant seam to figure out why this error occurs when 'user_id' is on the Profile model. Help! The Profile is getting a FK from the Django user form and the id_user is on the Profile model. Im following a code along it works fine for the instructor but not for me. I want to see a profile in the admin portal. Here is my models from django.db import models from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='book-icon.png') location = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username here is my views def signup(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if User.objects.filter(email=email).exists(): messages.info(request, 'Email Taken') return redirect('signup') elif User.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('signup') else: user = User.objects.create_user(username=username, email=email, password=password) user.save() #log user in and redirect to settings page #create a Profile object for the new user user_model = User.objects.get(username=username) new_profile = Profile.objects.create(user=user_model, id_user=user_model.id) new_profile.save() return redirect('settings') else: messages.info(request, 'Password Not Matching') return redirect('signup') else: return render(request, 'signup.html') Here are my Urls from django.urls import path from . … -
Why is Invoke task reexecuted on code change?
I have defined Invoke task that runs foo function and then starts my Django app. Whenever I change the code, the whole task is reexecuted. I don't understand why reload mechanism triggers the task. I want foo function to be called only on docker-compose up. Can somebody explain? Setup: docker-compose.yml: version: '3' services: backend: entrypoint: ["invoke", "my_task"] volumes: - .:/code tasks.py: from invoke import task import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") django.setup() @task def my_task(context): foo() management.call_command("runserver", "0.0.0.0:8000") -
Error message "Forbidden you don't have permission to access this resource "
I want to deploy a django app using ubuntu 22.04 as a wsl package on windows laptop and i am using an ec2 instance to host, i've made all configurations and settings but when i try to access the website on chrome using it's public IP i get error "Forbidden, you don't have permission to access this resource. Apache/2.4.52 (Ubuntu) Server at 54.81.101.238 Port 80 I've tried different solutions found online, even the ones found on stackoverflow i've given apache permissions to my app folder, made various changes to my apache2.conf and virtualhost file but i still get the same error my virtualhost conf file: <VirtualHost *:80> #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /home/rotisary/postly #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined #Include conf-available/serve-cgi-bin.conf Alias /static /home/rotisary/postly/static <Directory /home/rotisary/postly/static> Require all granted </Directory> Alias /media /home/rotisary/postly/media <Directory /home/rotisary/postly/media> Require all granted </Directory> <Directory /home/rotisary/postly/postly> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/rotisary/postly/postly/wsgi.py WSGIDaemonProcess django_app python-path=/home/rotisary/postly:/home> WSGIProcessGroup django_app apache has access to all my folders, from the root directory (home) to the directory of my django app -
How to change user password from Cognito Forgot Password using Lambda and triggers?
I'm building an SSO process to integrate an app with Cognito. For that I'm using Django (the app), Mozilla OIDC (for integration with Cognito) and AWS Cognito. I'm able to migrate users from the already existing app to Cognito User Pool. I need to contemplate the situation where a user clicks on "Forgot Password", which should trigger a Lambda, and allows me to update the user's password (hashing it) into the Database by writing the lambda_handler code. Now I don't understand how to achieve this. More specifically, the flow and which trigger to use. So far, when a user clicks on Forgot Password, it sends an email with a confirmation code, which the user has to enter along with the new password and new password confirmation. I need that when the user CONFIRMS that new password, I would capture that event and that new password I would hash it and update the database. All the hashing and updating the database, I know how to do. This is what I'm doing: Push a docker image that contains Django, boto3 and psycopg2 to an AWS ECR. This image gets pulled up when the lambda gets triggered (I think there are generic triggers … -
What is the best way to publish my django application in azure
I have a Django + Celery + AI application, and I want to publish it to Azure App Service using Docker. My question is simple. What are the best practices to do it? I've read a little about it, and in some cases they use Nginx and Gunicorn. Should I do it too? Are both necessary? -
Django SSL Operations Causing Slow API Response - How to Improve Performance?
I am a beginner at Django , I made a read request to an Api endpoint in a django appliation, it takes about 15 seconds to retrieve its content, which is a very long time, I profilled the django application and got this back, , I know it is related to SSL operations, What can I do to reduce the SSL-related latency and improve the response time of my Django application when making API requests over SSL? What I've Tried: I profiled my Django application using a profilling module and found that a significant amount of time is spent on SSL operations when making API requests to the server. I noticed that SSL handshakes and some other SSL related functions are taking a long time. I expected the API requests to be processed much faster, like very much faster, 15 seconds is too -
<script src="https://js.stripe.com/v3/"></script> stripe submit button not working in django
html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ transaction_id }} Payments setup</title> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} <style> .bill-details-container { height: fit-content; padding: 1rm; } tr { border-bottom: 1px solid gray; } </style> <script src="https://js.stripe.com/v3/"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12 text-center"> <h1>Order details</h1> <hr> </div> <div class="col text-center mt-3"> <div class="row"> <div class="col"> <h5 class="fw-bold" style="color: #404145;">{{ package_name }}</h5> </div> <div class="col"> <h5 class="fw-ligh" style="color: #404145;">₹{{ actual_price }}</h5> </div> <div class="col-md-12"> <p>{{ package_discription }}</p> </div> </div> <div class="row"> <div class="col" style="background-color: #f5f5f5;"> <center> <div class="bill-details-container col"> <table width="100%"> <tr> <td style="text-align: center; padding-top: 10px; padding-bottom: 10px;">Service fee</td> <td style="text-align: left; padding-top: 10px; padding-bottom: 10px;"> {{ service_fee }}</td> </tr> <tr> <td style="text-align: center; padding-top: 10px; padding-bottom: 10px;">Package payment</td> <td style="text-align: left; padding-top: 10px; padding-bottom: 10px;">{{ actual_price }}</td> </tr> <tr> <td class="fw-bold" style="text-align: center; padding-top: 10px; padding-bottom: 10px;">Total payment</td> <td class="fw-bold" style="text-align: left; padding-top: 10px; padding-bottom: 10px;"> {{ actual_price_fee_added }} </td> </tr> </table> </div> </center> </div> <div class="col-md-12 mt-3"> <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-6"> <div class="card"> <div class="card-header"> Payment Information </div> <div class="card-body"> <form action="{% url 'success' transaction_id request.user.username %}" id="payment-form"> <div id="card-element"> </div> <script> … -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect:VSCode Terminal Python Interpretter - Miniconda environment
I am on Windows 10 OS, using VSCode, Miniconda environment with python 3.10 and django 4.1. I encountered the following error after installing an VSCode extension to view .xlsx files in VSCode. I uninstalled it since it did not work. The problems started after this. The following error displays in VSCode Python Interpreter virtual environment enabled terminal after typing in command: conda env list Also, no other 'conda' commands work without '--no-plugins' option. The highlighted text in below block is the error message: ERROR REPORT <<<<<<<<<<<<<<<<<<<<<< Traceback (most recent call last): File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\exception_handler.py", line 17, in __call__ return func(*args, **kwargs) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\main.py", line 54, in main_subshell parser = generate_parser(add_help=True) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\conda_argparse.py", line 127, in generate_parser configure_parser_plugins(sub_parsers) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\conda_argparse.py", line 354, in configure_parser_plugins else set(find_commands()).difference(plugin_subcommands) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\find_commands.py", line 71, in find_commands for entry in os.scandir(dir_path): **> OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\jkcod\\AppData\\Local\\Programs\\Microsoft VS Code\\binC:\\Program Files\\Python310\\Scripts\\'** C:\Users\jkcod\miniconda3\Scripts\conda-script.py env list` environment variables: CIO_TEST=<not set> CONDA_DEFAULT_ENV=base CONDA_EXE=C:\Users\jkcod\miniconda3\condabin\..\Scripts\conda.exe CONDA_EXES="C:\Users\jkcod\miniconda3\condabin\..\Scripts\conda.exe" CONDA_PREFIX=C:\Users\jkcod\miniconda3 CONDA_PROMPT_MODIFIER=(base) CONDA_PYTHON_EXE=C:\Users\jkcod\miniconda3\python.exe CONDA_ROOT=C:\Users\jkcod\miniconda3 CONDA_SHLVL=1 CURL_CA_BUNDLE=<not set> HOMEPATH=\Users\jkcod LD_PRELOAD=<not set> PATH=C:\Users\jkcod\miniconda3;C:\Users\jkcod\miniconda3\Library\mingw- w64\bin;C:\Users\jkcod\miniconda3\Library\usr\bin;C:\Users\jkcod\minic onda3\Library\bin;C:\Users\jkcod\miniconda3\Scripts;C:\Users\jkcod\min iconda3\bin;C:\Users\jkcod\miniconda3\condabin;C:\Program Files\Python310\Scripts;C:\Program Files\Python310;C:\Program Files\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows ;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C :\Windows\System32\OpenSSH;C:\Program Files\Java\jdk-17.0.1\bin;C:\Program Files\Git\cmd;C:\Users\jkcod\AppD ata\Local\Microsoft\WindowsApps;C:\Users\jkcod\AppData\Local\Programs\ Microsoft VS Code\binC:\Program Files\Python310\Scripts\;C:\Program Files\Python310\;C:\Program Files\Common Files\Oracle\Java\javapath;C: \Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\Syste m32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;%JAVA_HOME%\b in;C:\Program Files\Git\cmd;C:\Users\jkcod\AppData\Local\Microsoft\Win dowsApps;C:\Users\jkcod\AppData\Local\Programs\Microsoft VS Code\bin PSMODULEPATH=C:\Program … -
Why when view returns a list of objects from db html file didn't pick the value
def index(request): context = get_all_tasks() return render(request, 'sentixplorerapp/index.html',context) above is my view function when I return this to below html code snippet it return the accepted outcome. {% extends 'sentixplorerapp/base.html' %} {% block content %} <table border="1" style="width: 80%;" class="table table-striped"> <thead> <tr> <th>Id</th> <th>Task Name</th> <th>File Path</th> <th>Result</th> </tr> </thead> <tbody> {% for task in tasks %} <tr> <td>{{ task.id }}</td> <td>{{ task.taskName }}</td> <td>{{ task.filepath }}</td> <td>{{ task.result }}</td> </tr> {% endfor %} <!-- You can add more rows as needed --> </tbody> </table> {% endblock %} but when I change my view function as below It didn't get any values to html view. Can you help me to understand why? def index(request): context = {'tasks': get_all_tasks()} return render(request, 'sentixplorerapp/index.html',context) I'm expecting to get table data that return from get_all_task() view in html when it look like this, def index(request): context = {'tasks': get_all_tasks()} return render(request, 'sentixplorerapp/index.html',context) -
How to make Django tree view
html {% for acc in accs %} <ul class="tree" id="tree"> <li> <details> <summary>{{acc.acc_id1}} {{acc.E_name1}} </summary> <ul> <details> <summary> {{acc.acc_id2}} {{acc.E_name2}}</summary> <ul> <details> <summary>{{acc.acc_id3}} {{acc.E_name3}}</summary> <ul> <li>{{acc.acc_id4}} {{acc.E_name4}}</li> </ul> </details> </ul> </details> </ul> </details> </li> </ul> {% endfor %} models.py from django.db import models class Mainacc (models.Model): acc_id1 = models.IntegerField(unique=True) E_name1 = models.CharField(max_length=10) A_name1 = models.CharField(max_length=10) def __str__(self): return f'{self.acc_id1} {self.E_name1}' class Aacc (models.Model): acc_id1 = models.ForeignKey(Mainacc, on_delete = models.CASCADE) acc_id2 = models.IntegerField( db_index=True, unique=True) E_name2 = models.CharField(max_length=50) A_name2 = models.CharField(max_length=50) def __str__(self): return f' {self.acc_id2} {self.E_name2}' class Bacc (models.Model): acc_id2 = models.ForeignKey(Aacc, on_delete =models.CASCADE) acc_id3 = models.IntegerField( db_index=True, unique=True) E_name3 = models.CharField(max_length=100) A_name3 = models.CharField(max_length=100) def __str__(self): return f' {self.acc_id3} {self.E_name3}' class Cacc (models.Model): acc_id3 = models.ForeignKey(Bacc, on_delete=models.CASCADE) acc_id4 = models.BigIntegerField( db_index=True, unique=True) E_name4 = models.CharField(max_length=100) A_name4 = models.CharField(max_length=100) def __str__(self): return f' {self.acc_id4} {self.E_name4}' views.py def Acc(request): mainacc_list = Mainacc.objects.all() aacc_list = Aacc.objects.all() bacc_list = Bacc.objects.all() cacc_list = Cacc.objects.all() acc_list = list(chain(mainacc_list, aacc_list,bacc_list,cacc_list)) return render (request,'templates\\acc\\acc.html',{'accs':acc_list}) -
Deploy Django with TailwindCSS on Elastic Beanstalk
Good day, I recently deployed a Django project to Elastic Beanstalk using the following tutorial: https://testdriven.io/blog/django-elastic-beanstalk/ This is the website: http://gmoonline4-dev.us-east-1.elasticbeanstalk.com/ The website works fine, including the admin and database, except for the CSS, which gives an error This template loads properly in development, but you can see the end product after deployment. I tried including the container_command "python3 manage.py tailwind start", but this fails the deployment. Can anyone assist me with this? I am not sure if this is an error in my django application or my EB configuration. Thanks! If you need any code, I'll post it here -
why i get None instead of the model id in django ImageField path
When attempting to add a new event through the Django admin panel, the image is incorrectly being stored at the path "media/events/None/poster/file.png" instead of the intended path "media/events/{instance.id}/poster/file.png." I have added a print(...) statement to the get_poster_image_path function for testing purposes. : def get_poster_image_path(instance, filename): print(f""" from get_poster_image_path ==================\n type :{type(instance)}\n instance :{instance}\n instance.id :{instance.id}\n instance.name :{instance.name} """) return f'events/{instance.id}/poster/{filename}' class Event(models.Model): name = models.CharField(max_length=50) poster = models.ImageField(upload_to=get_poster_image_path,null=True,blank=True) .... the result: from get_poster_image_path ============================= type :<class 'events.models.Event'> instance :myevent instance.id :None instance.name :myevent -
Custom Session backend for Django using firestore
We are tryng to create a custom backend session engine using firestore. The autentication methodology is FireBase Auth. We have created the following code for the custom session and while we are abl to create collections in Firestore , data with session_key and uid is not being written to docs in the collection. We are hoping to eliminate the use of SQLite or any other sql for production -
python: can't open file '/Users/hillarytembo/Desktop/studybudy/manage.py': [Errno 2] No such file or directory
I made this command “python manage.py runserver” I got this error “ python: can't open file '/Users/hillarytembo/Desktop/studybudy/manage.py': [Errno 2] No such file or directory” how can i fix this I tried to check if the file was there and I found the file was there -
get_absolute_url does not work in my django app
in my django app, i have used get_absolute_url in model. from django.db import models from django.urls import reverse class nm(models.Model): name = models.CharField(max_length=50) no = models.IntegerField() def __str__(self): return f"\n{self.name}|{self.no}\n" def get_absolute_url(self): return reverse("number-str-url", args=[self.name]) but in django template when i want to link that, it does not work {% extends "base.html" %} {% block title %}Numbers{% endblock title %} {% block content %} <ul> {% for number in numbers %} <li><a href="{{number.get_absolute_url}}">{{number|title}}</a></li> {% endfor %} </ul> {% endblock content %} i want to show list of numbers one, two, three, four and five. when user clicks on one of them, the link navigate user to dedicated page of the number. something like this: One Two Three Four Five -
Django Python+Ajax : how to update variable from frontend to back end? My ajax function isn't working
When the user submits this form I want to save the rgb color code as a variable to be stored on the back end (using django), so whenever the card is loaded (the colour picked on this page) will be loaded. I asked GPT, which suggested using ajax (I've never used it before). This is a snippet from my js : function updateSetColor(color) { console.log(color); $.ajax({ type: "POST", url: "/Flashcard/", beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken")); }, data: { color: color }, error: function(error) { console.log("Error updating color"); }, cache: false, }); } This is a snippet from my view that uses the color variable sent from the data : def flashcard(request): form = Flashcard_verif(request.POST) if request.method == "POST" and form.is_valid() and request.accepts('main/Flashcard.html'): print(request.POST) color = request.POST.get("color") # Get the color from the AJAX request print(color) As you can see I've got the console to output the color picked by the user and on the backend I've got the server to output the color that should've been recieved. The output from the console is correct but the output from the server is 'None'. I suspect its due to the ajax function. Any help would be appreciated or new ways of … -
Django Serializer with Many To Many fileld returns empty list, How to fix it?
I have two models Product and Lessons. I join them in one Product serializer. But I get empty list in lesson fileld. This is what I am getting now: { "id": 1, "name": "Python", "owner": 1, "lessons": [] # here should be lessons }, my modelds.py class Product(models.Model): name = models.CharField(max_length=250) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Lesson(models.Model): name = models.CharField(max_length=255) video_link = models.URLField() duration = models.PositiveIntegerField() products = models.ManyToManyField(Product, related_name='lessons') My serializers.py class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ('id', 'name', 'video_link', 'duration') class ProductSerializer(serializers.ModelSerializer): lessons = LessonSerializer(read_only=True, many=True) class Meta: model = Product fields = ['id', 'name', 'owner', 'lessons'] And my view.py class LessonListView(ListAPIView): serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): lesson_view = Product.objects.all() return products_view I can see many topics in the internet about that but I it is not working for me at all. How can I resolve it and get my data that I have for lessons field ? -
Django: How to enable app usage for different societies
I have a django project that has many apps. There is a core app that has all the main models that other secondary apps will use. One model in the core app is called SocietyEntity: class SocietyEntity(models.Model): id = models.AutoField(primary_key=True) referenceName = models.CharField(max_length=200, verbose_name="Nombre") members = models.ManyToManyField(get_user_model()) administrator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, verbose_name="Administrator") As shown, the societies can have one o more users as members. What I want to achieve is some kind of relation between societies and the other secondary apps of the project, that enable that society to make use of the app. Something like a manytomany kind of relation between SocietyEntity and app names? I'm not sure but I think I need some way to relate societies to apps, if that is even possible. If a society doesn't have permission to use an app, this shouldn't be listed in the admin interface for example. Any suggestion is well received! Thanks -
Django Table2 reverse ManyTomany
Here is my models : class Appellation(models.Model): name = models.CharField(db_index=True, max_length=255) region = models.ForeignKey(Region, on_delete=models.CASCADE) class Ranking(models.Model): name = models.CharField(db_index=True, max_length=200) initials = models.CharField(db_index=True, max_length=10, blank=True, null=True) appellation = models.ManyToManyField(Appellation) In the Ranking Table, i arrived to have a column with all the appellation of a ranking : appellation = tables.ManyToManyColumn(lambda obj: format_html('<span class="badge py-3 px-4 fs-7 badge-light-primary">{}</span>', str(obj)), separator=' ') It's OK. No, i would like to have in the Appellation Table, a column with all the rankings of the appellation. Thanks you for your help. Regards -
Csrf token verification failing for admin form after using AbstractUser class in Deployement?
I am using Abstract User class for authentication in Django. Works fine on Localhost but when deployed the admin route is redirecting and csrf verification is failing with 403 Error. https://rallys.azurewebsites.net/admin/login/?next=/admin/ ALLOWED_HOSTS = ['*'] CSRF_TRUSTED_ORIGINS = ['https://rallys.azurewebsites.net'] AUTH_USER_MODEL = 'home.User' I have looked at modifying the Authenticate_user_model but the error persists. I noticed that the passwords field is no longer hashed in the admin panel on local host except for the SuperUser I created using CLI. -
How can I see the values of a ManyToMany field based on a Foreign key value in Django Admin Panel?
I am making a Django app for multiple choice question-answer exam. I have created a Subject, Question and Exam model as below. class Subject(models.Model): subject_name = models.CharField(max_length=200, blank=False) subject_code = models.IntegerField(blank=False) class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) question_name = models.CharField(max_length=200,null=True) class Exam(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) questions = models.ManyToManyField(Question) date_of_exam = models.DateField(blank=False) users = models.ManyToManyField(CustomUser) Here in Question I am connecting subject by Foreign Key relation. In Exam I have subject as Foreign key and questions as ManyToMany relation from Question model. I want to create exam from admin panel. I want that when I select a subject only the questions of that subject should be displayed in the manytomany field to select from (As questions have foreign key of subject I think it should be possible). (I want to do this from admin panel only and not from a template.) How can I achieve this? Any suggetion is very much appreciated. Thanks in advance for the suggestions!! :) -
What should I know before shifting from Django to Wagtail
I am python programmer ,I know how django works but I'm trying to move to Wagtail. I seem not to understand about how Wagtail works , it mixes Models with templates and I also find out that it doesn't use any views ,this goes against how django works. Can you please explain to me what is a Wagtail Page exactly. I know its sort of a model but I don't seem to understand how it works. I would also like to know how do I get to use Wagtail Pages to render different data depending on data in the database lets say images of Users in the database. Also ,do I have to create a Page for everything eg If I want to create a User Model or Profile Model ,does it have to be a Page also. Please Help. I tried to actually to use Wagtail docs to create a web app but I don't seem to be in control .Wagtail doesn't have an views so i don't know how i can handle the requests in my own way then send the response of my own ,lets say JSON data. -
FastAPI Endpoint List as parameter not working
I I want to create an endpoint that receives a list of strings, which will be called and used as assets in the endpoint function. The endpoint http://localhost:8000/api/v1/equipments works correctly. Debugging I have verified that enters in and executes perfectly the function. @equipments_router.get("/equipments", summary="Equipments data") def get_equipments(assets: List[str] = None, Authorization: str = Header(None)): However, I have seen that if I make a GET to http://localhost:8000/api/v1/equipments?assets=first&assets=second, the value of assets is None. I'm pretty sure that Authorization has no role to play in the problem. -
Sending Django Channels message from inside async_task
I am using Django-Q for some moderately long tasks and would like to send a message from within the task to an websocket connection that I have established with Django channels. I am able to send the message if the task is run synchronously, ie, by calling the function, or passing sync=True to async_task. I am relatively new to this, and was not able to find out why the message is never sent, when the task is being run asynchronously. Is this not possible to achieve, or what is it that I am missing? I am aware that I could use Celery for this, though I would prefer not to unless this cannot be done with Django-Q. Here is the setup: #views.py def testview(request, uuid): task_id = async_task(dummy_task, uuid) event_triger(uuid, task_id) # This message shows up. def event_triger(uuid, message): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( uuid, { 'type': 'send_message_to_frontend', 'message': message } ) def dummy_task(uuid): for i in range(3): event_triger(uuid, "") time.sleep(3) The consumers.py file has the following: class NotificationConsumer(WebsocketConsumer): def connect(self): self.uuid = self.scope["url_route"]["kwargs"]["uuid"] async_to_sync(self.channel_layer.group_add)( self.uuid, self.channel_name ) self.accept() self.send(text_data = json.dumps({ "type": "est", "msg": self.uuid, "channel": self.channel_name })) def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.uuid, self.channel_name ) print("DISCONNECED CODE: ",code) def send_message_to_frontend(self,event): …