Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why are we inheriting object in this django class?
class Cart(object): def __init__(self,request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart` -
My Django URL tags remove a portion of the desired link only when in production
I have been struggling with an issue that affects the Django {%url%} tags when I deploy my app to my GoDaddy hosted website. My app works 100% fine on my local machine. The link when viewed in the 'view source code' seems to be missing the LAST character of the url. For example: I need the link to be '/dreamstream/similar-result/name' however, the link is made to be '/dreamstrea/similar-results/name' *missing the 'm' in dreamstream. So far I have tried modifying the Django Root details in the settings.py without any success. settings.py import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My apps 'search_dreamstream', 'user_dreamstream' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'proj_dreamstream.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'proj_dreamstream.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { … -
Django converting table to a pdf file takes too much time using weasyprint
I have a table with 7000 rows and 10 columns and it is expected to grow further. Creating a csv and xls file has immediate response. While rendering a pdf file with WeasyPrint takes too much time like 20s. Is there any way to improve the response time? By the way I am using server-side processing to show data to the user. -
How to fetch data from API and save into data base in rest framework in Django?
How to fetch data from API and save it to the database as given below code in rest framework in Django? if user is None: URL = "http://172.31.0.3:8000/studentapi/" URLDATAS = "https://reqres.in/api/users?id=2" data1 = {} if uname is not None: data1 = {'id':uname} json_data = json.dumps(data1) headers = {'content-Type':'application/json'} r_get = requests.get(url = URLDATAS, headers=headers, data = json_data) data = r_get.json() r_post = requests.post(url = URL, headers=headers, data = data) -
why django don`t work on domain? but work on server ip address
i have buyed domen example.ru and server ip adress 111.11.1.11 when i visit 111.11.1.11 my home page loads and works fine but when i visit example.ru my home page doesn't work oh, and the main, when i visit example.ru/auth/login the page loads fine that is, when I load a link with a directory, everything works, but the main domain address does not want to load my nginx site file: server { listen 80; server_name justdo-fulfillment.localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /opt/justdo_full_site; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
I keep getting the error name 'Blog_Post' is not defined
I am makeing a blog and the blog has a delete button. hen ever you click the button you are, spouse, to get taken back to the home page but you get this error name 'Blog_Post' is not defined. Ant help would be appreciated. views.py from django.shortcuts import render, redirect from django.views import generic from . import models from django.contrib.auth import get_user_model User = get_user_model() from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin class create_blog_post(generic.CreateView): model = models.Blog_Post template_name = 'blog_app/creat_post.html' fields = ('post_title', 'blog_content') success_url = reverse_lazy('blog_app:all') class view_blog_post(generic.DetailView): model = models.Blog_Post template_name = 'blog_app/view_post.html' def delet_blog_post(request, id): blog_post = Blog_Post.objects.get(id=blog_post_id) blog_post.delete() return redirect("/") class all_blog_posts(generic.ListView): model = models.Blog_Post template_name = 'blog_app/all_posts.html' #slug_url_kwarg = "slug" -
Populating choices from another Models objects
Quick question, I can not for the life of me figure out how to get this to work and need some help. Problem I need to be able to query another model's objects to use for choices in a different model. I was thinking about a foreign key but I really do not need it to extend the other model. I have a group called Group that will display choices from another model called Games. These objects will already be saved in the database. I just can't figure out how to display the choices. Models.py for the Model we are trying to display the choice in game is the field we want the choices from the Games model from django.db.models.aggregates import Max from games.models import Games # Create your models here. class Group(models.Model): name = models.CharField(max_length=200) game = models.ForeignKey(Games, on_delete=models.CASCADE) size = models.IntegerField() total_size = models.CharField(max_length=200) play_time = models.DateTimeField() description = models.TextField(max_length=200) roles = models.CharField(max_length=200) is_full = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return self.name Models.py from the Model we want to generate the choices from I want to use the name field from this model for the choices on the Group game field. from django.db import models from django.db.models.aggregates … -
How to avoid classmethod side effect using celery
I am running a class based app using celery, but I am noting that when two processes run simultaneously, certain staticmethods in the class are not acting independently. Here is the app invocation: import os from PriceOptimization.celery import app from .Tasks_Sim.sim import Sim, final_report @app.task(name='Simulations.tasks.scoring') def simulation(clients, deciles): s = Sim(**sim_params) market_by_year = s.control_flow(my_save_path) report = final_report(market_by_year) return report Within my Sim app, I have a class method that creates id's for my instance as follows: class Company: company_id = 0 @classmethod def set_company_no(cls): cls.company_id += 1 return cls.company_id-1 def __init__(self, companies, year): self._company_id = Company.set_company_no() self._company_year = year Usually the first task instantiated will complete successfully, but on the next invocation, I am getting a "list index out of range error" that suggests to me that my workers are not indepedent and that my company_id object is not commencing from zero with the next invocation. How can I prevent this side effect and have each app run independently? -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' in terminal
I made a change to my models added a foreign key and added a many to many field. I am now getting this error when I try to save an object to my form: TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' My models were working and creating objects before I updated and applied migrations. I have tried to look through similar issues but don't see anything that closely matches the error I see. Can anyone help? here are my files. // views.py def createTrip(request): trip_creator = User.objects.get(id = request.session['loggedInID']) newTrip = Trip.objects.create( city = request.POST['city'], country = request.POST['country'], description = request.POST['description'], creator = trip_creator, # photo = request.POST['photo'] ) print(newTrip) return redirect('/home') // models.py class Trip(models.Model): city = models.CharField(max_length= 255) country = models.CharField(max_length= 255) description = models.CharField(max_length= 255) creator = models.ForeignKey(User, related_name = 'trips_uploaded',on_delete= CASCADE) favoriter = models.ManyToManyField(User, related_name= 'fav_trips') photo = models.ImageField(upload_to='static/img/trips') -
How to use django-autocomplete-light inside a table row?
I'm trying to use django-autocomplete-light forms inside a table row. More specifically, I'm using the boiler plate code from App-Seed. This is an AJAX datatable, here's the code to where they create the inline forms: https://github.com/app-generator/boilerplate-code-django-dashboard/blob/master/apps/templates/transactions/edit_row.html I can create an autocomplete form outside of the table with no problem. However, if I try to put that same form inside the table, the selection values aren't updating properly. I'm guessing this has to do with the rows being generated dynamically, but I don't know how I can fix this. I'm using django-autocomplete-light 3.9.4 and the most recent version of boilerplate-code-django-dashboard. Are any considerations to using django-autocomplete-light with datatable rows generated from AJAX? -
Django rest framework: How to add authorization header in the url endpoint?
New to django rest framework here and I'm trying to add the header that contains Authorization Token into the url including the query string params. I got it to work perfectly in POSTMAN (see below), but not in the browser. How do I do this to work the browser's url or even in the CLI using $ curl? In Postman: it works perfectly In the browser: Not working I tried something like this: http://localhost:8000/api/scraped-items/?webproviders=available&domains=all Authorization=Token f4b2d04a39d6fe6e4a7e04d444924daaefa33497 http://localhost:8000/api/scraped-items/?webproviders=available&domains=all access-token=f4b2d04a39d6fe6e4a7e04d444924daaefa33497 In CLI using $ curl: Not working either Also, I'm also trying to test it in the cli using $ curl. I can't get to work either. In the offical doc, there's no example using query string params $ curl -X GET http://localhost:8000/api/scraped-items/?webproviders=available&domains=all -H 'Authorization: Token f4b2d04a39d6fe6e4a7e04d444924daaefa33497' -
How to stop objects (posts) from overlapping each other
I am trying to create the landing page of a blog, however, posts keep on overlapping with other content. How can I stop these objects from overlapping each other? I have attached an image of how the frontend looks like for better understanding. This is how the frontend looks like Here is my index.html <style> .headslider{ background-image: url("{% static 'assets/img/post-slide-1.jpg' %}"); } .postslide{ background-image: url("{% static 'assets/img/post-slide-2.jpg' %}"); } .postslide1{ background-image: url("{% static 'assets/img/post-slide-3.jpg' %}"); } .postslide2{ background-image: url("{% static 'assets/img/post-slide-4.jpg' %}"); } .box{ width: 250px; height: 200px; margin:20px; padding: 20px; } </style> </head> <!-- ======Some sections skipped====== --> <!-- ======= Post Grid Section ======= --> <section id="posts" class="posts"> <div class="container" data-aos="fade-up"> <div class="row gx-5"> {% for post in posts %} <div class="post-entry-1 col-lg-3 box mx-1"> <a href="single-post.html w-300 h-200"><img src="{{post.image.url}}"></a> <div> <div class="post-meta"><span class="date">Culture</span> <span class="mx-1">&bullet;</span> <span>{{post.created_at}}</span></div> <h2><a href="">{{post.title}}</a></h2> </div> <p class="mb-4 d-block">{{post.body|truncatewords:20}}</p> <div class="d-flex align-items-center author"> <div class="photo"><img src="{% static 'assets/img/person-1.jpg' %}" alt="" class="img-fluid"></div> <div class="name"> <h3 class="m-0 p-0">OlePundit</h3> </div> </div> </div> {% endfor %} <br> <!-- Trending Section --> <div class="col-lg-3 mx-10 pl-10"> <div class="trending"> <h3>Trending</h3> <ul class="trending-post"> <li> <a href="single-post.html"> <span class="number">1</span> <h3>The Best Homemade Masks for Face (keep the Pimples Away)</h3> <span class="author">Jane Cooper</span> </a> … -
Rendering multiple matplotlib plots in my Django view using BytesIO
I'm struggling with rendering multiple matplotlib plots in my Django View. When doing it with one plot, it works fine, but as soon as i try adding more than one plot in my view, the second plot doesn't render correctly. I'm quite sure it has something to do with how i'm using BytesIO(). In my HTML, when commenting out the Portfolio construction plot part (first plot), the Efficient frontier plot renders perfectly (second plot). So it's definitely the portfolio plot that comes first that messes up the efficient frontier one, but why? from re import search from sys import set_coroutine_origin_tracking_depth from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, render from django.db.models import Q from datetime import datetime, date from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from io import BytesIO import base64 import pandas as pd import seaborn as sns from matplotlib.pyplot import figure from matplotlib import pyplot as plt sns.set() import os import riskfolio as rp from .forms import UploadFileForm def index(request): data_path = format(os.getcwd()) + "/app/data/" df = pd.read_csv(data_path + "portfolio_data.csv", sep=";", decimal=",") df['Date'] = pd.to_datetime(df['Date'], infer_datetime_format=True) df.set_index('Date', inplace=True) df = df.sort_values(by="Date", ascending=True) for column in df: df.insert(loc=df.columns.get_loc(column)+1,column= column + " Returns", value=df[column].pct_change()) returns_columns = [x for … -
Django, when i change the name of my pizza_type view function to something else it starts working, why. Im new here please be nice
My code here says that pizza_type or anything with pizza is not a valid view function and i don't understand why. <p> <a href="{% url 'pizzas:index' %}">Pizzeria</a> - <a href="{% url 'pizzas:pizza_type' %}">Pizzeria</a> </p> {% block content %}{% endblock content %} -
I would like to have my group-list-item div class to have all of the stuff inside inline vertically right now it is listed horizontally like a burger
Hi there creating an application where I can have the the inputs pop up on the bottom when they add them I was just wondering why after I add them the contents in my list group look like it's horizontally flipped, I want it to be vertically inline. Also I tried d-inline in group-list-item it didn't work. html file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" /> <link rel="stylesheet" href="{% static 'habits/styles.css' %} " /> <title>Habit</title> </head> <body class="bg-light"> <!--good--> <div class="container"> <!--good--> <div class="row mt-5"> <!--good--> <div class="col-md-8 offset-md-2"> <!--good--> <div class="card"> <!--good--> <div class="card-header shadow-sm bg-white"> <h1 class="display-5 text-info"> Habits <i class="fa fa-unlock-alt" style="color: red"></i> </h1> <div class="card-body"> <ul class="list-group"> <li class="list-group-item"> <form action="{% url 'insert_habit_item'%}" method="post" autocomplete="off" > {% csrf_token %} <!-- value used by server to make sure if the post or response is from a trusted source or not --> <div class="input-group"> <input type="text" class="form-control" name="habit" /> <div class="input-group-append text-info"> <span class="input-group-text bg-white py-0" ><button type="submit" class="btn btn-sm text-info"> <i class="fa fa-plus-circle fa-lg"></i> </button> </span> </div> </div> </form> </li> {% for habit … -
How to use same serializer class for get and post method in Django?
I have been trying, but fail miserably, to use only a single serializer class for both post and get api call. I have a Person model which has some fields. What I need is I want to create a person object using post API with certain fields and however needs to show some other fields while doing get request. For eg: My model: class Person(models.Model): name = models.CharField(max_length=255,blank=True) email = models.EmailField(unique=True) phone = models.CharField(max_length=16) address = models.CharField(max_length=255,blank=True) roll = models.IntegerField() subject = models.CharField(max_length=255,blank=True) college_name = models.CharField(max_length=255,blank=True) Now my serializer will look like this. class PersonSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ['id','email','name','phone','roll','subject','college_name', 'address'] For eg, I have a view that handles both post and get request (probably using APIView), then what I need to do is, to create a person object I only using name, phone, and email. So for post API call, I only need three fields whereas while calling the get API I only need to display the fields name, roll, subject, and college_name not others. In this situation, how can I handle using the same serializer class?? -
AgoraRTC can't add multiple users in the webpage. can't figure out what went wrong
i was trying to make a streaming website using Agora.io in my JavaScript, i made a player template which will add to my webpage every time a new user enters. the client.on method should detect a new user coming & call back the function which should add the new user to the stream! const APP_ID = "fe45f285661941ada5ef5d451fe8f626" const CHANNEL = "main" const TOKEN = "006fe45f285661941ada5ef5d451fe8f626IABxEPnj4KCl8i4+gcrg2F7Cc+nmjmOiRWq49ICnSOHfdGTNKL8AAAAAEACXVkQu42OcYgEAAQC9Y5xi" const client = AgoraRTC.createClient({mode:"rtc",codec:"vp8"}) let localTracks = [] let remoteUsers = {} let UID let joinAndDisplayLocalStreams = async ()=> { client.on("user-published",handleUserJoined) UID = await client.join(APP_ID,CHANNEL,TOKEN,null) localTracks = await AgoraRTC.createMicrophoneAndCameraTracks() let player = ` <div class="video-container" id="user-container-${UID}"> <div class="name-wrapper"><span class="user-name">My name</span></div> <div class="video-player" id="user-${UID}"></div> </div>` document.getElementById("video-streams").insertAdjacentHTML("beforeend",player) localTracks[1].play(`user-${UID}`) await client.publish([localTracks[0],localTracks[1]]) } let handleUserJoined = async(user,mediaType)=>{ remoteUsers[user.uid]= user await client.subscribe(user,mediaType) console.log(mediaType) if(mediaType==="video"){ let player = document.getElementById(`user-container-${user.uid}`) if(player!=null){ player.remove() } player = `<div class="video-container" id="user-container-${user.uid}"> <div class="name-wrapper"><span class="user-name">My name</span></div> <div class="video-player" id="user-${user.uid}"></div> </div>` document.getElementById("video-streams").insertAdjacentElement("beforeend",player) user.videoTrack.play(`user-${user.uid}`) } if(mediaType==="audio"){ user.audioTrack.play() } } joinAndDisplayLocalStreams() -
Creating a login page without registration
I want to list all my datas in one admin page. But it will be just one username and password. I won't create any registration page. How can I do that?(I'm using Django 1.11) Thanks for your help. -
How do I create a dynamic "About Me" page in Django?
Here, by dynamic I mean, I wouldn't want to update my template in order for me to update changes. I'd want them to edit in the admin page on my production site. At first, I thought I'd create a model for "About Me" itself, but then I'd need to create a model for just one instance. I need help with this, better ways to edit my pages dynamically on the admin site. -
Should i manualy save client ID and client secrets? using django rest framework
This is my first django rest framework project and my question is about manually saving clientID and client secrets vs using a package that automates this. What I am trying to build is something similar to the Spotify developer dashboard. It gives each user the option to create several projects. Once a project is created, the user gets a client ID and a client secret for the project (both are different for each project the user creates). Like in other API dashboards users can generate a new client secret. This is what it looks like: My first shot at solving this topic was to handle all user-level authorization (like browsing through the website using the developer dashboard) with simple-jwt token authorization, which will handle the blacklisting of tokens and many other things itself. But for the project level authorization, I am manually saving a permanent client ID and client secret as UUID to the project model. Here you can see the project model (it extends from a base model which includes a UUID as Primary key + date created + date modified). Blacklisted client secrets will be moved to a custom blacklist model when users want o generate a new … -
I am trying to figure out how to increment and decrement the values with Django but I get this error cannot unpack non-iterable ModelBase object
Hi there I am having an issue incrementing and decrement a value in the views.py file in my application, also I am getting the error of "cannot unpack non-iterable ModelBase object" Everything else works beside the increment and decrement function. As soon as I press the increment or the decrement button it does not work and it spits that error out. Also I will post the view.py file, the html file, and the urls just so there can be more context. the views.py file from django.shortcuts import get_object_or_404, redirect, render from django.http import HttpResponse,HttpRequest from .models import Habit # Create your views here. def list_habit_items(request): context = {'habit_list':Habit.objects.all()} return render(request,'habits/habit_list.html',context) def insert_habit_item(request:HttpRequest): habit=Habit(IndHabit =request.POST['habit']) habit.save() return redirect('/habits/list/') def delete_habit_item(request,habit_id): habit_to_delete = Habit.objects.get(id=habit_id) habit_to_delete.delete() return redirect('/habits/list/') def increment_habit_value(request,habit_id): habit_to_increment = Habit.objects.get(Habit,id=habit_id) habit_to_increment.values += 1 habit_to_increment.save(['values']) return redirect('/habits/list/') def decrement_habit_value(request,habit_id): habit_to_decrement = Habit.objects.get(Habit,id=habit_id) habit_to_decrement.values -= 1 habit_to_decrement.save(['values']) return redirect('/habits/list/') the models class Habit(models.Model): #this makes a attribute that describes the individual Habit #the individual Habit and Value. IndHabit=models.TextField() IndValue=models.IntegerField() the urls.py file from django.urls import path from . import views urlpatterns=[ path('list/',views.list_habit_items), path('insert_habit/',views.insert_habit_item,name='insert_habit_item'), path('delete_habit/<int:habit_id>',views.delete_habit_item,name='delete_habit_item'), path('increment_habit/<int:habit_id>',views.increment_habit_value,name='increment_habit_value'), path('decrement_habit/<int:habit_id>',views.decrement_habit_value,name='decrement_habit_value'), ] the html file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> … -
django.db.utils.ProgrammingError: relation "app_bugs" already exists
After I deleted all the migration files and made them again using "python3 manage.py makemigrations" and "python3 manage.py migrate", the following error occurred: root@chat-manager:/var/www/jinabot# python3 manage.py migrate Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions Running migrations: Applying app.0002_auto_20220604_2133...Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "app_bugs" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/migrate.py", line 246, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/operations/models.py", line 92, in database_forwards schema_editor.create_model(model) File "/usr/local/lib/python3.7/dist-packages/django/db/backends/base/schema.py", line 331, in create_model self.execute(sql, params or None) … -
how to keep loop runnning while user gets redirected back to form after making a post request to start the loop
I have a django app with a view that handles a post request from a user to start an infinite loop. The problem is after succesful post request loop starts and the browser keeps loading waiting for response from the server resulting to timeouts from proxy server handling this request. Is there anyway to start the loop and keep it running while redirecting or giving back response to the browser to prevent timeouts view code below: def ticket_miner(request): mining_urls = credentials.mining_urls if request.method == 'GET': form = forms.UpdateForm() return render(request, 'tickets/mine.html', {'form': form}) else: net_test = network_acess.network_test(urlpaths.net_urls) while net_test: with requests.session() as s: try: print('logging in ....') s.post(login_url, data=payload, headers=headers, timeout=5) r = s.get(success_url, timeout=5) print(r) if r.status_code == 200: print('Logged in successfully') while r: count = 0 for mining_url in mining_urls: r2 = s.get(mining_url, timeout=5) count += 1 response_result = r2 if response_result.status_code == 404: print('TICKET NOT FOUND!') pass else: new_data = response_result.json() miner.ticket_mapper(new_data) print('mining') continue print('mining successfull restarting ...') else: print('Unable to authenticate... redirect detected') except requests.exceptions.ConnectionError as e: print(f'ConnectionError: {e.response} response. No internet connections!!') except requests.exceptions.InvalidURL as e: print(f'InvalidURL: {e.response} response. Incorrect url specified!!') except requests.exceptions.Timeout as e: print(f'ConnectTimeout: {e.response} response. Network interrupt') except requests.exceptions.RequestException as e: … -
Django automated email sending
I am building a multivendor market place using django and I have to send automated emails for two reasons. I have to verify their email each time someone signs up (A verification email will automatically be sent when they completed their form). Automated email is sent to the user when order is ordered. All the above worked fine when I test them, but I used my gmail account for that purpose. I have read that gmail is not the perfect choice for business purposes. Plus there is no online payment system in my country for payed services and all the free options I see can only send very limited emails per day. So should I continue using gmail? Or is there any other system I can use? Thank you in advance! -
How can I utilize the JWT for authintication and authorization in Django
I started learning Django two weeks ago, while I was searching for authentication and authorization in Django I found the following lines for Jason Web Tokens (JWT): project urls.py from django.contrib import admin from django.urls import include, path from rest_framework_simplejwt import views as jwt_views urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/cookie-stand/", include("cookie_stands.urls")), path("api-auth/", include("rest_framework.urls")), path( "api/token/", jwt_views.TokenObtainPairView.as_view(), name="token_obtain_pair", ), path( "api/token/refresh", jwt_views.TokenRefreshView.as_view(), name="token_refresh", ), ] app permission.py from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True if obj.owner is None: return True return obj.owner == request.user My question is: Tokens are usually sent as a header with the request, how does Django do that? I mean for example, how can I use Django and JWT to make an authorized group of users?