Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error: 'utf-8' codec can't decode byte when trying to create downloadable file
I have created an app, to do some process and zip some files. Now I need to make the zip file downloadable for users, so they can download the zip file. I am working with Django and here is the in views.py: def download(request): context = {} if request.method == 'POST': if form.is_valid(): userInput = form.cleaned_data['userInput'] createFiles(userInput) filename = 'reports.zip' filepath = '/home/download/' fl = open(filepath, 'r') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response return render(request, 'download.html', context) But I am getting an error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x83 in position 11: invalid start byte Which is breaking on this line: response = HttpResponse(fl, content_type=mime_type) Any suggestions how to fix this? -
How to access elements in list of dictionaries?
I’m working with a CSV file that looks as follows: POS,Transaction id,Product,Quantity,Customer,Date 1,E100,TV,1,Test Customer,9/19/2022 2,E100,Laptop,3,Test Customer,9/20/2022 3,E200,TV,1,Test Customer,9/21/2022 4,E300,Smartphone,2,Test Customer,9/22/2022 5,E300,Laptop,5,New Customer,9/23/2022 6,E300,TV,1,New Customer,9/23/2022 7,E400,TV,2,ABC,9/24/2022 8,E500,Smartwatch,4,ABC,9/25/2022 In order to grab elements out of it this gets each line into a callable line by assignment: with open(obj.file_name.path, 'r') as f: rdr = csv.DictReader(f) for row in rdr: pos = row['POS'] product = row['Product'] transaction_id = row['Transaction id'] quantity = row['Quantity'] customer = row['Customer'] date = row['Date'] try: product_obj = Product.objects.get(name__iexact=product) except Product.DoesNotExist: product_obj = None For example to print each row from the CSV I can now type: pos, transaction_id, product, quantity, customer, transaction_id, date = row print(row) Resulting in this terminal output: file is being uploaded {'POS': '1', 'Transaction id': 'E100', 'Product': 'TV', 'Quantity': '1', 'Customer': 'Test Customer', 'Date': '9/19/2022'} {'POS': '2', 'Transaction id': 'E100', 'Product': 'Laptop', 'Quantity': '3', 'Customer': 'Test Customer', 'Date': '9/20/2022'} {'POS': '3', 'Transaction id': 'E200', 'Product': 'TV', 'Quantity': '1', 'Customer': 'Test Customer', 'Date': '9/21/2022'} {'POS': '4', 'Transaction id': 'E300', 'Product': 'Smartphone', 'Quantity': '2', 'Customer': 'Test Customer', 'Date': '9/22/2022'} {'POS': '5', 'Transaction id': 'E300', 'Product': 'Laptop', 'Quantity': '5', 'Customer': 'New Customer', 'Date': '9/23/2022'} {'POS': '6', 'Transaction id': 'E300', 'Product': 'TV', 'Quantity': '1', 'Customer': 'New Customer', 'Date': '9/23/2022'} … -
get parameters in a get request in django rest framework?
I want to get the parameters sent to my rest api what I want is to obtain the parameters that to use them consume another api and return the response of the third party api but in name and comic i get None http://127.0.0.1:8000/searchComics/ {name:"3-D Man","comics":12} this is my view class MarvelApi(APIView): def get(self, request): private_key = "88958f2d87bd2c0c2fa07b7ea654bcdf9f0389b3" public_key = "8d415ffcc9add56b0a47c0a7c851afc3" ts = 1 md5_hash = "46ecbbd63108b0561b8778a57823bd34" query_params = self.request.query_params name = query_params.get('kword', None) comic = query_params.get('comic', None) end_point = f"https://gateway.marvel.com:443/v1/public/characters?ts={ts}&apikey={public_key}&hash={md5_hash}&name={name}&comic={comic}" response = requests.get(end_point) response_json = json.loads(response.text) return Response(status=status.HTTP_200_OK, data=response_json) I think the problem is these two lines name = query_params.get('kword', None) comic = query_params.get('comic', None) that do not capture the values correctly, do you know how to solve it? -
admin.SimpleListFilter with related_query_name to filter occurances
I try to filter items in a admin list: class Product(models.Model): name = models.CharField("name", max_length = 128) def associated_stores(self): stores = set([f"""{s.number}""" for sin self.store_name.all()]) if len(stores) == 0: return None return ", ".join(stores) class Store(models.Model): products = models.ManyToManyField(Product, related_name = "%(class)s_name", related_query_name = "product_store_qs", blank = True) number = ... Now I want to implement a SimpleListFilter that can filter in the products list for products that are available in no stores, or show the store names: class AssociatedStoresFilter(admin.SimpleListFilter): title = "associated stores" parameter_name = "assoc_stores" def lookups(self, request, model_admin): return [(True, "yes"), (False, "no")] def queryset(self, request, queryset): qs = queryset.annotate(assoc_stores = Case(When(product_store_qs__isnull = False, then = 1), default = 0)) if self.value() == "False": return qs.filter(assoc_stores = 0) elif self.value() == "True": return qs.filter(assoc_stores = 1) else: return queryset The filter for no stores have the product works, but the one where only products should be shown that are available in a store shows one entry for every store of a product (with all stores) instead of only one entry (with all stores) only. How do I cut down my results to hold every product only once after filtering? edit: I know I can solve my problem … -
How do I tackle this issue in my Guess The Flag Django web app
I'm completely new to Django and I'm trying to build this guess the flag web game with it. In main page when someone presses the 'play' button, he's sent to a page where a list of 4 randomly selected countries from the DB is generated, and only of one these 4 countries is the actual answer. Here's the code from views.py in my App directory : context = {} context['submit'] = None context['countries_list'] = None score = [] score.clear() context['score'] = 0 def play(request): len_score = len(score) countries = Country.objects.all() real_choice = None if request.POST: get_guess = request.POST.get('guess') print(request.POST) if str(get_guess).casefold() == str(context['submit']).casefold(): score.append(1) else: score.clear() len_score = len(score) choices = random.sample(tuple(countries),4) real_choice = random.choice(choices) context['countries_list'] = choices context['submit'] = real_choice context['score'] = len_score return render (request, 'base/play.html', context) Everything works as expected when there's only one person playing, or the site is opened in only one tab. The issue here is one someone else opens the site or it's opened in more than one tab, the score gets reset and a new list of random countries is generated for all users, so your guess will never be right! How do I go about to solve this? Again, I'm completely … -
Test Django ModelForm fails but html is present?
Trying to write a very simple test for the start of a ModelForm in Django. My Model: # models.py class Grade(models.Model): paper = models.ForeignKey( Paper, on_delete=models.PROTECT, related_name="grades" ) exam = models.ForeignKey( Exam, on_delete=models.PROTECT, related_name="grades" ) level = models.ForeignKey( Level, on_delete=models.PROTECT, null=True, blank=True, related_name="grades", ) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) created_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_created_by" ) updated_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_updated_by" ) deleted_at = models.DateTimeField(blank=True, null=True) class Meta: verbose_name = "Grade" verbose_name_plural = "Grades" My form looks like this: # forms.py class GradeForm(ModelForm): class Meta: model = Grade fields = [ "exam", "level", "paper", "created_by", "deleted_at", "updated_by", ] My tests look like this: #test_forms.py class GradeForm(TestCase): def setUp(self): self.grade = GradeFactory() def test_empty_form_fields(self): # THIS PASSES form = GradeForm() self.assertIn("created_by", form.fields) self.assertIn("deleted_at", form.fields) self.assertIn("exam", form.fields) self.assertIn("level", form.fields) self.assertIn("paper", form.fields) self.assertIn("updated_by", form.fields) def test_empty_form_html_elements(self): form = GradeForm() # THESE THREE ASSERSTIONS FAIL: # But I can see the HTML in the debugger if I print(form.as_p()) # And the HTML is exactly as it is below in the assertions... self.assertInHTML( '<select name="exam" required id="id_exam">', form.as_p(), ) self.assertInHTML( '<select name="paper" required id="id_paper">', form.as_p(), ) self.assertInHTML( '<select name="level" id="id_level">', form.as_p(), ) def test_form(self): form = GradeForm( data={ "expectation": self.grade.exam.id, "summary": … -
Is the Django Two-Factor Authentication framework working with MongoDb?
i have been trying to implement the Django Two-Factor Authentication tool in my project and was not able to make it work. I am getting until the log in page but when I actually try to log in I am getting a weird Database Error with no provided exception message. Keyword: None Sub SQL: None FAILED SQL: ('SELECT "otp_static_staticdevice"."id", "otp_static_staticdevice"."user_id", "otp_static_staticdevice"."name", "otp_static_staticdevice"."confirmed", "otp_static_staticdevice"."throttling_failure_timestamp", "otp_static_staticdevice"."throttling_failure_count" FROM "otp_static_staticdevice" WHERE ("otp_static_staticdevice"."user_id" = %(0)s AND "otp_static_staticdevice"."confirmed")',) Params: ((4,),) Version: 1.3.6) When checking the requirements it states that version 1.0 of django-formtools is supported. However my project does not run with this version of formtools at all. Also on their github the build is shown as failing. I however have seen it working in other projects. Do I get the errors due to me using djongo and MongoDb as a Database? Or is my fear true and the tool is not working and 2FA should be implemented on my own? Thank you very much in advance -
Why is my Django view hanging when I use asyncio.gather on a sync_to_async function call, but not when I call it directly?
I have a Django view that calls an asgiref.sync.async_to_sync function that queries a remote API - I'm updating payslip data for a bunch of Employees. Within one of these calls I have to access the DB again so have a asgiref.sync.sync_to_async decorated function to gather that data. I run the Employee update function calls concurrently using asyncio.gather, but this hangs indefinitely and never even enters the DB call - this occurs even if I only have one call in the gather list. Awaiting the function works fine though. Everything is running as an ASGI app under Uvicorn. Any ideas? Here's a minimal reproduction: @sync_to_async def _get_database_employee_payslips(employee_data): print(f"Entering DB function") return employee_data @async_to_sync async def get_full_employees_data(_, __): print(f"This works") ret = await _get_database_employee_payslips({'id': 1625841}) print(f"Got {ret}") print(f"This doesn't") ret = await asyncio.gather(*[ _get_database_employee_payslips({'id': employee_id}) for employee_id in [1625841] ], return_exceptions=True) print(f"We're hung in the above call") return ret and the results: INFO 2022-09-27 14:20:20,234 on 10776 140271592661440 Application startup complete. DEBUG 2022-09-27 14:20:22,163 middleware 10776 140271484180032 process_request DEBUG 2022-09-27 14:20:22,163 model_factory 10776 140271484180032 No maximum request body size is set, continuing. DEBUG 2022-09-27 14:20:22,183 model_factory 10776 140271484180032 Created new request model with pk 161dfa90-4082-4ef1-8ab0-84d613c25550 This works Entering DB function Got {'id': … -
Django- disallow url in robots.txt that contains variable [duplicate]
In my App I use an API to handle likes for blog posts. The urls are structured like path('post/<int:pk>/<slug:slug>/', views.DetailPostView, name='post-detail'), path('post/<int:pk>/like', PostLikeToggle.as_view(), name='like-toggle'), path('api/post/<int:pk>/like', PostLikeAPIToggle.as_view(), name='like-api-toggle'), The issue is google search console is giving me errors because it is trying to index the likes url and not the true url. How would I prevent the likes URL's from being index by google as I cannot find a way to pass variables in robots.txt or is there a different way to prevent these pages from being indexed. Update: Based on the suggested post I'm just a bit confused on how to implement this. Is it just as simple as Disallow: /*/like Would this block a url such as /post/999/test/unsportsmanlike/foo Updated: I discovered the google robots.txt Tester and was able to determine that the above query works -
django - server is slow to render response, how to manage user experience
My django app is responding slowly on some pages. While I'm working on improving the query efficiency, indexing on the db, etc, my question is how to manage the user experience. What I think is to run some kind of waiting icon, but my research only finds js that works on page loading delays once the browser receives the new page (e.g some element within the document takes time to present). I'm asking about after the user clicks on a url, the message goes off to the server, and before the server responds with a page. The browser shows the "old" page while the server churns away generating the new page. The only clue the user has that something is processing is the "stop/refresh" icon in the url bar is an "x" (in firefox). Are there any ideas, standard approaches, or solutions on how to approach the user experience while the next page is being "resolved/generated?" I guess I could move the offending elements to an API so the response comes more quickly and the do the "working" icon while the page finishes loading. But, suppose that's not something we'd like to do if possible (at least right now). Thanks … -
WebSocket connection is not return any data?
I run this code the handshake and connection work fine but I don't get any results after I run the client.even though the code is working perfectly without any issues. is there any idea to fix the problem? note: I'm using graphql and Django framework in my project import asyncio import graphene from channels.routing import ProtocolTypeRouter, URLRouter class Query(graphene.ObjectType): hello = graphene.String() @staticmethod def resolve_hello(obj, info, **kwargs): return "world" class Subscription(graphene.ObjectType): """Channels WebSocket consumer which provides GraphQL API.""" count_seconds = graphene.Float() async def resolve_count_seconds(root, info): for i in range(10): yield i await asyncio.sleep(1.) schema = graphene.Schema(query=Query, subscription=Subscription) class MyGraphqlWsConsumer(channels_graphql_ws.GraphqlWsConsumer): """Channels WebSocket consumer which provides GraphQL API.""" schema = schema async def on_connect(self, payload): pass application = channels.routing.ProtocolTypeRouter({ "websocket": channels.routing.URLRouter([ django.urls.path("graphql/", MyGraphqlWsConsumer.as_asgi()), ]) }) ASGI_APPLICATION = 'graphql_ws.urls.application' client: from graphql_client import GraphQLClient ws = GraphQLClient('ws://localhost:8000/graphql/') def callback(_id, data): print("got new data..") print(f"msg id: {_id}. data: {data}") query = """ subscription { countSeconds } """ sub_id = ws.subscribe(query, callback=callback) -
Since django 4.1, templates are cached with DEBUG=True. Is this solution right?
As described in the documentation, since 4.1 the default behavior for template loading changed drastically. If I understand it right, until 4.0 it worked like this: With DEBUG enabled, the templates are loaded in every request, therefore if you keep making changes and reloading while working on a template, you always see the latest version. With DEBUG disabled, the templates are cached when initializing the application, therefore you can only see changes in your templates if you also restart the application. That way, the template caching was seamlessly enabled in production which is great. Now this ticket proposal was included and, if I get it correctly, the template loading method must be specified and it's not anymore tied to DEBUG setting, AND, by default are cached. We want the original behavior so the frontend developer can see the changes without having to restart the app, and we also want the production deployment to have the caching enabled, so we did this: develop_loaders = [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ] production_loaders = [ ("django.template.loaders.cached.Loader", [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", "path.to.custom.Loader", ]) ] TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ "templates", ], "OPTIONS": { "context_processors": [ "maintenance_mode.context_processors.maintenance_mode", "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "wagtail.contrib.settings.context_processors.settings", ], "loaders": develop_loaders … -
searchable and able to sleelct all options in Django
How can I make a form that I can do these with: 1_ seaerchable choice field like cities. 2_a button that make me able to select all of cities. -
NoReverseMatch , Reverse for 'profilepage' with arguments '('',)' not found. 1 pattern(s) tried: ['profilepage/(?P<pk>[^/]+)/\\Z']
def profilki(request): profilki = profile.objects.all() context = {'profilki':profilki } return render(request,'base/profilki.html',context) def profilepage(request,pk): user = Trainingvalue.objects.get(id=pk) trainingplan = Trainingvalue.objects.all() profilepage= profile.objects.get(id=pk) user_training= Trainingvalue.objects.filter(user=profilepage.user) context ={‘user_training’:user_training,‘user’:user,‘profilepage’:profilepage, ‘trainingplan’:trainingplan,} return render(request, 'base/profilepage.html' , context) url : path (‘profilepage/str:pk/’,views.profilepage, name=“profilepage”) profilepage in context profile page has an attribute id profilepage.id entity does not provide value - yet i can access it through the borwser… so technically this should work in html template: profile i get error: Reverse for 'profilepage' with arguments '('',)' not found. 1 pattern(s) tried: ['profilepage/(?P<pk>[^/]+)/\\Z'] -
Why do I get MIME type error on Django/React app when loading css/js from Aws?
So I deployed a Django-Rest/React app on Heroku where I serve my static and media files on AWS S3 buckets. After pushing to Heroku and accessing the API URL or admin URL everything works fine but when I try to access my React URLs I get a MIME type error. On the network tab of developer tools, I get status 301 on my JS and CSS file. And in the console I get: Refused to apply style from 'https://app.herokuapp.com/static/css/main.9d3ee958.css/' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. app.herokuapp.com/:1 Refused to apply style from 'https://app.herokuapp.com/static/css/main.9d3ee958.css/' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. app.herokuapp.com/:1 Refused to execute script from 'https://app.herokuapp.com/static/js/main.3b833115.js/' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Even though the URL above is correct and I do have those files in my bucket. Here are my production settings: from decouple import config import django_heroku import dj_database_url from .base import * SECRET_KEY = config('SECRET_KEY') DEBUG = False ALLOWED_HOSTS = ['*'] ROOT_URLCONF = 'portfolio.urls_prod' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/build') ], … -
how to reverse fetch data in django models
I am working on a project and stuck somewhere to fetch the data child model which has a foreignkey of parent model. this is how my model looks like class Projects(models.Model): project_name = models.CharField(max_length=100,null=False) class ProjectTask(models.Model): project_id = models.ForeignKey(Projects,on_delete=models.CASCADE,null=False) class TaskBlockers(models.Model): task_id = models.ForeignKey(ProjectTask,on_delete=models.CASCADE,null=False,related_name='task_id_related') blocker = models.CharField(max_length=100,null=False) now what I want is to get all the blockers under a projectTask which has a projectid = something. ProjectTask.objects.filter(project_id=1) this will give a queryset right? and for each element in a queryset i want the blocker from TaskBlockers table. can you tell me how we can achieve this? Thanks for your help. -
django project search bar
I'm trying to implement a search bar in my application I use an API to retrieve product data then I search by code product, But after searching it does not display the product found Views.py def search(request): code=request.GET.get('search') url='http://myAPI/Product/GetProducts' x=requests.post(url) content=x.json() all_products=content['products'] selected_product= next((item for item in all_products if item['code']== code),None) if selected_product!= None: product=selected_product context={'product':product} return render(request,'cart/search.html',context) search.html <h3>Results:</h3> {% for search in product %} {{search.code}} {{search.designation}} {% endfor %} And I noticed at the level of the url of my browser, that there is no value for action (http://127.0.0.1:8000/cart/search/?search=or21&action= ) Here is the form <form method="GET" action="/cart/search/"> <input type="search" name="search" placeholder="Exemple name product"> <button class="btn waves-effect waves-light" type="submit">Search <i class="material-icons right">search</i> </button> </form> -
Django breadcrumb html tag define list in include tag
I want to for loop the names with bclist in breadcrumb.html {% include 'breadcrumb.html' with bcTitle=category.name bcList=["test","tester"] %} breadcrumb.html: {% for i in bcList %} <li class="breadcrumb-item" aria-current="page">{{ i }}</li> {% endfor %} -
I'm doing the migration, but the table is not created in the database
When I do the migration, I get the following message in the terminal: Migrations for 'bookList': bookList/migrations/0001_initial.py: Create model bookList And then I run the migrate command: Operations to perform: Apply all migrations: admin, auth, bookList, contenttypes, sessions When I look at mysql, a table named books does not appear. I've included the contents of my models.py file below: from django.db import models # Create your models here. class BookList(models.Model): site_name = models.TextField() site_id = models.TextField() image = models.TextField() book = models.TextField() author = models.TextField() publisher = models.TextField() price = models.TextField() link = models.TextField() category_name = models.TextField() category_id = models.TextField() class Meta: managed = False db_table = 'books' The contents of my 0001_initial.py file are as follows: # Generated by Django 4.1.1 on 2022-09-26 13:17 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='BookList', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('site_name', models.TextField()), ('site_id', models.TextField()), ('image', models.TextField()), ('book', models.TextField()), ('author', models.TextField()), ('publisher', models.TextField()), ('price', models.TextField()), ('link', models.TextField()), ('category_name', models.TextField()), ('category_id', models.TextField()), ], options={ 'db_table': 'books', 'managed': False, }, ), ] What do I need to do to be able to view my books table in mysql? -
Mongo update array of nested dict in Django
I'm trying to update a data but I'm facing the issue because it's nested form some fields are already present in the database I have fetched them and stored them in the DF variable the existing data structure looks like this { "created_by_id":122, "updated_by_id":123, "farm_area": [ { "area_id": 1, "area_name": "Area 1", "area_acerage": 4, "zone_latest_id": 1, "zone_name": "test zone", "zone_acerage": 2, "area_zone":[ { "zone_acerage":0.3 } ] "device_info":[ { "device_id":232, "device_type":"sensor" } ] }, { "area_id": 2, "area_name": "Area 2", "area_acerage": 4, "area_structure_type": "polyhouse" } ] } and I am trying this existing data by sending new data which { "created_by_id":122, "updated_by_id":123, "farm_area": [ { "area_id": 1, "area_name": "Area 1", "area_acerage": 4, "zone_latest_id": 1, "zone_name": "test zone", "zone_acerage": 2, "area_zone":[ { "zone_acerage":0.3 } ] "device_info":[ { "device_id":232, "device_type":"sensor" } ] }, { "area_id": 2, "area_name": "Area 2", "area_acerage": 4, "area_structure_type": "polyhouse", "area_zone":[ { "zone_acerage":0.3, "zone_name":"Test Zone" } ] "device_info":[ { "device_id":232, "device_type":"sensor" } ] } ] } But every time I run this command collection.update_one({"_id": ObjectId(str(kwargs['pk']))}, {"$set": request.data}, upsert=True) The data is getting replaced by the new one and due to this I'm losing some of my columns from the database But I'm looking for the output in which both of … -
Django - RecursionError: maximum recursion depth exceeded while calling a Python object
I came across an error that was poorly explained when I wanted to customize the magic str function of my "ApiCall" model. My Model : HOME_PAGE = 1 CONSUMPTION_PAGE = 2 PROFILE_PAGE = 3 ROUTES = ( (HOME_PAGE, "Page d'accueil"), (CONSUMPTION_PAGE, "Page de consommation"), (PROFILE_PAGE, "Page de profil"), ) class ApiCall(TimeStampedModel): user = models.ForeignKey(MobileUser, on_delete=models.CASCADE) route = models.PositiveSmallIntegerField('Page consultée', choices=ROUTES) def __str__(self): return f"Appel API du {self.user.phone} le {self.created_at.strftime('%d/%m/%Y %H:%M')} sur la page {self.get_route_display}" Error : RecursionError: maximum recursion depth exceeded while calling a Python object -
Location based recomendation on user location Django
I'm developing an e-commerce and each product has a location. Through the user's location, I want to recommend products from the same city as the user. How can I get the location of the authenticated and anonymous user? for the backend to do what I need -
Calling Ajax from django template fails with error: Field 'id' expected a number but got 'populate_sections'
I have one URL in urls.py file as given below:- urlpatterns = [ ........ path('edit_student/<student_id>', views.edit_student, name="edit_student"), path('populate_sections', views.populate_sections, name="populate_sections"), .......... ] In views.py file edit student function is defined as follows: @login_required def edit_student(request, student_id): form = UpdateStudentForm() context = { "form": form } return render(request, "edit_student.html", context) Now the template edit_student.html has a Ajax call:- $("#id_class_name").change(function(){ var class_name = $(this).val(); $.ajax({ url: 'populate_sections', type: 'GET', data: {class_name:class_name}, dataType: 'json', success: (data) => { $("#id_section_name").empty(); for( var i in data.context){ $("#id_section_name").append("<option value='"+data.context[i].id+"'>"+data.context[i].name+"</option>"); } } }); }); The views.py file function populate_section is declared as follows:- @login_required def populate_sections(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax: if request.method == 'GET': class_name = request.GET.get("class_name") class_object = Classes.objects.get(id=class_name) sections = Sections.objects.filter(classes=class_object) return JsonResponse({'context': list(sections.values())}) return JsonResponse({'status': 'Invalid request'}, status=400) else: return HttpResponseBadRequest('Invalid request') Whenever i change the field which triggers Ajax function call i am getting the value error: ValueError at /edit_student/populate_sections Exception Value: Field 'id' expected a number but got 'populate_sections'. I understand that it is expecting the student id but how to do that. Thanks & Regards Neha Singh -
Submit forms in django without refreshing the page
Okay, first of all, I know that there are a lot of videos and tutorials out there to help with the question I have raised. However, my case is a little different than the usual. So, basically, I am trying to build out a chat app on Django. For this I am planning to save the messages that the user wants to send in the database and then render them on screen. Now, in order to send this data to the server, I wish to use Ajax as it would prevent page reload and thus make for a much smoother UX. However, that raises an issue. The issue is that how do I keep track of the fact that which room/ chat is the message coming from and which user sent it? The obvious solution that comes to mind is the create a hidden field inside if my form and then pass in the room details of it through that hidden field. But won't that be highly insecure as the data could be subject to change, allowing users to send messages from a chat they have access to, to a chat they don't have access to? The username part can … -
Cannot resolve manager type when using django-polymorphic with mypy django-stubs
I'm trying to use django-polymorphic to extend a DRF project that uses typeddjango with mypy-stubs. I recently started to use PolymorphicModels and mypy instantly started to complain and throw errors: error: Could not resolve manager type for "<MyModel>.objects" I included "polymorphic" and "django.contrib.contenttypes" in the INSTALLED_APPS of the project, and can't really make sense of why mypy keeps complaining. I read about inherited managers in the django-polymorphic doc which could be a cause for troubles, but I didn't manage to identify the root cause to find a fix. I opened a ticket here: https://github.com/typeddjango/django-stubs/issues/1158 with more details. If anyone has some info, I'd love to hear..