Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail get all pages in GraphQL
I need to get all pages in wagtail with GraphQL with title and body fields by Page model in wagtail and pass body from child pages. How can I get all the inheritors inherited from Page in the wagtail with their body fields, where it is in the child pages class HomePage(Page): body = StreamField([ ('intro_header', blocks.TextBlock(icon="title")), ('intro_sub_header', blocks.TextBlock(icon="title")), ('intro_image', ImageChooserBlock()), ('technologies_title', blocks.TextBlock()), ], blank=True, null=True) class AboutPage(Page): body = StreamField([ ('header', blocks.TextBlock(icon="title")), ('content', RithTextBlock()), ], blank=True, null=True) query pages { pages { id title body } } -
TypeError: is_valid() missing 1 required positional argument
I have write models and form files successfully but still showing some error in views after passing argument is the self is not defined after defining self it is showing NoneType' object has no attribute 'is_bound -
Django transaction not working as expected
I want to add a job information into MySQL database via Django framework and make sure not to add the job already exist in the database. And I have already use transaction atomic with savepoint but still not working during testing. Could anyone have some ideas about how to make it work? Thanks in advance ! Django view function: def insert(request): name = request.GET["name"] jobs = Job.objects.filter(~Q(status='DONE'),name=name) if len(jobs) > 0: return HttpResponse("Already insert!") else: try: with transaction.atomic(): sid = transaction.savepoint() newJob = Job(name=name,status='NEW') newJob.save() # Could throw exception jobs = Job.objects.filter(~Q(status='DONE'),name=name) if len(jobs) > 2: transaction.savepoint_rollback(sid) return HttpResponse("Rollback Already insert!") transaction.savepoint_commit(sid) return HttpResponse("insert "+ name +" successfuly") except IntegrityError: transaction.savepoint_rollback(sid) return HttpResponse("Rollback insert error!") transaction.clean_savepoints() Test function: import multiprocessing import os import random import time from multiprocessing import Pool, Process import requests def run_proc(name): print("exec "+name) payload = {} payload['name'] = name r = requests.get("http://localhost:8080/dashboard/insert",params=payload) print(r.text) if __name__ == "__main__": pool = multiprocessing.Pool(processes = 10) for j in range(10): for i in range(10): pool.apply_async(run_proc, (str(j), )) print("Start") pool.close() pool.join() print("Sub-process(es) done.") And in Database: 1 0 2019-08-18 06:00:39.408953 NEW 2 1 2019-08-18 06:00:41.477532 NEW 3 2 2019-08-18 06:00:43.530742 NEW 4 3 2019-08-18 06:00:45.569131 NEW 5 4 2019-08-18 06:00:47.618674 NEW … -
Dupla camada de Cadastro
Tô iniciando no Django, e tenho algumas dúvidas: 1° No código abaixo, como vocês podem ver, tem uma classe chamada Aluno que tem relação com a classe Responsável, eu gostaria de numa tela de cadastro mostrassem as form das duas classes para realizar o cadastro, já que é necessário um Responsável para cadastrar aluno. Eu consegui fazer com o código abaixo, mas não sei se tem algum jeito melhor. Segue uma imagem de como eu quero, e consegui(https://imgur.com/bp6Aa2Z). Mas minha dúvida é, Tem algum modo melhor de realizar essa tarefa? 2º Eu queria também, pegar a altura e o peso do aluno, para realizar o IMC dele. Como eu faço isso? Quando eu faço a função que pega a altura e o peso, e comparo com EX: 18.5, diz que não é possível comparar a função com o valor. Tentei também colocar o valor do calculo numa variável, e também aparece um erro dizendo que não é possivel comparar um valor Floadinput com Float. Então alguma solução para isto? OBS: Ali no views.py percebam que há respform e cadform, a dúvida Nº 1, é em respeito a isso, tem como eu fazer em só 1? Tipo, em cadform eu realizar … -
How do I add or delete attributes on the 127.0.0.1:8000/admin/auth/user page?
How do I add or delete attributes on the 127.0.0.1:8000/admin/auth/user page? I don't know how to add or remove properties from an existing page class CustomAdmin(admin.ModelAdmin): list_display = ['emp_no', 'first_name', 'last_name', 'gender', 'birth_date', 'hire_date'] admin.site.unregister(User) admin.site.register(User, UserAdmin) Nothing changes -
not displaying objects from object.procedure_set.all
i am having objects that are linked with one to many relationship and i am trying to display data of object linked with foriegn key but displaying nothing, I have also tried to use the qs in view but ending up with error views.py : @login_required def discharge_detail(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method == "POST": procedure = ProcedureForm(request.POST) if procedure.is_valid() : procedure.save() return HttpResponseRedirect(request.path_info) else: return HttpResponse(procedure.errors.as_data()) else: procedure = ProcedureForm() return render(request, 'dischargedetails.html', {'object':object, 'procedure':procedure}) template: {% for ab in Ipd.procedure_set.all %} <div class="col-lg-12"> <div class="feed-activity-list"> <div class="feed-element"> <div class="media-body"><small class="pull-right">{{ab.time}} {{ab.date}}</small> <p class="font-bold alert alert-success m-b-sm" > <a data-toggle="modal" id="1028" data-target="#modal-form-invest-update"> {{ab.report}} </a> {% endfor %} </p> </div> </div> </div> -
Django, What happens with pre_delete if model.delete() fails
seems like a simple question, but I can't find any documentation... when using pre_delete, if the model.delete() call fails for whatever reason (let's assume a child constraint fails), does the pre_delete signal still fire? -
trying to let users add new topics to page, but page only returns the bullet points, NO topic names. works fine in admin backend but defeats purpose
Working thru my 1st python/Django project. Need to let users add new topics to a blog page, but page only returns the bullet points, NO topic names. Works fine on admin back end which of course defeats purpose of user entry" {% extends 'blog/base.html' %} {% block content %} <p>Add a new topic:</p> <form action="{% url 'blog:new_topic' %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name='submit'>add topic</button> </form> {% endblock content %} {% extends 'blog/base.html' %} {% block content %} <p>BlogPosts</p> <ul> {% for topic in blogposts %} <li> <a href="{% url 'blog:topic' topic.id %}">{{ topic }}</a> </li> {% empty %} <li>Nothing's yet been posted</li> {% endfor %} </ul> <a href="{% url 'blog:new_topic' %}">Add a new topic:</a> {% endblock content %} -
Django channels cannot import name RequestAborted from exceptions
Using daphne here's my setup: PROCFILE: web: daphne my_application.asgi:application --port $PORT --bind 0.0.0.0 -v2 SETTINGS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'channels', 'django_summernote', .... ] CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], } } } ASGI_APPLICATION = "my_application.routing.application" ROUTING FILE: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.conf.urls import url application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( [ url(*), .... ] ) ), }) ASGI.PY - WHERE THE ERROR OCCURS """ ASGI entrypoint. Configures Django and then runs the application defined in the ASGI_APPLICATION setting. """ import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_application.settings") django.setup() # HERE IT THROWS THE IMPORT ERROR application = get_default_application() REQUIREMENTS: ... channels channels_redis ... So, using the latest 2.(2?) package I believe which I just verified has the source code required. IMPORT ERROR from channels.exceptions import RequestAborted, RequestTimeout ImportError: cannot import name 'RequestAborted' I clearly have the right package and this is available per the source code so wtf is going on here.....? -
How to Debug Django coode with Docker?
I am doing a project in Django, I use PyCharm in Windows 8.1. To start the web server and the database I use Docker installed on Debian (Linux) through a virtual machine (do not install Windows Docker for compatibility problems). The problem is that by working in this way, I can't find a way to debug the code (put breakpoints, etc.). I was looking everywhere but I didn't find any solution. Maybe someone could solve this problem. In case I leave the file docker-compose.yml: version: '3.4' services: db: image: postgres container_name: csuperior-postgres environment: POSTGRES_USER: xxxxxxx POSTGRES_PASSWORD: xxxxxxx broker: image: rabbitmq container_name: csuperior-broker environment: - RABBITMQ_DEFAULT_USER=xxxxxxx - RABBITMQ_DEFAULT_PASS=xxxxxxx web: container_name: csuperior-web volumes: - .:/code/ build: . ports: - '8000:8000' command: python3 manage.py runserver 0.0.0.0:8000 depends_on: - db - broker Thanks! -
can't debug django app in VS Code with docker database: 'could not translate host name "db" to address: Name or service not known'
My django app is connecting to a postgreSQL database that runs in a docker container. I can connect to this container no problem if I run the app manually: ./src/manage.py runserver However, if I try to run a debug configuration through VS Code, I get this error: psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known Here is the code the VSCode is running when I try to debug (I did not set any of these settings): /home/me/Developer/myproject/venv/bin/python /home/me/.vscode/extensions/ms-python.python-2019.8.30787/pythonFiles/ptvsd_launcher.py --default --client --host localhost --port 37153 /home/me/Developer/myproject/src/manage.py runserver --noreload How can I get my debug configuration to work? -
iframe on load function only triggers on certain loads, not all internal clicks
$('iframe').on('load', function () { ... } I have this piece of code, but the iframe can navigate away from it's core page, yet I can't seem to trigger a function from when the navigation has loaded. I want to be able to trigger an ajax call in django for every click's load to update the data over the top of the iframe. -
I have an author CharField, and i want to make it optional, but it gives me an error when i use required=False someone can help me?
i want to unrequire the field author because some times i need it but other times no so Traceback (most recent call last): File"C:\Users\hdPyt\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File"C:\Users\hdPyt\AppData\Local\Programs\Python\Python37\lib\threading.py" line 870, in run self._target(*self._args, **self._kwargs) File "D:\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\venv\lib\sitepackages\django\core\management\commands\runserver.py", line 109, in inner_runautoreload.raise_last_exception() File "D:\venv\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "D:\venv\lib\site-packages\django\core\management__init__.py", line337, in execute autoreload.check_errors(django.setup)() File "D:\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\venv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\venv\lib\site-packages\django\apps\registry.py", line 114, in populateapp_config.import_models() File "D:\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File"C:\Users\hdPyt\AppData\Local\Programs\Python\Python37\lib\importlib__init__.py", line 127, in import_m return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "D:\firstblog\blog\models.py", line 14, in class Post(TimestampModel): File "D:\firstblog\blog\models.py", line 17, in Post auteur = models.CharField(max_length=80, required=False) File "D:\venv\lib\site-packages\django\db\models\fields__init__.py", line 1037, in init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'required' -
request.user not working properly and can't be assigned to hidden model field
I am making a little image sharing website which is a lot like a blog. When I try to assign form.author = request.user, it doesn't work and the form on my website returns 'this field is required' error. I tried even other similiar projects on github to check if the error is in the project but it seems not because I get errors there too. But the interesting part is when I try to print the request.user object it prints the object without a problem but when I try to assign it for some reason it returns null. Then I tried twisting the code in every possible scenario but I couldn't debug it. This is my models.py class Meme(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) meme = models.ImageField(upload_to='memes/') This is my view def upload(request): form = MemeUploadForm(request.POST or None) if request.method == 'POST': print(request.user) if form.is_valid(): obj = form.save(commit=False) obj.author = request.user obj.save() redirect('blog-index') return render(request, 'blog/upload.html', {'form': form}) This is my form class MemeUploadForm(ModelForm): class Meta: model = Meme fields = ['title', 'meme'] When I try to get the view to return the request.user it gives me Attribue error: User' object has no attribute 'get' but when I … -
RUN pip install -r requirements.txt does not install requirements in docker container
I am new to django, docker and scrapy and I am trying to run a django app that also uses scrapy (I basically create a django app that is also a scrapy app and try to call a spider from a django view). Despite specifying this scrapy in requirements.txt and running pip from the Dockerfile, the dependencies are not installed in the container prior to running 1python manage.py runserver 0.0.0.0:8000` and the django app fails during the system checks, resulting in the web container exiting because of the following exception: | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner web_1 | self.run() web_1 | File "/usr/local/lib/python3.7/threading.py", line 870, in run web_1 | self._target(*self._args, **self._kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run web_1 | self.check(display_num_errors=True) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check web_1 | include_deployment_checks=include_deployment_checks, web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks web_1 | return checks.run_checks(**kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks web_1 | new_errors = check(app_configs=app_configs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique web_1 | all_namespaces = _load_all_namespaces(resolver) web_1 | File … -
If I want to create table in django which database will be easier for CSV files and How to insert CSV file in django using pycharm?
I have 4 csv files with me for creating online test i need to make a table containing 1 column for question, 4 columns for 4 options of answer and last column for correct answer and then need to import in django so how to do? -
javascript function should switch between 2 images in a django template but doesn't
I have a js function that should switch between 2 images when a button is clicked. This function worked fine switching images in an html page but when I used it inside a django project fails to change images in the template. The initial situation was like this: the first image is displayed when the page is loaded, when the button is clicked it tries to change to the second images but fails to locate the source and gives a 404 error, a second click also fails to load the first image back; so I fixed the path to the second image, now pressing the button once correctly load the second image but when clicked again fails to load the first image, pressing the button a third time correctly loads the second image tho, a step foward. So I fixed the path to the first image (both images have the same path) and now clicking the button does nothing, the first images stands still. the path is this: ProjectName/AppName/static/AppName/dog1.jpg {%load static%} <img id="avatar" src="{% static 'AppName/dog1.jpg' %}" class="avatar"> <button id="Btn">Click me to change dogs<button> const dogs = [ "dog1.jpg", "/static/AppName/dog2.jpg" ]; const avatar = document.getElementById('avatar'); /*const dogs this way makes … -
how to connect to remote MS SQL Server using pyodbc
I am trying to connect to MS SQL Server 2016 Database using pyodbc with django. i tried on the localhost and it work fine but when i tried to connect to server on the same network it did not work and display the below error : InterfaceError at /connect/ ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') I tried to check the ODBC Driver on the server and it display these drivers: ODBC Driver 13 for SQL Server SQL Server and i tried both of them but no success. views.py from django.shortcuts import render import pyodbc # from .models import Artist # Create your views here. def connect(request): conn = pyodbc.connect('Driver={ODBC Driver for SQL Server};' 'Server=AB-INT-SQL;' 'Database=testDB;' 'Trusted_Connection=yes;') cursor = conn.cursor() c = cursor.execute('SELECT * FROM Artist') return render (request,'connect.html',{"c":c}) connect.html {% for row in c %} {{ row }} {% endfor %} -
Save uploaded data to database in django
I do want to save all my excel-file data(that i uploaded) to database. {kindly ignore indentation problem},I also tried to change df to df.column.values but it also doesnt work .I am mainly facing problem in for loop .I am getting full dataframe in df variable but unable to save that in corresponding model. views.py : from django.shortcuts import render import openpyxl import pandas as pd from .models import dataset import csv def index(request): if "GET" == request.method: return render(request, 'myapp/index.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size xl = pd.ExcelFile(excel_file) names =xl.sheet_names df = xl.parse(names[0]) for row in df: created = dataset.objects.create( CGI=row[0], country=row[1], service_provider=row[2], zone=row[3], town=row[4], site_name=row[5], site_addr=row[6], landmark=row[7], latitude=row[8], longitude=row[9], shared=row[10], azimuth_angle=row[11], status=row[12], status_change_date=row[13],) return render(request, 'myapp/index.html', { }) models.py:: from django.db import models class dataset(models.Model): CGI = models.CharField(max_length=100) country = models.CharField(max_length=100, blank=True) service_provider = models.CharField(max_length=100, blank=True) zone = models.CharField(max_length=100, blank=True) town = models.CharField(max_length=100, blank=True) site_name= models.CharField(max_length=100, blank=True) site_addr= models.CharField(max_length=400, blank=True) landmark= models.CharField(max_length=100, blank=True) latitude= models.CharField(max_length=100, blank=True) longitude=models.CharField(max_length=100, blank=True) shared=models.CharField(max_length=100, blank=True) azimuth_angle=models.CharField(max_length=100, blank=True) status= models.CharField(max_length=100, blank=True) status_change_date= models.CharField(max_length=100, blank=True) I tried this code but its giving row value as country and I am not getting required result,plz help! -
Unable to rebuild elasticsearch indexes when using postgresql as database in Django project
I am playing with a Django project and elasticsearch(using django-elasticsearch-dsl , and till now i had been using sqlite as database for it. Now I thought to also try to use postgresql. The issue is that when I run the project with the sqlite everything is fine and data in elasticsearch are being populated correctly. Though when i make it to use postgresql (following this guide), then when i run python manage.py search_index --rebuild the following error comes up. elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'Root mapping definition has unsupported parameters: [prettyUrl : {type=text}] [summary : {analyzer=html_strip, fields={raw={type=keyword}}, type=text}] [score : {type=float}] [year : {type=float}] [genres : {analyzer=html_strip, fields={raw={type=keyword}, suggest={type=completion}}, type=text}] [id : {type=integer}] [title : {analyzer=html_strip, fields={raw={type=keyword}, suggest={type=completion}}, type=text}] [people : {analyzer=html_strip, fields={raw={type=keyword}, suggest={type=completion}}, type=text}]') This is the documents.py I am using. INDEX.settings( number_of_shards=1, number_of_replicas=1 ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @INDEX.doc_type class MovieDocument(DocType): """Movie Elasticsearch document.""" id = fields.IntegerField(attr='id') prettyUrl = fields.TextField() title = fields.StringField( analyzer=html_strip, fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField(), } ) summary = fields.StringField( analyzer=html_strip, fields={ 'raw': fields.KeywordField(), } ) people = fields.StringField( attr='people_indexing', analyzer=html_strip, fields={ 'raw': fields.KeywordField(multi=True), 'suggest': fields.CompletionField(multi=True), }, multi=True ) genres = fields.StringField( attr='genres_indexing', analyzer=html_strip, fields={ 'raw': fields.KeywordField(multi=True), 'suggest': fields.CompletionField(multi=True), … -
Is source url case sensitive for html5 video tag?
A video file name with known name '/media/hello.' (case sensitive), but unknown case extension, such as '.mOv', '.MOV' or '.mov' Real file is '/media/hello.MOV'. The following video sometimes work if Django web server running from MacPro, but if running from Ubunto production server, video file name '/media/hellow.mov' does not work (More tests makes me more confused, as it seems Ubutntu production server status is unclear). <video id="video" defaultMuted autoplay playsinline controls> <source src="/media/hello.mov" type="video/mp4"> Your browser does not support the video tag. </video> I want to know if file extension is case sensitive. -
Rendering an image in django-tables2 on basis of value from Model
I am using django-tables2 and I am trying to display badges (css class) in my tables on basis of value being populated in the table. The problem i am facing is that i am only able to get my else badge. Probably, its not able to read and compare Sim.sim_status == 1. If my if is true, then i want that "Administrator" badge should be displayed. class ManageSimTable(tables.Table): status = tables.Column() def render_status(self): if Sim.sim_status == 1: return format_html('<span class="badge badge-danger">Administrator</span>') else: return format_html('<span class="badge badge-success">Operator</span>') -
No User matches the given query. Page Not found 404?
In my blog website I want to open another user's profile on clicking one of the links. But it keeps on showing 404 error saying No user matches the given query. Here's that link in a base.html <a href="{% url 'blogapp:userprofile' username=view.kwargs.username %}">{{ view.kwargs.username }}</a> Here's my url pattern for the function- path('userprofile/<str:username>/',views.userprofile,name='userprofile'), Here's my function view- @login_required def userprofile(request,username): user = get_object_or_404(User,username='username') return render(request,'blogapp/userprofile.html',{'user':user}) here's my template file {% extends 'blogapp/base.html' %} {% block content %} <div class="row"> <img src="{{ user.profile.image.url }}"> <div class="details"> <h2>{{ user.username }}</h2> <p>{{ user.email }}</p> </div> </div> <p style="margin-top: 10px; margin-left: 138px;">{{ user.profile.description }}</p> <hr> {% endblock %} {{ view.kwargs.username }} gives the perfect username that I search for. But problem is somewhere in the userprofile view. It goes to the perfect route http://127.0.0.1:8000/userprofile/username/ but it still shows a 404 error. -
DialogFlow fulfillment for Facebook Messenger Webview
Button to open web view on Facebook Messenger keeps opening a browser, on mobile and desktop I've created Facebook Messenger Bot, created a Test Page and a Test App, currently receiving webhooks from every message on DialogFlow, which respond correctly to the first message, in which i return a DialogFlow card, with a button, this button supposed to open a webview, but keeps opening a browser tab, on mobile and desktop, now, i'm aware for open a webview on desktop the are some modifications to the code that need to be made but mobile should be working by now and that is not the case. I'm following this flow: https://cloud.google.com/dialogflow/docs/images/fulfillment-flow.svg) This the webhook response sent from my Django instance to DialogFlow: "fulfillmentMessages": [ { "card": { "title": "Smoked Turkey Melt", "platform": "facebook", "subtitle": "card text", "imageUri": "https://ucarecdn.com/6a3aae10-368b-418f-8afd-ed91ef15e4a4/Smoked_Turkey_Melt.png", "buttons": [ { "type": "web_url", "text": "Get Recipe", "postback": "https://assistant.google.com/", "webview_height_ratio":"compact", "messenger_extensions": "true" } ] } }],} This is the view for responding to postback button: @csrf_exempt def get_recipe(request): """ """ response = render(request, "recipe_item.html") response['X-Frame-Options'] = 'ALLOW-FROM https://messenger.com/ https://www.facebook.com/ https://l.facebook.com/' response['Content-Type'] = 'text/html' return response And this is the Messenger Extensions SDK been installed on the HTML for the view corresponding to … -
Proper usage fetch js with django
I've got a problem when I am trying to use fetch with django. What I do wrong? # page.html <button id="btn">CLICK</button> <script> let url = '{{ url }}'; # /exp/ $('#btn').on('click', () => { console.log(url); fetch(url).then((data) => { console.log(JSON.stringify(data.json())) # {} }) }) </script> # views.py def page(request): if request.is_ajax(): return JsonResponse({'num': 123}) return render(request, 'exp/page.html', {'url': reverse('exp:page')})