Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
All static files returning 404 error when deploying Django Project using Digital Ocean
404 error imageI have tested my app in development and successfully got it fully functional in development running on my local server. I have now been trying to push it into development and none of the static files are being served. The connection has been successful as the domain shows the app with just plain HTML. However, all static files are returning the same 404 error. i have tried to modify my static_root in my settings.py. I have my paths set up like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') -
Why django codes not updating automatically using supervisorctl and Gunicorn?
Using Supervisor, I deployed Django. Django codes are not updated, instead I must restart Nginx or Supervisor. If you could help me with this issue, that would be great. Supervisor configuration [program:program_name] directory=/home/user/django/dir/django_dir/ command=/home/user/django/dir/venv/bin/gunicorn --workers 3 --bind unix:/home/user/django/dir/name.sock ingen> #command=/home/user/django/dir/venv/bin/gunicorn_config.sh numprocs=3 process_name=name%(process_num)d autostart=true autorestart=true stopasgroup=true user=user Group=www-data stderr_logfile=/home/user/django/dir/logs/supervisor_err.log stdout_logfile=/home/user/django/dir/logs/supervisor.log redirect_stderr=true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 I am trying to restart the supervisor process with the below command in order to update the Django backend codes, but it doesn't always work. sudo supervisorctl restart program_name:* //'program_name' refers to the name of the program in the supervisor configuration file METHOD 2 A second trail with a ssh_filename.sh file and the second command in the above supervisor configuration is used to run the ssh_filename.sh script. #!/bin/bash NAME="django_dir" #Django application name DIR_PARENT=/home/user/django/dir DIR=${DIR_PARENT}/django_dir #Directory where project is located USER=user #User to run this script as GROUP=www-data #Group to run this script as WORKERS=3 #Number of workers that Gunicorn should spawn SOCKFILE=unix:${DIR_PARENT}/dir.sock #This socket file will communicate with Nginx DJANGO_SETTINGS_MODULE=django_dir.settings #Which Django setting file should use DJANGO_WSGI_MODULE=django_dir.wsgi #Which WSGI file should use LOG_LEVEL=debug cd $DIR source ${DIR_PARENT}/venv/bin/activate #Activate the virtual environment export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR_PARENT:$PYTHONPATH #Command to run the progam under supervisor exec ${DIR_PARENT}/venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ … -
APNS Server Error - Bad Device Token (Only on production not develop of Heroku)
We are getting the following error when trying to send a notification to a user on the production version of our iOS app: enter image description here However, it is working properly on the development version. Our tech stack is using SwiftUI on the frontend, Django on the backend and for notififcations we are usign the django-push-notifications library and APNS. Please let us know if you have any ideas! We tried viewing logs, resetting package dependencies, and changing the settings.py file by turning sandbox to false among other things. -
M-Pesa payment gateway integration Django
I need m-Pesa payment gateway integration in node or Django. Want to get reference from the code and modify it according to my need. Do anyone integrated before? -
How to startapp from inside docker-compose
I have a problem in the steps of testdriven.io The definitive guide to Django Celery, when i want to start a new tdd app if i execute these commands ` $ docker-compose exec web bash (container)$ ./manage.py startapp tdd ` it creates an app that is read only and pycharm cant change read only status. Some solutions say that it is because i created the app from root user but i cannot understand how to solve it. Here are the Dockerfile and the Docker-compose. version: '3.3' services: web: build: context: . dockerfile: ./compose/local/django/Dockerfile image: testdriven_web # '/start' is the shell script used to run the service command: /start # this volume is used to map the files and folders on the host to the container # so if we change code on the host, code in the docker container will also be changed volumes: - .:/app ports: - 8010:8000 # env_file is used to manage the env variables of our project env_file: - ./.env/.dev-sample depends_on: - redis - db db: image: postgres:14-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_DB=hello_django - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django redis: image: redis:7-alpine celery_worker: build: context: . dockerfile: ./compose/local/django/Dockerfile image: testdriven_celery_worker command: /start-celeryworker volumes: - .:/app env_file: - … -
How to create api endpoint to create super user in django
Hey i have one question about creating superuser with djangorestframework. I want to create superuser with POST request using DRF 3.14 How should i do that if i'm using Android as a client for example? -
Django - Import Models from an installed Package
I have all of my Django models in another package which I install using pip in a Django app. models_package | - models.py | - setup.py and in models.py i have from django.contrib.auth.models import AbstractUser class User(AbstractUser): .... in my Django app i have my_django_app | ... | models.py website | ... | settings.py manage.py in my_django_app.model i have from models_package.models import * and in website.settings.py i have AUTH_USER_MODEL = "my_django_app.User" but when i run python manage.py runserver i get: RuntimeError: Model class my_django_app.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The Thing is User which comes from models_packages.models and models_packages is not a Django app which I add to INSTALLED_APP in settings.py. it is only a package containing all shared Models that I need in multiple different Django apps. Is there any way to use models in models_package.models without adding it to INSTALLED_APP inside website.settings.py -
How to make Django Formset Management Forms Generate Unique IDs for Fields
I am making an 'Project' program where users can write articles with a variable number of images and associate a list of various important dates with their article. According to the Django documentation, using formsets along with javascript can create dynamic forms for this purpose. However, when trying to implement this for both my image_formset and mydate_formset I opened the console to find that both the {{ image_formset.management_form }} and {{ date_formset.management_form }} had the same IDs for every field. Because of this I cannot use javascript to update the form-TOTAL_FORMS fields to properly reflect how many forms are currently being used. Is there any way to fix so that each form-TOTAL_FORMS can be selected uniquely? I may attempt to work around the problem by adding the parent of {{ date_formset.management_form }} to the script's criteria for selection, but I think having two html elements with the same ID is generally a bad idea. -
How to know that a single user is connected through websocket from multiple devices? In django
I'm working on social media app in django. I have one user who is logged in from multiple devices and connected to websocket. How do i know that from which devices user is connected through websocket and through which is not. So i can send push notifications to user's device from which user is not connected.? For now im handling it through making a table called user devices. This table is connected to user table with foreign key. So whenever user login from a particular device Im storing its information like device id, device token, is_online. And whenever user gets connected through websocket im Changing its state to is online true. And whenever user disconnects from websocket im Changing it to false according to multiple devices. I just want to know is there any more efficient way then this. -
Django - Where do you store non-django .py files in your app?
I have three python files (two that scrape data and 1 with my functions) I'm using in my app. Each file is about 150 lines, I don't want to include this code in views.py to keep my views as clean and readable as possible. Is there a best practice to keep things tidy? A separate folder inside the app with all external non-django .py files (similar to 'Templates' for .html or 'Static' for .css)? Any suggestions are appreciated. A Google search didn't yield any results. -
JWT auth dosen't create token for Custom user model in Django?
I have the following problem : i created a custom UserModel and Djoser for jwt auth. when i create a superuser by terminal it created with hashed password but when i create it with an APIVIEW it created without being hashed so when i need to create a token for created user it gives me "detail": "No active account found with the given credentials" but when i create a token for the superuser it created successfully. my custom user model: class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_("Please enter your email address")) email = self.normalize_email(email) new_user = self.model(email = email, **extra_fields) new_user.set_password(password) new_user.save() return new_user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Super user should have is_staff True')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Super user should have is_superuser True')) if extra_fields.get('is_active') is not True: raise ValueError(_('Super user should have is_active True')) return self.create_user(email, password, **extra_fields) class User(AbstractUser): username = models.CharField(max_length=200, unique=True) email = models.EmailField(max_length=200, unique=True) phone_number = PhoneNumberField(null=False, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'phone_number'] objects = CustomUserManager() def __str__(self): return self.username User View: class UserView(APIView): def get(self, request): user = User.objects.all() serializer = … -
how to give specific permission to users and moderator django
I am working on a django project where it has two type of users. One is moderator (admin) and another one is normal user (researcher). I want the admin can not create blogpost. blogposts can only normal users. normalusers can create, update, delete, view blogpost created by himself and also view other people's posts. The admin can view normal user's post but can not edit their post. The admin the delete or approve post made by normal users. blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) content = RichTextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization') approved = models.BooleanField('Approved', default=False) like = models.ManyToManyField(get_user_model(), related_name='likes', blank=True) def __str__(self): return self.title users.models.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization', blank=True, null=True) profile_pic = models.ImageField(default='default_person.jpg', upload_to='profile_pics') blog/researcher-profile.html {% extends 'users/base.html' %} {% block content %} <div class="content-section"> <div class="media"> … -
How do class-based views work in Django Rest Framework?
I want to have an understanding to reason about Django + DRF. I'm following along the tutorial on the Django Rest Framework site Consider the SnippetList class in views.py: class SnippetList(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data) I'm used to JavasCript and to a more imperative way of doing things and it feels that there is a lot of magic here since I'm not explicitly instantiating any classes nor calling any methods. So, my question is, what happens when I request this view? How can I reason about the steps and the process? I visit the endpoint in http://127.0.0.1:8000/snippets/ to get a list of all the snippets and what is the cascade of events thereafter? How is the /snippets/ query parameter passed to the view class? I realise it's it might not be a specific enough question but I'm trying to disentangle the magic happening behind the scenes. -
Django rest framework 401 error with React Axios
Im working on a project with Django rest framework backend and React as frontend. Axios is used for http request and JWT for authentication. I issue im facing is that, after login and getting token django is throwing 401 error for every request. But this issue is resolved if header config is toggled for Axios. Please find the below codes for your reference and help to resolve. Thanks in advance. DRF **settings.py** REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=2), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': True, } CORS_ALLOWED_ORIGINS = [ "http://localhost:3000" ] **axios setup** const axiosClient = axios.create({ baseURL: import.meta.env.VITE_API_URL, headers: { "Content-Type": "application/json", }, }); export default axiosClient; const jToken = useSelector((state) => state.authSlice.accessToken); axiosClient.interceptors.request.use(function (config) { config.headers.Authorization = `Bearer ${jToken}`; return config; }); **Axios request** const fetchData = async () => { try { const response = await axiosClient.get(AppContext.managementStudentUri); // console.log(response.data); setData(response.data); setIsLoading(false); } catch (error) { apiErrorHandler(error); } }; -
Django dumpdata-loaddata serialize custom class
[Django 2.2] I'm trying to create a set of fixtures from my database using the dumpdata command provided by Django. I want to be able to load these fixtures using the loaddata command. One of the Models I'm trying to dump has a custom field: particularly, I'm facing my problem with a field (of type MyHStoreField) that inherits from django.HStoreField. Django is incapable of serializing MyHStoreField. From the Django docs, I think that what this class needs to be serialized is a custom JSONEncoder (https://docs.djangoproject.com/en/2.2/topics/serialization/#json-1). However, I don't know how to tell both dumpdata and loaddata to use this Encoder. Is there any kind of registry that django uses in order to know which Encoders are available, or do I need to override the loaddata and dumpdata commands somehow? -
how to reflect changes that applied directly though database shell to django model?
We had to change the datatype of a table primary key from int to bigint but we did it manually through PSQL for many reasons and now we want that to be reflected in Django. changing the id type like that id = models.BigAutoField(primary_key=True) will create a migration and it will be applied is there any way to mark migration as applied or edit Django tables to avoid migrations here? As we have a really restricted pipeline and changing it to run migration with --fake is a really big hassle so I prefer code changes or database changes over running --fake -
Django- error in if condition of django template language while cheking != condition
here the request.user = timon and user.username = timon so the if couldn't should not run for user timon but it does???? in the list of send message to the timon should not be included -
In Wagtail, I want to expose the API but only to internal/authorized services
I followed the Wagtail instructions to set up the API v2 in my Wagtail CMS. The CMS will be used in headed mode, but I still want to enable the API so that another service can query for the raw information directly. However, I don't want to enable the API to just be publicly accessible, since that would allow malicious actors to completely scrap the contents of my website. How could I add authentication to the API url paths, so that only certain services can access it (probably by sharing a secret)? I've seen that, on a view, I could add something like @login_required, but 1) I'm not sure if I really want other services to be logged in, I just need them to be identified with some secret value and 2) ideally I'd do this at the url rather than the view level, which could change with updates. Even so, I tried extending the PagesAPIViewSet to have a CustomAPIViewSet(PagesAPIViewSet) that included the @login_required tag, but I wasn't able to make that work either (it complained about the get_urlpatterns, for which I could find no workaround trying to extend the method of the BaseAPIViewSet) -
Hot reload in Django app inside docker containers not working
So today is my first day ever to use docker, I tried use it many times but I noticed that hot reload does not work I opened the container using vscode and navigate through the files and tried changing files and nothing happens here's Dockerfile FROM python:3.8-slim-buster WORKDIR /usr/project ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 COPY . . RUN pip install -r requirements.txt and here's docker-compose.yml version: '3.7' services: web: restart : always build: context: . dockerfile: Dockerfile command: sh -c "python manage.py runserver 0.0.0.0:8000" ports: - "8000:8000" env_file: - .env volumes: - .:/user/project even unchecked docker-compose 2 from desktop docker and restarted the app and the containers, still nothing happens, so what am I doing wrong? -
Django - Form-Select field set as not required not working
I have a form and want to make some fields not required. It's working for most, but pairing_rum field (and a few others) are causing some difficulties. For this question I removed the other fields as they are in the same format as rum_pairing. Here is what I tried so far: using the same format as venue ie forms.ModelChoiceField(queryset = Venue.objects.all() - but how can I filter to only get the choices contained within the field of the model? I also tried to modify the forms __init__, but no luck (example below - sorry for the formatting, stack is not letting me putting it in a code format) def init(self, *args, **kwargs): super(ReviewRating, self).init(*args, **kwargs) self.fields['pairing_rum'].required = False Which renders the following error: super(type, obj): obj must be an instance or subtype of type What would be the best way to make pairing_rum field not requried? My current code is as follows: models class ReviewRating(models.Model): user = models.ForeignKey(User,blank=True,null=True, on_delete=models.SET_NULL, related_name="usercomments") product=models.ForeignKey(Product,related_name="comments",null=True, on_delete=models.SET_NULL) pairing_rum = models.IntegerField(choices=RUM_PAIRING, default=0, blank=True) review =models.TextField(max_length=250, blank=True) rating =models.IntegerField(choices=RATING, default=0) venue = models.ForeignKey(Venue, blank=True, null=True, related_name="venues", on_delete=models.SET_NULL) forms class ReviewForm(forms.ModelForm): venue = forms.ModelChoiceField(queryset = Venue.objects.all(),required=False) class Meta: model = ReviewRating fields = ['review', 'rating','venue','pairing_rum'] widgets = { … -
How to see what data is passed to the class?
I have a product model with a json field as product attributes. I want to make filters on all keys of this field. I am using Djnago-filter. enter image description here When I declare a field and process this request in the method, everything works. Example: tip = django_filters.CharFilter(method = 'filter_attrs') "api/v1/product/?tip=Городской" name = tip in the "filter_attrs" method I get the name argument which is equal to the key in the filter. Its work. But if I make such a "api/v1/product/?ves=30" request, the method is not even called. So I want this method to process requests regardless of what is in the name argument. I wanted to see inside the class what request comes in and in what case the method is called, and override this rule. But I don't understand how to do it. Please help me how to learn how to do this so that in the future I can cope with such tasks on my own I tried to call the "init" method inside which to call print(request,queryset), but this method was apparently not called, I did not see anything in the terminal. I tore off the files filterset.py(djang0_filters/rest_framework/filterset.py) and tried to find methods in which … -
Tell me how to transfer this code from Html to models
There is a code in html {{post.author.posts.count}} that counts the number of posts by the author. I have such a question, how to transfer it to views.py The code looks like this. enter image description hereenter image description here I need to find an existing post, find its author and sort all posts by this author and calculate the total number of posts -
psycopg2.errors.ActiveSqlTransaction: CREATE DATABASE cannot run inside a transaction block
I am trying to create a Django app that creates a new database for every user when he/she signs up. I am going with this approach due to some reason. I have tried many ways using management commands and even Celery. But I am still getting the same error. 2022-12-23 07:16:07.410 UTC [49] STATEMENT: CREATE DATABASE tenant_asdadsad [2022-12-23 07:16:07,415: ERROR/ForkPoolWorker-4] Task user.utils.create_database[089b0bc0-0b5f-4199-8cf3-bc336acc7624] raised unexpected: ActiveSqlTransaction('CREATE DATABASE cannot run inside a transaction block\n') Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/app/user/utils.py", line 45, in create_database cursor.execute(f'CREATE DATABASE tenant_{tenant_id}') psycopg2.errors.ActiveSqlTransaction: CREATE DATABASE cannot run inside a transaction block This is my task @shared_task def create_database(tenant_id): conn = psycopg2.connect(database="mydb", user="dbuser", password="mypass", host="db") cursor = conn.cursor() transaction.set_autocommit(True) cursor.execute(f'CREATE DATABASE tenant_{tenant_id}') cursor.execute(f'GRANT ALL PRIVILEGES ON DATABASE tenant_{tenant_id} TO dbuser') cursor.close() conn.close() I have tried several ways but I always get the same error This is my API call def create(self, request, *args, **kwargs): serializer_class = mySerializer(data=request.data) if serializer_class.is_valid(): validated_data = serializer_class.validated_data or = validated_data["org"] or = Org.objects.create(**org) create_database.delay(str(or.id)) return Response(create_user(validated_data)) -
Why does Django app through an error when run in a Docker container
Am building a Django microfrontend App using in docker. When i run the dev server with python manage.py runserver ```, the app spins up at http://127.0.0.1:8000/ but after configuration with Dockerfile and docker-compose.yml, as **Dockerfile** FROM python:3.9 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 8.8.0.0:8000 **docker-compose.yml** version: '3.8' services: backend: build: context: . dockerfile: Dockerfile ports: - 8000:8000 volumes: - .:/app depends_on: - db db: image: mysql:5.7.22 restart: always environment: MYSQL_DATABASE: admin MYSQL_USER: root MYSQL_ROOT_PASSWORD: root volumes: - .dbdata:/var/lib/mysql ports: - 33066:3306 docker-compose up throughs the error; Django version 3.1.3, using settings 'admin.settings' backend_1 | Starting development server at http://8.8.0.0:8000/ backend_1 | Quit the server with CONTROL-C. backend_1 | Error: That IP address can't be assigned to. admin_backend_1 exited with code 1 what am I doing wrong, thanks tried to change the server port at CMD python manage.py runserver 8.8.0.0:8000 to CMD python manage.py runserver 0.0.0.0:8000 expecting to host using my host machine IP address, but all in vain -
Complete the code below to create a query that returns all products with a price greater than 50 that have the word "red" in their name:
`from myapp.models import Product products = Product.objects. #Complete here` I tried to do it but I didn't understand, because I'm a beginner