Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Comment() got an unexpected keyword argument 'initial'
I am creating a Django blog and when trying to implement a comment system I got the above error. I am not really sure what caused the problems, but I'll describe some of the things I did before I got the error. I decided to use Django's class-based views to display all of my data. In the PostDetailView shown I tried making it inherit from both DetailView and FormView so I get both the detail and form view displayed. The commented-out code is code that I was going to use for the form view but I didn't know how to make it share the same template and URL route. Views.py from django.views.generic import DetailView, FormView from .forms import Comment from .models import Post class PostDetailView(DetailView, FormView): model = Post template_name= 'optionhouseapp/post-detail.html' form_class = Comment def form_valid(self, form): return super().form_valid(form) # class CommentFormView(FormView): # template_name= 'optionhouseapp/post-detail.html' # form_class = Comment # success_url ='/' # def form_valid(self, form): # return super().form_valid(form) Here is the form page forms.py from django import forms from .models import Comment class CommentForms(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') Here is the associated model models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = … -
save() method does not save form data to the database (Django ModelForm)
I'm making a simple todo list using Django, it works fine except that whatever data is entered into the form does not save to the database (and does not get displayed). My models.py: from django.db import models class TodoListItem(models.Model): content = models.TextField() def __str__(self): return self.content forms.py: from .models import TodoListItem from django.forms import ModelForm class TodoListForm(forms.ModelForm): class Meta: model = TodoListItem fields = ['content'] views.py: from django import forms from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from .models import TodoListItem from .forms import TodoListForm def home(request): context = { 'items': TodoListItem.objects.all() } return render(request, 'home.html', context) def enter_task(request): if request.method == 'POST': form = TodoListForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/') else: return HttpResponse('Form not valid') else: form = TodoListForm() return render(request, 'form.html', {'form': form}) I did it according to the documentation, what I fail to understand is why the line form.save() won't execute when return HttpResponseRedirect('/') right underneath it does. The form.html file, just in case: <!DOCTYPE html> <html> <head> <title>Add task</title> <h1>Add Task</h1> </head> <body> <form action="{% url 'home' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </body> </html> I know that the error has to be in views.py because I used … -
Django not running on MacOS 11.1 (command not found: django-admin)
I am trying to run Django in my Mac's terminal, but it seems like Python cannot find it. I get the error in the title when I try to use the command python -m django startproject scriptsite I get the error command not found: django-admin when I try to use the command django-admin startproject scriptsite When I try installing Django, all four packages are already there, but commands involving Django don't seem to work. Importing Django in a python file is okay, though. How do I fix these problems? And are the previous commands necessary to use Django? I'm just planning to run a simple script on an HTML website, so I'm not sure if I'll even need the web server stuff in the Django tutorial. -
Following tutorial TDD with Python, change default url from localhost to IP
I'm working through "Test Driven Development with Python" The book uses Django 1.11 I'm following along with Chapter 6 and I'm stuck with the server configuration. I can't use --liveserver=IP_ADDRESS as it was deprecated in 1.10 and I can't quite figure out how to set the live_server_url to use the specific IP_ADDRESS I want. The error says: ====================================================================== ERROR: test_can_start_a_list_and_retrieve_it_later (functional_tests.tests.NewVisitorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/me/TUTORIALS/tdd/superlists/functional_tests/tests.py", line 29, in test_can_start_a_list_and_retrieve_it_later self.browser.get('self.live_server_url') File "/home/me/.virtualenvs/superlists/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 333, in get self.execute(Command.GET, {'url': url}) File "/home/me/.virtualenvs/superlists/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/home/me/.virtualenvs/superlists/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidArgumentException: Message: Malformed URL: URL constructor: self.live_server_url is not a valid URL. I would appreciate any tips on how to move forward. -
Why is it recommended to ad sqlite database to gitignore?
I understand other files being ignored. But why would I ignore the sqlite database file if that holds data needed to run the website. How can the website function without a database? -
Trying to Build url path through DetailView , but am getting duplicate values in html page
I am starting to learn django. I want to create a directory site. I want it to be: home page -> list of States -> List of Restaurant Types -> List of Restaurant names I have 'list of States' as a generic.ListView and it works perfect. I tried making 'List of Restaurant Types' as a ListView as well but it wouldn't pull any data in the html. Changing it to a DetailView it pulls the data but has duplicate entries. Is there a way to restrict it as unique outputs in either views.py or the restaurant_detail.html? The current html code is: <p><b>Restaurant SECTION</b></p> {% for name in states.restaurant_name_set.all %} <p>{{name.restaurant_types}}</p> {% endfor %} I get something like: Fine Dining Buffet Buffet Buffet Food Truck I want just one of each I can then link to go to a list of Restaurant Names -
Add strikethrough to a radio input
In my html I have a button and a radio form where the inputs are created using a for loop. <form id="form" class="mb-1"> {% for option in option_list %} <input class="form-check-input text-primary" type="radio" name="option" value="{{option}}"> {{option}} <br> {% endfor %} </form> <button type="button" class="btn btn-primary" id="btn">Button</button> When the button is clicked, the radio inputs are either disabled or enabled based on some condition, which I have working fine, but when disabling an option, I also want to add a strike to the input to better show it's disabled. My js file has something like this. $(document).ready(function() { $('#btn').click(function() { $('#form *').filter(':input').each(function(){ if (condition) { $(this).prop('disabled', false) } else { $(this).prop('disabled', true) } }); }) }) I've tried putting label tags around the inputs and using .wrap() and .css(("text-decoration", "line-through"), but it didn't work. They work on regular text fine, so I think I'm just not formatting the radio input labels correctly? -
'wordItem' object has no attribute 'len',django,python
I'm making word counter by using django. ↓this is views def wordcountView(request): all_word_contents = wordItem.objects.all() return render(request, 'count.html', {'all_contents':all_word_contents}) ↓this is models class wordItem(models.Model): content = models.TextField() I also add path in urls. However, I was given AttributeError: 'wordItem' object has no attribute 'len' this error. -
How to instantiate different classes based on Django model field
I have a table Webhook with a CharField called type that has a list of choices from enum WEBHOOK_TYPE. For each of these types, I want to treat POST requests to the same endpoint differently. So I'm trying to use that same enum to map to a class. For example the view is something like: def get_integration(message_type): webhook_to_message_map = { WEBHOOK_TYPE['FACEBOOK']: Facebook, WEBHOOK_TYPE['TWITTER']: Twitter } def post(req, **kwargs): webhook_type = Webhook.objects.get(kwargs['webhook_id']).type message_type_class = get_integration(webhook_type) message_type_instance = message_type_class() return JsonResponse(message_type_instance.some_function()) I'm having a ton of difficulty situating this such that I don't have circular dependencies, so what's the "correct" way to do this in Django? -
deploying channels with nginx
I have deployed django with nginx following the tutorials in digital ocean. Then I blindly followed the section "Example Setup" in the channels document after installation. My confusions are: When setting up the configuration file for supervisor, it says to set the directory as directory=/my/app/path Should I write down the path where the manage.py is or the path where the settings.py is? When I reload nginx after changing nginx configuration file, I get an error saying that host not found in upstream "channels-backend" in /etc/nginx/sites-enabled/mysite:18 nginx: configuration file /etc/nginx/nginx.conf test failed I did replace "mysite" by the name of my website. I had another error earlier saying that no live upstreams while connecting to upstream but could not recreate the situation. I am new to using the channels, so any additional information on upstream would be helpful. Please let me know if I need to provide more information. -
data passing by one to one field in Django
I have two models Employee and myCustomeUser in my Django project. My models.py: class myCustomeUser(AbstractUser): username = models.CharField(default="abcdef", max_length=150, unique="True") password = models.CharField(default="12345", max_length=150) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_IndustryOwner = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Employee(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='releted_user') extraField = models.TextField(blank=True) Now I am trying to entry an Employee's data with views.py like this: Employee_obj = Employee.objects.create(releted_user.username=this_username, releted_user.password=this_password, releted_user.is_Employee=True) Employee_obj.save() But It shows error like this: Employee_obj = Employee.objects.create(releted_user.username=this_username, releted_user.password=this_password, releted_user.is_Employee=True) ^ SyntaxError: expression cannot contain assignment, perhaps you meant "=="? How can I solve this problem? Mainly I need to save any employee's data by Employee.objects.create() -
How to Build vue components in a django project in Ubuntu
I am working on a project with Django and Vue. In the ReadMe files it has the below instructions. I am in my django terminal on pycharm working in Ubuntu 18.04.5 LTS *) Install vue requirements: cd vuekhal npm init I did the above in the npm init I just kept pressing enter all the way *) Build the vue components (still inside vuekhal): ./node_modules/.bin/webpack --config="build/webpack.prod.conf.js" How do I configure the above components. What code do I add below (venv) samir@VB:~/path to/vuekhal$ -
Django: Create an editable form for each instance within a queryset all in one page?
Sorry if this is too much code, but I believe it is all relevant to the question at hand. Long story short, on my series_detail page, all episodes belonging to each series is shown, as well as forms to add a new episode or edit an existing one. The edit episode form, however, requires an instance, which always returns the very first object of the episodes queryset. This is presumably because of the .first(), but I used this since you can only have one object passed as an instance. What I am trying to achieve is: after showing the edit modal next to each episode, show the instance of each episode instead of only the first episode. save only that episode's instance after the form is filled achieve this without redirecting to an edit page models.py class Series(models.Model): name = models.CharField(max_length=100) class Episode(models.Model): series = models.ForeignKey(Series, on_delete=models.CASCADE) name = models.CharField(max_length=100) episode_no = models.IntegerField(null=True) description = models.TextField(max_length=500) image = models.ImageField(upload_to='pics/episodes',) forms.py class EpisodeForm(forms.ModelForm): name = forms.CharField() description = forms.CharField(widget=forms.Textarea, required=False) episode_no = forms.IntegerField() class Meta: model = Episode fields = ['name', 'description', 'episode_no' ,'image'] views.py def series_detail(request, pk): try: series = Series.objects.get(pk=pk) except: return render(request, 'error_404.html') episodes = Episode.objects.filter(series=series).first() if request.method … -
Problem render a function on a Django file
Hello Friends I have this program in views.py Im using django with websockets to take the RFID data from antenna and send to my server. The problem is that in the function def tag_seen_callback(llrpMsg): """Function to run each time the reader reports seeing tags.""" global numtags tags = llrpMsg.msgdict['RO_ACCESS_REPORT']['TagReportData'] if len(tags): logger.info('saw tag(s): %s', pprint.pformat(tags)) for tag in tags: numtags += tag['TagSeenCount'][0] else: logger.info('no tags seen') return I cant renderd to send the data to the websocket in my script on html file I trie with all but everytime its the same error This is my entire code from django.shortcuts import render from django.http import HttpResponse import datetime from django.template import Template,Context from django.template import loader import sys import os sys.path.append(os.path.abspath(os.path.join(__file__, '..', '..', '..'))) from argparse import ArgumentParser from logging import getLogger, INFO, Formatter, StreamHandler, WARN from sllurp.llrp import LLRP_PORT, LLRPClientFactory import smokesignal from twisted.internet import reactor from sllurp.util import monotonic ''' Sllurp/Tornado Example This file contains an example showing how to use Sllurp with Tornado to update a web page via websockets when rfid tags are seen. ''' numtags = 0 start_time = None def tag_seen_callback(llrpMsg): """Function to run each time the reader reports seeing tags.""" global numtags tags … -
Django views KeyError on production
I have a small NewsAPI application that returns JSON data when I run it locally but after deploying it on Heroku I get a KeyError in the logs and a 500 on the webpage. The log appears to show that the error is in the views: 2020-12-25T23:21:33.571005+00:00 app[web.1]: File "./evening_brew/news/views/api.py", line 114, in get 2020-12-25T23:21:33.571006+00:00 app[web.1]: news = self.requestNewsApi() 2020-12-25T23:21:33.571006+00:00 app[web.1]: File "./evening_brew/news/views/api.py", line 60, in requestNewsApi 2020-12-25T23:21:33.571006+00:00 app[web.1]: return self.extractDataFromNewsApi(responseData) 2020-12-25T23:21:33.571007+00:00 app[web.1]: File "./evening_brew/news/views/api.py", line 31, in extractDataFromNewsApi 2020-12-25T23:21:33.571007+00:00 app[web.1]: for posts in data["articles"]: 2020-12-25T23:21:33.571008+00:00 app[web.1]: KeyError: 'articles' Here's the full code for the view that the log is referring to: class NewsViewSet(MultipleSerializerMixin, viewsets.GenericViewSet): permission_classes = [AllowAny] def get_queryset(self): queryset = News.objects.all().order_by("-published_at") return queryset def extractDataFromNewsApi(self, data): articles = [] for posts in data["articles"]: post = {} post["headline"] = posts["title"] post["link"] = posts["url"] post["snippet"] = posts["description"] post["content"] = posts["content"] post["image_url"] = posts["urlToImage"] post["published_at"] = posts["publishedAt"] post["source"] = "news" articles.append(post) return articles def requestNewsApi(self, query=False): headers = {"Authorization": "Basic "} if query: url = ( settings.NEWS_API_URL + "everything?q=business+finance&pageSize=50&apiKey=" + settings.NEWS_API_KEY ) r = requests.get(url, headers=headers, params={"q": query}) else: url = ( settings.NEWS_API_URL + "everything?q=business&pageSize=50&apiKey=" + settings.NEWS_API_KEY ) r = requests.get(url, headers=headers) responseData = json.loads(r.text) return self.extractDataFromNewsApi(responseData) def storeInDb(self, articles, query=False): … -
Why does my Django Model not work correctly?
Currently making a basic django project, following a well set out tutorial off youtube. All's going well and I usually try to debug isses myself and I wouldn't be asking if i was stuck. Issue: This code is meant to check the image size onces it's reuploaded and then format to make it square but looking at the image linked, this isnt the case. Is my code wrong? is there another way to check and validate images? Code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) [Refrence Image for context][1] [1]: https://i.stack.imgur.com/g8uf6.png -
Catching classes that do not inherit from BaseException is not allowed with Redis in Django Rest Framework
so i'm working on a small DRF application, and I've implemented a custom config backend using redis: class RedisBackend(ConfigBackend): CONFIG_SET = Config.objects if "migrate" not in sys.argv else MagicMock() def __init__(self): ip = settings.CONFIG['REDIS']['HOST'] port = settings.CONFIG['REDIS']['PORT'] db = settings.CONFIG['REDIS']['DB'] password = settings.CONFIG['REDIS']['PASSWORD'] from redis import Redis self.redis = Redis(host=ip, port=port, db=db, password=password) # other methods omitted for brevity It all works fine until I quit the server with CTRL-C, at which point, I get this rather unsavoury exception: Exception ignored in: <bound method Connection.__del__ of Connection<host=localhost,port=6379,db=0>> Traceback (most recent call last): File "E:\Programming\programs\anaconda\lib\site-packages\redis\connection.py", line 537, in __del__ File "E:\Programming\programs\anaconda\lib\site-packages\redis\connection.py", line 667, in disconnect TypeError: catching classes that do not inherit from BaseException is not allowed I have no idea what I can do to fix this. Any ideas? I already tried closing the socket in the __del__ method of the config backend, but no dice. -
Passing Pandas Data Frame to Angular
Someone can explain why my function is no working? I want to get some data(pandas data frame and plot) from my django backend to angular frontend. Plot is working correctly, but i have problem with data frame. In browser console i have no notifications about this endpoint. import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map, tap } from 'rxjs/operators'; @Component({ selector: 'app-entry', templateUrl: './entry.component.html', styleUrls: ['./entry.component.scss'] }) export class EntryComponent { title = 'FRS'; imgsrc = ''; pandas = ''; resavg = ''; constructor(private http: HttpClient) { } getDF(){ this.http.get('/getdata').pipe(map(r => r.toString()), tap(v => this.pandas = v)); } getimage(){ this.imgsrc = '/getimg'; } } -
how to change status by a link or a button in django
So I want to make a link or a button that should be able to change status from 1 to 0 in the database actually I have the link like this <a href="{% url 'articles:delete' slug=article.slug %}" class="btn btn-danger mr-1 float-left">Delete</a> and in url.py path('delete-article/<slug:slug>/', views.delete_article, name='delete'), now I want to make a function in views.py that change the status to 0 whenever the link is clicked -
NoReverseMatch at /questions/4/detail
I don't know why but when I click on a question's "more", I get this error: Reverse for 'category_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P[0-9]+)/questions$'] what does it have to do with category_detail?! I'm trying to access questions:quesiton_detail not questions:category_detail !! views.py from django.shortcuts import render, get_object_or_404, redirect from questions.models import Question,Category from questions.forms import QuestionForm from django.views.generic import TemplateView, ListView, DetailView, CreateView from django.urls import reverse_lazy class HomeTemplateView(TemplateView): template_name = 'questions/index.html' class AboutTemplateView(TemplateView): template_name = 'questions/about.html' class QuestionListView(ListView): model = Question template_name = 'questions/posts/allPosts.html' class QuestionDetailView(DetailView): model = Question template_name = 'questions/posts/detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.object.num_of_views += 1 self.object.save() self.object.refresh_from_db() return context class QuestionCreateView(CreateView): model = Question form_class = QuestionForm template_name = 'questions/posts/add_question.html' success_url = reverse_lazy('questions:all_questions') def get(self, request): question_form = QuestionForm() return render(request,'questions/posts/add_question.html', {'form': question_form}) def post(self, request): question_form = QuestionForm(request.POST) if question_form.is_valid(): cleaned_data = question_form.cleaned_data current_user = request.user question = Question(title=cleaned_data['title'], text=cleaned_data['text'], category=cleaned_data['category'], user=current_user) question.save() return redirect('questions:all_questions') class CategoryQuestionsDetailView(DetailView): model = Category template_name = 'questions/categories/category_questions.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # context['category'] = Category.objects.get(id=pk) context['cat_ques'] = context['category'].category_questions.all() context['questions'] = Question.objects.all() return context questions/urls.py from django.urls import path from questions import views app_name = 'questions' urlpatterns = [ path('', views.HomeTemplateView.as_view(), name='home'), … -
How to query and return list of dates that aren't present in Django Model table?
I have a query, FinalizedSalesReportObject.objects.filter(created__gte=datetime.now()-timedelta(days=7)).extra({'day':"date(created)"}).values('day').annotate(count=Sum('total')) on my model which has total = DecimalField() and created=DateTimeField() Currently, it returns <QuerySet [{'day': '2020-12-22', 'count': Decimal('148.980000000000')}, {'day': '2020-12-25', 'count': Decimal('54.3600000000000')}]> I would like to have all 7 days from 7 days ago until now returned in this, but am not sure if that's going to be possible using just a query. I can implement a function to populate the missing data, but am having trouble figuring out the best way to do this as well. -
django_neomodel can't find attribute MAX_POOL_SIZE
I am trying to set my first Django project using neo4j as database and neomodel as OGM, so I am following this directions. Nevertheless, when a try to start Django server, I get this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python@3.8/3.8.6_2/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.8/3.8.6_2/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django_neomodel/apps.py", line 20, in ready self.read_settings() File "/Users/hugovillalobos/Documents/Code/attractoraproject/attractora_backend/AttractoraVenv/lib/python3.8/site-packages/django_neomodel/apps.py", line 17, in read_settings config.MAX_POOL_SIZE = getattr(settings, 'NEOMODEL_MAX_POOL_SIZE', config.MAX_POOL_SIZE) AttributeError: module 'neomodel.config' has no attribute 'MAX_POOL_SIZE' I am using python 3.7 and Django 3.1.4. -
Django models NameERROR in the same file?
good day to everyone, i had the name error in this code, someone can explain me why, please??? category = models.ManyToManyField(Category) NameError: name 'Category' is not defined from django.db import models from datetime import datetime # Create your models here. class Store(models.Model): bussines_name = models.CharField(max_length=100, null=False, verbose_name='Nombre') nit = models.PositiveIntegerField(null=False,default=0,verbose_name='NIT') category = models.ManyToManyField(Category) def __str__(self): return self.bussines_name class Meta: db_table = 'Store' verbose_name = 'Tienda' verbose_name_plural = 'Tiendas' ordering = ['id'] class Category(models.Model): name = models.CharField(max_length=150, verbose_name='Name') def __str__(self): return self.name class Meta: verbose_name = 'Categoria' verbose_name_plural = 'Categorias' ordering = ['id'] thanks for your comments -
Gunicorn service not starting EXEC 203
I am trying to start gunicorn service. My gunicorn configuration file is the following: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=root WorkingDirectory=/var/www/www.techsoftconsulting.mx/app/ ExecStart=/var/www/www.techsoftconsulting.mx/techsoftenv/bin/gunicorn --workers 3 --bind unix:/var/www/www.techsoftc$ [Install] WantedBy=multi-user.target The working directory I am working is owned by user root and group root When I run systemctl start gunicorn and then systemctl status gunicorn I see the following: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Fri 2020-12-25 20:54:10 UTC; 15min ago Process: 803756 ExecStart=/var/www/www.techsoftconsulting.mx/techsoftenv/bin/gunicorn --workers 3 --bind unix:/var> Main PID: 803756 (code=exited, status=203/EXEC) Dec 25 20:54:10 48B23E4 systemd[1]: Started gunicorn daemon. Dec 25 20:54:10 48B23E4 systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Dec 25 20:54:10 48B23E4 systemd[1]: gunicorn.service: Failed with result 'exit-code'. -
Running untrusted code (Python-as-a-Service)
I would like to create a simple Python-as-a-Service service. This means the python code which executes the first http request does not trust the python code which executes the second http request. But both should be executed in the same interpreter to avoid constant starting/stopping of the interpreter. How could I clean up after the first http request was run and before the second http request gets executed. I would like to use Django for this, but AFAIK this does not matter much for the current question.