Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I update my filter function to work generically?
I overrode the SAVE function in one of my models, and now I want to put it in a MIXIN to be used by other models. But I have one part I'm not sure how to make generic. It looks like this: MyModel.objects.filter(code=code).exists() How can I make this generic so it will work with whatever model imports the override? -
Why am i getting "Error running :Checksum"?
Error running 'Checksum': Cannot run program "D:\pythonProject\Estore\venv\Scripts\python.exe" (in directory "D:\Estore\cart\PayTm"): CreateProcess error=2, The system cannot find the file specified. -
how can i collect imgaes from template and save it to database in django
I want users to add blogs with images. So I have to collect images from them through the template and save them to the database. But it's just collect the name of the images. views.py ''' def create_post(request): if request.method == 'POST': title = request.POST['title_id'] catagory = request.POST['catagory_id'] #author = request.POST['author_id'] description = request.POST['description_id'] notes = request.POST['notes_id'] image = request.POST['image_id'] author = request.user if not User.objects.filter(username=author).exists(): messages.warning(request,'There is no account by this username. Please make sure you intput your username associated with your account') return redirect("/blog/create_blog/") blog_post = Applyforposting(title=title, catagory=catagory,content=description,author=author,notes=notes, images=image) blog_post.save() messages.success(request,'Your Submission is successful. Wait for approval') return render(request,'blog/create_post.html')''' models.py ''' class Applyforposting(models.Model): approved = models.BooleanField(null=True, blank=True, default=False) serial_number = models.AutoField(primary_key=True) title = models.CharField(max_length=100) catagory = models.CharField(max_length=15) content = models.TextField() author = models.CharField(max_length=100) apply_date = models.DateTimeField(auto_now=True) notes= models.CharField(max_length=300, null=True, blank=True) images = models.ImageField(upload_to='media/', null=True, blank=True) def __str__(self): return str(self.serial_number) + '->' + self.author + '->' + str(self.apply_date) + 'approved>>>'+str(self.approved)''' -
Pagination with annotated prefetch data
I wanted to speed up the API, so i had added pagination with annotations to get a count of a certain data. The problem with the prefetched annotated data is that it doesn't consider the pagination and if there are 1000 records it'll prefetch the data for annotation of 1000 records even if i want only 10 records in the first page.Is there a way to prefetch data to work with pagination? class ListCourseAssignments(generics.ListAPIView): serializer_class = AssignmentModuleSerializer pagination_class = SetByTenPagination filter_backends = [filters.SearchFilter] search_fields = ['name'] permission_classes = [ permissions.IsAuthenticated, CreateAssignmentPermission] def get_queryset(self): active_statuss = [EnrolmentStatusValues.APPROVED.value, EnrolmentStatusValues.WITHDRAW_PENDING.value] now = timezone.now() assignments = SimpleAssignmentModule.objects.filter( course_share_item__course__id=self.kwargs.get('pk')) unit = self.request.query_params.get('unit') if unit: assignments_in_unit = CourseShareItemModule.objects.filter(module__in=assignments.values_list( "id", flat=True), group__id=unit).select_related('module').values_list("module__id", flat=True) assignments = assignments.filter(id__in=assignments_in_unit) assignments = assignments.annotate( subject_id=Subquery(SimpleAssignmentModule.objects.filter(id=OuterRef('id')).only('id').annotate( subject_name=F('course_share_item__course__id')).values('course_share_item__course__id')[:1]), unit_id=Subquery(CourseShareItemModule.objects.filter(module__id=OuterRef('id'), course_share_item=OuterRef( 'course_share_item')).only('id').annotate(unit_name=F('group__id')).values('group__id')[:1]), subject_name=Subquery(SimpleAssignmentModule.objects.filter(id=OuterRef('id')).only('id').annotate( subject_name=F('course_share_item__name')).values('course_share_item__name')[:1]), unit_name=Subquery(CourseShareItemModule.objects.filter(module__id=OuterRef('id'), course_share_item=OuterRef( 'course_share_item')).only('id').annotate(unit_name=F('group__name')).values('group__name')[:1]), submitted_count= SQCount( AssignmentModuleProgress.objects.filter( Q(module_progress__module_progress_course_progresses__course_progress_userenrolments__expiry_date__isnull=True) | Q( module_progress__module_progress_course_progresses__course_progress_userenrolments__expiry_date__gt=now), module_progress__module_progress_course_progresses__course_progress_userenrolments__deleted=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__user__is_suspended=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__user__tenant__is_suspended=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__status__short_name__in=active_statuss, module_progress__module__id=OuterRef('id'), is_submitted=True, ).values( 'module_progress__module_progress_course_progresses__course_progress_userenrolments').distinct() ), to_grade_count= SQCount( AssignmentModuleProgress.objects.filter( Q(module_progress__module_progress_course_progresses__course_progress_userenrolments__expiry_date__isnull=True) | Q( module_progress__module_progress_course_progresses__course_progress_userenrolments__expiry_date__gt=now), module_progress__module_progress_course_progresses__course_progress_userenrolments__deleted=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__user__is_suspended=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__user__tenant__is_suspended=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__status__short_name__in=active_statuss, module_progress__module__id=OuterRef('id'), is_submitted=True, score=None ).values( 'module_progress__module_progress_course_progresses__course_progress_userenrolments').distinct() ) ) return assignments.order_by(F('due_date').asc(nulls_last=True)) -
Django can't connect MySQL But MySQL server is normally work
I Installed mysqlclient for python 3.8.4 and My django Database Setting is this. DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.mysql', 'NAME' : 'testdb', 'USER' : 'root', 'PASSWORD' : 'tjdnftkfka0501', 'HOST' : '127.0.0.2', 'PORT' :'3306', } } [MYSQL Server is Good][1] [1]: https://i.stack.imgur.com/owfW4.png and I Tested Again that in the vscode. the result it server successfully connect . so ..My question is.. why Django can't connect MySQl??? jun_webserver2) C:\Users\lenovo\TechBlog\Server\Server>py manage.py migrate Traceback (most recent call last): File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection return Database.connect(**conn_params) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\MySQLdb\__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\MySQLdb\connections.py", line 179, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2059, <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\lenovo\Envs\jun_webserver2\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, … -
How can I use slice filter in Django?
How can I filter content like 0-9 then 9-18 then 18-28 and so on.. in Django using a slice filter or any other option?, SO please suggest me. <li class="mega-title"><span>column 01</span> <ul> {% for category in categories %} {% for subcategory in category.children.all|slice:":9" %} <li><a href="{% url 'shop' shop='shop' pk=subcategory.pk %}">{{subcategory.title}}</a></li> {% endfor %}{% endfor %} </ul> </li> <li class="mega-title"><span>column 02</span> <ul> {% for category in categories %} {% for subcategory in category.children.all|slice:"[09:9]" %} <li><a href="{% url 'shop' shop='shop' pk=subcategory.pk %}">{{subcategory.title}}</a></li> {% endfor %}{% endfor %} </ul> </li> -
settings.DATABASES is improperly configured” error django 3.1 while running inspect db
I am trying to create models using inspect db command from postgres db. When i run the command,i am getting raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Below is my settings.py DATABASES = { 'default': { }, 'population_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS' : { 'options': '-c search_path=dbo' }, 'NAME': 'SQLOPS_Population', 'USER': 'devsqlservice', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } } -
How to correctly enforce field combination in another table (Django)?
I have Outcode model that has a one-to-many relationship with SubOutcode model: class Outcode(models.Model): outcode = models.CharField(max_length=4, primary_key=True) class Meta: managed = True db_table = 'outcode' SubOutcode model: class SubOutcode(models.Model): outcode = models.ForeignKey('Outcode', models.DO_NOTHING) sub_outcode = models.CharField(max_length=4, default="") class Meta: managed = True constraints = [ models.UniqueConstraint(fields=['outcode', 'sub_outcode'], name='unq_sub_outcode') ] db_table = 'sub_outcode' I want to be able to create Property records only if the matching combination of fields exists in SubOutcode. How do I setup Property correctly? My current setup doesn't work as it looks if Outcode and SubOutcode exist separately as per below, but I want Property to enforce the combination if that makes sense? Thank you for your help. class Property(models.Model): property_outcode = models.ForeignKey('Outcode', models.DO_NOTHING) property_sub_outcode = models.ForeignKey('SubOutcode', models.DO_NOTHING, to_field='sub_outcode') -
set a form field as None value before saving it
i have a model filed like this : lat = models.DecimalField(max_digits=19, decimal_places=16,null=True,blank=True) in my views i need to set it as None before saving the form and somehow i can't figure out how! it raises this error: IntegrityError at /meeting/create-meeting/ NOT NULL constraint failed: meeting_meeting.lat how can i solve it? meeting=form.save(commit=False) meeting.number_of_member = len(form.cleaned_data['members_email'].split(',')) members = form.cleaned_data['members_email'] if "is_virtual" in request.POST: meeting.lat = None meeting.lng = None else: meeting.lat= round(form.cleaned_data['lat'],14) meeting.lng = round(form.cleaned_data['lng'],14) Many Thanks! -
How to update the status of a particular user type on creation of the User
I have a particular User_type model in my database. I use them to determine the types of the user and also determine what they have access to in my web application. I am able to set the user_type status to is_admin=True when using the create_superuser but it doesn't work when creating the user from the Django Admin Dashboard. models.py class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = datetime.datetime.now(pytz.utc) email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user = self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) user_type.objects.update_or_create( user=user, defaults={ 'is_admin': True } ) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) # CUSTOM USER FIELDS picture = models.ImageField(upload_to='images/users', blank=True, null=True, default='images/users/profile-pixs.jpg') created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) class user_type(models.Model): is_admin = models.BooleanField(default=False) is_manager = … -
Django 3 delete field items via Admin panel
I have a Django app, in which i have a model of Candidate, and the candidate has a field Video - goes as file. I do have the option to change the field, for example upload a new video, and it will replace it, but how can i delete a video of a candidate, and leave it empty? currntly i have something like this in the admin panel: Currently: uploads/VIDEOS/mediarecorder_11.mp4 Change: [Coose File] No file chosen how can i just delete the video, and leave it empty? -
Pagination in django keeps showing all the contents
Good day, I implemented pagination in my Django project, the pagination works ok, but all the contents keep showing. I used Django documentation I'd show some screen shots when the pages number is clicked, it reloads but nothing seemed to change, and it did not reduce the number of contents to the specified number views.py from django.shortcuts import render from django.core.paginator import Paginator from .models import Order def order_list(request): orders = Order.objects.all() current_user = request.user success = Order.objects.filter(user=current_user.id).filter(paid=True) fail = Order.objects.filter(user=current_user.id).filter(paid=False) success_paginator = Paginator(success, 10) success_page = request.GET.get('page') posts = success_paginator.get_page(success_page) fail_paginator = Paginator(fail, 10) fail_page = request.GET.get('page') failpost = fail_paginator.get_page(fail_page) return render(request, 'orders/order/order_list.html', { 'success': success, 'fail': fail, 'current_user': current_user, 'orders':orders, 'posts': posts, 'failpost': failpost, }) list.html (for posts) <nav aria-label="Page navigation example"> <ul class="pagination"> {% if posts.paginator.num_pages > 1 %} {% if posts.has_previous %} <li class="page-item"><a class="page-link" href="?page={{posts.previous_page_number}}">Previous</a> </li> {% endif %} {% endif %} <li class="page-item"><a class="page-link" href="#">{{ posts.number }}</a> </li> {% if posts.has_next %} <li class="page-item"><a class="page-link" href="?page={{ posts.next_page_number }}">Next</a> </li> <li class="page-item"><a class="page-link" href="?page={{ posts.paginator.num_pages }}">Last</a> </li> {% endif %} </ul> </nav> list.htm (for failpost) <nav aria-label="Page navigation example"> <ul class="pagination"> {% if failpost.paginator.num_pages > 1 %} {% if failpost.has_previous %} <li class="page-item"><a class="page-link" href="?page={{failpost.previous_page_number}}">Previous</a> … -
DRF How to change the field key names in JSON response
I want to display all objects of a particular model, and it's related objects ( object-wise ). Is there a way to change/customize the JSON output? (In terms of the key names, values, or the nesting?) views.py @api_view(['GET']) def api(request): q = Question.objects.all() s = QuestionSerializer(q, many=True) print(ChoiceSerializer()) return Response(s.data) serializers.py class QuestionSerializer(serializers.ModelSerializer): choices = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Question fields = '__all__' models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(auto_now_add=True, editable=False, name='pub_date') def __str__(self): return self.question_text def __unicode__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices') choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text def __unicode__(self): return f"{self.choice_text}" def related_question(self): q = self.question.question_text return q Output HTTP 200 OK Allow: OPTIONS, GET Content-Type: application/json Vary: Accept [ { "id": 1, "choices": [ 1, 2, 3 ], "question_text": "Question 1", "pub_date": "2020-12-19T23:07:25.071171+05:30" }, { "id": 2, "choices": [ 4, 5 ], "question_text": "Question 2", "pub_date": "2020-12-21T13:58:37.595672+05:30" } ] In the output, choices shows the pk of the objects. How can I change that to show, say, the choice_text or a custom string? Also, can the way the objects are nested be … -
Testing if a endpoint called a function using pytest
I want to create a test that returns if a function was called by an endpoint. This is my scenario: I have a function in file tasks.py: def function_called_by_endpoint(): pass And I have a endpoint in file views.py: class ExampleViewSet(viewsets.ModelViewSet): @action(detail=True, methods=["post"]) def should_call_the_function(self, request, pk=None): pass I would like to know if function_called_by_endpoint was called by should_call_the_function. I'm trying to do it that way: def test_call_func(self, db, client): resp = client.post( "/api/v1/example/1/should_call_the_function/", data={"something": "is ok"}, format="json" ) from my_app import tasks tasks.should_call_the_function() But I get this error: E AttributeError: 'should_call_the_function' object has no attribute 'assert_called' Does anyone have any idea what's missing? -
I am getting the following error after deploying the django project using NGINX. Using Django channels ASGI
My asgi files looks like this. After running daphne -b 0.0.0.0 -p 8001 ludomission.asgi:application this command I am getting this error. I am stuck with this error since 3 days. Please help """ ASGI config for ludomission project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os #from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from django.urls import path from game import consumers from django.urls import re_path from django.core.asgi import get_asgi_application from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ludomission.settings') django.setup() application = get_default_application() django_asgi_app = get_asgi_application() ws_pattern= [ ] application= ProtocolTypeRouter( { # "http": django_asgi_app, 'websocket':(URLRouter(ws_pattern)) } ) -
Adding values in choices fields in form from django model
I have model called as settings, storing 'product_type' in key and {'product1','product2'} in its value class Settings(models.Model): key = models.CharField(max_length=100) value = models.CharField(max_length=1000) And I have Django form field called as product_type. From Settings models, I'm fetching the tuple value value and appending as choices in product_type form field class InspectionForm(forms.Form): PRODUCT_TYPES = [(product, product.upper()) for product in eval(Settings.objects.get(key='product_type').value)] product_type = forms.ChoiceField(choices=PRODUCT_TYPES) The problem I'm facing is that whenever I add new value in tuple ( which gets store in settings models ), the form field product_type is showing old values only, during rendering the template from view ( which calls the InspectionForm() class ) But when I do runserver, then its shows the lastest values. -
possible Form Field Errors for ChangePasswordForm Django
I'm trying to customize the form field errors for a changepasswordview in Django, however, to do that I believe I need to know the attribute names of the field errors so that I can do something like this: class UserUpdatePassword(PasswordChangeForm): class Meta: model = User fields = ('password') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['old_password'].label = "Password antiguo" print(self.fields['new_password1'].error_messages) self.fields['new_password1'].label = "Nuevo Password" self.fields['new_password1'].help_text = "Mínimo 8 caracteres, números y letras" self.fields['new_password2'].label = "Confirmar nuevo Password" self.fields['new_password1'].error_messages = {'password_mismatch': "Los Passwords ingresados no son iguales",} I know there are errors for password and password confirmation mismatch, when the password is not long enough, only letters or numbers, etc. Where can I find the attribute names? (e.g. 'password_mismatch') -
Open-Source Frameworks based on Django for E-Commerce?
Can someone help me with some good open-source frameworks / platforms based on Django to kickstart my E-Commerce Project? I have already tried the following: Saleor Django-Oscar Django-salesman -
Django: NOT NULL constraint failed: new__create_post.author_id
Error: NOT NULL constraint failed: new__create_post.author_id models: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) -
Import to database (mysql, django) very slow
Good day! I have some problems. I need import some data from txt-file to databes. Ok i wrote this function: def handle_import_airlines(f): reg = r"([A-Z]{3})\t([A-Z,\. ()]+)\t([A-Z ]+)\t([A-Z ]+)\n" with open('temp.txt', 'wb+') as n: for ch in f.chunks(): n.write(ch) with open('temp.txt', 'r') as r: for line in r: m = re.match(reg, line, re.MULTILINE) if m: a = Airlines(code=m.group(1), full_name=m.group(2), name=m.group(3), country=m.group(4)) a.save() os.remove('temp.txt') But it is very slowly. I think it is because i make request to database for write each item. How can i mak one big request for import all items in one request? -
How to get form field through html in Django
I unable to get gender data, because i am directly importing the other fields of django form like {{ form.name }}, What I tried in html to access the field is mentioned below: Want to use this .html <input type="radio" id='radio_button_value_male' name="gender" value="Male"> <label for="radio_button_value_male">Male</label><br> <input type="radio" id='radio_button_value_female'name="gender" value="Female"> <label for="radio_button_value_female">Female</label><br> Instead of this .html, <!-- <div class="">{{ form.gender }}</div> --> models.py, gender = models.CharField(choices=CHOICES,max_length=200,default=None) Please guide me... -
K8s - Celery liveness probe
can smb tell me how to setup a good liveness/readiness probe for celery worker/beat under K8s? Im Using celery in version 5.0.4 (Latest at the moment). This question has already been explained here: https://github.com/celery/celery/issues/4079 Problem now is that Celery has dropped the support for the Module celery.task, also see: Django and Celery - ModuleNotFoundError: No module named 'celery.task' So using something like this wont work anymore: readinessProbe: exec: command: [ "/usr/local/bin/python", "-c", "\"import os;from celery.task.control import inspect;from <APP> import celery_app;exit(0 if os.environ['HOSTNAME'] in ','.join(inspect(app=celery_app).stats().keys()) else 1)\"" ] Can smb help or maybe can share a snipped of his K8s manifest? Thanks in advance -
try to make my website see if there a used email
I am new to Django and i am trying to make my first registration app!! I used the UserCreationForm But when i run The code and try to register if i put the same email form many user it didn't give me any error My forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] my views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages # Create your views here. from .forms import RegisterForm def registerUser(request): form = RegisterForm() if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = RegisterForm() return render(request, 'register.html', {'form':form}) def loginUser(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Username or Password is Incorrect') else: messages.error(request, 'Fill out all the fields') return render(request, 'login.html', {}) def home(request): return render(request, 'home.html', {}) def logoutUser(request): logout(request) return redirect('home') def Profile(request): return render(request, 'profile.html', {}) so please any help or tips -
why does "Unknown command: 'startaap'. Did you mean startapp"?
the following happens when i try to make an aap (also i am C:\Users\lenovo\mysite>py manage.py startaap polls Unknown command: 'startaap'. Did you mean startapp? Type 'manage.py help' for usage. -
How to access Queryset returned to template by AJAX response - Django
I want to return a queryset to a template using ajax. this is my ajax function in a seperate js file: $(document).ready(function(){ $("#data_to_plot_button").click(function(){ var serialized_data = $("#data_to_plot_form").serialize(); $.ajax({ url: $("data_to_plot_form").data('url'), data: serialized_data, type: 'post', success: function(response){ $("#graph").append('<p>data returned successfuly</p>'); //this line is printed correctly. $.each(response, function(i, val) { $('graph').empty().append( $('<li>').addClass('list-group-item list-group-item-success').text(val) ) }); // this block adds nothing to the #graph div } }) }); }); and my views.py: def my_products(request): queryset_list_intro_products = Intro_products.objects.all().order_by('title') products = 0 if request.method == 'POST': products_checkbox = request.POST.get('products') if products_checkbox: products = serializers.serialize('json', list(queryset_list_intro_products)) context = { 'products': products, } return JsonResponse(context, status=200) return render(request, 'users/basket/my_products.html') based on an answer to this question, I try to access the returned products which is in response. but the js code adds nothing to the #graph div. in XHR section of network tab of inspects in chrome, the ajax call's status is 200 and in the preview section I can see the products as following: products: "[{"model": "products.intro_products", "pk": 5, "fields": {"products_intro": false, "ip_sensor_intro": false, "control_valve_intro": false, "water_quality_sensor_intro": false, "accessories_intro": true, "cover_intro": "photos/products/intro_cover/solutions.png", "title": "Accessories", "subtitle": "", "description": "description", "detailed_description": "", "video_link": "", "is_published": true, "image_left": "", "title_left": "", "description_left": "", "image_right": "", "title_right": "", "description_right": ""}}, …