Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.IntegrityError: CHECK constraint failed
when I am migrating I am getting the error django.db.utils.IntegrityError: CHECK constraint failed. I am using django-cms. this error popped up after trying to add editor.js to the project full Error: Applying advita.0003_auto_20220615_1506...Traceback (most recent call last): File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: CHECK constraint failed: (JSON_VALID("sub_title") OR "sub_title" IS NULL) 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 "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\mulla\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\operations\fields.py", line 236, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) … -
Django call a class based view from another class based view
I have two classes corresponding to two different forms. When one is submitted, i need to call the other one. class FormsPreInput(CreateView): template_name = "form_preinput.html" def get(self, request, *args, **kwargs): form = preinput_form() return render(request, self.template_name, {"form": form}) def post(self, request, *args, **kwargs): form = preinput_form(request.POST) if form.is_valid(): return FormsInput.as_view()(request=self.request) class FormsInput(CreateView): template_name = "input_form.html" def get(self, request, *args, **kwargs): print("inside input get") def post(self, request, *args, **kwargs): print("inside post ") So the problem is the code is FormsInput is being called using the POST request object, so the code goes to FormsInput.post() without going to FormsInput.get() -
Joining two filtered objects two produce a single data object
I have two filtered objects based on months in a year. I wanted to return a single object based on the same months, but with the different summed values. I thought of a way I could do this, and at the moment, I have the setup running. I intend to cache the result and update it upon any database changes. I just can't help but feel like there could be a better way to do this. @permission_classes([IsAuthenticated]) @api_view(["GET"]) def refBonus(request): user = request.user referralBonus = AddToWallet.objects.filter(user=user, type="Referral").annotate(month=TruncMonth('date') ).values('month').annotate(Sum('amount')) aggregatedProfit = Profit.objects.filter(user=user).annotate(month=TruncMonth('date')).values( 'month').annotate(Sum('amount')) newList = [] for i in aggregatedProfit: for e in referralBonus: if i["month"] == e["month"]: h = {'month': i["month"], "profit": i["amount__sum"], "bonus": e["amount__sum"]} newList.append(h) months = [] for i in newList: # Append all months in newList to months variable months.append(i["month"]) # Check if a month present in aggregatedProfit is not present in months already, add it to the months variable along # with bonus being 0 as it means bonus does have data for that month for i in aggregatedProfit: if i["month"] not in months: h = {'month': i["month"], "profit": i["amount__sum"], "bonus": 0} months.append(i["month"]) # Append the month the months variable newList.append(h) # Check if a month … -
How to set permissions for a group automatically?
When creating the Django model, Django will automatically create permissions for CRUD operations. Provided that user groups have been created earlier, the question arises: how to add the necessary permissions for a group automatically? At the moment, I create data migrations in which I add the necessary permissions for the group "manually". Maybe there is a way to do this without data migration? -
Populate Related Field Based on Query Parameter
I'm trying to implement a way to show full details of a related field, rather than just the ID or a specific field, when it is specified in a query parameter, e.g http://api_url/courses?populate="author" I can currently show full details of the field by using a nested serializer, like so, or show just the UUID (or any other field) using a SlugRelatedField. class CourseSerializer(serializers.ModelSerializer): author = UserSerializer() class Meta: model = Course fields = "__all__" Any help is much appreciated. -
django-csp -- Why I am getting CSP violation error even if nonce is set up?
I am getting error in my browser as Refused to execute inline script because it violates the following Content Security Policy directive: "script-src-elem 'self' 'self' https://cdn.jsdelivr.net/". Either the 'unsafe-inline' keyword, a hash ('sha256-lcRjLlr3aCdbAn5uZatA01Jri58xjpKG86fd61W4h9Y='), or a nonce ('nonce-...') is required to enable inline execution. I am using django-csp to set up Content Security Policy. In my settings.py, I have included the following. MIDDLEWARE = [ # added middleware 'csp.middleware.CSPMiddleware', ... ] CSP_DEFAULT_SRC = ["'self'", ] CSP_INCLUDE_NONCE_IN = ['script-src'] I have written the JavaScript as - <script nonce="{{ request.csp_nonce }}"> do_something() </script> Please help me to resolve the issue. -
Dynamically prevent opening a page if someone else is actively using it
I am using Django for backend, and normal HTML/CSS/JavaScript for frontend without any interactive UI libraries like React. Current Approach: I have a page that contains a form to edit instance X as an example. If someone opens this page for editing, I am adding a value in my database that this instance is locked by this editor. After he finalizes editing, he should press "save" or "close" button to unlock it for others. Problem: If the editor didn't save and forgot to "close", the instance will remain locked till he come back and close it. Required Approach: But, I want to dynamically prevent the others to open it because someone is actively editing X now. By "actively" word, I mean that this user is using the page now, and the page tab is active in his browser. So, if he just closes the tab or browser, or leaves the tab inactive for maybe 5 minutes, I want to unlock the instance for editing. -
Download files as stream without downloading complete files into memory
I want to download files as stream from a remote server and make them zip stream and return it to frontend as stream without waiting all files to complete downloads. Is it possible in python and framework of python ?? I tried as below but its not working i am using Django framework: zip_buffer = io.BytesIO() with zipstream.ZipFile(zip_buffer,"w", zipfile.ZIP_DEFLATED, False) as zf: url = "https://download-file/zy" r = requests.get(url, stream=True) zip_inf = zipstream.ZipInfo(file_name) zf.write_iter(zip_inf, r.content) response = StreamingHttpResponse(zip_buffer.getvalue(), content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=zip-files.zip' return response -
Problem with connect local postgres to docker container
I have docker.compose.yml file: version: '3.8' services: web: build: ./kazarm command: python manage.py runserver 0.0.0.0:8000 volumes: - ./kazarm/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:13.0-alpine ports: - 127.0.0.1:5432:5432 environment: - POSTGRES_USER=kazarma - POSTGRES_PASSWORD=kazarma - POSTGRES_DB=kazarma networks: outside: external: true In Django DB setting.py SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=kazarma SQL_USER=kazarma SQL_PASSWORD=kazarma SQL_HOST=127.0.0.1 SQL_PORT=5432 In pg_hba.conf file # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. local replication all trust host replication all 127.0.0.1/32 trust host replication all ::1/128 trust and in postgres.cong also listen_addresses = '*' And I try to use the different SQL_HOST like localhost, 127.0.0.1 all don't work. But when I get SQL_HOST=db then it works. docker-compose log file django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "127.0.0.1" and accepting web_1 | TCP/IP connections on port 5432? I want to use the local Postgres because the data is very important and when I down my docker I … -
microsoft django authentication
I want to authenticate my Django base website users by Microsoft authentication, I have followed a multiple solutions but not getting the results so can you please tell me that how can I integrate Microsoft authentication as a third party with my Django project. -
login(request, user) not working in python django
urls.py this is my url page path('login/',views.login_view, name="login"), views.py this is my views if request.method == "POST": user_name = request.POST.get("username") pass_word = request.POST.get("password") user = authenticate(request, username=user_name, password=pass_word) # print("user1 -->", user) if user is not None: # print("user-->",user) login(request, user) return render(request, "index.html") else: return render(request,"http://127.0.0.1:8000/login") else: #return render(request, "order.html") return render(request, "login.html") error I am getting is TypeError at /login/logincheck/ login() missing 1 required positional argument: 'user' -
How to identify Oracle instantClient in a Django project?
I try to link an external Oracle database on which I have read-only privileges to my Django project and then only send it raw SQL queries. So I first created a second table in my project settings (because I still need the default database) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'oracleDB':{ 'ENGINE': 'django.db.backends.oracle', 'NAME': 'my_dsn', 'USER': 'my_user', 'PASSWORD': 'my_password', 'HOST': 'my_host', 'PORT': 'my_port', 'OPTIONS':{ 'threaded':True } } Then in my view I call it this way (seen on a forum): views.py from django.db import connections def my_function(request): with connections['oracleDB'].cursor() as cur: cur.execute( "SOME SQL QUERY") print(cur.fetchall()) And I get this error DPI-1047: Cannot locate a 64-bit Oracle Client library: “C: ProgramData Oracle12c product 12.1.0 client_1 bin oci.dll is not the correct architecture”. See cx_Oracle 8 Installation — cx_Oracle 8.3.0 documentation for help I know that I need the Oracle instantclient to connect, I used to use it in connection with the cx_Oracle package and it worked well (so i'm certain the version is good). Except that now I connect with Django and its settings where I can’t specify the path to my Oracle instantclient. Do you have any idea how to enable Django … -
Repeating record using for loop in database
in this code am trying to add the student record in the attendance database whenever the student image is captured by the webcam so name = image name stored adding that the image name is the same as the studentid stored in Student entity, whenever the detected face name exist in Name = the list of images name then it will add the student info to the attendance database. The code just works fine but it keeps repeating the records how can I limit it to add the record just once and not repeating it. def markattendance(name): for n in Names: if name in Names: # print(name, "Exist") # fitches the information related to the detected name attend = Student.objects.filter(student_id=name).values('student_id', 'student_fname', 'student_lname','fk_course_id_id') #print(attend) # filter returns a queryset. A queryset isn't a single object, it's a group of objects so it doesn't make sense # to call save() on a queryset. Instead you save each individual object IN the queryset: for object in attend: #print(object) if object.get('student_id') not in attend: # INSERT SQL statement behind the scenes. Django doesn’t hit the database until you explicitly call save(). reg = Attendance(student_id=object.get('student_id'), student_fname=object.get('student_fname'), student_lname=object.get('student_lname'), course_id=object.get('fk_course_id_id')) # print(reg) reg.save() else: pass -
Create a folder with models,views and urls inside an app.How to import these models in the main app model?
I have created an App using the startapp command and inside that i have created other files.But when i try to import that model in the init file of main app it get this as an error:: from subapp1.models.models import TodoList ModuleNotFoundError: No module named 'subapp1' How can i import this? I am written this in the main app init file-->> from subapp1.models.models import TodoList all = ['TodoList',] -
How to customize field representation in django drf AutoSchema?
I am new to using Django drf schema generation. I installed and configured the schema according to the documentation. It generates the OpenAPI schema. Now I want to customize the choice field representation and add some description in front of each field. Current schema is like below: condition: enum: - used - new - like new type: string nullable: true I want the following: condition: enum: - used: "for used items" - new: "for new items" - like: new " brand new items" type: string nullable: true In the documentation I could find little on how to customize the AutoSchema class but that was above my knowledge. I would be grateful if someone can help me on how can I override the schema methods to represent customize fields? -
Issue with circular import in Django tutorials?
I am getting a circular import error with a basic Django page setup and I have no idea why. Am following the guides of at least 4 or 5 different tutorials with the same result. I have varied the syntax in the webapps urls.py to no avail. Any ideas ? mainproject urls.py file from django.contrib import admin from django.urls import include, path urlpatterns = [ path('members/', include('members.urls')), path('admin/', admin.site.urls), ] webapp Views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello world!") urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Error "/Users/Desktop/website/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 706, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'members.urls' from '/Users/Desktop/website/main/members/urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. -
extra query after logging in to the site (django3.2)
Why after logging in to the site, an extra query is taken on all pages to get that user information? Is this related to Django it self? Or can this extra query be deleted and optimized? What the Django-debug-toolbar shows on all pages: SELECT ••• FROM "accounts_user" WHERE "accounts_user"."id" = '1' LIMIT 21 And the user with the id=1 is the user I logged in with. -
Django datetime TypeError: fromisoformat: argument must be str
Internal Server Error: /api/orders/add/ Traceback (most recent call last):strong tenter image description hereext File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\backend\base\views\order_views.py", line 31, in addOrderItems order = Order.objects.create( File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\query.py", line 514, in create obj.save(force_insert=True, using=self.db) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 806, in save self.save_base( File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 857, in save_base updated = self._save_table( File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 1000, in save_table results = self.do_insert( File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 1041, in do_insert return manager.insert( File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\query.py", line 1434, in insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql for … -
Postgresql is not getting data from CRUD form
I am new to POSTgreSQL and I have been making a CRUD code using django,python,html,and POSTgreSQL here's my code templates\employee_register\base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Employee Register</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js" integrity="sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> </head> <body> <div class="container"> <div class="col-md-10 offset-md-1 mt-5"> <div class="jumbotron"> <h1 class="display-4">Employee Register</h1> <p class="lead-front-italic">python django project for crud implementation</p> <hr class="my-4"> {% block content %} {% endblock content %} </div> </div> </div> </body> </html> employee_form.html {% extends "employee_register/base.html" %} {% load crispy_forms_tags %} {% block content %} <form action="" method="post" autocomplete="off"> {% csrf_token %} {{form.first_name|as_crispy_field}} {{form.middle_name|as_crispy_field}} {{form.last_name|as_crispy_field}} <!-- <div class="row"> --> <!-- <div class="col-md-4"> --> {{form.emp_code|as_crispy_field}} <!-- </div> --> <!-- <div class="col-md-8"> --> {{form.department|as_crispy_field}} {{form.designation|as_crispy_field}} {{form.location|as_crispy_field}} {{form.status|as_crispy_field}} {{form.date_of_birth|as_crispy_field}} {{form.date_of_joining|as_crispy_field}} {{form.gender|as_crispy_field}} <!-- </div> --> <!-- </div> --> <button type="submit" class="btn btn-success"> <i class="fa-solid fa-database"></i>Submit </button> </form> {% endblock content %} employee_register.html {% extends "employee_register/base.html" %} {% block content %} <p>we'll show list of employee from the table</p> {% endblock content %} models.py from django.db import models class Position(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title # Create your models here. class Employee(models.Model): first_name=models.CharField(max_length=100) middle_name=models.CharField(max_length=100) … -
Increase integer when an object is created in Django
Hello I have two models Teaching Semester and Enrollments , i wanted to count the number of students in a particular course. Practically i wanted to have a registered students field which will be increased everytime when Enrollments object is created. Here is my model for Teaching Semester class TeachingSemester(models.Model): department = models.ForeignKey(Department,on_delete=models.CASCADE) program = models.ForeignKey(Program,on_delete=models.CASCADE) faculty = models.ForeignKey(FacultyData,on_delete=models.CASCADE) semester_choices = ( ('Spring' , 'Spring'), ('Fall' , 'Fall'), ('Summer' , 'Summer') ) sem_choice = models.CharField(max_length=30,choices=semester_choices,default='Spring') course_date = models.DateField(default=datetime.date.today()) section = models.CharField(max_length=5,default = 1) faculty_course = models.ForeignKey(Course,on_delete=models.CASCADE) And model of Enrollments class Enrollment(models.Model): student = models.ForeignKey(StudentData,on_delete=models.CASCADE) faculty = models.ForeignKey(TeachingSemester,on_delete=models.CASCADE) -
In booking viewset I've to list all bookings when admin is logged in and normal user can see objects created by that particular user using id =pk
given are the views.py and models.py Here in my "class BookViewSet(viewsets.ModelViewSet)" and "class BookingRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView)" I need to create functionality given in the problem statement. Problem statement for (class BookViewSet(viewsets.ModelViewSet)) (a) If Admin is logged-in display all bookings of all users and can create bookings. (b) If a regular user logged in displays records created by that particular user and can create a user too. (c) at the time of API testing how to use the simple-jwt token to verify user as I've added permission for access control. for (class BookingRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView)) (a) if Admin is logged-in get/put/delete functionality for every user's booking. (b) if a regular user logged-in get/put/delete for that particular user booking records. Note: I've tried to do this without this functionality and simply using custom permission but it's not working maybe because it cannot get user identified. permissions.py from django.contrib.auth import get_user_model from rest_framework.permissions import BasePermission User = get_user_model() class IsUserOrIsAdmin(BasePermission): """Allow access to the respective User object and to admin users.""" def has_object_permission(self, request, view, obj): return (request.user and request.user.is_staff) or ( isinstance(obj, User) and request.user == obj ) Views.py from django.shortcuts import render from django.http import Http404, JsonResponse #from django.http import HttpResponse, JsonResponse from rest_framework.views import … -
How to get two models data in for loop with filter: Django
I do have two model as below, like patient details model and patient visit model. I want to list the visits of all patients (if exist). in views.py I am passing both models data by get all. how to filter and show it in the template by using for loop. I am using two for loop it shows total number of patient multiply total number of visit which is wrong.. class patientprofile(models.Model): pat_Fname = models.CharField(max_length=100) pat_Lname = models.CharField(max_length=100, blank=True) def IntegerField(self): return self.id class visits(models.Model): pat_ID = models.ForeignKey(patientprofile, on_delete=models.CASCADE) visit_date = models.DateField(blank=False, null=False) visit_time = models.TimeField(blank=False, null=False) views.py @login_requireddef visitslist(request): patpro=patientprofile.objects.all() vis=visits.objects.all() return render(request, 'pmp/visitslist.html', {'vis':vis, 'patpro':patpro}) Template as below {% for a in vis %} <tr> <td> {{ a.visit_time }} </td> <td>{{ a.visit_date }}</td> <td>{{ patpro.id }}</td> <td>{{ patpro.pat_Fname }}</td> </td> </tr> {% endfor %} -
Why submit didn't work in my jquery script?
My html and script is like below. It's using Django and it's a Django template but I think this is a issue not related to Django. It displays a list of dir or files(if any) which are arranged in ul and li elements. When I click on any list item(li element), I expect it will trigger a submit. I can saw the alert() window, but I didn't see the post request from the server side. I have a similar snippet in another place of my project and that works, but this don't. I can't think out what I had missed? <form id="id_f_sel" action="{% url 'integratedTest:addCase' %}" method="post"> {% csrf_token %} <input type="hidden" id="id_f_clked" name="f_clked" value=""> <ul id="id_dirlist"> {%for item in dirs %} <li><img src="{% static 'image/folder.png' %}" alt="unclicked folder image"> <span class="caret">{{item}}</span></li> {%endfor%} </ul> <ul id="id_flist"> {%for item in files %} <li><img src="{% static 'image/file.png' %}" alt="file image"> <span class="caret">{{item}}</span></li> {%endfor%} </ul> </form> <script> $(document).ready(function() { $('li').on('click', function() { clk_val = $(this).text() alert(clk_val) $('#id_f_clked').val(clk_val) $('#id_f_sel').submit() }); }); </script> -
Wagtail removes style of rich text when saving and rendering
I was trying to use TinyMCE for Wagtail as my rich text editor, but Wagtail seems to be not accepting style changes on elements, although it's shown in the section it disappears when I am trying to save the draft or preview it. TinyMCE Editor Source The actual HTML that was being saved -
django_embed_video module throws error "e doesn't look like a module path"
I have been 6 hours trying to figure out why doesn't the django_embed_video module work as supposed. I followed the documentation. Created a model with VideoEmbed Field. All i am trying to achieve is to view a youtube video in my template, but i keep getting this error: detect_backend(str(backend_or_url)) File "project\venv\lib\site-packages\embed_video\backends.py", line 61, in detect_backend backend = import_string(backend_name) File "project\venv\lib\site-packages\django\utils\module_loading.py", line 27, in import_stringraise ImportError("%s doesn't look like a module path" % dotted_path) from err ImportError: e doesn't look like a module path template.html ... {% load static %} {% load embed_video_tags %} ... {% for tid, t in tests.items %} <div class="embed-responsive embed-responsive-16by9"> <!-- Bootstrap responsive layout --> {% video t.ytvideo.url %} <!-- iterate tests and get YT video of each test --> </div> {% endfor %}