Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What do these 3 lines do exactly in django function views?
I am trying to create a simple blog site and in the tutorial, the teacher wrote this function view. I am unable to understand what do these lines do exactly. I have them as comments in the code This is the Function View @login_required def add_comment_to_post(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == "POST": #Below is line no.1 form = CommentForm(request.POST) if form.is_valid(): #Below are lines no.2 & 3 comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail',pk=post.pk) else: form = CommentForm() return render(request,'blog/comment_form.html',{'form':form}) This is my Models.py file from datetime import time from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now()) published_date = models.DateTimeField(blank=True,null=True) def publish(self): self.published_date = timezone.now() self.save() def approved_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post',related_name='comments',on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now()) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse("post_list", kwargs={"pk": self.pk}) def __str__(self): return self.text I have two forms in my forms.py file namely PostForm and CommentForm. -
'str' object has no attribute 'id' django
Am trying to add a package on my django app. I finished all the installation process but ma getting this error which i don't know. I tried entering into the file and modify but i was not luck. here is the error. Am using my own custom user model that's why i am importing accounts.model: AttributeError at /s/about/ 'str' object has no attribute 'id' Request Method: GET Request URL: http://localhost:8000/s/about/ Django Version: 2.2.17 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'id' Exception Location: /home/Comfort_Chambeshi/.local/lib/python3.7/site-packages/djangorave/templatetags/djangorave_tags.py in pay_button_params, line 32 Python Executable: /usr/bin/python3 Python Version: 3.7.3 Python Path: ['/media/Comfort_Chambeshi/Reserved/projects/web/ludocs_emark', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/Comfort_Chambeshi/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sat, 21 Nov 2020 22:40:43 +0000 Error during template rendering In template /home/Comfort_Chambeshi/.local/lib/python3.7/site-packages/djangorave/templates/djangorave/pay_button.html, error at line 13 'str' object has no attribute 'id' 3 <!-- 4 User email is required by Rave, therefore user must be signed in before 5 button will be displayed. 6 --> 7 <script> 8 function createPaymentParams() { 9 // 10 // Create payment params which will be sent to Rave upon payment 11 // 12 {% autoescape off %} 13 let pay_button_params = JSON.parse('{% if user.is_authenticated %}{% pay_button_params user=user payment_type=payment_type %}{% endif %}'); 14 {% endautoescape %} … -
Apache + mod_wsgi + django: send a default response for a backlogged request
I am running a web server using Apache 2.4, mod_wsgi, and Django. The server overloads occasionally due to high traffic. I want to setup the server such that it responds with a pre-determined default response to backlogged requests (i.e., requests that have been waiting in the queue over a certain timeout). What is the best way to do this? Additionally, I want to the keep the connection alive after sending the default response. Any help is much appreciated. -
Django create form field with a model of the current user
I have a simple app, where a user has multiple businesses, and each business has multiple products, what I´m trying to do is a make product creatView, where i can select a business from the ones owned by the current user. I tryed editing the init() method of the ModelForm like this: class Producto_Form(forms.ModelForm): class Meta: model = Producto_Model fields = ("Nombre_Producto","Negocio","Descripcion_Producto",'Precio_Producto','Tags',"Foto") def __init__(self, *args, **kwargs): super(Producto_Form, self).__init__(*args, **kwargs) self.fields['Negocio'].queryset = Negocio_Model.objects.all().filter(Administrador_id=kwargs['user'].id) and then i changed the get_form_kwargs from the create product view like this: class crear_producto(LoginRequiredMixin, CreateView): template_name = "tienda/crear_producto.html" form_class= Producto_Form success_url = reverse_lazy('tienda_app:crear_producto') login_url = reverse_lazy('register_app:logIn') def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs(*args, **kwargs) kwargs['user'] = self.request.user return kwargs I was following this question but I keep getting the error __init__() got an unexpected keyword argument 'user' -
Django webcam threads streaming won't stop
I'm hosting django app where I can see feed from IP cam's. I'm using threads to optimize video processing. To render stream I use StreamingHttpResponse. My biggest problem I'm facing is when user stops viewing the stream, connection from camera won't stop. stop and exit function is not called. How can I fix this? here is my camera class: class VideoCamera(object): """ Class to handle IP cameras with opencv """ def __init__(self, ip): """ Init the camera with provided IP address, /mjpeg stands for url address, which is hosted by ESP camera :param ip: """ self.cam = 'rtsp://' + str(ip) + ':8554/mjpeg/1' self.video = cv2.VideoCapture(self.cam) self.W, self.H = 640, 480 self.video.set(cv2.CAP_PROP_FRAME_WIDTH, self.W) self.video.set(cv2.CAP_PROP_FRAME_HEIGHT, self.H) self.video.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')) self.video.set(cv2.CAP_PROP_BUFFERSIZE, 1) (self.grabbed, self.frame) = self.video.read() self.started = False self.read_lock = Lock() def start(self): if self.started: return None self.started = True self.thread = Thread(target=self.update, args=()) self.thread.deamon = True self.thread.start() return self def update(self): while self.started: (grabbed, frame) = self.video.read() self.read_lock.acquire() self.grabbed, self.frame = grabbed, frame self.read_lock.release() def read(self): self.read_lock.acquire() frame = self.frame.copy() self.read_lock.release() return frame def stop(self): self.started = False self.thread.join() def __exit__(self): self.video.release() and here is my view.py: def index(request): return render(request, 'cameras/home.html') def gen_frame(cap): """ Function for rendering camera … -
How can I do to modify a charfiled to foreign key?
I am trying using django to modify my charfield to a foreign key using : python3 manage.py makemigrations python3 manage.py migrate But when I do python3 manage.py migrate I got django.db.utils.ProgrammingError: ERREUR: the relation « myproject_django » does not exist. I don't want to do python3 manage.py --migrate because I want to do my migrations but I don't know how to do ? Could you help me please ? -
Concurrency issue when processing webhooks
Our application creates/updates database entries based on an external service's webhooks. The webhook sends the external id of the object so that we can fetch more data for processing. The processing of a webhook with roundtrips to get more data is 400-1200ms. Sometimes, multiple hooks for the same object ID are sent within microseconds of each other. Here are timestamps of the most recent occurrence: 2020-11-21 12:42:45.812317+00:00 2020-11-21 20:03:36.881120+00:00 <- 2020-11-21 20:03:36.881119+00:00 <- There can also be other objects sent for processing around this time as well. The issue is that concurrent processing of the two hooks highlighted above will create two new database entries for the same single object. Q: What would be the best way to prevent concurrent processing of the two highlighted entries? What I've Tried: Currently, at the start of an incoming hook, I create a database entry in a Changes table which stores the object ID. Right before processing, the Changes table is checked for entries that were created for this ID within the last 10 seconds; if one is found, it quits to let the other process do the work. In the case above, there were two database entries created, and because they were … -
Could UUID be used as a tracking number that user will use?
I am developing a Reporting system where a user can report another user for a variety of issues. To display the report to the user, I am thinking of doing something like localhost:8000/reports/(UUID from model). Essentially use it as a tracking number that I will be displaying to the user so that they can track their reports. Are there any reasons that I shouldn't do it this way (security? something simpler?) Thanks a lot in advance! -
Django Formset template
Probably easy stuff, I want to display each field from a formset using 2 model, but I can only display the "facture" model which is the parent. I have the issue in my template"facture_form.html", I'm not really confortable with the formset .... Here is my code model.py : from django.db import models from clients.models import Client, Patient from articles.models import Article class Facture(models.Model): Status = ( ('D', 'Devis'), ('F', 'Facture'), ('PA', 'Payement en attente'), ('FC', 'Facture clôturée'), ('NC', 'Note de credit'), ) status = models.CharField(max_length=20, choices=Status, default='Facture', verbose_name='Status') nom_complet = models.CharField(max_length=200, blank=True, verbose_name='Nom') nom_patient = models.CharField(max_length=200, blank=True, verbose_name='Nom patient') class ArticleFac(models.Model): facture = models.ForeignKey(Facture, null=True, on_delete=models.CASCADE, verbose_name='Facture') name_fr = models.CharField(max_length=200, verbose_name='Nom') price_htva = models.IntegerField(default=0, verbose_name='Prix') def __str__(self): return self.name_fr + " " + self.price + " €" forms.py : from .models import ArticleFac, Facture from django.forms.models import inlineformset_factory ArticleFacFormset = inlineformset_factory( Facture, ArticleFac, fields='__all__' ) views.py : from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from .models import ArticleFac, Facture from .forms import ArticleFacFormset class IndexView(generic.ListView): template_name = 'factures/index.html' context_object_name = 'factures' def get_queryset(self): return Facture.objects.order_by('id') class FactureCreateView(generic.CreateView): #auto load facture_form.html model = Facture fields = '__all__' def get_context_data(self, **kwargs): # we need to overwrite get_context_data … -
Django Nginx Apache Reverse Proxy
I have the following nginx config (I use nginx as reverse proxy): server{ listen 443 ssl default_server; listen [::]:443 ssl default_server; listen 80 default_server; listen [::]:80 default_server; server_name _; return 444; } server { listen 443 ssl; listen [::]:443 ssl; listen 80; listen [::]:80; access_log off; error_log off; server_name example.com; return 301 https://www.example.com$request_uri; } server { listen 80; listen [::]:80; access_log off; error_log off; server_name www.example.com; return 301 https://www.example.com$request_uri; } server{ listen 443 ssl; listen [::]:443 ssl;; server_name www.example.com; add_header Strict-Transport-Security "max-age=31536000;"; location ^~ /static/ { alias /static/; autoindex off; expires max; } location ^~ /images/ { alias /public/images/; autoindex off; expires max; } location / { proxy_pass http://127.0.0.1:8080; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 120; proxy_send_timeout 120; proxy_read_timeout 180; } } What I want to do is related to How to disable Django's invalid HTTP_HOST error? In nginx I set to return 444, when the server is not example.com I do the same in apache: <VirtualHost *:8080> <Directory /> SetEnvIfNoCase Host example\.com VALID_HOST Order Deny,Allow Deny from All Allow from env=VALID_HOST </Directory> SetEnvIf X-Forwarded-Proto "https" HTTPS=on </VirtualHost> The problem is that I see the page when I enter example.com:8080 (without … -
Understanding the def clean(self) method inside custom login form class
Django Version = 2.2.2. Does it not make sense to take out the def clean(self) method from class LoginForm(form.ModelForm) class LoginForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = Account fields = ['email', 'password'] def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] if not authenticate(email=email, password=password): raise forms.ValidationError('Invalid login') and put it inside the view function for login: def login_screen_view(request): context = {} if request.POST: form = LoginForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) return redirect('home') else: form = LoginForm() context['login_form'] = form return render(request, 'account/login.html', context) So that the above two blocks of code becomes now this: class LoginForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = Account fields = ['email', 'password'] def login_screen_view(request): context = {} if request.POST: form = LoginForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) return redirect('home') else: raise forms.ValidationError('Invalid login') #i added this line else: form = LoginForm() context['login_form'] = form return render(request, 'account/login.html', context) The reason why I say all this is because in the def clean(self) method aren't you basically checking if the form is valid? We also check if the … -
how to execute the api call inside a django view only if the template coresspanding to this view is called
hi im trying to get access token for my application but i have a problem with executing an api call inside my "profile_token" django view because i want to execut the call only if the template coresspanding to this view is called, otherwise it keeps breaking the server because the user should first sign in to ebay then i can make this call thank you for your help here is a sample of the code api = Connection(config_file='ebay.yaml', domain='api.sandbox.ebay.com', debug=True) url_vars = {'SignIn&RuName': RuName, 'SessID': SessionID} url = 'https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?' constructed_url=(url + urllib.parse.urlencode(url_vars)) final_url=urllib.parse.unquote(constructed_url) def profile(request): context={ 'final_url':final_url } return render(request,'users/profile.html',context) request= { 'SessionID': SessionID } # i tried this def profile_token(request): response = api.execute('FetchToken', request) return render(request, 'users/profile_token.html') # and this def profile_token(request): if profile_token: response = api.execute('FetchToken', request) return render(request, 'users/profile_token.html') -
uuid in javascript inside django template?
I'm trying to find a way to pass uuid fk value for a django tag inside javascript, previusly I managed to make this work with and integer id, now I change the datatype of the pk with UUIDField, but I cant find a way to make this work original solution with integer: var det = "{% url 'det_proparr' 1010 %}".replace(/1010/, e.target.feature.properties.pk.toString()); I first replaced the 1010 with a sample ascii number, but I got the "Could not parse the remainder" error, I tried to generate a uuid with javascript code, but I cant put the variable name inside the url tag any ideas?? is there a uuid similar identifier generator that work with integers? -
fuzzy search in django without using Elasticsearch
I try to incorporate fuzzy serach function in a django project without using Elasticsearch. 1- I am using postgres, so I first tried levenshtein, but it did not work for my purpose. class Levenshtein(Func): template = "%(function)s(%(expressions)s, '%(search_term)s')" function = "levenshtein" def __init__(self, expression, search_term, **extras): super(Levenshtein, self).__init__( expression, search_term=search_term, **extras ) items = Product.objects.annotate(lev_dist=Levenshtein(F('sort_name'), searchterm)).filter( lev_dist__lte=2 ) Search "glyoxl" did not pick up "4-Methylphenylglyoxal hydrate", because levenshtein considered "Methylphenylglyoxal" as a word and compared with my searchterm "glyoxl". 2. python package, fuzzywuzzy seems can solve my problem, but I was not able to incorporate it into query function. ratio= fuzz.partial_ratio('glyoxl', '4-Methylphenylglyoxal hydrate') # ratio = 83 I tried to use fuzz.partial_ratio function in annotate, but it did not work. items = Product.objects.annotate(ratio=fuzz.partial_ratio(searchterm, 'full_name')).filter( ratio__gte=75 ) Here is the error message: QuerySet.annotate() received non-expression(s): 12. According to this stackoverflow post (1), annotate does not take regular python functions. The post also mentioned that from Django 2.1, one can subclass Func to generate a custom function. But it seems that Func can only take database functions such as levenshtein. Any way to solve this problem? thanks! -
django-celery supervisord configuration error on aws
#!/usr/bin/env bash # Get django environment variables celeryenv=`cat /var/app/current/project_name/.env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g' | sed 's/%/%%/g'` celeryenv=${celeryenv%?} # Create celery configuraiton script celeryconf="[program:celery-worker] ; Set full path to celery program if using virtualenv command=/var/app/venv/*/bin/activate/celery worker -A project_name -P solo --loglevel=INFO directory=/var/app/current/project_name user=root numprocs=1 stdout_logfile=/var/log/celery-worker.log stderr_logfile=/var/log/celery-worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; if rabbitmq is supervised, set its priority higher ; so it starts first priority=998 environment=$celeryenv" # Create the celery supervisord conf script echo "$celeryconf" | tee /usr/etc/celery.conf # Add configuration script to supervisord conf (if not there already) if ! grep -Fxq "[include]" /usr/etc/supervisord.conf then echo "[include]" | tee -a /usr/etc/supervisord.conf echo "files: celery.conf" | tee -a /usr/etc/supervisord.conf fi if ! grep -Fxq "[supervisord]" /usr/etc/supervisord.conf then echo "[supervisord]" | tee -a /usr/etc/supervisord.conf fi if ! grep -Fxq "[supervisorctl]" /usr/etc/supervisord.conf then echo "[supervisorctl]" | … -
Check results of model object query in django
Using: Checking for empty queryset I have the following code: models.py from django.db import models class Currency(models.Model): currency_name = models.CharField(max_length=100) currency_value_in_dollars = models.FloatField() currency_value_in_dollars_date = models.DateField() def __str__(self): return self.currency_name class User(models.Model): user_name = models.CharField(max_length=200) user_pass = models.CharField(max_length=200) join_date = models.DateField() def __str__(self): return self.user_name class Transaction(models.Model): transaction_type = models.CharField(max_length=200) transaction_amount = models.FloatField() transaction_date = models.DateField() transaction_currency = models.ForeignKey(Currency, on_delete=models.CASCADE) transaction_users = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.headline views.py: def get_latest_currency(self): """ Return most up to date value """ filtered_currency = Currency.objects.filter( currency_value_in_dollars_date__lte=timezone.now() ).order_by('-currency_value_in_dollars_date')[:1] if not filtered_currency: # No objects yet; fetch currencies update_coins_table() Even though I have no entries update_coins_table() is not executed. Why doesn't filter work as expected? (contain the results of the query?) When the if is reached, the following error is thrown: django.db.utils.ProgrammingError: relation "manage_crypto_currency_currency" does not exist LINE 1: ...y_currency"."currency_value_in_dollars_date" FROM "manage_cr... I have no idea how the relation manage_crypto_currency_currency was created since that string is not even in the code. -
id field is not serialized when performing POST method in django
I have a model which has 3 simple fields. And a serializer to serialize its data. All works fine with GET method. But when I do a POST request, the id of newly created object is not included in the json response. Anyone has a clue? I'll include my serializer and model and view Serializer class ChapterSerializer(serializers.HyperlinkedModelSerializer): course_id = serializers.IntegerField(source='course.pk', required=False) class Meta: model = Chapter fields = ('id', 'name', 'creation_time', 'course_id') def create(self, validated_data): course = Course.objects.get(pk=int(self.data['course_id'])) chapter = Chapter.objects.create(course=course, creation_time=validated_data.get('creation_time', 0), name=validated_data.get('name', '')) return chapter View class CourseChaptersViewSet(generics.ListAPIView, generics.ListCreateAPIView, generics.UpdateAPIView): serializer_class = ChapterSerializer def get_queryset(self): queryset = [] if 'course_id' in list(self.request.query_params.keys()): course_id = int(self.request.query_params['course_id']) queryset = [chapter for chapter in Chapter.objects.all() if chapter.course.pk == course_id] return queryset Model class Chapter(models.Model): name = models.CharField(max_length=100, null=False, blank=False) creation_time = models.BigIntegerField(null=False, blank=False, default=0) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='chapter', default=None) def __str__(self): return self.name -
Django can't overwrite logout view
I use django.contrib.auth.urls to logout user. I want and I have view logout but I don't know why when I go to accounts/logout/ url django use not mine but default view for logout. from django.urls import path, include import django.contrib.auth.urls from . import views app_name = 'accounts' urlpatterns = [ path('', views.index, name='index'), path('accounts/', include('django.contrib.auth.urls')), path('accounts/sign_up/', views.sign_up, name="sign-up"), path('accounts/logout/', views.logout_view, name="logout"), ] def logout_view(request): print(request.user) context = {'user2': request.user} logout(request) return render(request, 'accounts/logged_out.html', context) -
My product overlap with each other when I resize my window
My images overlap with each other when I resize my window <div class="new_arrivals" > <div class="container"> <div class="row"> <div class="col text-center"> <div class="section_title new_arrivals_title"> <h2>New Arrivals</h2> </div> </div> </div> <div class="row align-items-center"> <div class="col text-center"> <div class="new_arrivals_sorting"> <ul class="arrivals_grid_sorting clearfix button-group filters-button-group"> <li class="grid_sorting_button button d-flex flex-column justify-content-center align-items-center active is-checked" data-filter="*">all</li> <li class="grid_sorting_button button d-flex flex-column justify-content-center align-items-center" data-filter=".women">women's</li> <li class="grid_sorting_button button d-flex flex-column justify-content-center align-items-center" data-filter=".accessories">accessories</li> <li class="grid_sorting_button button d-flex flex-column justify-content-center align-items-center" data-filter=".men">men's</li> </ul> </div> </div> </div> <div class="row"> <div class="col"> <div class="product-grid" data-isotope='{ "itemSelector": ".product-item", "layoutMode": "fitRows" }'> </div> </div> </div> </div> </div> *In this I m filtering products and when I resize the window images overlap * -
In Django how best do I find differences between current database table schemas and schemas migrations would generate?
./manage.py migrate looks at the django_migrations table to find out what migrations have run, not at the current state of the database. How best do I detect discrepancies that may have sneaked in via manual SQL interventions? Note: My database is MySQL, but I have the same doubts with a Postgres, SQLite and soon MS SQL projects -
Getting Images from an API in python
I am trying to get images from the ratehawk hotel data search GET endpoint but the links with the images look like this https://cdn.ostrovok.ru/t/{size}/content/cc/37/cc37cca4456d243aa02c4930444ff7d974750928.jpeg" . Notice the { size } that kind of breaks up the link making it difficult to display the image in my html. how do I get rid of the { size } here's the code import requests import json data1 = { 'id':'crowne_plaza_berlin_city_centre', 'language':'en', } data=json.dumps(data1) url=f'https://api.worldota.net/api/b2b/v3/hotel/info/?data={data}' payload = { } headers = { 'Content-Type': 'application/json', 'Authorization': BASIC, 'Cookie': COOKIE } response = requests.request("GET", url, headers=headers, data = payload) print(response.text.encode('utf8')) -
How to generate a pdf of html template Python
I have been given a task,do i need some help in this. How to generate a pdf of html template and the generated pdf file should show images,css with external path like (http://)? -
'str' object has no attribute 'items' Django during api call
I'm getting this error, and I've tried methods from the json module to no avail from django.shortcuts import render,redirect import requests import json import ast def dashboard(request, exception=None): url = 'https://napi.arvancloud.com/cdn/4.0/domains/{DOMAIN-NAME}/reports/traffics' req = requests.get(url, headers={"Authorization: Apikey ************"}).json() return render(request, 'dashboard.html', {'req':req}) -
Django render list of json data via ajax
I want to render a data frame to the front-end so that I can create a table on my html page. Usually, if I use simple render (without ajax involves), I transfer it to a list of json data and then render it to html page: my_function.py: def df_to_json(df): json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) return data The json data look like this: [{"category":0, "sales":135, "cost": 197, "em_id":12}, {"category":0, "sales":443, "cost": 556, "em_id":12}, {"category":2, "sales":1025, "cost": 774, "em_id":15},...] Then in my views.py and based.html page: views.py: def home(request): dict_search = request.GET.get('inputtxt_from_html') df = my_function.myfunction1(dict_search) df_json = my_function.df_to_json(df) return render(request, 'base.html', {'df_json': df_json}) based.html: <div class="container"> <table class="table table-dark table-striped" id='table1'> <tbody> {% if df_json%} {% for i in df_json%} <tr> <td>{{i.sales}}</td> <td>{{i.cost}}</td> <td>{{i.em_id}}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </div> The problem now is that I want to do something like above but this time the input is from ajax. And it seems like I cannot directly get the render results {{df_json}} for my html page. I tried to do something in the "success:" part of my ajax, but it either show "Object" or just text. How shouldI code in "success:" part to … -
Is there a way to run multiple concurrent Django apps (different settings, same code) in one process?
Basically this would be a situation where I'd want to run the same Django codebase, but use different settings for different incoming domain. For example, foo.bar might use the settings/foo_bar.py settings file, with a different database, etc. I'd like to have one process that, at runtime, "spins up" instances. Eg def find_django_app(wsgi_request): settings_file = ... django.use_settings(settings_file) # Does this exist? django.setup(set_prefix=False) return WSGIHandler() Is anything like that possible?