Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Method takes 2 positional arguments but 3 were given
My method actually gets 2 arguments other than self: class MyService(object): def my_method(self, instance, **kwargs): In the test code: my_service.my_method(old_instance, new_data) and Python says that: takes 2 positional arguments but 3 were given Actually method has self among arguments so I was expecting to have no problem. What am I missing? -
Removing List tag and single quotes in django template
I've created dataframe. Showing that data on front end side using django templates. Like mentioned here: In that dataframe getting list for Business Segment column. But I want to remove that list and single quotes and show it like Bag | Cement. How can I do this using django template filters? -
I can't communicate with others in Realtime-django-video-streaming-app
I can't Communicate In Django-Realtime-Video-Streaming Application. Only Single side Communication, other pages video is Off Development server is running successfully I have created a connection and all the necessary things and the setup was successfully created well. But I'm not able to communicate with other page(person) only in one 1 page VIDEO is visible. I have attached a screenshot please look into those and anyone can help me in better way. -
Integrating Django Admin Dashboard with Discord Server for Real-time Synchronization
I'm developing an admin dashboard for a Discord server using Django as the backend framework and npm as the frontend. The dashboard allows administrators to perform actions like creating roles, assigning roles to users, creating channels and other management tasks. I want to achieve real-time synchronization between the admin dashboard and the Discord server so that any changes made in the dashboard are automatically reflected on the Discord server. For example, if an admin creates a new role in the dashboard, I want that role to be created on the Discord server as well. Can someone provide guidance on the best approach to integrate the admin dashboard with the Discord server for real-time synchronization? Specifically, I would like to know: How can I establish a real-time connection between the Django backend and the Discord server? What is the recommended method for propagating changes made in the admin dashboard to the Discord server? Are there any specific libraries, tools, or techniques that would be helpful for implementing this integration? Any code examples, tutorials, or resources related to this topic would be really appreciated. Thank you for the help! -
django, can't login to admin page during test
I'm using Django 4.2, what I am trying to do is a test (a login in the admin page). So, first I create an admin with loaddata command (in fixtures.py) then the tests are run. They both fail. test_admin_page.py @pytest.mark.selenium def test_dashboard_admin_login(live_server, db_fixture_setup, chrome_browser_instance): browser = chrome_browser_instance browser.get(f"{live_server.url}/admin/login/?next=/admin/") user_name = browser.find_element(By.ID, "id_username") user_pwd = browser.find_element(By.ID, "id_password") submit = browser.find_element(By.XPATH,'//input[@value="Log in"]') user_name.send_keys("admin@email.com") user_pwd.send_keys("123admin") submit.click()#send_keys(Keys.RETURN) assert "Site administration" in browser.page_source # this would mean successful login @pytest.mark.django_db def test_admin_login(request): user = authenticate(request, username='admin@email.com', password='123admin') if user is not None and user.is_active and user.is_staff: login(request, user) assert True else: assert False fixtures.py @pytest.fixture(scope="session") def db_fixture_setup(django_db_setup, django_db_blocker): """ Loads DB data fixture """ with django_db_blocker.unblock(): call_command("loaddata","db_admin_fixture.json") db_admin_fixture.json [ { "model": "website.user", "pk": 1, "fields":{ "email": "admin@email.com", "password": "123admin", "is_superuser": true, "is_staff": true, "is_active": true } } ] The first assert fail because "Site administration" is not in the page, so it fails. In the second test the problem is that the user is None, so the function goes in the 'else' and assert False. I know maybe it's a question too generic, but i don't know how to be more specific. What can be the reasons these tests fails? Any help is appreciated :) -
Django App: Chart.js is ignoring my options
Why is my Chart.js code ignoring the options I am setting? I am attemptint to plot a simple chart with two variables that should appear on two y axes. I tried to hide the secondary y axis (which, according to the documentation, should simply require a display:false setting), and that's when I realized that the code is ignoring the values I've put in the chartOptions variable. I am building a Django application, so I'm using a base.html file for each page and I am calling a few Python variables. I have already checked that the Python component is not creating issues, this is 100% a Javascript problem: {% extends 'base.html' %} {% block content %} <form method="post"> {% csrf_token %} <br/> &nbsp;<label for="ticker">Enter ticker:</label> <input type="text" name="ticker" id="ticker" value=""> <label for="timeframe">Enter timeframe:</label> <select name="timeframe" id="timeframe"> <option value="1d" {% if chart_data.timeframe == "1d" %}selected{% endif %}>1 day</option> <option value="1wk" {% if chart_data.timeframe == "1wk" %}selected{% endif %}>1 week</option> <option value="30m" {% if chart_data.timeframe == "30m" %}selected{% endif %}>30 minutes</option> <option value="5m" {% if chart_data.timeframe == "5m" %}selected{% endif %}>5 minutes</option> </select> &nbsp; <button type="submit" class="btn btn-primary" style="--bs-btn-padding-y: .25rem; --bs-btn-padding-x: .5rem; --bs-btn-font-size: .75rem;">Run</button> </form> {% if chart_data %} <div> {% if chart_data.latest_price … -
Django-mptt model does not order by profile (ForeignKey), but it does after rebuild()
Django-mptt model does not order by (order_insertion_by) profile (ForeignKey), but it does after rebuild() models.py class Product(MPTTModel): # fields profile = models.ForeignKey( Profile, blank=True, null=True, on_delete=models.CASCADE, ) # more fields class MPTTMeta: order_insertion_by = ['profile'] Profile is also an MPTT model connected to User by OneToOneField models.py class Profile(MPTTModel): # fields user = models.OneToOneField(User, on_delete=models.PROTECT) # more fields class Meta: abstrat = False ordering = ["user__last_name", "user__first_name", "user__username"] class MPTTMeta: parent_attr = "manager" def get_name(self): return f"{self.user.last_name}, {self.user.first_name}" def __str__(self): return self.get_name() If I save some data, then order_insertion_by will order the data by id and not by last_name,first_name. But if I save and rebuild() the Product objects Product.objects.rebuild(), then it orders by last_name,first_name. The structure is: Product (root) Product (child) (needs to be sorted by profile) Product (child of child) Product (child of child of child) I want to understand why I need to use rebuild(), as rebuild() takes a lot of resources. -
The CORS policy has prohibited access to XMLHttpRequest
I'm using django code for the app server, which is available at https://github.com/AgoraIO/Agora-Chat-API-Examples/tree/main/chat-app-server-django, and this for the web SDK, which is available at https://github.com/AgoraIO-Usecase/AgoraChat-web. i am getting the CORS error. Do I need to enable any Agora settings. A call can also be put up, right? Getting this error : The CORS policy has prohibited access to XMLHttpRequest at 'https://localhost:8000/app/user/register' from origin 'http://localhost:3000': Preflight response fails access control verification: The requested resource doesn't have a 'Access-Control-Allow-Origin' header. Access-Control-Allow-Origin: * -
How to make a custom file upload handle in django to handle large files without using MemoryFileUploadHandler and TemporaryFileUploadHandler
everyone I have been working on building a reels type feature using django and exploring various methods. Initially the best way I found to handle large files is to do the uploading of files directly to files to the s3 directly. But I am trying to find a way through the server without increasing load on it much. So django uses 2 image handles - MemoryFileUploadHandler and TemporaryFileUploadHandler based on the image size which stores file into memory or disk temporarily. I want to make a custom handler that will directly store the files into s3 with using the memory or disk of the server. Not sure if it is possible. Even if we do it by chunks, it will read the file which ultimately get stored in server for sometime. I am looking for a more feasible way to make a custom file handler to directly upload chunks to s3 without writing or reading it into the system. I am not sure it is possible. If you have any workaround I should go for, I would be of great help. Sharing the code I am trying but at each point, I either have to use the above handlers. import … -
How to display images in Flutter app from Django Rest API?
I have problems with displaying images, that are saved in my database in Django Rest API. This is my postman output for the API: [ { "id": 1, "name": "firstshow", "image": "/media/images/firstshow.jpg" }, { "id": 2, "name": "secondshow", "image": "/media/images/secondshow.jpg" }, { "id": 3, "name": "thirdshow", "image": "/media/images/thirdshow.jpg" } ] This is my model: class ShowsModel{ int? id; String? name; String? image; ShowsModel({this.id, this.name, this.image}); ShowsModel.fromJson(Map<String, dynamic> json) { id = json['id']; name = json['name']; image = json['image']; } static List<ShowsModel> showsFromSnapshot(List showsSnapshot) { return showsSnapshot.map((data) { return ShowsModel.fromJson(data); }).toList(); } } I have created promocard widget, which requires imageUrl. My homepage uses promocard slider widget, which returns 3 promocards. class PromoCardSlider extends StatelessWidget { const PromoCardSlider({Key? key, required this.showsList}) : super(key: key); final List<ShowsModel> showsList; @override Widget build(BuildContext context) { return Container( height: 200, child: ListView.builder( itemCount: 3, shrinkWrap: true, scrollDirection: Axis.horizontal, itemBuilder: (ctx, index) { return promoCard( imageUrl: showsList[index].image![0]); })); } } On this line imageUrl: showsList[index].image![0]); I get error: Exception has occurred. RangeError (RangeError (index): Invalid value: Valid value range is empty: 0) How do I fix this? -
Separate permission_classes for GET and POST method
(Sorry for my bad english) I'm developing an API and I'm looking a way to select allow access for the a given method depending on if the user is authenticated. Ex: An user can only access the GET method if he is authenticated but users and gests can access the POST method. django rest framework has the "permissions.IsAuthenticated" class, but affects every method in the Class based View. Here is my code for reference: class ServiceSupplierApiView(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request, *args, **kwargs): lista =ServiceSupplier.objects.all() serializer = ServiceSupplierSerializer(lista,many = True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request, *args, **kwargs): data = { 'name': request.data.get('name'), } serializer = ServiceSupplierSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request, *args, **kwargs): instance = Supplier.objects.get(id = request.data.get('id')) data = { 'name': request.data.get('name'), } serializer = ServiceSupplierSerializer(instance = instance,data=data,partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, id, *args, **kwargs): instance = self.get_object(id, request.user.id) if not instance: return Response( {"res": "Object with id does not exists"}, status=status.HTTP_400_BAD_REQUEST ) instance.delete() return Response( {"res": "Object deleted!"}, status=status.HTTP_200_OK ) Ive tried looking it up, but haven't found an answer. -
Permissions not working while using djangorestframework-simplejwt
Permissions are not working for the library djangorestframework-simplejwt while using Django Rest. Only authentication is working correctly. Users without model permissions are still able to get the data. settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissions', ], 'DEFAULT_PAGINATION_CLASS': 'bookings.drf.pagination.StandardResultsSetPagination', #'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], 'EXCEPTION_HANDLER': 'bookings.drf.custom_exception_handler.exception_handler', } Viewset class BookingViewSet(viewsets.ModelViewSet): queryset = Booking.objects.all().order_by('-created_at') serializer_class = BookingListSerializer permission_classes = [permissions.DjangoModelPermissions] Django version 4.1.7 djangorestframework-simplejwt 5.2.2 -
Calling a ModelViewset route in Django
There's a viewset on the route: router.register(r'myview', MyViewSet) and let's say class MyViewSet(viewsets.ModelViewSet): def perform_update(self, serializer): .... When I call following request, I get a 301. curl -IL "http://127.0.0.1:8000/myview/perform_update/" What am I missing? -
Sending a list from 1st url to second url in django
I have a form in html, django and when i submit i want that a list from the 1st page should go on the second page how can i do that pls help in python I WANT to send a lsit from first page to second page but it should not be in the url and the form method must be GET -
Routes of ModelViewset in Django
There's a viewset on the route: router.register(r'myview', MyViewSet) and let's say class MyViewSet(viewsets.ModelViewSet): def perform_update(self, serializer): .... What is the url to access perform_update? -
How to put the actual model (referenced in a foreign key) in the json representation of the referencing model (Django)
I have this Employee model: class Employee(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) MARITAL_STATUS_CHOICES = ( ('S', 'Single'), ('M', 'Married'), ) id = models.IntegerField(default=20230000, primary_key=True) name = models.CharField(max_length=100) email = models.EmailField(default="mail@gmail.com") phoneNumber = models.CharField(max_length=20) address = models.CharField(max_length=100) gender = models.CharField( max_length=1, choices=GENDER_CHOICES, default='M') maritalStatus = models.CharField( max_length=1, choices=MARITAL_STATUS_CHOICES, null=True) availableVacationDays = models.IntegerField(default=0) approvedVacationDays = models.IntegerField(default=0) salary = models.IntegerField() birthDay = models.DateField(null=True) def __str__(self) -> str: return f"Employee: {self.name}" and this Vacation model: class Vacation(models.Model): STATUS_CHOICES = ( ('P', 'Pending'), ('A', 'Approved'), ('R', 'Rejected'), ) employee = models.ForeignKey( Employee, on_delete=models.CASCADE, related_name='vacation') startDate = models.DateField() endDate = models.DateField() vacationReason = models.TextField() status = models.CharField( max_length=1, choices=STATUS_CHOICES, default='P') def __str__(self) -> str: return f"{self.employee} wants to take a vacation from {self.startDate} to {self.endDate}." When I send the vacations through a JsonResponse, def get_vacations(request): vacations = Vacation.objects.all() vacation_list = serializers.serialize('json', vacations) return JsonResponse({"vacations": vacation_list}) I get only the employee_id instead of the actual object. How can I include the actual Employee object in the json sent in JsonResponse? I tried this, but it did not work def json(self): return { "employee": self.employee, "startDate": self.startDate, "endDate": self.endDate, "vacationReason": self.vacationReason, "status": self.status, "hello": "hello" } It just replaced the key name of employee_id with … -
Handling Periodic celery tasks in a Disaster Recovery setup
I am having a web application named WEB_APP. This web application is deployed in 3 datacenters, WEB_APP_1, WEB_APP_2, WEB_APP_3. WEB_APP is a django rest framework based application which has a few periodic celery tasks running in the background and also make changes to the database. WEB_APP_1, WEB_APP_2 and WEB_APP_3 all point to the same database. The periodic celeries run in all 3 datacenters and cause changes to the database multiple times. Is there a way to make the periodic celeries active only for the datacenter web app which is pointed by the GSLB? -
Long or background callbacks in django-plotly-dash
I have been using the django-plotly-dash package lately and was wondering if I could implement a progress bar for a very long-running task of my app. Below I have the demo-version of the progress bar I would like to implement. Is it even possible in the django-plotly-dash package? If not does anyone have any suggestions how I should deal with that? I'm very thankful for any replies helping since I'm kinda stuck... import time import os import dash from dash import DiskcacheManager, CeleryManager, Input, Output, html if 'REDIS_URL' in os.environ: # Use Redis & Celery if REDIS_URL set as an env variable from celery import Celery celery_app = Celery(__name__, broker=os.environ['REDIS_URL'], backend=os.environ['REDIS_URL']) background_callback_manager = CeleryManager(celery_app) else: # Diskcache for non-production apps when developing locally import diskcache cache = diskcache.Cache("./cache") background_callback_manager = DiskcacheManager(cache) app = dash.Dash(__name__, background_callback_manager=background_callback_manager) app.layout = html.Div( [ html.Div( [ html.P(id="paragraph_id", children=["Button not clicked"]), html.Progress(id="progress_bar", value="0"), ] ), html.Button(id="button_id", children="Run Job!"), html.Button(id="cancel_button_id", children="Cancel Running Job!"), ] ) @dash.callback( output=Output("paragraph_id", "children"), inputs=Input("button_id", "n_clicks"), background=True, running=[ (Output("button_id", "disabled"), True, False), (Output("cancel_button_id", "disabled"), False, True), ( Output("paragraph_id", "style"), {"visibility": "hidden"}, {"visibility": "visible"}, ), ( Output("progress_bar", "style"), {"visibility": "visible"}, {"visibility": "hidden"}, ), ], cancel=Input("cancel_button_id", "n_clicks"), progress=[Output("progress_bar", "value"), Output("progress_bar", "max")], prevent_initial_call=True ) def update_progress(set_progress, … -
I am having difficulties while deploying wagtail app in cPanel
I am getting this error while deploying wagtail app in cpanel Collecting pillow==8.4.0 Downloading Pillow-8.4.0.tar.gz (49.4 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 49.4/49.4 MB 11.6 MB/s eta 0:00:00 Preparing metadata (setup.py) ... done Building wheels for collected packages: pillow Building wheel for pillow (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [135 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-38 creating build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/ImageQt.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/PcxImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/ImtImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/BufrStubImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/JpegPresets.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/SpiderImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/WebPImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/PdfImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/MpoImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/ImageDraw.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/DdsImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/FitsStubImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/Hdf5StubImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/MpegImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/PyAccess.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/features.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/DcxImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/TiffTags.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/_util.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/ImImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/FontFile.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/JpegImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/SgiImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/GbrImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/ImageChops.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/GimpPaletteFile.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/ImageSequence.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/ImageFont.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/XpmImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/_tkinter_finder.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/PpmImagePlugin.py -> build/lib.linux-x86_64-cpython-38/PIL copying src/PIL/McIdasImagePlugin.py -> … -
django sends error report showing {% elif tag%} line
{% if category %} {% with posts=category.blogpost_set.all %} {% for post in posts %} {% include 'blog/compenent/_post.html' %} {% endfor %} {% elif tag %} {% with posts=tag.blogpost_set.all %} {% for post in posts %} {% include 'blog/compenent/_post.html' %} {% endfor %} {% endwith %} {% endif %} message :emplateSyntaxError: Invalid block tag on line 20: 'elif', expected 'endwith'. Did you forget to register or load this tag? -
Fetching nested data to reactjs
How can I fetch this nested data and display in Reactjs [ { "pk_id": "HTR4q", "name": " Contagious Bovine Pleuropneumonia(CBPP)", "species": "cattle", "language": "en-uk", "translations": { "en-uk": { "subcategory": "Diseases with respiratory/breathing signs", "subcategory_desc": "Diseases described in this section are those that have respiratory/breathing signs as the main indication of illness. These include Contagious Bovine Pleuropneumonia and East Coast fever.", "name": "Contagious Bovine Pleuropneumonia (CBPP)", "local_names": "Somali Berfur, Sambab\r\nBorana Sombes\r\nRendille Argab Looyo\r\nSamburu Lkipei, Loonkishu\r\nTurkana Loukoi Angaatuk\r\nGabra Sombes", "other_livestock_affected": "It affects cattle only.", "transmission": "Susceptible cattle become infected by inhalation of droplets from an affected animal. Urine droplets from a sick animal can also transmit the disease. Transmission can occur even if a healthy animal is between 20 to 200 metres away from an infected one.", "distribution": "", "number_affected": "In unexposed populations, up to 100% are affected. In areas where the disease is common, 10–60% of the animals are affected.", "death_rate": "In unexposed populations, the disease can kill more than 50% of the animals. In areas where the disease is common, less than 10% of the– animals die from the disease.", "predisposing_factors": "Occurs in all seasons\r\nLivestock movement – mixing of herds at watering points and on grazing fields\r\nPresence of susceptible animals\r\nSub … -
Not redirecting to homepage in django
I Have a problem in redirecting in django: code:- def search(requests): return HttpResponse("<a href="{% url 'home' %}">home</a>") but it is showing error:- Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/search/%7B%25%20url%20''%20%25%7D Using the URLconf defined in example.urls, Django tried these URL patterns, in this order: admin/ [name='home'] search/ [name='search'] I was expecting it will redirect to homepage but..... -
django sending file to another server using threads
"I am sending file to another server using request.post . For reducing the time i am using the daemon thread. I am not doing any operation on the file but still getting ValueError: I/O operation on closed file. " class UploadDocument(APIView): permission_classes = ([DeviceDocumentLimitAuth]) def post(self, request): try: notebookId=request.data.get('notebookId') file= request.FILES['file'] notebook = get_single_notebook_sercive(notebookId) file_name = request.data.get('file').name upload_file = request.FILES.getlist('file') upload_file_link=upload_file[0] daemon = Thread(target=uploadDocument_service, daemon=True, name='Monitor',args=(file, notebookId, file_name, upload_file_link)) daemon.start() return success(message="successfully uploaded the document", response_data={'data': "ingestion in progress"}) except Exception as err: return error(message=str(err)) def uploadDocument_service(file,notebookId,file_name,upload_file_link): source_response = requests.post(create_source_api, data={ 'notebook_id':notebookId, 'source_type': 'PDF' }, files={'file': file}) print('made the request',source_response.status_code,source_response.json()) if source_response: result = source_response.json()['result'] source = result['source'] sourceId = source['source_id'] document = create_document_model( file_name=file_name,upload_file_link=upload_file_link,notebookId=notebookId, sourceId=sourceId) -
some objects of ForeignKey not display in dropdown form
some of objects of Foreign Key in model skipped to show! report = models.ForeignKey( Report, on_delete=models.SET_NULL, verbose_name="انتخاب پرونده" ,related_name='report', null=True) skipped objects with id 591 , 592 and 599 !!! and not display in drop down list to select them! -
I am trying to block submit form. any advice?
HTML Forms First name: Last name: submit with button submit with button not blocked becquse id blockfor; already used above If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php". document.getElementById("blockform").addEventListener("click", function(event){ event.preventDefault() }); is that correct? I am not sure it is the best way