Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.11 live app upgrade
Python Django I want to build a web app that python django 1.11 LTS. If just build web app with Django 1.11 LTS, this version supports only April 2020. Next Django LTS is 2.2 it release on April 2019. My web app is live so, how can upgrade new version of Django. Without shut down my web app. -
TypeError at /polls/ context must be a dict rather than RequestContext.
This is view.py tab of my poll app in django. I can't debug the error 'Type Error: context must be a dict rather than RequestContext.' It is taken from video 6 of youtube collection of 'my first django app' of channel 'The Codex'. Please help from django.shortcuts import render from django.http import HttpResponse from django.template import loader, RequestContext from .models import Question def index(request): latest_questions = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = RequestContext(request, { 'latest_questions': latest_questions }) return HttpResponse(template.render(context)) def detail(request, question_id): return HttpResponse("This is the detail view of the question: %s" %question_id) def results(request, question_id): return HttpResponse("These are the results of the question: %s" %question_id) def vote(request, question_id): return HttpResponse("Vote on question: %s" %question_id) -
How do I add parameter in django 2.0 using path
I've installed django version 2.0 and default for urls is path I know that if in django 1.x can be urls and follow with regular expression, how do I use path for parameters instead of urls, and so I dont want to use urls because django by default add path not urls if its can be or use urls still I want to know how to use a path with parameters in django 2.0 here's my code from django.urls import include, path from . import views urlpatterns = [ path('', views.articles_list), path('add', views.articles_add), path('edit', views.articles_edit) ] -
App Registry Not Ready while upgrading to Django 1.11 from 1.8
I'm facing this issue while upgrading to Django version 1.11. Here's the list of errors what I'm getting for Djagno auth user model. ``` File "/customer/models/customer.py" from django.contrib.auth.models import User File "/environment/lib/python2.7/site-packages/django/contrib/auth/models.py" from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/environment/lib/python2.7/site-packages/django/contrib/auth/base_user.py" class AbstractBaseUser(models.Model): File "/environment/lib/python2.7/site-packages/django/db/models/base.py" app_config = apps.get_containing_app_config(module) File "/environment/lib/python2.7/site-packages/django/apps/registry.py" self.check_apps_ready() File "/environment/lib/python2.7/site-packages/django/apps/registry.py", in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") ``` I've tried get_user_model() in the place of "import User" but got the same "AppRegistryNotReady('Apps aren't loaded yet.')" error. Thanks in advance for your suggestions. -
Django Channels: can't separate consumers with routing
So maybe I'm getting everything wrong, but I'm a little confused with routing. Let's say I want to separate the consumers dealing with messages coming from my domain root: http://example.com/ and my /import/ route: http://example.com/import/ I have my routing as so: fb_routing = [ route("websocket.connect", consumers.connect_face), route("websocket.receive", consumers.get_face), route("websocket.disconnect", consumers.disconnect_face) ] channel_routing = [ include(fb_routing, path=r'^/import/'), route('websocket.connect', consumers.ws_connect), route('websocket.disconnect', consumers.ws_disconnect), route('websocket.receive', consumers.ws_receive), ] I'm also separating the Javascript files for initiating the Reconnecting Websockets, in each file I set the path accordingly: root.js: var ws_scheme = window.location.protocol == "http:" ? "ws" : "wss"; *var ws_path = ws_scheme + '://' + window.location.host + "/";* console.log("Connecting to " + ws_path); var mysocket = new ReconnectingWebSocket(ws_path); and import.js: var ws_scheme = window.location.protocol == "http:" ? "ws" : "wss"; *var ws_path = ws_scheme + '://' + window.location.host + "/import/";* console.log("Connecting to " + ws_path); var mysocket = new ReconnectingWebSocket(ws_path); How can I prevent my receive consumer for import (see: consumers.get_face in routing) from getting or even listening to messages on the root (whose receive consumer is consumers.ws_receive), and vice versa? Right when I open the console, both messages are sent to both consumers. I guess I can parse the path from the messages, but … -
Calling a Function from another API to your API using Django
So I was to make an API that can make a fuction call already specifid in the previous API using Django Framework, all I need to do is get the data from the previous API so I don't think I will be needing models. Is there any way to connect my new made API to the API that is already there? -
How to format datetime in a serialized model Django
I have the following model class MyModel(models.Model): firstDate = models.DateTimeField(auto_now_add=True) another = models.CharField(max_length=30) I serialize it to JSON with query = MyModel.objects.all() data = serializers.serialize('json', query, use_natural_foreign_keys=True) The DateTimeField returns the following format: 2017-12-19T22:50:04.328Z The desired format is: 2017-12-19 22:50:04 Is there a simple way to achieve this without using the queryset.values() and queryset.extra() methods? -
Order by time of a Datetime field in django
I wanted to order a query set on the basis of a time of a datetime field. I have used the following (here Tasks is my model and datetime is the field) Tasks.objects.all().order_by('datetime.time') this doesn't work and also Tasks.objects.all().order_by('datetime__time') doesn't work as it is part of the same model. I tried using .annotate() but I don't know how exactly to do it. How should I go about doing this? -
How to extract data from a HTML Input field in django. Data needs to be extracted from a form which exists in the html file
Let us say the we have a simple HTML form in a file index.html myapp/templates/index.html In the form, the data must be sent using post method only. <form action="{% url 'myapp:update' %}" method="post"> <input type="text" name="first_field"/><br> <input type="text" name="second_field"/><br><br> <button type="submit" value="Submit"/> </form> The purpose of the form is to update the database. myapp/models.py from django.db import models class Person(models.Model): first_name=models.CharField(max_length=30) last_name=models.CharField(max_length=30) myapp/urls.py from django.urls import path,include from . import views app_name='myapp' urlpatterns = [ path('index/', views.index, name='index'), path('update/', views.update, name='update'), ] myapp/views.py In views.py file, any element in the form can be fetched using request.POST['nameOfTheFieldInTheForm'] from django.shortcuts import render # Create your views here. def index(request): return render(request, 'myapp/index.html', {}) def update(request): # print('Inside update function') if request.method=='POST': # print("Inside post block") first_field_data=request.POST['first_field'] second_field_data=request.POST['second_field'] x=Person(first_field=first_field_data, second_field=second_field_data) x.save() return index(request) -
Django + Pyinstaller Template doesn't exist
I'm working on pyinstaller to make an executable file from Django project. When i run script its generating Executable file, But when I run EXE from cmd its showing errors as below: I have checked settings, etc files in Django project file. The template is loading fine when I running on Django default server. I have seen many similar issues.But I couldn't find any good answer for those question. Error: Django version 1.9.13, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. static C:\Dev\EXE\cookie\dist\mysite\media http ('Unexpected error:', <class 'django.template.exceptions.TemplateDoesNotExist'> Traceback (most recent call last): File "crumbs_mysite\views.py", line 278, in parser File "crumbs_mysite\views.py", line 146, in licensevalidation File "site-packages\django\shortcuts.py", line 39, in render_to_response File "site-packages\django\template\loader.py", line 96, in render_to_string File "site-packages\django\template\loader.py", line 43, in get_template django.template.exceptions.TemplateDoesNotExist: activate_license.html Traceback (most recent call last): File "crumbs_mysite\views.py", line 278, in parser File "crumbs_mysiite\views.py", line 146, in licensevalidation File "site-packages\django\shortcuts.py", line 39, in render_to_response File "site-packages\django\template\loader.py", line 96, in render_to_string File "site-packages\django\template\loader.py", line 43, in get_template django.template.exceptions.TemplateDoesNotExist: activate_license.html [20/Dec/2017 10:21:09] "GET / HTTP/1.1" 500 27 -
Programs to use to build a Web App
I am planning to build a web app using open source to store/analyse/plot my test data. Basically: I am planning to use Python. I have some projects. For each project, i will have a series of different type of test data. I will analyse them and come out with about some interpretation parameters. I may some users to log in to import data into it. i will need to show the project locations on a map. I need to store the store data online so it can be used again. I need to plot the data including interpretation results. Plot can be interactive if it is not very hard to do. I am not a programmer, but have some C/Python/HTML knowledge. Can you suggest what open source program (flask,django, plotly, dash? et.al) i could use? -
Django rest framework djoser insert data when login
As i am doing a mobile app with token authentication, so when a user sign in, it will save information like app version, os ver and mobile type(tablet or mobile) + get a token back. This is to allow debug to be easier if the app crash on certain version. Djoser = http://djoser.readthedocs.io/en/latest/adjustment.html As i am using django rest framework djoser template, i wanted to customise their login function where i will save those 3 field into user table. I did try doing create and update function but only the 3 field isnt save inside the user table. Here is my code: Models.py class CustomUserManager(UserManager): def get_by_natural_key(self, username): return self.get( Q(**{self.model.USERNAME_FIELD: username}) | Q(**{self.model.EMAIL_FIELD: username}) ) class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) ethnicGroup = models.CharField(max_length=30, blank=True, null=True) mobileNo = models.IntegerField(blank=True, null=True) favoriteClinic = models.CharField(max_length=50, blank=True, null=True) appVer = models.FloatField(blank=True, null=True) osVer = models.FloatField(blank=True, null=True) mobileType = models.IntegerField(blank=True, null=True) # displaypicture = models.ImageField objects = CustomUserManager() def __str__(self): return self.username cserializer.py class TokenCreateSerializer(serializers.Serializer): password = serializers.CharField( required=False, style={'input_type': 'password'} ) appVer = serializers.CharField(required=False, allow_blank=True) osVer = serializers.CharField(required=False, allow_blank=True) mobileType = serializers.IntegerField(required=False) class Meta: model … -
django manytomany order_by number of relationships
I have a manytomany relationship with Products and Tags, and I want to find the products that match my set of tags the best. class Product(models.Model): def __str__(self): return self.title title = models.CharField(max_length=200) price = models.IntegerField() tags = models.ManyToManyField(Tag, related_name="products", blank=True) class Tag(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50) I have a Queryset of tags and I want to order my products by whichever products have the most of the selected tag? Are there any neat tricks to doing this? Or do I have to just query for all the Products and then sort them myself? For instance, if I have a QuerySet with 3 tags: STEM, Programming, K-6 and I have products: Computer Science Book (Programming), Engineering Puzzle (K-6, STEM), Cookie Cutters (K-6), Rocket (STEM, K-6, Programming), Backpack (K-6) I want to return those same items but in this order: Rocket (STEM, K-6, Programming), Engineering Puzzle (K-6, STEM), Computer Science Book (Programming), Cookie Cutters (K-6), Backpack (K-6) -
django rest framework: how to create yearly archive
I want to create a yearly archive of all the posts in my blog and pass its as JSON to my app. I am looking for something below. [ { year:2017 url: numbrofposts: 100 months: [ { month: Jan numberofposts: 10 url: listofposts: [ { id:, title,url} { id:, title,url} ] } ] } { year:2016 numbrofposts: 500 months: [ { month: Jan numberofposts: 30 listofposts: [ { id:, title, description, etc} { id:, title, description, etc} ] } ] } ... ] If possible how to add pagination because the number of posts will keep increasing in future. I am not sure should the pagination be based on year or months Assume i have a simple Posts model, with title and description and created_date -
Why is django admin not showing "currently" value of ImageField?
I'm facing an issue when deploying a django app in other machine. In my local machine is working fine, but in a linux machine is not showing the (Currently) current value of ImageField. Both environments have django 1.11. The model: class Company(models.Model): class Meta: verbose_name = ("Empresa") name = models.CharField(max_length=500, verbose_name="nombre") nit = models.CharField(max_length=50, verbose_name="nit") address = models.CharField(max_length=500, verbose_name="dirección", blank=True, null=True) telephone = models.CharField(max_length=15, verbose_name="teléfono", blank=True, null=True) cellphone = models.CharField(max_length=15, verbose_name="celular", blank=True, null=True) legal_representative = models.CharField(max_length=500, verbose_name="representante legal", blank=True, null=True) photo = models.ImageField(upload_to='company/img', verbose_name="imagen", blank=True, null=True) photo_thumbnail1 = models.ImageField(upload_to='company/img', verbose_name="imagen 250x250", blank=True, null=True) def __str__(self): return self.name def __unicode__(self): return self.name The admin: class CompanyAdmin(admin.ModelAdmin): exclude = ('photo_thumbnail1',) list_display = ('id','name', 'nit', 'address','telephone','cellphone','legal_representative',) def render_change_form(self, request, context, *args, **kwargs): # Just to show the photo url while rendering print('rendering') print(vars(kwargs['obj'])) if kwargs['obj'].photo: print(kwargs['obj'].photo.url) if kwargs['obj'].photo_thumbnail1: print(kwargs['obj'].photo_thumbnail1.url) return super(CompanyAdmin, self).render_change_form(request, context, args, kwargs) In my local machine, I can see the the current value for Photo when I previously saved: In linux machine, it is not showing the current value as if there is no image saved for this field. But I made sure it is getting the value when rendering by printing in console the urls: Please, if you have … -
How to i transpose rows and columns in Django excel export file
Here is the sample code which i am struggling to transpose the data def export_users_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="users.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Users') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Username', 'First name', 'Last name', 'Email address', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = User.objects.all().values_list('username', 'first_name', 'last_name', 'email') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response All line indentation are correct My goal is to create a file in excel format from the above code it's fine but the problem is rows and columns are not inter changing If you people suggest me any other library to do excel export file that can able to transpose the data -
Django REST Framework that doesn't alter the model data
I am trying to create a middleware web app that will allow users to control some services on our servers. To that end, I have several models created in Django that are used to track things like the current state of the server, or a list of which inputs are valid for any given service. The API needs to be able to: List all instances of a model Show detailed information from one instance of a model Accept JSON to be converted into instructions for the software (i.e. "This list of outputs should source from this input") I don't need to have any further access to the data - Any changes to the details of the models will be done by a superuser through the Django admin interface, as it will only change if the software configuration changes. So far all the DRF documentation I've found assumes that the API will be used to create and update model data - How can I use DRF for just GET calls and custom actions? Or should I forego DRF and just use plain Django, returning JSON instead of HTML? -
Django, is there a way to see what SQL queries are being executed?
I'm exploring https://github.com/shymonk/django-datatable, it looks nice but Im wondering if it will query the whole data or query the paginated data. This information is highly needed to determine performance. I would like to know in Django, is there a way to see what is the underlying queries is being executed ? Im using Django==1.11.7 -
I am getting timestamp as 2017-12-16 06:32:34.715731+00:00 i want it in the format of 2017-12-16 06:32:34
class Registration(models.Model): requester_first_name = models.CharField("First name", max_length=50) requester_last_name = models.CharField("Last name", max_length=50) requester_email = models.CharField("Email", max_length=50) requester_phone = models.CharField("Mobile", max_length=20) requester_title = models.CharField("Title", max_length=50) registration_date = models.DateTimeField(default=timezone.now) this is my model i have imported "from django.utils import timezone" and also in settings i have mentioned DATETIME_FORMAT = 'j N Y, P' -
Unable to load concatenated static file source
I am new to django and eventually I learnt the use of static files in Django and to my relief I was finally able to load the files while hardcoding the file name in the {%static filename.jpg %}. However, when I tried to create a string by replacing the hardcoded filename.jpg with the dynamic file name, I wasn't getting the output. Not working code snippet: <script> image_name = "1.png" static_start = "{% static '" static_end = "' %}" image_src = static_start.concat(image_name, static_end) window.alert(image_src) var para = document.createElement("img"); {% load static %} para.setAttribute("src", image_src) var element = document.getElementById("div_test"); element.appendChild(para); </script> Working Code snippet: <script> var para = document.createElement("img"); {% load static %} para.setAttribute("src", "{%static '1.png'%}") var element = document.getElementById("div_test"); element.appendChild(para); </script> What I am trying to do is that, I have a bunch of image files that I am getting from somewhere through an API and I am storing them in the static folder. After downloading those image, I am trying to load them on my webpage, for that I am using the static file and getting the file name dynamically as I do not know what would the file name of the downloaded file. The point is that string concatenation … -
Inlineformset causing metaclass conflict:
I am trying to add validation to my Django forms. I want to require at least one child model for my inlineformset. I am using the following as a reference: Inline Form Validation in Django I am still getting an error line 454, in formset_factory return type(form.name + str('FormSet'), (formset,), attrs) TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases from django.forms import inlineformset_factory from .models import * from django.forms.models import BaseInlineFormSet from django import forms class PropertyForm(forms.ModelForm): class Meta: model = Property exclude = () class UnitForm(forms.ModelForm): class Meta: model = Unit exclude = () class CustomUnitFormset(BaseInlineFormSet): def is_valid(self): return super(CustomUnitFormset, self).is_valid() and \ not any([bool(e) for e in self.errors]) def clean(self): # get forms that actually have valid data count = 0 for form in self.forms: try: if form.cleaned_data and not form.cleaned_data.get('DELETE', False): count += 1 except AttributeError: pass if count < 1: raise forms.ValidationError('You must have at least one unit') UnitFormSet = inlineformset_factory(Property, Unit, form=PropertyForm, formset='CustomUnitFormset', extra=0, min_num=1, validate_min=True, validate_max=True, max_num=10, ) I have also tried to understand the inheritance issues explained here:Triple inheritance causes metaclass conflict... Sometimes But I dont see where i have … -
ImportError: cannot import name 'multiarray' when i use conda env in apache
my environment: ubuntu server 16.04 apache2 (libapache2-mod-wsgi-py3) django 1.11 python 3.6 (use conda env) when i use shell,i write: import numpy import numpy.core.multiarray it is all right my apache conf: ServerName localhost:7080 ServerAdmin sdfsa@163.com WSGIDaemonProcess comengine python-path=/home/yangtao/miniconda3/envs/compoengine/lib/python3.6/site-packages WSGIProcessGroup comengine WSGIScriptAlias / /home/serverend/comengine/comengine/wsgi.py <Directory /home/serverend/comengine/comengine> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error-comengine.log CustomLog ${APACHE_LOG_DIR}/access-comengine.log combined </VirtualHost> but,but when i use it in my django code。come error like this: [.867314 2017] [wsgi:error] [] Traceback (most recent call last): [.867317 2017] [wsgi:error] [] File "/home/yangtao/miniconda3/envs/compoengine/lib/python3.6/site-packages/numpy/core/__init__.py", line 16, in < module> [.867319 2017] [wsgi:error] [] from . import multiarray [.867330 2017] [wsgi:error] [] ImportError: cannot import name 'multiarray' [.867332 2017] [wsgi:error] [] [.867333 2017] [wsgi:error] [] During handling of the above exception, another exception occurred: [.867335 2017] [wsgi:error] [] [.867337 2017] [wsgi:error] [] Traceback (most recent call last): [.867339 2017] [wsgi:error] [] File "/home/yangtao/miniconda3/envs/compoengine/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner [.867341 2017] [wsgi:error] [] response = get_response(request) [.867343 2017] [wsgi:error] [] File "/home/yangtao/miniconda3/envs/compoengine/lib/python3.6/site-packages/django/core/handlers/base.py", line 172, in _get_response [.867345 2017] [wsgi:error] [] resolver_match = resolver.resolve(request.path_info) [.867347 2017] [wsgi:error] [] File "/home/yangtao/miniconda3/envs/compoengine/lib/python3.6/site-packages/django/urls/resolvers.py", line 362, in resolve [.867349 2017] [wsgi:error] [] for pattern in self.url_patterns: [.867351 2017] [wsgi:error] [] File "/home/yangtao/miniconda3/envs/compoengine/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ [.867353 2017] … -
Update method from the ajax call on django rest api?
There is a update view api made to update the content of employee. I can update from the django rest framework view. I'm using jquery ajax to update but its not working. $(document).ready(function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $(".update-employee").submit(function(event){ event.preventDefault() var this_ = $(this) var form = this_.serializeArray() $.each(form, function(key, value){ }) var formData = this_.serialize() console.log(formData); var temp = { "student_name": form[4].value, "email": form[1].value, "address": form[2].value, "phone_number": form[3].value, "username": {{ user_id }}, "school": {{ school_id}}, "language_id": {{ language_id }} } $.ajax({ url: "/api/student/{{ id }}", data: JSON.stringify(temp), beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, method: PUT, contentType: "application/json; charset=utf-8", dataType: 'json', success: function(data){ console.log(data) }, error: function(data){ console.log("error") console.log(data.statusText) console.log(data.status) } }) }); }); … -
Error during uning testing in Django Tutorial
I've been having trouble with Part 5 of Django Tutorial, available at here. Basically, the current output when I try to test it after using the command python manage.py test polls is: ====================================================================== FAIL: test_past_question (polls.tests.QuestionDetailViewTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/anybus/DjangoTut/polls/tests.py", line 118, in test_past_question self.assertContains(response, past_question.question_text) File "/usr/lib/python3.6/site-packages/django/test/testcases.py", line 393, in assertContains self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr) AssertionError: False is not true : Couldn't find 'Past question.' in response ---------------------------------------------------------------------- Ran 10 tests in 0.030s Here's my current tests.py file: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase # Create your tests here. import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() returns False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() returns False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=1, seconds=1) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() returns True for questions whose pub_date is within the last day. """ time = timezone.now() … -
How to get HTML textbox context from django views.py?
I'm completely new in web development. I want to take the content from textbox then i'll process it in views.py. I'm trying to take id=anahtarkelime and id=url textbox values in Sonuc function when i click to id=search button. Current code: HTML file <form action="" method="post">{% csrf_token %} <label for="anahtarkelime">Anahtar Kelime</label> <input type="text" id= "anahtarkelime" name="anahtarkelime"> <label for="url">Aranacak URL</label> <input type="text" id= "url" name="url"> <br><br> <input id="search" type="button" value="ARA" /> </form> views.py def Sonuc(request): if(request.method == 'POST') and request.is_ajax(): word = request.POST['word'] url = request.POST['url'] print(word + ", " + url) data = { 'word': word, 'url': url} return HttpResponse(data) else: return render(request, 'html_files/Sonuc1.html') JS file $(document).ready(function(){ $("#search").click(function(){ $.ajax({ type: "POST", url: "/Sonuc/", data: { 'word': $('#anahtarkelime').val(), 'url': $('#url').val(), } }); }); });