Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect to a new template using already rendered data in django
I do have a model called Pollers which consists of individual questions asked by users. One template renders an overview of the latest questions asked. Now I would like to redirect the user to a new template for a specific question upon click of its container. Now my understanding is that I would define a url that contains a <slug:slug> field to catch some data from the first template to query the correct item from the database to render the new template. But how do I grab the data (in my case it would probably be the UUID?) pass the data to the url and use it in a new view to query the database for this certain question? Model class Questions(models.Model): # Assign unique ID to each poller poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # Assign timestamp of creation created_at = models.DateTimeField(auto_now_add=True) # Assign the user who created the poller by her ID via user session created_by = models.CharField(max_length=100) # Poller Text poller_text = models.CharField(max_length=250) # Choices given by user poller_choice_one = models.CharField(max_length=30) poller_choice_two = models.CharField(max_length=30) [...] View def pollboard(request): # Query Pollers questions_queryset = Questions.objects.all() # Convert to list qs_list = list(questions_queryset) # Shuffle the list shuffle(qs_list) # Create … -
What is an efficient way of inserting hundreds of records into an SQLite table using Django?
I have a CSV file with hundreds of data, I want to insert everything into my SQLite DB in my Django app. Inputting each value one by one will be a complete waste of time. What is a more efficient way to approach this? -
Best practice for sending POST request from client side to Django models?
Relatively new to Django so apologies if I'm not getting all the wording here right. I'm sending data from my client side (React) to my models through a POST request. Django can handle this either through its class-based views, something like this: views.py class ListCreateView(ListCreateAPIView): queryset = Users.objects.all() serializer_class = UsersSerializer serializers.py class UsersSerializer(serializers.ModelSerializer): class Meta: model = Users fields = "__all__" urls.py urlpatterns = [ path('', ListCreateView.as_view()), ] or through something like this: views.py def create_user(request): if request.method == 'POST': response=json.loads(request.body) user_db = Users() user_db.user = response['user'] user_db.save() return(HttpResponse(200)) What's better? I'm using something similar to both of these, and they both work. What should I be thinking about? Thanks. -
PostgreSQL error "unable to connect to server
I start learning Django, and I had a problem using the Postegres database, The server worked fine with sqlite3, but as soon as I declared Postgres in the project, the server stopped working DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', # on utilise l'adaptateur postgresql 'NAME': 'sarah disquaires', # le nom de notre base de donnees creee precedemment 'USER': 'sarra', # attention : remplacez par votre nom d'utilisateur 'PASSWORD': '', 'HOST': '', 'PORT': '5432', } } I get this error: python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\sarra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", … -
Django adding words to image url
I want to load an image on my template using: <img src="{{ item.pic }}"> It works fine sometimes but once I start doing it from a view it adds the path of that view to my image src automatically causing the image to fail to load. I want it to be src="images/item.jpg" for example, but because of different views it may end up as "view1/images/item.jpg" or "anotherview/images/item.jpg" causing Django to be unable to find the image. Is there a way to code it so that view names won't be added to the src? -
Django filter by looping through each day of a date range
I have a model called Orders which is for an e-commerce web-app and I'd like to know how many orders was made from each day in the past year. so I filtered the Orders as follows: product_orders = Order.objects.filter( ordered=True, variant__product=self, date__range=[(timezone.now() - timedelta(weeks=52)), timezone.now()]) I'd like to loop through each day from this time range and get the number of orders from each day, the result should look something like this: [ { date: "2021-06-21", quantity: 6 }, { date: "2021-06-22", quantity: 0 } ] where the quantity is Order.objects.filter(...).count() -
bulk create for models with foreign key
I have these two models: class Item(models.Model): item_id = models.CharField(max_length=10, primary_key=True) item_name = models.CharField(max_length=100) description = models.CharField(max_length=500) slug = models.CharField(max_length=200) price = models.FloatField() def __str__(self): return self.item_name class Image(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) image_url = models.CharField(max_length=200) I have a lot of items, and each Item has some images assigned to it. To add items in the database, I do it through a bulk create: it = (Item( item_id = item['id'], item_name= item['title'], description = item['description'], slug = item['slug'], price = item['price']['amount'] ) for item in items ) while True: batch = list(islice(it, batch_size)) if not batch: break Item.objects.bulk_create(batch, batch_size) This works perfectly fine, ok. But I want to do the same with the images, since I have too many images to do it individually. For now I do it like this: for item in items: for image in item['images']: Item.objects.get(item_id = item['id']).image_set.create(image_url = image['urls']['big']) But this is too slow in uplaoding all the Images (it may take 30 minutes), so I want to upload in bulk like I do it with Item, but since Image model has Item as a foreign key, I cannot do it the same way. How can I upload Images in a more efficient manner? I … -
Where to store media file of Django on production?
So I am learning Django. And I have made some websites with it. Now I am hosting those to Heroku. I am using free Dyno on Heroku. Also, I am using supabase.io database instead of Heroku's because supabase gives more space for the database on the free tier. Now the problem I am facing is with the media files. I can not access them on Heroku since I don't have any place to store them. I have seen some addons on Heroku for the file storage but to use those I need to provide my credit card information, which I do not have. But I have seen an object storage option on supabase.io. It gives 1 GB free storage which is more than enough for me now. But I don't know how can I use it with my Django application. That is why I am looking for help. Also if there are any free alternatives to store my media file without credit card information, please feel free to guide me. Since I do not own any card. -
How to fix "Failed to restart gunicorn.service: Unit gunicorn.socket not found." error?
I'm trying to deploy a django application to a DigitalOcean droplet. I created a systemd service to start gunicorn on boot. Here is my config file: (/etc/systemd/system/gunicorn.service) [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data Environment="DJANGO_SETTINGS_MODULE=core.settings.production" WorkingDirectory=/home/myproject-api/src ExecStart=/home/myproject-api/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock core.wsgi:application [Install] WantedBy=multi-user.target When I run "ExecStart" line on directly on terminal, it works. But I cant start the gunicorn service. I get this error when I try to start gunicorn: Failed to start gunicorn.service: Unit gunicorn.socket not found. I checked the gunicorn executable, it exists: test -f /home/myproject-api/env/bin/gunicorn && echo "Gunicorn exists." I'm able to run server with gunicorn --bind 0.0.0.0:8000 core.wsgicommand. When I run like this, i can access the server using the server's IP address. Normally, the socket file should been created when I start the server. Also I tried to create the socket file with "touch /run/gunicorn.sock" but it didn't work. I double-checked file and directory names. No mistake. How can I solve this problem? -
how to login a user with email or username in django custom user model
This is my current code can anyone please add the required code to allow a user to login with email or username backends.py from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend, UserModel class CaseInsensitiveModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: case_insensitive_username_field = '{}__iexact'.format(UserModel.USERNAME_FIELD) user = UserModel._default_manager.get(**{case_insensitive_username_field: username}) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user -
Cannot switch EMAIL_BACKEND to smtp.EmailBackend
I have a weird problem although my settings.py file specifically says EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" my Django app still uses django.core.mail.backends.console.EmailBackend, how can that be? No matter if I have debug True or False # Email settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" DEFAULT_FROM_EMAIL = "yes@gmail.com" SERVER_EMAIL = "yes@gmail.com" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "yes@gmail.com" EMAIL_HOST_PASSWORD = "yes" EMAIL_USE_TLS = True EMAIL_USE_SSL = False -
ModuleNotFoundError: No module named 'fontawesomefree'
I am getting this error when I try to import fonrawesomefree icons to my django project. I used official django docs requirements.txt file have following # some other requirements fontawesomefree==5.15.4 settings.py have following: INSTALLED_APPS = [ # some other installed apps 'fontawesomefree', ] base.html file have following <head> #some other link & script files <link href="{% static 'fontawesomefree/css/all.min.css' %}" rel="stylesheet" type="text/css"> </head> Project structure [projectname]/ ├── [projectname]/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py | |── [App1] |── [static]/ | ├── [css] | ├── [Javascript] | └── [Images] | |── [templates] |── manage.py └── requirements.txt When I try to run server I get following error: ModuleNotFoundError: No module named 'fontawesomefree' Any help is appreciated -
how to use an authentication api in frontend part django
I implemented a login and register API that I want to use in frontend part of the project. I could use some clarifications about the mechanism of using an API for login and register request so I can understand what is wrong. here is my code : user_registration.html {% extends 'core/base.html' %} {% block head_title %}Banking System{% endblock %} {% block content %} <h1 class="font-mono font-bold text-3xl text-center pb-5 pt-10">Register</h1> <hr /> <div class="w-full mt-10"> <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"> {% csrf_token %} <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> First Name </label> <input name="firstname" type="text" placeholder="Your first Name" class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 'rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"> </div> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> Last Name </label> <input name="lastname" type="text" placeholder="Your last Name" class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 'rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"> </div> </div> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> Email </label> <input name="email" type="text" placeholder="user@example.com" class="appearance-none block w-full bg-gray-200 text-gray-700 border … -
Pass dynamic choice list to form from Views in class based views
I just want to pass a list which will look like this from views to form , FYI i'm using MultipleChoiceField [('ad7d4d7c5fbd4678bafd9f2b93fdd4b5', 'Chandrayaan'), ('b55d7c02c29d4501b8d3f63053fef470', 'MOM'), ('b90a66ea9eb24d019102fadde900fdda', 'Galactica')] i have another issue related to this question as well which i have posted already here -
user sending an input form to another user in the platform - django
in my app I want that if userA selected a userB he can send him an input form that contain fields. those users have a class profile. I don't know what should I do in my views. do someone have any idea or already worked on this before. I really need your help in this -
Postgres: sanitize string before searchin for it
I have a website which uses Postgres as a database. I now want users to be able to search the database for strings and am using pg_trgm for that. I can imagine that it is very dangerous to just search the database for the plain user input, as it could be malicious. So my question is: what security measures do I have to take in order to search for a string in Postgres, which could potentially contain malicious code? Are there for example certain characters which should be escaped? Thanks in advance, Kingrimursel -
Decoupling auth/auth from Django applications
I author a couple of Django applications that I deploy behind an auth/auth system. Currently, my apps' class-based views are hard-coded with my particular auth requirements, by using DRF's authentication_classes and permission_classes and Django's permission_required decorator (and friends). The problem I have is that I can't really figure out any way to configure these on a project level. For example, while testing, I don't want to have to deal with my auth system--creating test users, logging in, etc. I just want to test my app. But even though I have a separate Django environment for production and development, there's no elegant way for me to, in my dev environment's settings.py, say (for example) MYAPP_AUTH_MODEL=None and in my prod environment, say something like MYAPP_AUTH_MODEL=permission_required('myperm_create'). As another example, how could I give consumers of my app complete control over how they secure their deployment, including allowing them to choose not to secure it at all? How does one write a Django app that can be secured with auth/auth, without writing anything into the app that places restrictions on how it's secured in any given deployment? -
Migrating Django from 2.2 to 3.2
I am migrating my application in Django 2.2 to version 3.2 and when passing the tests it gives me the following error that seems native to the framework. The application works perfectly, but the tests stopped working. python manage.py test --keepdb Using existing test database for alias 'default'... Traceback (most recent call last): File "/home/proyecto/src/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/home/proyecto/env/lib/python3.6/site-packages/django/test/runner.py", line 725, in run_tests old_config = self.setup_databases(aliases=databases) File "/home/proyecto/env/lib/python3.6/site-packages/django/test/runner.py", line 645, in setup_databases debug_sql=self.debug_sql, parallel=self.parallel, **kwargs File "/home/proyecto/env/lib/python3.6/site-packages/django/test/utils.py", line 183, in setup_databases serialize=connection.settings_dict['TEST'].get('SERIALIZE', True), File "/home/proyecto/env/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 79, in create_test_db run_syncdb=True, File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 246, in handle fake_initial=fake_initial, File "/home/proyecto/env/lib/python3.6/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 "/home/proyecto/env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, … -
How can I insert a checkbox in my django Sign Up form?
This is my forms.py file class SignUpForm(UserCreationForm): email = forms.EmailField(widget= forms.EmailInput(attrs={'class':'form-control'})) first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class':'form-control'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' I want to add a boolean checkbox on my signup form, but not quite getting there. Any help would be appreciated. -
django.core.exceptions.FieldError: Unsupported lookup 'exact' when run in apache2
I know, similar problems have been posted and discussed here and in other forums. Nonetheless, I was not able to get around the issue. The follwing code snipped from File "/data/django/jukeoroni/player/jukeoroni/juke_radio.py" works just fine in python manage.py runserver @property def last_played(self): try: return Channel.objects.get(last_played=True) except Channel.DoesNotExist: LOG.info('no last_played channel, returning None.') return None [09-12-2021 15:03:49] [INFO] [Dummy-10|2989487200] [player.jukeoroni.jukeoroni]: Button press detected on pin: 16 button: 0X00 (2), label: Play [09-12-2021 15:03:49] [INFO] [Dummy-10|2989487200] [player.jukeoroni.jukeoroni]: Media inserted: deathmetal (type <class 'player.models.Channel'>) However, the same code results in the titles error when run within apache2: [09-12-2021 15:00:32] [INFO] [Dummy-10|2843735072] [player.jukeoroni.jukeoroni]: Button press detected on pin: 16 button: 0X00 (2), label: Play Traceback (most recent call last): File "/data/django/jukeoroni/player/jukeoroni/jukeoroni.py", line 813, in _handle_button if self.radio.last_played is None: File "/data/django/jukeoroni/player/jukeoroni/juke_radio.py", line 126, in last_played return Channel.objects.get(last_played=True) File "/data/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 424, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 941, in filter return self._filter_or_exclude(False, args, kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/data/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1393, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/data/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1415, in _add_q … -
order_by("-date") not working correctly with paginator
SO i have more than 500 records and want organize them by date, it was pretty simple and it worked but when i used paginator to add pagination it all got messed up, there is no sense in this ordering right now can anyone help me understand what's happening and what i need to do in order to get my order_by() working. Here is a my view: if request.method == "GET": if request.session["store_year"] == "" and request.session["store_month"] == "": request.session["store_year"] = "" request.session["store_month"] = "" timelineData = Timeline_english.objects.all().order_by("-date") timeline_list = [] timeline_date_list = set() for val in timelineData: obj = { "id": val.id, "image": val.image, "text": val.text, "url": val.url.replace(" ", "-").lower(), "date": val.date } timeline_list.append(obj) timeline_date_list.add(str(val.date)[:4]) page = request.GET.get('page', 1) print("page", page) paginator = Paginator(timeline_list, 9) try: timeline_list = paginator.page(page) except PageNotAnInteger: timeline_list = paginator.page(1) except EmptyPage: timeline_list = paginator.page(paginator.num_pages) print(timeline_list) try: page_count = math.ceil(timelineData.count()/9) page_limit = 3 page_count_arr = [] if page_count > page_limit: new_pagecount = int(page)+page_limit else: new_pagecount = page_count last_page_number = { "mode": "yes" if page_count == int(page) else "no", "index": page_count } if page_count > int(page): for i in range(int(page), new_pagecount+1): page_count_arr.append({ "mode": "yes" if i == int(page) else "no", "index": i }) data.update({"quotes_list_pages": page_count_arr}) else: … -
Django Leaflet Ajax
How to list and map located data: At one point In an interval In a rectangle In a circle of rayoun R thank you so much -
Translating django tables2 template column header
Hi i'm working with django-tables2 and I have a table where I need to translate the headers of each column. class ModelTable(tables.Table): name = tables.columns.Column() edit = tables.TemplateColumn('<a href='{% url "edit_my_model_instance" record.id %}'>Edit</a>', verbose_name=u'Edit', ) delete = tables.TemplateColumn('<a href='{% url "del_my_model_instance" record.id %}'>Delete</a>', verbose_name=u'Delete', ) class Meta: model = models.Model The above code without translations work fine, but when I add the gettext for translate like this : delete = tables.TemplateColumn('<a href='{% url "del_my_model_instance" record.id %}'>Delete</a>', verbose_name=_(u'Delete'), ) Where I added gettext as _ : verbose_name=_(u'Delete') I receive the following error TypeError: 'TemplateColumn' object is not callable The thing is if I use tables.Column it works fine with translation, so the problem is only when I user TemplateColumn. If you can guide me through this I'd appreciate it, thanks. -
Django Rest Framework Swagger API expand_all fields not working
I have a REST API described with Swagger. When I try to expand some fields, I get a valid JSON response (Response 200). However, when I try to expand all fields, I get no response (Response 500) I compared the logs when I expanded some fields vs when I expanded all fields. Below are some excerpts of logs from generics.py In generics.py,in function paginate_queryset, self.paginator= <rest_framework.pagination.PageNumberPagination object at 0x7fa32f2d01d0> In generics.py,in function paginate_queryset, self.paginator is NOT None In generics.py,in function paginator, self.pagination_class = <class 'rest_framework.pagination.PageNumberPagination'> . self._paginator= <rest_framework.pagination.PageNumberPagination object at 0x7fa32f2d01d0> In generics.py,in function paginator, self._paginator.django_paginator_class= <class 'django.core.paginator.Paginator'> . page_size = 10 . page_query_param = page . page_size_query_param= None . max_page_size= None . template = rest_framework/pagination/numbers.html, *************BELOW LINES ARE DISPLAYED ONLY WHEN I EXPAND SOME FIELDS & ARE NOT DISPLAYED WHEN I EXPAND ALL***************** In generics.py,in function paginate_queryset, self.request= <rest_framework.request.Request object at 0x7fa32f2d0b70> .return = [<Exon: Exon object (1)>, <Exon: Exon object (2)>, <Exon: Exon object (3)>, <Exon: Exon object (4)>, <Exon: Exon object (5)>, <Exon: Exon object (7)>, <Exon: Exon object (8)>, <Exon: Exon object (9)>, <Exon: Exon object (10)>, <Exon: Exon object (11)>], What could be the issue that prevents the paginate_queryset from being called, when I expand … -
getting null value when posting data to django using ajax
Am trynig to post data from an input to my django view to do some processing on this data ,which is a text, and am using AJAX but I get the input NULL in my view $(document).on('submit', '#post-form',function(e){ $.ajax({ type:'POST', url:'{% url "index" %}', data:{ inp:$('#qst').val() csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, dataType: 'json', success:function(json){ document.getElementById("post-form").reset(); $(".messages_area").append('<div class="messages__item messages__item--visitor">'+json.inp+'</div>') $(".messages_area").append('<div class="messages__item messages__item--operator">'+json.answer+'</div>') }, error : function(xhr,errmsg,err) { console.log(xhr.status + ":" + xhr.responseText); // provide a bit more info about the error to the console } }); }); And this is my view def chat(request): context={} inp="" response_data = {} if request.method == 'POST' and request.is_ajax: inp = request.POST.get('inp') answer=respond(inp) response_data['answer'] = answer response_data['inp'] = inp return JsonResponse(response_data) return render(request, 'templates/rhchatbot/index.html',context ) But when I print the inp value I get : {'inp':null}