Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app deployment through ECS with uWSGI and nginx can't find some files
I'm currently deploying a containerized Django application on Amazon ECS using uWSGI and nginx, but I'm having some issues with my proxy finding some of the static content. When I test a local proxy deployment using docker-compose it works fine, but not when it's deployed through ECS. Here's my settings.py: # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/static/' MEDIA_URL = '/static/media/' STATIC_ROOT = '/vol/web/static' MEDIA_ROOT = '/vol/web/media' STATICFILES_DIRS = [ # '/var/www/static/', os.path.join(BASE_DIR, 'core/static'), ] Here's my proxy config: server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } Container definition for ECS: [ { "name": "app", "image": "${app_image}", "essential": true, "memoryReservation": 256, "environment": [ {"name": "DJANGO_SECRET_KEY", "value": "${django_secret_key}"}, {"name": "DB_HOST", "value": "${db_host}"}, {"name": "DB_NAME", "value": "${db_name}"}, {"name": "DB_USER", "value": "${db_user}"}, {"name": "DB_PASS", "value": "${db_pass}"}, {"name": "ALLOWED_HOSTS", "value": "${allowed_hosts}"} ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "${log_group_name}", "awslogs-region": "${log_group_region}", "awslogs-stream-prefix": "app" } }, "portMappings": [ { "containerPort": 9000, "hostPort": 9000 } ], "mountPoints": [ { "readOnly": false, "containerPath": "/vol/web", "sourceVolume": "static" } ] }, { "name": "proxy", "image": "${proxy_image}", "essential": true, "portMappings": [ { "containerPort": 8000, "hostPort": 8000 } ], "memoryReservation": 256, "environment": [ {"name": "APP_HOST", "value": … -
Creating Registration Form with Reactive and Bbackbone.js and use django in backend
Can someone help me. I am new to Reactive and Backbone.js . I have to create a application for candidate form for filling up all candidate details and resume upload with reactive and backbone and Used django as backend. Please suggest me how can i do this . -
Frontend Technology-> Angular and Backend technology-> Django = SaaS product
I am trying to deploy a SaaS product with the subject line mentioned tech stack. The problem I am facing is how we can dynamically map the frontend to the corresponding backend provided that these tech stacks are deployed in one server per each customer. I will be using AWS EC2 capabilities to launch the product but instead of manually mapping the frontend to the backend , I wanted to know if anyone can guide me on how to dynamically launch the frontend and backend mapped correctly to each other per user. Thanks, Winston John -
Django queryset latest object's attributes after group by
This is my model class MyLog(models.Model): email = models.EmailField() date = models.DateTimeField(auto_now_add=True) comment = models.CharField(max_length=150) What i am trying to do is group by email, then filter the query by repetitions greater than 5 after that get the comment field's value of the latest object (from latest date value). I am not able to acheive the last part. Here my query so far MyLog.objects.values("email").annotate(Count("id")).filter(id__count__gte=5) This much is correct I am getting output like <QuerySet [{'email': 'test@test.com', 'id__count': 6,}]> How can I query the latest comment ? I am not able to figure out how to query that. -
JSONDecodeError at /main Expecting value: line 1 column 1 (char 0) Django
I'm getting this error constantly. I have tried json.load/loads and dump to no avail. This is the documentation for the api https://www.arvancloud.com/docs/api/cdn/4.0#operation/reports.traffics.total The request is going through as I get a success message as a response but the json being returned throws this error. 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/{DomainName}/reports/traffics' req=requests.get(url,headers{"Authorization":"Apikey********","Contenttype":"application/json"}).json() print(req) return render(request, 'dashboard.html', {}) -
Django ORM distinct values by determined date having a MySQL DB
I want to read some logs of database with Django but I been having problems. My objective is to count how many users made requests in each day in the last 7 days. I've tried this by logs_seven_days = Log.objects.filter( created_at__gte=datetime.now()-timedelta(days=7))\ .extra({'date_of_request' : "date(created_at)"}) \ .values('date_of_request') \ .values('api_key__name') \ .distinct() \ .annotate(request_of_this_date_count=Count('id')) I was wanting something like this: distinct_user_requests date 4 2/21/2020 21 2/22/2020 5 2/23/2020 0 2/24/2020 43 2/25/2020 22 2/26/2020 -
Django MOD_WSGI Settings ? MOD_WSGI Apache2 403 You don't have permission to access this resource
I'm testing an app on Ubuntu Server 18.04(VirtualBox) before bought VPS service. This is my first deployment even if it's a test and on VB. I'm facing some kind of Apache WSGI error. Error: You don't have permission to access this resource Apache/2.4.29 (Ubuntu) Server at 192.xxx.xx.xxx Port 80 Before WSGI setup, i did run few test at 8000 port and it was running well. When i setup the WSGI on the server i can't get app running. App and venv located under /home/alp/diricanelektronik directory. My server username: alp and app name is diricangrup (I did change conf file and restart apache service) My head is about to explode. You are my last hope, please help me ufw status: 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) app home directory: (/home/alp/diricanelektronik/diricangrup) ├── contact │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── diricangrup │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── media ├── references │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── tests.py │ └── views.py ├── … -
I've imported some mysql data into the Django mysql db. How do I get Django models to work with my existing data?
I have an existing process building data daily. I've copied tables from my main mysql to a test-mysql so I can work with the data and get it right. I found an excellent post about building the correct model python manage.py inspectdb {tablename} which was 99% correct. I have a table called main which I'd like to connect to the main model. I've 50+ tables with titles like 1234 linked by a foreign key column called G to G in main. I've just realised the way Django stores models is completely different. It stores data in tables by {appname}_{model} Have I gone about this backwards? Should I have created the Django database first, and then added to it by its conventions? I've already put a lot of work into this and it would be a lot to redo it. If its best, that's what I'll do. Thanks, T -
'Profile' object is not iterable
views.py @login_required def friends_profile(request): f_profiles = Profile.objects.get(user=request.user) return render(request, 'mains/friends_profile.html', {'f_profiles':f_profiles} ) urls.py path('friends_profile/', views.friends_profile, name='friends_profile'), template = friends_profile.html {% extends "mains/base.html" %} {% block content %} {% for friends in f_profiles %} {{ friends.full_name }} {% empty %} <li>NO DATA</li> {% endfor %} {% endblock content %} 'Profile' object is not iterable. This is raising when i open this template( friends_profiles.html ). Please... Help me in this ERROR. What am i missing in this ? -
Django REST framework api root empty
I've setup a Django REST framework project but the api root hasn't been populated with anything eg a users ViewSet and I can't access the expected url with a list of users. There is one app users, with a custom user model. (and the django project is named api) main urls.py from django.contrib import admin from django.urls import path, include from rest_framework.routers import DefaultRouter urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('users.urls')), ] the users app urls.py from django.contrib import admin from django.urls import include, path from rest_framework.routers import DefaultRouter from users.views import CustomUserViewSet router = DefaultRouter() router.register("users", CustomUserViewSet, 'users') urlpatterns = [ ] urlpatterns += router.urls users models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass def __str__(self): return self.username users serialisers.py from rest_framework.serializers import ModelSerializer from .models import CustomUser class CustomUserSerializer(ModelSerializer): class Meta: model = CustomUser fields = '__all__' users app views.py from django.shortcuts import render from rest_framework.viewsets import ViewSet from .serializers import CustomUserSerializer from .models import CustomUser class CustomUserViewSet(ViewSet): serializer_class = CustomUserSerializer queryset = CustomUser.objects.all( And empty api root at localhost:8000/api/ and 404 error at localhost:8000/api/users/ -
Django: Ajax data changes when Django gets it
Something weird is happening to me and I don't know why: I have this data that I want to send throught ajax to django: const params = { "status__in":['pendant','confirmed'], "access_date__year":2020, "access_date__month":05, "billable":true } I use datatable to creat a table with the data that I receive, this is the ajax options for datatable: const ajax_options = { ajax: { url:get_consumptions_url, data: params } } Then I get the ajax params with this code: ajax_data = request.GET.dict() SO before trying to add an array to my params everything worked fine but when I check the ajax params debugging in python I get this: { 'access_date__month': '10', 'access_date__year': '2020', 'billable': 'true', 'status__in[]': 'confirmed' } Check "status__in" it completly changed from that I had in my params. Why is this happening? -
Occasional Client 400 Errors or Prematurely Closed Connections
I have been dealing with an issue that is rare and I can't repeat it. I have 100s of users everyday uploading files to my server. 99% of the time users are fine and have no issues uploading. Occasionally though someone will have trouble uploading and the issues seems to be client side. It can be resolved by having them go to another computer to upload. Having them clear their cache and cookies I assume would work to, but it is difficult to explain to a non technical user how to do that. I use django and manifset static files so they get cache busted anytime new scripts are added. Old scripts shouldn't be being used in their browser. I have implemented multiple methods of upload for when this happens. The standard way is an ajax single request to get a progress bar. If things fail I revert them to the most basic form request no progress bar. If that fails I also have a chunked upload method that allows them to upload in chunks. The most recent time this happened it failed on all those methods. The user received a 400 error when uploading via chunked. It seemed looking … -
Django Variable not getting showed
I have started my Djnago Journey, I am trying to print a defined variable in html file but not getting anything, please let me know whats wrong with the code my views.py, see the last method where I'm trying to post the data from django.shortcuts import render from django.http import HttpResponse, JsonResponse # Create your views here. def bootstrappage(request): return render(request, 'index.html') def secondpage(request): return render(request, 'common.html') def thirdpage(request): var = 'this is my first variable' mydictionary = { "first": var, 'two':"data of two" } print(mydictionary["first"]) return render(request, 'third.html', context=mydictionary) third.html file where I am trying to print the variable <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> {% extends 'index.html' %} {% block title %}Third page{% endblock %} {% block name %}Viewing Third page!{% endblock %} {{first}} {{two}} </body> </html> index.html file, this is taken from official bootstrap site, basic code of navbar. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>{% block title %}bootstrap{% endblock %}</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div … -
Async logging in Django
I have created a simple weather webapp in Django using API. Logging is enabled and are written into files in Windows. I want logging to be asynchronous that is at the end of execution. How can we do async logging in Django? -
How can I install Django in my Docker file?
I am a newbie to Docker. I have created one Django project and can run it in Docker. However, I have started a second project and have encountered a problem. I created a virtual env and entered it pipenv install django~=3.1.0 && pipenv shell I created a Django project django-admin startproject config . I ran it within the virtualenv python manage.py runserver and could see the Django spaceship I then exited the virtualenv and created a Dockerfile Dockerfile # Pull base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ I ran docker build . and it reported a successful build I created a docker-compose.yml file docker-compose.yml version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 When I run docker-compose up it complains ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I have read in the comments to this question that virtual envs should not … -
How to get rid of no carparks found for no such campus
{% if campus %} <h2>{{ campus }}</h2> {% else %} <h2>No such campus</h2> {% endif %} {% if carparks %} <ul> {% for carpark in carparks %} <li>{{carpark.name}}: {{carpark.spaces}} spaces, {{carpark.disabled_spaces}} spaces for people with disabilities <br>Spaces available: {{ carpark.spaces_available }}<br><br> </li> {% endfor %} {% else%} <p>No carparks found</p> {% endif %} </ul> This is my carparks.html code, when I type the name of a campus that is not stored in the Django database, it says both 'No such campus' and 'No carparks found'. How do I only print 'No such campus' for a campus that does not exist? -
Validating keycloak bearer token on behalf of client
I want to validate bearer tokens in an API, which are passed from a browser application. The API will validate the tokens against Keycloak by calling the ../userinfo endpoint and respond with the desired content if the check runs ok. Problem is that If I pass a bearer token from the browser, or any other app for that matter (e.g. postman), to the api and try to validate it - I get "401 Token verification failed". The following works: Fetch token from Keycloak through Postman by using username and password. Fetch userinfo from Keycloak through Postman using the resulting bearer token. OR Fetch token from Keycloak directly from the API by using username and password. Fetch userinfo from Keycloak from the API using the resulting bearer token. The following does NOT work: Fetch token from Keycloak through Postman by using username and password. Send request to API, running in a docker container, containing the bearer token. API tries to fetch userinfo using the token = "401 Token verification failed" Using same client_id and client_secret in all scenarios. Is this a docker networking thing? Or is some Keycloak configuration necessary in order for the API to validate token "on behalf" of … -
aws boto3 s3bucket CreateMultipartUpload access denied overwriting
I am using s3bucket with django and it was worked very well. My client given access to his aws and i used in the application of my own credentials that he created for me. It was really working well for deleting, updating, creating, uploading for anything. But now Revoked the access of the user that created for me and he created another user for his another developer, so he updated the access key and the secret key of that newly created account in the script. Even now with the new updated key, everything working but it's not working once I/we try to overwrite a pdf file. It fires me/us this error: raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the CreateMultipartUpload operation: Access Denied Most of the file is being created with my access key and secret but as a client using another key and secret, the overwriting is failed for that file that it created by my access key. I am not getting what is the reason of this and how to solve this problem. I went through too much StackOverflow solution but no luck. We are using same bucket but with a different access key and … -
Reverse for 'topping' not found. 'topping' is not a valid view function or pattern name
When i try to run server i get the error "Reverse for 'topping' not found. 'topping' is not a valid view function or pattern name." Error at line 11 9 <a href="{% url 'pizza:index' %}"> Pizzeria</a>- 10 <a href="{% url 'pizza:pizzas' %}"> Pizzas </a>- 11 <a href="{% url 'pizza:topping' %}"> Toppings </a> views.py def topping(request, pizza_id): pizza = Pizza.objects.get(id=pizza_id) toppings = Pizza.topping_set.order_by('id') context = {'pizza': pizza, 'toppings' : toppings} return render(request, 'pizza/topping.html', context) app/urls.py urlpatterns = [ #homepage url(r'^$', views.index, name='index'), #pizzas page url(r'^pizzas/$', views.pizzas, name='pizzas'), # Detail page for a single pizza url(r'^pizza/(?P<pizza_id>\d+)/$', views.topping, name='pizza'), ] topping.html {%block content%} <p>Pizza : {{pizza}}</p> <p>Toppings:</p> <ul> {%for topping in toppings%} <li>{{topping}}</li> {%empty%} <li>no topping have been added yet.</li> {%endfor%} base.html <a href="{% url 'pizza:index' %}"> Pizzeria</a>- <a href="{% url 'pizza:pizzas' %}"> Pizzas </a>- <a href="{% url 'pizza:topping' %}"> Toppings </a> -
Django in-memory database
I am running a web application with a low latency requirement using Django. However, my MySQL server is currently being a bottleneck. I want to replace it with a completely in-memory database. However, the solutions I have looked at so far create an in-memory database that is local to a particular process. I am running multiple Django processes and need the database to be shared among them. Are there any such databases that can be integrated with Django? -
Django randomly stopped working post homebrew update
I installed gnu-prolog via homebrew, then homebrew updated itself. Now, django has stopped working entirely. I used a venv to install and run django - the path to that is desktop/tinker/thanos within that is my project folder - django_project Everything was working perfectly fine until this homebrew update. I have looked up countless stack overflow threads, yet each solution just pops up a new problem. Now I have the following problems - (thanos) django_project $python manage.py runserver File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax on changing python to python3 - (thanos) django_project $python3 manage.py runserver Traceback (most recent call last): File "/Users/X/Desktop/tinker/thanos/django_project/manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/X/Desktop/tinker/thanos/django_project/manage.py", line 21, in <module> main() File "/Users/X/Desktop/tinker/thanos/django_project/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? the virtual environment is activated. here is the manage.py file - #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', … -
How to break single migration file into multiple migration file in django
At the start of the Project, I was having 3 migrations files (as there were 3 model classes) but somehow my code was not working so I deleted all of them and executed migration code. But after executing the same, only 1 migration file got created and entry of all model classes are there. So can someone please let me know how to break this single file into 3 migration file in Django so that I can run my code again. Thanks in advance.. -
Generate an HTML page using Django
I am making a small website, I have a basic (working) inteface: Home, about us, login/register ... What I'd like to do now it to setup a page with a "form" page which would generate and save an HTML page containing the data of the form and make it accesible from the "home" page. I know how to make the form, but I don't know if it's possible to create a HTML page in django. Thanks in advance -
Related Name Issue in my Django Application
I am trying to change the Django default User Authentication and permissions classes. While trying to do that, I got issues related to the related name and when I added it to my codes it still continued giving me the same issue. Here is the error log django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. core.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. core.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. System check identified 4 issues (0 silenced). Here is my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have … -
Initialize counter inside html django
Is there any way to initialize a counter and increase it during a for loop in django html? I have the following code that display a list of matrices as tables. {% if matrixs %} <h5 style="text-align: center;">Simple Gaussian Elimination </h5> {%for matrix in matrixs%} <table class="result" align="center" style="text-align:center;"> {% for row in matrix %} <tr> {% for element in row %} <td> {{ element }} </td> {%endfor %} </tr> <br> {%endfor %} </table> <br> {%endfor%} {% endif %} I want to be able to display the number of the iteration in top of the table like "matrix 1", "matrix 2", ... Thank you