Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is this the best way to trigger a django background task?
I have a background task which will countinuously add data to a DB every second. This is my views.py file. tasks is the method that triggers the start of the background task, after receiving a POST request. from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from logging import getLogger from .tasks import stream_data logger = getLogger(__name__) @csrf_exempt def tasks(request): if request.method == 'POST': return _post_tasks(request) else: return JsonResponse({}, status=405) def _post_tasks(request): message = request.POST['message'] # Call every second stream_data(repeat=1, repeat_until=None) return JsonResponse({}, status=302) And this is my tasks.py file: from background_task import background from logging import getLogger from .models import DbData from datetime import datetime import random logger = getLogger(__name__) @background(schedule=1) def stream_data(): time = datetime.now() value = random.uniform(0, 1) d = DbData(time=time, type='F', value=value) d.save() logger.debug('Added TIME:{} ; VALUE:{}'.format(time, value)) To trigger it, I just run this from the cmd line: curl -d message='' http://localhost:8000/data/tasks/ which triggers the tasks function from views.py. Do I actually need to trigger it this way, or is there any way for me to just run the background task as soon as I run python manage.py runserver Also, I'm seeing in the documentation https://django-background-tasks.readthedocs.io/en/latest/ the parameter MAX_RUN_TIME which I'm not … -
django urls.py: two modules with similar paths
I have two modules in my django app, let's say cats and dogs, and I want to have urls like this: /fluffy/meow.html - Fluffy is a cat's name /fluffy/eat.html /jackie/bark.html - Jackie is a dog /jackie/eat.html - same name as in cats module There will be a lot of different cats and dogs, but it's guaranteed, that cat and dog can't have the same name. If I make urls.py like this: urlpatterns += [ path('<slug:cat_name>/', include('cats.urls')), path('<slug:dog_name>/', include('dogs.urls')), ] request /jackie/eat.html wil be caught by cats module, but there's no cat with name jackie, so it will give 404 error. Is it possible to make django check another url path instead of getting 404 error? -
Django Allauth - How to hook to custom signals?
I am utilizing Django All Auth for my applications user management. I want to add some custom logic for after an email has been confirmed. I found these in the docs/library (Page 50). There are several signals emitted during authentication flows. You can hook to them for your own needs. • allauth.account.signals.email_confirmed(request, email_address) Sent after the email address in the db was updated and set to confirmed. And inside their signals.py file: email_confirmed = Signal(providing_args=["request", "email_address"]) I created my own signals.py file and added the following code: from allauth.account.signals import email_confirmed from django.dispatch import receiver @receiver(email_confirmed) def custom_logic(sender, **kwargs): a = 0 import ipdb; ipdb.set_trace() if a: pass But when I register an account, and follow the URL to confirm the email, my debugger statement is not being triggered (Note, I am using Debug=True and following the URL from my console, I am not sure if this changes things). Am I connecting to the signal correctly? How would I go about testing this out? -
Create a logging system to log user activity in Django
I would like to have a functionality to log a user activities after they have been logged into my Django app. The log will consist of user tracking details such as how long a user spent on a webpage, how often the webpage is being served up for the user. Mainly getting details on how popular a certain webpage or data in my Django app so that I could create more content that users prefer. Any ideas or tools to implement this? -
Razorpay accessing callback URL using GET method instead of POST
I have implemented the Razorpay payment gateway to my platform according to the documentation. As per the documentation after successful payment, the gateway will try to access the URL using the POST method with the order payment information to process the order on the platform. This is the success page I am seeing after the payment as the account is in test mode. After clicking on the success it is redirecting the callback URL using GET method without any data, so I am not able to process the order at my end. According to the docs, it should access using POST method. Does anyone know in what case the gateway is accessing the callback URL with GET method ? -
How to mock out the form_valid() superclass from a Python unit test?
I have a function within one of my views: def form_valid(self, form): ...some functionality... return super().form_valid(form) And am trying to test some part of the functionality, but would like to mock out the 'form_valid' superclass to prevent it from trying to redirect to the success url. How can I do this? -
I'm trying to make model in django. but error. why?
I'm newbie coder. I'm trying to make model. but when i make superuser, always error appear this is my code. i use abstractbaseuser and create account. my account contain username, userid, company, company_code. not use password. but i don't know how to fix this error bold from django.contrib.auth.models import(BaseUserManager, AbstractBaseUser, PermissionsMixin) from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): def create_account(self, username, userid, company, company_code, password=None): if not username: raise ValueError(_('Users must have an name!')) user = self.model( Name=username, UserId = userid, Company= company, Code = company_code, ) user.set_password(password) user.save(self._db) return user def create_superuser(self, username, userid, company, company_code, password): user = self.create_user( Name=username, UserId = userid, Company = company, Code = company_code, password=password, ) user.Name = True user.is_superuser = True user.is_admin = True user.is_staff = True user.save(self._db) return user class User(AbstractBaseUser): Name = models.CharField(max_length=10, unique=True) UserId = models.CharField(max_length=100, unique=True) Company = models.CharField(max_length=10) Code = models.CharField(max_length=100) Created_date = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) class Meta: db_table = 'user' objects = UserManager() USERNAME_FIELD = 'Name' REQUIRED_FIELDS = ['UserId', 'Company', 'Code'] def __str__(self): return self.Name def get_full_name(self): return self.Name def get_short_name(self): return self.Name @property def is_staff(self): "Is the user a member of staff?" … -
password reset error in django 3.0 and up
i am facing issue to to send email link to reset password kindly refer my code and and guide us setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mygmailid@gmail.com' EMAIL_HOST_PASSWORD = 'mygmailpassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'TestG2 Team <noreply@TestG2.com>' urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static # for social login from django.contrib.auth import views as auth_views urlpatterns = [ path('', include('pages.urls')), path('admin/', admin.site.urls), # here using authentication app contain views &urls we use in i.e login and logout page # and create registration folder in path('', include('django.contrib.auth.urls')), # url(r'^login/$', auth_views.login, name='login'), # url(r'^logout/$', auth_views.logout, name='logout'), path('oauth/', include('social_django.urls', namespace='social')), # path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), # path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), # path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), # path('reset_password_complete/', auth_views.PasswordResetConfirmView.as_view(), name="Password_reset_confirm"), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # customizing admin text admin.site.site_header = 'ContactApp' admin.site.index_title = "Control Panel" admin.site.site_title = 'Admin Area' i have created registration folder inside i have added code for each and every page page is displaying content properly also everything is running normal but noly problem is it is not sending email to my gmail as per the configuration for reset password, please guide … -
How to change this create view to handle multiple forms in django
hey guys how to change this create view to handle and save multiple forms in django. please have a look at this code. this has 2 forms and how to connect the 2 forms while creating the post? views class CreateVideoPostView(LoginRequiredMixin, BSModalCreateView): def get(self, *args, **kwargs): form = VideoPostForm() v_form = VideoFileForm() context = { 'form':form, 'v_form':v_form, } return render(self.request, 'videos/video/create_video.html', context) def post(self, *args, **kwargs): form = VideoPostForm(self.request.POST or None) v_form = VideoFileForm(self.request.POST or None, self.request.FILES or None) if form.is_valid() and v_form.is_valid(): videopost = form.save(commit=False) videofile = VideoFile(videopost=videopost) videopost.user = self.request.user videopost.save() videofile.save() form.save_m2m() return redirect('videos:my_video_home') else: raise ValidationError('Check all the formfields') forms class VideoFileForm(forms.ModelForm): class Meta: model = VideoFile fields = ['video',] class VideoPostForm(forms.ModelForm): class Meta: model = VideoPost fields = ['title', 'tags',] -
What type of Authentication System does Django use out of the box?
What type of Authentication System does Django use out of the box? Looks to me like Session Based Authentication? -
Deployed Django - project static files css only working for some
I have a question regarding Django's handling of static files. I deployed a Django project on Heroku and use following Procfile web: python3 manage.py collectstatic --noinput; gunicorn testapp.wsgi --log-file - I have a list of different css files which all worked for one html template (applies the style changes). Now I added a second html template which uses the same css files. However, for this file only some css files are discovered while others are completely ignored. For example (one working while the other doesn't) href="/static/css/sidesection.dd3c29e22478.css" --> applies the style changes href="/static/css/checker.5ffe0baa6d94.css" --> does not apply the style changes Does someone have experience regarding this matter and could eventually also provide an explanation? This issue is not the more common issue where the static files do not load at all. It loads all of them for one html but not all for another. -
how to integrate Stripe in my web app without creating products on Stripe dashboard
I have a web app (Angular 8, Django 3) that allows one set of users to create products with whatever price they seem fit. And a second set of users that is going to load these products into the cart and purchase them. All I want Stripe to do is process the card payment for a certain amount (determined by my backend/server side). On the Stripe website it says I have to create products and prices in the "Accepting One Time Payment" section (https://stripe.com/docs/payments/checkout/accept-a-payment). I dont want to do this. I just want to process a payment for an amount that I determine. From the Stripe documentation it says to create a checkout session: const stripe = require('stripe')('sk_test_UO9wbdk2YOZaQK9dDubCYwSO00RIV3STO8'); const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items: [{ price: '{{PRICE_ID}}', quantity: 1, }], mode: 'payment', success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url: 'https://example.com/cancel', }); Could i just change the line_items object to have a price that is what I determined on my server and a quantity of 1 to get around this? -
Changing image in django user change form
I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed. This is my USER CREATION FORM: class SignUpForm(UserCreationForm): photo = forms.ImageField(required=False) bio = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'})) designation = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'})) university = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'})) company_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"})) grad_year = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'})) phone = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'})) address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'})) city = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'})) company_category = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's category"})) company_desc = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"})) company_site = forms.CharField() no_employees = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'})) technologies = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'})) markets = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'})) linkedin = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'})) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) del self.fields['password2'] for fieldname in ['password1']: self.fields[fieldname].help_text = None self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'}) self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'}) self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'}) self.fields['company_site'].widget.attrs.update({'placeholder': "Enter … -
Django - VueJS - Can't be null
i work on a project with Django and VueJs. I have a problem with a field can't be null but i don't understand why. models.py from django.db import models from django.conf import settings class Tache(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) echeance = models.DateTimeField(null=True, blank=True) titre = models.CharField(max_length=240) sous_titre = models.CharField(max_length=240, null=True, blank=True) content = models.CharField(max_length=240) fait = models.BooleanField(default=False) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="taches") def __str__(self): return self.content serializers.py from rest_framework import serializers from taches.models import Tache class TacheSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) created_at = serializers.SerializerMethodField(read_only=True) # echeance = serializers.SerializerMethodField() echeance = serializers.DateTimeField(format = "%Y-%m-%dT%H:%M:%S") slug = serializers.SlugField(read_only=True) class Meta: model = Tache exclude = ["updated_at"] def get_created_at(self, instance): return instance.created_at.strftime("%d" + "/" + "%m" + "/" + "%Y") # def get_echeance(self, instance): # if instance.echeance != None: # return instance.echeance.strftime("%Y-%m-%dT%H:%M:%S") My problem "field can't be null are on "echeance" field. You can see i have 4 lines in comments because => don't work so i do that : echeance = serializers.DateTimeField(format = "%Y-%m-%dT%H:%M:%S") I think my problem come here... Do you have any idea why "echeance" can't be null...? Thank's -
I have a problem with the django authenticate function
When I input the same username and password as in the database it shows "invalid credentials" instead of "Success". def login(request): if request.method == 'POST': username = request.POST.get('user') password1 = request.POST.get('password1') a = authenticate( username=username, password=password1) if a is not None: return HttpResponse("Success") else: return HttpResponse("Invalid Credentials") return render(request, 'login.html') -
Confusion while using the django-celery-beat to perform some task periodically?
I am learning how to implement celery in django. I want to use the custom scheduler classes to schedule the task from the database so I used the django-celery-beat. But for this I am not using schedular from the database just to check whether it works or not since it is my first time with celery. I placed the celery.py , init.py , tasks.py files as in the django-celery-beat documentation. But I got no idea how to write the tasks and the views. For example I want to create task object in the database every 1 minute so I wrote the views for this with some django logic and I implemented scheduler like this but it is not working. In the console it is throwing this error. celery.beat.SchedulingError: Couldn't apply scheduled task run_every_1_minutes: add_task() missing 1 required positional argument: 'request' What would be the right approach in this example i.e. to create the task object every 1 minute ?How can I write views.py and tasks.py file for this? celery.py inside settings directory from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_demo.settings') … -
Get the length of messages storage Django
I am using messages framework of django (https://docs.djangoproject.com/en/3.0/ref/contrib/messages/) When a user register, i do some check and add messages error to my storage : messages.error(request, gettext("username_already_exists")) In my code i would like to know the length of messages.error, like that i can check if there is error or not in my form. I tried this : if len(messages.error) <= 0: User.objects.create_user( username, email, password, ) But i can't because message 'object of type 'module' has no len()' Do you know a way to check if there is messages errors stored in the messages Framework please ? Thank you ! -
Convert Sql query (Many to Many) to Django ORM query
Please let me know, Is it possible to convert the following query to Django query (Without using raw). SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined", "chat_roomdetails_participants"."user_id", "chat_roomdetails_participants"."id", "chat_roomdetails_participants"."roomdetails_id" FROM "auth_user" LEFT JOIN "chat_roomdetails_participants" ON ("chat_roomdetails_participants"."user_id" = "auth_user"."id") INNER JOIN "chat_roomdetails" ON ("chat_roomdetails"."id" = "chat_roomdetails_participants"."roomdetails_id") INNER JOIN "chat_roomdetails_participants" AS ROOM ON (ROOM."roomdetails_id" = "chat_roomdetails"."id" AND ROOM."user_id" = {LOGIN_USER_ID}) WHERE "auth_user"."is_superuser" = false GROUP BY ("auth_user"."id"); Here is my RoomDetails model: class RoomDetails(models.Model): room = models.CharField(max_length=8, unique=True, null=False, blank=False, verbose_name="Room unique name (Randomly generate)") room_name = models.CharField(max_length=50, blank=False, null=False) room_type = models.IntegerField(choices=RoomType, default=RoomType[0][0]) participants = models.ManyToManyField(settings.AUTH_USER_MODEL) is_active = models.BooleanField(default=True, verbose_name="Is room Active") created = models.DateTimeField(auto_now_add=True) Requirement: After login, the User can see all the user(Except superuser) with roomdetails (Contain only logged In User's belonging roomdertails, Not all roomdertails). The relation between RoomDetails and User has many-to-many. -
How to show a form and assign values to database in a class based detail view
I have two models.Article model and Comment model.I use detail view for a particular article details.I want to add comments on that detail classBased view using form_class.But I can not assign foreign key instance.It gives Comment.post" must be a "Article" instance error. class Article(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) details = RichTextUploadingField() #details = RichTextField() title_image = models.ImageField(default='default_title.jpg', upload_to='Article_heading_pics') publish_date = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User,related_name="likes", blank=True) def __str__(self): return self.user.username def total_likes(self): return self.likes.count() class Meta: ordering = ['-publish_date'] COMMENT MODEL class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Article, on_delete=models.CASCADE) cmnt = models.CharField(max_length=400) cmnt_date = models.DateTimeField(auto_now=True) def __str__(self): return '{}--{}'.format(self.post.title, str(self.user.username)) class Meta: ordering = ['-cmnt_date'] Detail view class ArticleDetailView(ModelFormMixin,DetailView): context_object_name = 'article_detail' model = models.Article template_name = 'blogs/detail.html' form_class = CommentForm def get_context_data(self, **kwargs): context = super(ArticleDetailView, self).get_context_data(**kwargs) comments = Comment.objects.filter(post=self.kwargs['pk']) total_cmnt = comments.count() context['comments'] = comments context['total_cmnt'] = total_cmnt context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): cmnt = self.request.POST.get('cmnt') comment = Comment.objects.create(post=self.kwargs['pk'],user=request.user,cmnt=cmnt) comment.save() messages.success(request, 'your cmnt is posted successfully') return HttpResponseRedirect(reverse('blogs:detail', args=[self.kwargs['pk']])) It gives Comment.post" must be a "Article" instance error. -
How to test django app without giving an app_name
My project structure looks like this: backend/src/apps/app_name/tests/foo.py and when I'm trying to run the tests by entering a command python manage.py test it runs 0 tests. The only correct way to test is python manage.py test src.apps.app_name but I'm to lazy to do it with every app. 😄 -
Login Required decorator not redirecting to login url | Django
@login_required decorator not redirecting me to logging page When I click the add to cart button it doesn't redirect me to the login page. It just doesn't do anything. I tried the login required decorator in another function. Like the home view action. And when I try to access the home page it directly redirects me to the login page. But in the combo_add_to_cart it doesn't seems to work. But I have found something in the terminal. I have seen that when I click the add to cart button it first sends a post request of "POST /carts/cart/combo/add-to-cart/ " then it sends a get request "GET /accounts/login/?next=/carts/cart/combo/add-to-cart/". accounts views.py class Login(FormView): form_class = LoginForm success_url = '/' template_name = 'accounts/login.html' def form_valid(self, form): request = self.request next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("/") return super(Login, self).form_invalid(form) cart views.py @login_required(login_url='/accounts/login/') def combo_add_to_cart(request): combo_id = request.POST.get('combo_id') if combo_id is not None: try: combo_obj = Combo.objects.get(id=combo_id) except Combo.DoesNotExist: return("carts:cart") combo = combo_obj cart_item, created = ComboCartItem.objects.get_or_create( combo=combo, user=request.user, ordered=False ) cart_obj, … -
How to create a custom queryset from a json file
Is it somehow possible to create a custom queryset from a given json file? I have the json file and I want the queryset in order to use the queryset for presentation with django_tables2 and filtering with django_filters. The key point is that I do not have any model and I do not want to create a model with the data from json. I just want to create the queryset. existence = 1 try: offer_request = requests.get(url, headers=headers) existence = 2 except: print("nothing") if existence == 2: offers=json.loads(offer_request.text) The offers variable contains my json. -
Angular loading files from backend using the wrong port
My Angular frontend application is using default port 4200. My Django backend application is running on port 8000. Frontend can upload files and images to backend, a then get their links to show on page. Uploading is working fine, but then when I try to get images from backend, Angular is downloading them from frontend port 4200 and all views are breaking, because there is no such files on that path. Briefly, I need file path in that way - http://localhost:8000/media/uploads/myfile, but I get http://localhost:4200/media/uploads/myfile. I use proxy to get backend api: { "/api": { "target": "http://localhost:8000", "secure": false } } I do not know where the problem may be. -
django allauth custom signup form not rendering
Background I have two types of users, buyers & sellers, mapped to an extended AbstractUser via a OneToOneField. I want to request different information from them upon sign up, so I extended the allauth SignupForm as described in this helpful post. I have two routes, accounts/signup/user and accounts/signup/seller, which links to the BuyerSignupView and SellerSignupView respectively. The two views extend the allauth SignupView but instead renders custom templates that use my custom forms. Problem The forms aren't rendering at all on the webpage. Clicking inspect on the web shows no html tags related to the form, but calling form.as_p() in the python shell correctly converts my form to its corresponding html components. # view.py class UserSignupView(SignupView): template_name = "accounts/user_signup.html" form_class = UserSignupForm class SellerSignupView(SignupView): template_name = "accounts/seller_signup.html" form_class = SellerSignupForm # forms.py class UserSignupForm(SignupForm): GENDER_CHOICES = [("F", "Female"), ("M", "Male"), ("O", "Other")] AGE_CHOICES = [ ("A", "18-"), ("B", "18-25"), ("C", "25-35"), ("D", "35-45"), ("E", "45+"), ] first_name = forms.CharField(max_length=30, label="First Name") last_name = forms.CharField(max_length=30, label="Last Name") gender = forms.ChoiceField(choices=GENDER_CHOICES, required=False, label="Gender") age = forms.ChoiceField(choices=AGE_CHOICES, required=False, label="Age") phonenumber = PhoneNumberField() def signup(self, request, user): user.first_name = self.cleaned_data["first_name"] user.last_name = self.cleaned_data["last_name"] user.save() new_profile = Profile( user=user, # TODO - add followed_tags = … -
How to run a python script in django server using a button
I want to run my script (makes changes to my database and creates users on another website using an API) whenever a user presses the button on my website. So far i have tried these solutions but they are not working for me. How can i trigger a Python script in background from HTML tag button, in Django? Run python script in Django website when clicking on button submit