Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Is annotating twice with same lookup a bad practice?
I want to annotate a queryset to filter with this annotation. In some cases, my queryset might already have the annotation set. What happens if I annotate my queryset twice (same lookup, and same values): Does it perform unnecessary jobs on the DB side? Example: queryset = MyModel.objects.annotate(my_annotation=F("some stuff")).filter(my_annotation="some other stuff") # a bit later queryset = MyModel.objects.annotate(my_annotation=F("some stuff")).filter(my_annotation="some other stuff") If yes, how can I check the already annotated lookups without evaluating my queryset? -
Add another and remove is not showing django formset is anythng i missed in html
I have created a formset, which is showing in html but its not showing add another or delete links. When I check the console. I am getting an error like this also, custom.min.js:1 Uncaught TypeError: $(...).slimScroll is not a function at HTMLDocument.<anonymous> (custom.min.js:1) at c (jquery.min.js:3) at Object.fireWith [as resolveWith] (jquery.min.js:3) at Function.ready (jquery.min.js:3) at HTMLDocument.H (jquery.min.js:3) Is this happening because of above error or i missing something in my code. I am attaching my code below. i already tried to add id's which is not working(inside the loop). forms.py class ImageForm(forms.ModelForm): class Meta: model = ProductImage fields = ('item','images') ImageFormset = formset_factory(ImageForm) views.py class CreateProduct(View): def get(self, request): form = ProductForm() formsetx = ImageFormset(prefix='formsetx') context = { 'form' : form, 'formsetx' : formsetx, 'title' : 'Add Product', 'sub_title' : 'Product', } return render(request, 'f_supp/add_product.html', context) add_product.html <form class="uk-form-stacked" method="POST" action="{% url 'f_supp:add-product' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <table cellpadding="0" cellspacing="0" class="table"> <tr> <th>Images</th> <th>Item</th> </tr> {% for f in formsetx.forms %} {{ f.id }} <tr class="form_set_rowp5"> <td> <span class="input1"> {{ f.images }} </span> </td> <td> <span class="input1"> {{ f.item }} </span> </td> <td>{% if f.instance.pk %}{{ f.DELETE }}{% endif %}</td> </tr> {% endfor %} </table> {{ … -
Passing request to messages.error in TemplateView Class
I'm replacing my view defs with classes. I first tried a View: class DiscoverView(View): def get(self, request): page_name = 'discover' try: page = Pages.objects.get(name='discover') except (Pages.DoesNotExist, Pages.MultipleObjectsReturned): messages.error(request, 'Page is not configured: ' + page_name) return redirect('MS_Home') context = { 'page': page, } return render(request, 'base/discover.html', context) This worked fine. I next decided to do a TemplateView with an intervening parent class to try to stay dry. class PageView(TemplateView): def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) page_name = kwargs['page_name'] try: page = Pages.objects.get(name=page_name) except (Pages.DoesNotExist, Pages.MultipleObjectsReturned): messages.error(self.request, 'Page is not configured: ' + page_name) return redirect('MS_Home') context['page'] = page return context class AboutView(PageView): template_name = 'base/about.html' def get_context_data(self, *args, **kwargs): kwargs['page_name'] = 'about' context = super().get_context_data(**kwargs) return context The normal path works. When the exception is thrown, it dies on the message.error: context must be a dict rather than HttpResponseRedirect. If I take out self.request in the messages.error() call, it complains about a missing parameter so I'm pretty sure it doesn't like self.request. How should I pass request to messages.error()? -
How to use html snippets into django template in vscode?
I want to write HTML snippets when I'm using the Django Template but Visual Studio Code doesn't recognize them. I installed HTML Snippet extension but didn't work. I know that i can use HTML template and install django snippets but i want to do the said before. some help? -
Django TransactionManagementError: select_for_update cannot be used outside of a transaction
I am using multiple db environment using DJANGO_DB_ROUTERS. But I am facing this error. TransactionManagementError: select_for_update cannot be used outside of a transaction. Django transaction is used inside django library so I can't use using=db_name. Both read and write are only happening from master but even after I am getting this error ----> 1 create_type(t()) ~/setup.py in create_type(t) 1791 object_identifier=oi, 1792 tenant=t, -> 1793 defaults=data 1794 ) 1795 ~/backend/venv/lib/python3.6/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs) 80 def create_method(name, method): 81 def manager_method(self, *args, **kwargs): ---> 82 return getattr(self.get_queryset(), name)(*args, **kwargs) 83 manager_method.__name__ = method.__name__ 84 manager_method.__doc__ = method.__doc__ ~/backend/venv/lib/python3.6/site-packages/django/db/models/query.py in update_or_create(self, defaults, **kwargs) 501 with transaction.atomic(using=self.db): 502 try: --> 503 obj = self.select_for_update().get(**lookup) 504 except self.model.DoesNotExist: 505 obj, created = self._create_object_from_params(lookup, params) ~/backend/venv/lib/python3.6/site-packages/django/db/models/query.py in get(self, *args, **kwargs) 395 if self.query.can_filter() and not self.query.distinct_fields: 396 clone = clone.order_by() --> 397 num = len(clone) 398 if num == 1: 399 return clone._result_cache[0] ~/cftr/backend/venv/lib/python3.6/site-packages/django/db/models/query.py in __len__(self) 252 253 def __len__(self): --> 254 self._fetch_all() 255 return len(self._result_cache) 256 ~/backend/venv/lib/python3.6/site-packages/django/db/models/query.py in _fetch_all(self) 1177 def _fetch_all(self): 1178 if self._result_cache is None: -> 1179 self._result_cache = list(self._iterable_class(self)) 1180 if self._prefetch_related_lookups and not self._prefetch_done: 1181 self._prefetch_related_objects() ~/backend/venv/lib/python3.6/site-packages/django/db/models/query.py in __iter__(self) 51 # Execute the query. This will also fill compiler.select, klass_info, … -
Apache2.4 + Django 3 - No module named 'django'
I am trying to configure my first Django + Apache application. I am using Django 3.05, Python 3.8, Ubuntu 16.04 and Apache 2.4.18. I encountered the No module named 'django' error. Target WSGI script '/srv/tacdb/mysite/wsgi.py' cannot be loaded as Python module. Exception occurred processing WSGI script '/srv/tacdb/mysite/wsgi.py'. Traceback (most recent call last): File "/srv/tacdb/mysite/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' If I activate the virtual environment and run the server, it works just fine. This is my wsgi.py: import os from mysite.wsgi import get_wsgi_application os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" application = get_wsgi_application() This is the apache configuration file: Listen 80 <VirtualHost *:80> ServerName ServerAdmin ServerAlias DocumentRoot /srv/tacdb Alias /static /srv/tacdb/mysite/static WSGIDaemonProcess mysite python-home=/srv/tacdb/venv python-path=/srv/tacdb WSGIProcessGroup mysite WSGIScriptAlias / /srv/tacdb/mysite/wsgi.py <Directory /srv/tacdb/mysite> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/tacdb_error.log CustomLog ${APACHE_LOG_DIR}/tacdb_access.log combined </VirtualHost> I have installed the latest version of mod_wsgi. sudo apt-get install libapache2-mod-wsgi-py3 I am logged in as root. The structure of my project is: . └── tacdb ├── manage.py ├── mysite │ ├── admin.py │ ├── apache-site2.conf │ ├── apache-site.conf │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── static │ ├── tacdashboard │ ├── templates │ ├── urls.py … -
Django- How to read uploaded excel file in django
I am trying to upload multiple excel files in django and save it to a folder. Once the files have been saved I want to select the file on the GUI and show the data from that file. How do I handle reading particular file from the folder? -
create_user not returning full user object of the newly created user
I am doing simply: user = User.objects.create_user(**data) print(user['id']) # user.pk dont work. If i do print(user), I see username of the newly added user. Is there a way to return the user id along with first_name? Or must I query the model with the user name to get user details of the newly added user? -
Registration information not saving to database in Django
The registration part of the code does not work. After creating a new user it just redirects to the registration page and I can not figure out why. Also is there a way to edit the username and password elements in the RegisterForm like I did with the email element? forms.py from django import forms from django.contrib.auth import authenticate, models from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm class RegisterForm(UserCreationForm): email = forms.EmailField(max_length=100, required=True, widget=forms.EmailInput(attrs={'class': 'form_control', 'name': 'email', 'id': 'email', "placeholder": 'Your class Meta: model = User fields = ( 'username', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.username = self.cleaned_data user.email = self.cleaned_data user.password1 = self.cleaned_data if commit: user.save() return user views.py def addUser(request): if request.method == 'POST': form = RegisterForm(request.POST or None) if form.is_valid(): form.save() return redirect('home') else: form = RegisterForm() args = {'form': form} return render(request, 'login_register/register.html', args) register.html <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Register</title> <!-- Font Icon --> <link rel="stylesheet" href="{% static 'login_register/fonts/material-icon/css/material-design-iconic-font.min.css' %}" /> <!-- Main css --> <link rel="stylesheet" href="{% static 'login_register/css/style.css' %}" /> </head> <body> <div class="main"> <!-- Sign up form --> <section class="signup"> <div … -
Nginx isn't Serving Django Static Files Correctly Because of Trailing Slash
Currently, I have a Django web app being served by Gunicorn. Gunicorn does not serve static file requests so I am using Nginx in front of Gunicorn to serve static file requests. I am able to containerize the app fine with Docker and can successfully serve application requests but Nginx cannot serve the static file requests correctly because Django appends a trailing slash to static file requests. After running the Docker container with Django, Nginx, and Postgres services, I navigate to the home page of the web app and the first request is fine. HTTP Request 200 The rest of the incoming requests after navigating to the home page of the web app are static file requests all with 404 error codes. HTTP Request 404 The 404 error codes indicate that the server cannot find the static files but I can verify that my static files are stored in the correct location and are present. The 404 error codes are happening because Django static file requests append a trailing slash to the request. So, after reading the Nginx documentation, I discovered that Nginx treats all static file requests with trailing slashes as requests for directories and thus searches for an … -
Is sometimes single complicate query worse than two separate query?
I just came into the article on Django that says, when the amount of data is so huge it's better to split it and send them separately. I'm not really sure about this, because as far as I know, DBMS itself is so optimized and the networking is what causes the greatest portion of the latency. Are there really any cases like this? -
Django: Can't redirect to list page after clicking Submit button
Sorry for the long-ass post. I have a problem with my "update_fisher" view. It doesn't redirect to the "list_fishers" view after clicking the "Submit" button. What wonders me more is that "create_fisher" view uses the same html file for submitting forms, but it executes successfully. Here is the code for more details: fishers/views.py ... @ staff_member_required def create_fisher (request): form = FisherForm(request.POST or None) if form.is_valid(): form.save() form = FisherForm() return HttpResponseRedirect(reverse("fishers:list_fishers")) template_name = "fisher_form.html" context = {'form' : form} return render (request, template_name, context) @ staff_member_required def update_fisher (request, fisher_id): items = get_object_or_404(Fishers, fisher_id = fisher_id) form = FisherForm(request.POST or None, instance = items) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("fishers:list_fishers")) template_name = "fisher_form.html" context = {'fishers' : items, 'form' : form} return render (request, template_name, context) ... fishers/urls.py from django.urls import path from . import views # this is responsible for the "namespace" in admin > urls.py app_name = 'fishers' # urlpatterns = [ path('', views.list_fishers, name = "list_fishers"), path('add_fisher/', views.create_fisher, name = "create_fisher"), path('update_fisher/<int:fisher_id>', views.update_fisher, name = "update_fisher"), fishers/templates/fisher_form.html {% extends "base.html" %} <title> {% block title %} Add/Update Information {% endblock %} </title> {% block content %} <div class = "page-header"> <h2> Fisher's Information </h2> </div> <form method … -
How to optimize django-import-export?
I have a data in Excel around 20,000 records. I using django-import-export extension for import data.I tried to import data but very slow about 10 minute. I think one thing to make it slow that is django-import-export render 20,000 records on preview table. I want to know how to speedup ? -
requests.post from python script to my Django website hosted using Apache giving 403 Forbidden
My Django website is hosted using Apache server. I want to send data using requests.post to my website using a python script on my pc but It is giving 403 forbidden. import json url = "http://54.161.205.225/Project/devicecapture" headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'content-type': 'application/json'} data = { "nb_imsi":"test API", "tmsi1":"test", "tmsi2":"test", "imsi":"test API", "country":"USA", "brand":"Vodafone", "operator":"test", "mcc":"aa", "mnc":"jhj", "lac":"hfhf", "cellIid":"test cell" } response = requests.post(url, data =json.dumps(data),headers=headers) print(response.status_code) I have also given permission to the directory containing the views.py where this request will go. I have gone through many other answers but they didn't help. I have tried the code without json.dumps also but it isn't working with that also. How to resolve this? -
Retrieve Form Field Values With Ajax in Django
I have two forms. 1st form is CreateQuoteForm, which is used to create a Quote object - the user will fill this out first. The 2nd form is CreateProformaForm, which is used to create a Proforma object this will be completed second. I would like for the user to have the ability to select a Quote object from a select box and upon the click of a button, populate the CreateProformaForm fields with the data where there is overlap between the two models. Please see below for further illustration: models.py class Quote(models.Model): Name = models.CharField(max_length=30, null=True, blank=True) Shipment = models.ForeignKey(Shipment, null=True) Exporter = models.CharField(max_length=100, null=True, blank=True) QuoteNo = models.CharField(max_length=30, null=True, blank=True) class Proforma(models.Model): Name = models.CharField(max_length=30, null=True, blank=True) Shipment = models.ForeignKey(Shipment, null=True) Exporter = models.CharField(max_length=100, null=True, blank=True) QuoteNo = models.CharField(max_length=30, null=True, blank=True) Date = models.CharField(max_length=30, null=True, blank=True) Consignee = models.ForeignKey(Customer, null=True) As you can see, the models have similar fields. So after selecting the Quote in the selectbox, the fields Name, Shipment, Exporter, QuoteNo should populate in CreateProformaForm while Data and Consignee remain blank. Also to be clear - this should be an option for this user only, the form should be initialized blank. I am sure that this will … -
Uploading multiple csv files in Django using multiple file field form
I have tried uploading one csv file using Django file field form and it works well. However, switching the file field form into multiple file field form yields to an error when trying to read the csv file. What I initially tried for single csv file: in forms.py class UploadForm(forms.Form): file_field = forms.FileField(allow_empty_file = False) in views.py input_file = request.FILES['file_field'] data_set = input_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) model_list = [] for row in csv.reader(io_string, delimiter = ',', quotechar = "|"): #create Django model object based on the row and append it to model_list Sample_Model.objects.bulk_create(model_list) What I currently try for multiple csv files: in forms.py: class UploadForm(forms.Form): file_field = forms.FileField(allow_empty_file = False, widget=forms.ClearableFileInput(attrs={'multiple': True})) in views.py: input_files = request.FILES.getlist('file_field') for file in input_files: data_set = file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) model_list = [] for row in csv.reader(io_string, delimiter = ',', quotechar = "|"): #create Django model object based on the row and append it to model_list Sample_Model.objects.bulk_create(model_list) I got a Stop Iteration error at the next(io_string) line. Upon browsing for its meaning and analysing the code, it seems data_set = file.read().decode('UTF-8') is the source of the problem as it does not work properly now. Thank you! -
Static files moved to a STATIC_ROOT but still none are being shown
Trying to deploy my site and everything is working fine except that the CSS in the admin page is non-existent. I have looked through all of the other posts where people have had this issue but i have already done the steps most of them forgot. I have the static files directed to the base directory with STATIC_ROOT = os.path.join(BASE_DIR, 'static'), when I ran python manage.py collectstatic, they all seemed to move into the base DIR just fine. Heres the code/file structure: In settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' Then the structure that this created after collectstatic: Obviously something isn't right or I wouldn't be here but Im stuggling to figure out what is incorrect. All help is appreciated. Thank you! -
FOREIGN KEY constraint failed - Django, SQLite3
My application allows Tenantprofiles to apply for Property viewings that are listed by Landlord profiles. I can't seem to link the two tables together I can't get past FOREIGN KEY constraint failed error. views.py from django.shortcuts import render, redirect from projects.models import Properties, Property_Applications, Property_Reviews from users.models import Landlord_Profile, Tenant_Profile from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import CreatingListingForm, ListingApplicationForm def property_apply(request, pk): project = Properties.objects.get(pk=pk) applyButton = ListingApplicationForm(request.POST) profile = request.user.tenant_profile if request.method == "POST": link = applyButton.save(commit=False) link.tenant_apply = profile link.listing=project link.save() messages.success(request, f'You have applied!') return redirect('/tenantportal/') else: link = applyButton context = {'project': project, 'applyButton': link} return render(request, 'application_submit.html', context) models.py - projects from django.db import models from PIL import Image from django.contrib.auth.models import User from django.contrib.auth import get_user_model from django.conf import settings from users.models import Landlord_Profile, Tenant_Profile class Property_Applications(models.Model): tenant_apply = models.ForeignKey(Tenant_Profile, on_delete=models.CASCADE, default=1) property_owner = models.ForeignKey(Landlord_Profile, on_delete=models.CASCADE,default=1) listing = models.ForeignKey('Properties', on_delete=models.CASCADE) app_description = models.TextField(default='app description') created = models.TextField(default=1) class Properties(models.Model): User = settings.AUTH_USER_MODEL landlord = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=100) rentPrice = models.FloatField() description = models.TextField() bedRooms = models.IntegerField() bathRoom = models.IntegerField() tenantCondtions = models.CharField(max_length=100) image = models.ImageField(upload_to='house_preview/') models.py - users from django.db import models from django.contrib.auth.models import User from PIL … -
expired confirmation email to return a JSON response in django-rest-auth
using Django-rest-auth and Django-allauth to handle email verification and signup in my rest api. When a user tries to verify their email after the link has expired, I get an unpleasant error page. ---> I would like to get a JSON response saying the email has expired. Below is the error message I get when I confirm the expired verification email. -
custom form validation errors in template
how can i pass custome form validation errors in template? forms.py '''' def clean_username(self): inputusername = self.cleaned_data['username'] if len(inputusername) < 6: raise forms.ValidationError('Sorry, your username must be between 6 and 30 characters long.') else: return inputusername '''' views.py '''' def signup(request): signup_form = CreateUserForm() if request.method == 'POST': signup_form = CreateUserForm(request.POST) if signup_form.is_valid(): signup_form.save() context = {'signup_form':signup_form} return render(request, 'formvalidationapp/signupform.html', context) '''' temlate '''' <form method="post" action="{% url 'signup' %}"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <h1>Sign Up</h1> </div> </div> <div> #i want to pass error here </div> '''' -
Why can't my user can't check their inbox?
So I am attempting to query and display messages between two users in an inbox. I am running into a problem where no messages are appearing for request.user's inbox. It's showing as empty when there are messages. However, when I go into an inbox for another user that my request.user has messaged while still logged in to request.user, I can see the messages from both parties there and displayed correctly. For the life of me, I don't understand why this is happening. Hell, request.user.username is passed through the template and my user's username actually prints. Yes, django.template.context_processors.request is already in my context processor. I tried doing if msg.receiver_id == request.user but that still doesn't work. What the hell am I doing wrong here? views.py/messages def messages(request, profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user, receiver_id=profile_id,) | Q(sender_id=profile_id, receiver_id=request.user,) ).\ values('sender_id','receiver_id', 'message', 'date', ).\ order_by('date',) return render(request, 'dating_app/messages.html', {'messages': messages,}) messages.html {% for msg in messages %} {% if msg.receiver_id == user.id %} <li class="text-right list-group-item">{{ msg.message }}<br/>{{ msg.date }}<br/>{{ request.user.username }}</li> {% elif msg.sender_id == user.id %} <li class="text-left list-group-item">{{ msg.message }}<br/>{{ msg.date }}</li> {% endif %} {% empty %} {%endfor %} urls.py/messages path('messages/<int:profile_id>/', views.messages, name='messages') models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): … -
how to fix "Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL" Error?
public static void main(String[] args) throws Exception { // check if the user enter the right args from the command line. if(args.length != 2){ System.out.println("Usage: java Reverse " + "http://<location of your servlet/script> " + "string_to_reverse");// display the error. System.exit(1); // exit the program. } /**the sting that will be reversed may contain spaces or other * non-alphanumeric characters. These characters must be * encoded because the string is processed on its way to the server. * the URLEncoder class methods encode the characters.*/ String stringToReverse = URLEncoder.encode(args[1], "UTF-8"); // create object for the specified url for the command line. URL url = new URL(args[0]); // sets the connection so that it can write to it. URLConnection connection = url.openConnection(); connection.setDoOutput(true); // I tried the follow things to fix the error but still not working. //connection.setRequestProperty("http.agent", "Chrome"); //connection.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); // connection.setRequestProperty("User-agent", "Mozilla/5.0"); // connection.setRequestProperty("User-agent", "Mozilla"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); // The program then creates an output stream on the connection // and opens an OutputSteamWriter on it; OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream()); // the program writes the required information t the output // stream and closes the stream. out.write("string = " … -
Django user model. 1 admin account, 1 customer account with the same email and different password
Im trying to handle a use case where i have 2 roles. (admin , customer) There will be an admin portal and a customer portal (2 different login pages ). An admin can invite a customer An admin can be a customer as well , can invite himself into the customer portal An admin account must not share the same password as the customer account. Email is used as the unique field for both admin and customer account. For example : Admin account - customer@email.com /password1 Customer account - customer@email.com /password2 Solution 1: - Permission. Having 1 account with admin permission and customer permission. (This cant work to fit the bussiness use case) Based on this article: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html Solution 2: - Creating 2 django projects. One for each user model since both accounts cant share password. The reason for separating into 2 projects is because resources such as session,login, logout will not be shared. So each portal(admin,customer) has their own resource. A create Customer API to allow admin to create a customer account in customer django project. A shared db to share related data This is the only way i can think of to handle the use case. Please let … -
How to test a Django+Celery application with multiple queues
I am wondering if it is feasible to write functional tests for a Django application using multiple Celery queues. For a single queue, I used the solution explained here, and it worked great. What I would basically want to do is the following: from celery.contrib.testing.worker import start_worker from django.contrib.staticfiles.testing import StaticLiveServerTestCase from mysite.celery import app class MyTestCase(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.celery_worker1 = start_worker(app, perform_ping_check=False, queue="myqueue1") cls.celery_worker1.__enter__() cls.celery_worker2 = start_worker(app, perform_ping_check=False, queue="myqueue2") cls.celery_worker2.__enter__() @classmethod def tearDownClass(cls): super().tearDownClass() cls.celery_worker1.__exit__(None, None, None) cls.celery_worker2.__exit__(None, None, None) This code has two problems: I get the message /home/user/.local/lib/python3.7/site-packages/kombu/pidbox.py:74: UserWarning: A node named gen18391@Machine is already using this process mailbox! which leads me to think that multiple workers aren't handled properly. The "queue" argument isn't in the documentation and is likely not parsed at all. Consequently, the task sent to the second queue isn't being executed. -
What is the best practice for an internal API call in django
I've developed a chess API in django. I intend to develop a client for it as well. What would be the best practice for a client? Develop the client as another app in the same project in django, and perform internal API calls using requests(Is it better than calling the API externally performance wise? ) Develop the client as another app in the same project in django, and call the API's views using Django. (How would I do this, as the API expects JSON data in request) Develop the client as a standalone.