HTML

Writing here

In this article, I’m writing about «How to use Django to execute a Python file prepared on the server from a web page and output the data passed from html to a csv file».

Also, the writing environment is OS: macOS Catalina version 10.15.4 Python:3.7.6 Django:3.0.3 It has become.

About Django

In Previous article, I wrote about the flow from installing Django to displaying html, so please refer to that for the introduction of Django etc. Please refer.

Python file preparation

Creating a python file

First, prepare the Python file you want to run on Django’s server. For the sake of explanation, prepare the following Python file this time.

write_data.py

 # coding:utf-8 import os import csv #Record data from html to csv file def write_csv(data): datas = [data] with open(os.getcwd()+'/myapp/application/'+'data.csv','a') as f: writer = csv.writer(f, lineterminator='\n') writer.writerow(datas) 

This will write that data to data.csv by calling it by passing the data as an argument to write_csv (). Note that here it is assumed that the Python file will be placed in the ` / application«` folder & the csv file will be output, so «`os.getcwd () +’/ myapp / application /’ Although it is +’data.csv’ `, please read this part appropriately according to the environment.

Placement of Python files

Place the prepared Python file on Django’s server. If you put the Python file in the « ` / application«` folder, the directory in the app will look like this:

 - db.sqlite3 - manage.py - - __init__.py - asgi.py - settings.py - urls.py - wsgi.py - __pycashe__ - (.Multiple pyc files) - - __init__.py - admin.py - apps.py - models.py - tests.py - urls.py - views.py - migrations - __init__.py - application #Created folder - write_data.py #Prepared Python file - templates - static 

Of course, you don’t have to put it here, so you can place the file anywhere.

Allow Python files to be executed from html

スクリーンショット 2020-05-30 19.04.32.png

After preparing and arranging the file, let’s actually execute the Python file from html and create a csv file. Before that, I think that it is easier to work after understanding what the data flow is like, so I would like to write the data flow assumed this time. I made it with PowerPoint, sorry for the rough figure, There are many parts that are different from the program for simplification, but the data flow up to writing to the csv file is like this. I would be happy if the image could be conveyed somehow.

html(index.html) → Send data to call_write_data () in myapp / views.py → Execute the write_csv () method of application / write_data.py in call_write_data () → The passed data is written to the csv file.

Читайте также:  Contacts

Expressed in words, it looks like this. Based on this, we will edit each file so that we can actually execute the Python file from html from the next.

html: Send data to views.py using ajax

In order to pass the data to the call_write_data () method in views.py, I would like to send the data using ajax on html. I think there are various methods for this, so please use the method that suits your application.

index.html

        "/>    Please press the button after entering the characters 
Send

When you press the send button, clickBtn () is executed and the data is sent by ajax. The url part is myapp: call_write_data , which sends the data to the method called call_write_data () described in views.py.

The data part is data: ` «, and the data receiving side can get the target data by specifying «input_data». There is only one here, but you can freely set the data format such as the number and type of data like data: ` «. ..

myapp / views.py: Specify the Python file and method you want to execute and execute

myapp/views.py

 from django.shortcuts import render from django.http import HttpResponse # application/write_data.Import py from .application import write_data # Create your views here. def index(req): return render(req, 'index.html') #Method specified by url with ajax def call_write_data(req): if req.method == 'GET': # write_data.py write_csv()Call the method. #Of the data sent by ajax"input_data"To get by specifying. write_data.write_csv(req.GET.get("input_data")) return HttpResponse() 

Here, we get the data sent by ajax, pass it to the method of the Python file we want to execute, and call it.

myapp / urls.py: Allows html to send data to call_write_data () in views.py

myapp/urls.py

 from django.urls import path from . import views app_name = 'myapp' urlpatterns = [ path(r'', views.index, name='index'), #Add the following(views.py call_write_data()Allows you to send data to) path("ajax/", views.call_write_data, name="call_write_data"), ] 

By passing the path, you can send data from html to the specified method of views.py using ajax communication.

Check if it is actually written to the csv file

This completes the necessary editing.

$ python manage.py runserver 

Start the server with, access the displayed address (display html), enter appropriate characters in the input form, and then press the send button.

- - __init__.py . - application - write_data.py - data.csv #Generated csv file 

In this way, the csv file is generated in the application folder created in the application, and if the input character string is recorded in the file, the data is sent without any problem & the Python file is executed.

Supplement

This time I explained how to execute a Python file from html and write the sent data to a csv file, but vice versa.

For the sake of simplicity, I would like to do «get the data passed from write_data.py in views.py and pass it to html for display». Only the files with changes are listed below.

myapp/application/write_data.py Add a method called return_text ().

myapp/application/write_data.py

 # coding:utf-8 import os import csv #Record data from html to csv file def write_csv(data): datas = [data] with open(os.getcwd()+'/myapp/application/'+'data.csv','a') as f: writer = csv.writer(f, lineterminator='\n') writer.writerow(datas) #Add the following(return_text()When you call"Hello!!"Is returned) + def return_text(): + return "Hello!!" 

myapp/views.py Call return_text () added in write_data.py and get the returned character string (store it in data). Pass that data to html using `HttpResponse ()` .

Читайте также:  Плавное открытие аккордеона css

myapp/views.py

 from django.shortcuts import render from django.http import HttpResponse # application/write_data.Import py from .application import write_data # Create your views here. def index(req): return render(req, 'index.html') #Method specified by url with ajax def call_write_data(req): if req.method == 'GET': # write_data.py write_Call the csv method. #Of the data sent by ajax"input_data"To get by specifying. write_data.write_csv(req.GET.get("input_data")) # write_data.Newly written method in py(return_text())To call. + data = write_data.return_text() #Pass the received data to html. + return HttpResponse(data) 

index.html When ajax communication is successful, the argument passed by HttpResponse () is passed to the « `.done (function (data)

index.html

        "/>    Please press the button after entering the characters 
Send +
+ function clickBtn() < var txt = document.getElementById("input_form").value; $.ajax(< url: "", method: 'GET', data: , dataType: "text", contentType: "application/json", beforeSend: function(xhr, settings) < if (!csrfSafeMethod(settings.type) && !this.crossDomain) < xhr.setRequestHeader("X-CSRFToken", csrf_token); >>, error: function(xhr, status, error) < console.log("error") >>) .done(function(data) < // views.py call_write_data()HttpResponse returned in(data)Data can be obtained here. //Rewrite the contents of the span part added at the bottom of the form. + document.getElementById("text").textContent = data; console.log("Success"); >); // csrf_Used to get token 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; > //Csrf in header_Function that grants token function csrfSafeMethod(method) < // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); >; >

This will pass the string «Hello !!» to the html when the submit button is pressed and the Python file is executed correctly, and the string «Hello !!» passed to the bottom of the input form will be displayed. think.

By applying this, it is possible to execute the Python file on the server, read and write the data of the file on the server, and reflect the data on html.

Источник

[Answered]-How to execute code in the Django shell by an external python script?-django

Firstly, you should not be accessing your Python shell with sudo . There’s no need to be running as root.

Secondly, the way to create a script that runs from the command prompt is to write a custom manage.py script, so you can run ./manage.py deactivate_users . Full instructions for doing that are in the documentation.

Similar question

Open Django Shell python manage.py shell

Then run execfile(‘filename.py’)

thatzprem 4607

If you’re using Django 1.8+, then another useful option is to write your own script, and call it with manage.py runscript.

For example, you can write a script named db_init.py and put it under utils folder.
Then launch this script with:

python3 manage.py runscript utils.db_init 

Shahar Gino 105

Based on the comment by Daniel earlier in this thread I’ve created a simple script to get the job done. I’m sharing this for readers of this thread who are trying to achieve the same goal. This script will creates a working «manage.py deactivate_user» function.

This is an example reference of your Django app folder structure:

Django folder structure

You want to create the «deactivate_user.py» file and place it in management/commands/deactivate_user.py directory.

from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User class Command(BaseCommand): help = 'Deactivate user in the database' def handle(self, *args, **options): username = raw_input('Please type the username of the user you want remove: ') try: user = User.objects.get(username=username) user.is_active = False user.save() print ('User is now deactivated in the database.') except User.DoesNotExist: print ('Username not found') 

Call the script by using «python manage.py deactivate_user» You can also create an «activate_user» script with the same code but instead of user.is_active = False use = True.

Читайте также:  Java allow all certificates

scre_www 2290

If you want to execute a Python script that accesses Django models, you first need to set an environment variable:

import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", ".settings") 

In which you need to replace by your project directory, the one that contains the file settings.py .

You can then import your model files, for example:

from .models import User user = User.objects.get(username=FooBar) user.is_active = False user.save() 

Try to input the commands to the running django-shell as a here document:

$ sudo python manage.py shell  
  • How can I execute a heavy-processing, background python code after submitting a form in a Django website?
  • How to call a django view function from external python script
  • How to execute python manage.py django management command via button on the website on Heroku
  • How can I use django to call a python script and return the result in realtime?
  • how to send django website user input data to external python script
  • How to use external python script in django views?
  • How to import a django model into an external python script
  • How to pass parameter to a python script when I pipe it to a Django shell
  • Python code execute through django shell but not through file
  • Python script for Django app to access models without using manage.py shell
  • Execute code in Django after response has been sent to the client
  • In python django how do you print out an object's introspection? The list of all public methods of that object (variable and/or functions)?
  • Using python multiprocessing Pool in the terminal and in code modules for Django or Flask
  • Django - http code 304, how to workaround in the testserver?
  • How to use raw python code in a Django template?
  • How do I check the content of a Django cache with Python memcached?
  • Using Django models in external python script
  • How to enable history in Django shell in python
  • how to add Permissions in Django to Models and Test it using the shell
  • How to log production database changes made via the Django shell

More Query from same tag

  • Django: get count of ForeignKey item in template?
  • How to connect the views functions with two templates in django?
  • django registration change language
  • Best way to achive the opposite of PREPEND_WWW (e.g. redirect from "www" to root domain)?
  • how can I use pagination with django_filter
  • I can't cut of image using "crop" of "pillow"
  • Django manager with datetime.timedelta object inside F query combined with annotate and filter
  • How to make a post call with Django where your models are many to many?
  • How to get latest of many groups at once
  • How to uninstall pip packages which are installed from a *.txt file?
  • How can I add an object to a M2M field on my users profile from django rest frameworks class based create view?
  • django mysql gives page not found (404) while sqlite works fine
  • Displaying only the first paragraph of a body of text in a Django template
  • remove a migration from south migration history
  • Django test fails when creating test database

Источник

Оцените статью