Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where I can find modern django admin, that have good tools to work with images?
I want to create django project and connect it with modern admin. I want to get multiuploading images and immediate showing images when I choose them on PC (not after reloading). All that I can find - different CMS (with a lot of less tools) and some beautifiers for admin, that don't provide any new functionality. Can you recommend any? -
Django + Python vs PHP
I'm confused... Sorry for the stupid question, but I'm really confused about python I like PHP because it's so simple. You write logic in one file, then just reference it into your file OR you just write it directly in the php file that is rendering the markup... I thought python was going to be kind of the same, but it's not, to me it's way more complicated. I don't understand why I need Django or Flask to just write logic and manipulate data like I can in PHP. My Question Can I create a Website Backend like I can in PHP, but using Python without having to learn extra syntax and file structure from a framework? -
Celery disallowing the usage of dictionary data type
I have defined a shared_task with celery as follows: @shared_task(bind=True) def create_parameters_for_task_creation(project_type, dataset_instance_ids, filter_string, sampling_mode, sampling_parameters, variable_parameters, project_id) -> None: """Function to create the paramters for the task creation process. The function is passed arguments from the frontend which decide how the sentences have to be filtered and sampled. Args: project_type (str): Describes the type of project passed by the user dataset_instance_ids (int): ID of the dataset that has been provided for the annotation task filter_string (str): _description_ sampling_mode (str): Method of sampling sampling_parameters (dict): Parameters for sampling variable_parameters (dict): _description_ project_id (int): ID of the project object created in this iteration """ As soon as I try to run celery workers - celery -A shoonya_backend.celery worker -l info, I get the following errors. Unrecoverable error: TypeError("cannot pickle 'dict_keys' object") I believe that Celery is not allowing me to pass the dictionary data type which is weird because my settings allow json datatype. CELERY_BROKER_URL = 'redis://localhost:6380' result_backend = 'redis://localhost:6380' accept_content = 'json' result_serializer = 'json' task_serializer = 'json' What should be done? -
How do I connect my Django App to Postgres Databse?
How do I connect my Django App to Postgres Databse? Whenever I run python manage.py makemigrations after the changes, then I get this kind of error. How can I fix it? Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? warnings.warn( No changes detected -
How Do I Correctly Serialize and Send PayPal Transaction ID to Django Backend Doing Standard Client Side Integration
I'm trying to get PayPal's transaction ID after the payment was approved on the client-side. I'm doing client-side integration of PayPal and Django. I can totally get the Payment ID and order ID and so forth, but these will be discarded by PayPal after the payment got approved. PayPal only recorded Transaction ID which can be used to track the payment with PayPal. When I'm trying to serialize the return actions which capture the Transaction ID - somehow I got a status code of 500 - Internal Server Error. The funny thing is that I can totally do console.log(transaction.id) and get the transaction ID in the console. Anyway, my error prone code is below: In payment.html I got huge portion of html stuff, but I don't post it here. I only post where the JavaScript begins: <script> // Generating csrf_token on the fly function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + … -
Authorization header with Bearer token in swagger django DRF
During testing endpoints, for every refresh, I need to, again and again, generate a login bearer token --> go to authorize button of swagger--> add token ---> and authorize. Then I can test endpoints that need authentication. But, this is very repetitive. Once I have a token, Is there a way that I can auto-authorize swagger endpoints? -
pytest-django django_db_server fixture not working
I would like to use a specialized test database for unit testing my Django app. I'm using pytest along with pytest-django. Per the pytest-django instructions, I provided my own custom django_db_setup fixture in a conftest.py file as follows: from pathlib import Path import pytest from django.conf import settings @pytest.fixture(scope='session') def django_db_setup(): base_dir = Path(__file__).parent path = base_dir / 'test_db.sqlite3' assert path.exists() assert path.is_file() settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': path } I can confirm that this code is being executed when I run unit tests, and the test_db.sqlite3 database is being found. However, the unit tests are still referring to my development database not my test database. How do I get pytest-django to reference my test database instead of my development database? -
Both logging and print statements inside django channels consumer are not working
I'm trying to integrate celery with django channels but channels consumer is not working as it supposed. Logging or prints inside consumer functions are not displaying message in terminal. The following celery task is called from signals.py tasks.py from channels.layers import get_channel_layer @app.task def send_request_notification(): text = 'You have new cleaning request' channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'companies_received_request', # group name { 'type': 'send_notification', 'text': text } ) print("SENT ---") # can see result of this print consumers.py class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info("Connected to websocket") await self.channel_layer.group_add( 'companies_received_request', self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( 'companies_received_request', self.channel_name ) logger.info("Disconnected from websocket") async def send_notification(self, event): logger.info("Here in sending notification") text_message = event['text'] await self.send(text_message) print("EVENT.TEXT") print(text_message) settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [('127.0.0.1', 6379)], }, }, } I am supposed to get the output of prints and logging of consumer functions in terminal but I'm getting nothing -
What task queue should be used when using RabbitMQ in JAVA?
So I was switching my code base from Django to Spring Boot Java. But before that I was trying to find analogous framework and library for every feature that I have implemented in Django. One of the thing in which I was stuck was, for my message queues, In Django I was using Rabbit MQ as message Queue and Celery as the Task queue to process the queue content. Task Queue and Message Queue. RabbitMQ is a "MQ". It receives messages and delivers messages. Celery is a Task Queue. It receives tasks with their related data, runs them and delivers the results. In Java I can use RabbitMQ as message queue but what package do I have for spawning the workers? Processing the queue? What should I use as a task queue here? How does it work exactly in Java? -
Django mod_wsgi Apache error 403 Forbidden on Ubuntu 22.04
Django mod_wsgi on Apache application works fine in Ubuntu 20.04 and previous versions with the configuration mentioned below, but when I do the same configuration in Ubuntu 22.04 it gets 403 Forbidden error. and Permission denied: mod_wsgi in the error log. I tried changing permission on all files it's doesn't work, Apache config: <VirtualHost *:80> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/ubuntu/mydjango/mydjango> <Files wsgi.py> Require all granted </Files> </Directory> alias /static /home/ubuntu/mydjango/static <Directory /home/ubuntu/mydjango/static> Require all granted </Directory> WSGIDaemonProcess myapp python-home=/home/ubuntu/mydjango/venv python-path=/home/ubuntu/mydjango WSGIProcessGroup myapp WSGIScriptAlias / /home/ubuntu/mydjango/mydjango/wsgi.py </VirtualHost> Apache Error Log: Current thread 0x00007fb606719780 (most recent call first): <no Python frame> [Sun Jun 05 05:59:07.594727 2022] [wsgi:warn] [pid 37044:tid 140419768883072] (13)Permission denied: mod_wsgi (pid=37044): Unable to stat Python home /home/ubuntu/mydjango/venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/ubuntu/mydjango/venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/ubuntu/mydjango/venv' sys.base_exec_prefix = '/home/ubuntu/mydjango/venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/ubuntu/mydjango/venv' sys.exec_prefix = '/home/ubuntu/mydjango/venv' sys.path = [ '/home/ubuntu/mydjango/venv/lib/python310.zip', '/home/ubuntu/mydjango/venv/lib/python3.10', '/home/ubuntu/mydjango/venv/lib/python3.10/lib-dynload', ] Fatal Python … -
python3 - Pass function arguments to another function
def findUser(params): user=Users.objects.filter(params).first() if(user): return user return False findUser(name='a',code=123) How to do this ? In what way to pass parameters to another function? -
change celery tasks file in django
When using Celery in Django, we have to write the shared tasks in the tasks.py file. However, I have a app in my django project called tasks and saving a file called tasks can lead to a lot of confusion, hence, I would like to change the celery tasks.py file name to something else. Is there a way we can do that through the celery settings or some other way? -
Django Restframework - How to send ContactMe Email using SMTP gmail without using models or forms, and still get validation?
On my website that I am building I have a simple form: contat me form from my website I am using ReactJS to build the frontend and as backend I am using Django Restframework. In my views.py I got the following code: class SendEmailView(APIView): def post(self,request): subject = request.data['subject'] message = request.data['message'] email = request.data['emailAddress'] if len(subject)<5: raise ValidationError('Subject must be at least 5 characters long.') if len(message)<10: raise ValidationError('Message must be at least 10 characters long.') try: send_mail(subject=subject, message=message, from_email=settings.EMAIL_HOST_USER, recipient_list=[email], fail_silently=False) return Response({"success":True}) except Exception as e: print('Exception: ', e.message) return Response({'Exception: ', str(e)},status=status.HTTP_400_BAD_REQUEST) I just was experimenting a bit. But what I mainly doing here is I get the subject, message and email from the POST request and then send the email, which works perfectly. The thing that I cannot make work is that the view sends ValidationErrors as json to my frontend ReactJs app. For example, if the subject and / or message is too short... or if its not a valid email. I want to send back corresponding errors in the form of (or something similiar) {'errors':[{email:"not a valid email"}, {"subject":"The subject must contain at least 5 letters. You provided only 3."}]}. The thing is … -
How I send an image to the server using react native?
In react native project, I want to send image file to server (using django) but I got error like ** LOG Response = {"assets": [{"fileName": "rn_image_picker_lib_temp_baa977a6-ec57-4a5d-95a5-6c1aebab7d23.jpg", "fileSize": 195414, "height": 785, "type": "image/jpeg", "uri": "file:///data/user/0/com.frontend/cache/rn_image_picker_lib_temp_baa977a6-ec57-4a5d-95a5-6c1aebab7d23.jpg", "width": 785}]} LOG {"detail": "Multipart form parse error - Invalid boundary in multipart: None"} ** Here's my react native code CameraScreen.js import React, {Component} from 'react' import { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native' import {launchCamera, launchImageLibrary } from 'react-native-image-picker' import AsyncStorage from '@react-native-async-storage/async-storage'; class CameraScreen extends Component { //send image to server state = { avatar: '' } showImage = async () => { const userData = await AsyncStorage.getItem('userData'); const profile = JSON.parse(userData); launchImageLibrary({}, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled image picker'); alert('User cancelled image picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); alert('ImagePicker Error: ' + response.error); } else { alert(response.assets[0]) let source = response; this.setState({ avatar: response.assets[0].uri }); const fd = new FormData(); fd.append('file', { name: response.assets[0].fileName, uri: response.assets[0].uri, type: response.assets[0].type, }); fetch('http://localhost:8000/user/check/', { method: 'POST', headers: { 'Content-Type': 'multipart/form-data', Authorization: "Token " + profile.token, }, body: JSON.stringify({ fd, }) }) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); if(responseJson.status === 'success') { alert("hi"); … -
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'