Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
PostgreSQL JOIN query much slower via Django than on simple Python interpretor
here is a topic I have been struggling on for a small while now. For now, I decided to just limit the requests sizes, but I'd like to know why this happened. If you can take some time solving this problem, thank you. Context Here are the models: class Zone(Model): zone_id = BigAutoField(primary_key=True) type = CharField(max_length=6, choices=('TypeA', 'TYpeB', 'TypeC')) other_fields class User(Model): user_id = BigAutoField(primary_key=True) other_fields class Access(Model): access_id= BigAutoField(primary_key=True) zone_id = BigIntegerField(null=False, empty=False) user_id = BigIntegerField(null=False, empty=False) There are two databases. These models are on the one I do not own, I only have USAGE rights. That is why I did not add ForeignKeyField, fearing that Django would want to consider its own automatically generated indexes with this, while that's not how the database has been set. The database is using PostgreSQL. The table Zone has its indexes zone_access_id_idx and zone_user_id_idx set already, and that is why, I suppose, when I run the predictable JOIN sql query (detailed below) on psql console and even on simple python, independent script using psycop2, the result is instantaneous. (the size of zone table is like 100,000 in total, but I filter it to 100 in the query) (the nb of accesses I … -
Django: Passing argument via image to get a filtered view in next page
I am having a big confusion right now and can't any good answers online about my issue. What I am trying to do is, to let the users click on an image. I have 52 different images on my page and by clicking on the image i want to pass an int between 1-53 (52 is missing) in order to get a filtered view. What I have is models.py class CentroidCount(models.Model): id_centroid_count = models.AutoField(primary_key=True) id_observation = models.ForeignKey('Observation', models.DO_NOTHING, db_column='id_observation', blank=True, null=True) step = models.SmallIntegerField(blank=True, null=True) centroid = models.SmallIntegerField(blank=True, null=True) count = models.SmallIntegerField(blank=True, null=True) class Meta: managed = False db_table = 'centroid_count' ordering = ['id_observation', 'step', 'centroid'] def get_absolute_url(self): return reverse('centroid-detail', args=[str(self.id_centroid_count)]) def __str__(self): return 'Observation: %s' % (self.id_observation) urls.py urlpatterns = [ path('', views.index, name='index'), path('observations/', views.ObservationListView.as_view(), name='observations'), ] views.py class ObservationListView(generic.ListView): model = CentroidCount context_object_name = 'observation_list' queryset = CentroidCount.objects.filter(centroid__in=[]).order_by('id_observation').values_list('id_observation', flat=True).distinct() template_name = 'centroid_webapp/observation_list.html' def get_queryset(self): return CentroidCount.objects.filter(centroid__in=[2]).order_by('id_observation').values_list('id_observation', flat=True).distinct() and the image part of the html <div class="col-sm"> <img src="{% static 'images/1.png'%}" class='img-fluid' alt='Responsive image'> </div> What i still don't understand fully is how can be this done dynmaically. What i do have now is a static page that is filterint out all "id_observations" with the number 2. But … -
Django not serving static files and not stylizing anything
I downloaded a template in the form of a zip file on my machine. It has a file for a homepage, auth-login.html. If I load this on its own then it loads correctly, I see styling and I don't get any console errors. But it seems like I can't get this template to load its css and styling in my Django project via python manage.py runserver with DEBUG=true. I'm trying to just get this on a development server and I haven't really been able to get past step 1. When I try to go to my application's home page, I see unstylized times new roman text in my browser. No styling loads on the page at all. I'm not getting server/console errors either. My Django project is of the following structure lpbsproject/ project_root/ staticFiles/ (STATIC_ROOT, where collectstatic copies to) project_app/ settings.py urls.py wsgi.py, asgi.py, __init__.py... static/ (STATIC_URL, original location of static files) assets/ (this folder is copied/pasted from the template .zip) css/, js/, ... user_auth/ migrations views.py admin.py, models.py, apps.py, test.py ... templates/ manage.py Here's the <head> of my html file with all the <link> and <script> statements. These currently aren't generating errors. {% load static %} <!doctype html> <html … -
django.core.exceptions.ImproperlyConfigured: Cannot import 'educations'. Check that 'careers.apps.EducationsConfig.name' is correct
I can't import my apps. I think path is ok but don't know how to solve this problem. is there any problem in my code? carrers>apps.py from django.apps import AppConfig class CareersConfig(AppConfig): name = "careers" class EducationsConfig(AppConfig): name = "educations" django.core.exceptions.ImproperlyConfigured: Cannot import 'educations'. Check that 'careers.apps.EducationsConfig.name' is correct. settings.py > PROJECT_APPS = [ "cores.apps.CoresConfig", "users.apps.UsersConfig", "reviewers.apps.ReviewersConfig", "careers.apps.CareersConfig", "careers.apps.EducationsConfig", "conversations.apps.ConversationsConfig", "unions.apps.UnionsConfig", "posts.apps.PostsConfig", -
Default Language problem in django although Language_code is set
Default Language problem in django although Language_code is set.The problem is as follows: LANGUAGES = ( ('kmr', gettext_noop('Kurmanji')), ('ckb', gettext_noop('Sorani')), #('en', gettext_noop('English US')), ) LANGUAGE_CODE = 'kmr' if 'en' is in commented then default language works as required.But if I un-comment the 'en'then 'en' remains the default language in django app.whatever i tried it is always makes 'en' as default langues. -
Elastic Beanstalk Editing Files Online?
I deployed my Django website on AWS elastic beanstalk. I have deployed PHP websites previously on GoDaddy and some other hosting. As there is method to edit your PHP files over internet as I can login my account on another pc and edit the files. But until now I am unable to find a way to do so in elastic beanstalk to let me or some one else to edit the files online. Currently all my are on my laptop. It may be silly question but I just want to know. -
Django OSError [Errno 101]
when i test my project on my local machine it was work butt when i deploy my code on my host after submit form data i get this error and i don't receive email. settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'vanguardteam99@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = "*********" views.py: send_mail( 'همکاری با ما', 'name: {}\n, age: {}\n, cell_phone: {}\n, email: {}\n, skills: {}\n, message: {}\n'.format( name, age, cell_phone, email, dev_skills_str, description), settings.EMAIL_HOST_USER, ['vangaurdteam99@gmail.com'] ) error massage: OSError at /vanguard_projects/project_request [Errno 101] Network is unreachable Request Method: POST Request URL: http://vanguard-group.ir/vanguard_projects/project_request Django Version: 3.1.3 Exception Type: OSError Exception Value: [Errno 101] Network is unreachable Exception Location: /opt/alt/python37/lib64/python3.7/socket.py, line 716, in create_connection Python Executable: /home/vanguard/virtualenv/vanguard_land/3.7/bin/python3.7_bin Python Version: 3.7.8 Python Path: ['/home/vanguard/vanguard_land', '/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts', '/home/vanguard/virtualenv/vanguard_land/3.7/lib64/python37.zip', '/home/vanguard/virtualenv/vanguard_land/3.7/lib64/python3.7', '/home/vanguard/virtualenv/vanguard_land/3.7/lib64/python3.7/lib-dynload', '/opt/alt/python37/lib64/python3.7', '/opt/alt/python37/lib/python3.7', '/home/vanguard/virtualenv/vanguard_land/3.7/lib/python3.7/site-packages'] Server time: Tue, 24 Nov 2020 13:27:01 +0000 -
What's the best way to create a web mapping app with Django?
Should I use leaflet, vue-leaflet, folium, mapbox or other techno ? Thank you -
Django reverse foreignkey filter return multiple same objects
I have a favorite system. So I check that a user already liked the post. I've written this query. But there is a problem since I don't delete the favorite's records. I just change the status of favorite's record. So if the user deletes the favorite before, my queryset return 2 rows for each them. I use MySQL for the database. def is_favorite(self, user): if user.is_authenticated: return self.annotate(is_favorite=Case( When(Q(favorites__user=user, favorites__is_deleted=False), then=Value(True)), default=Value(False), output_field=BooleanField() ) ).prefetch_related("favorites") return self.annotate(is_favorite=Value(False, output_field=BooleanField())) My query Blog.objects.all().is_favorite(self.request.user).distinct() Queryset's return [ { "id" : 1, "title": "foo", "is_favorite" : false }, { "id" : 1, "title": "foo", "is_favorite" : true } ]