Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does anyone know if it's possible to put your Django Heroku apps onto App Store/Google Play?
I have several apps that i've written in Django and host on Heroku. The website address works great but if people want to use my app on their mobile device i have to instruct them to visit the website then click Add to Home Screen so an app icon appears on their phone. Is there a better way of doing this so they can just add the app from say the App Store/Google Play? Thanks in advance. -
ImportError: cannot import name 'TagHelperNode' from 'django.template.base'
I'm facing the error of cannot import name 'TagHelperNode' from 'django.template.base' while im trying to migrate to django 3.2 I know that the problem will be solved if I downgrad django but I can't do that -
Docker-compose environment variable is not set
Project tree /backend .env.dev docker-compose-dev.yml /project I have the following warning: docker-compose -f docker-compose-dev.yml up --build # i am in the /backend directory WARNING: The DB_USER variable is not set. Defaulting to a blank string. WARNING: The DB_PASSWORD variable is not set. Defaulting to a blank string. WARNING: The DB_NAME variable is not set. Defaulting to a blank string. It means that docker compose don't see my environment file. How can I fix it? docker-compose-dev.yml 1 version: '3.3' 2 3 services: 4 django: 5 build: ./project # path to Dockerfile 6 env_file: 7 - ./.env.dev 8 command: sh -c " 9 sleep 3 && gunicorn -w 8 --bind 0.0.0.0:8800 core_app.wsgi" 10 volumes: 11 - ./project:/project 12 - ./project/static:/project/static 13 - ./project/media:/project/media 14 - ./project/logs:/project/logs 15 expose: 16 - 8800 17 depends_on: 18 - db ....... How can I enable env file? -
How to get user of one microservice to another microservice and authenticated using DRF
I am trying to seprate the monolithic DRF project to microservices, i am using postgres database and planning to user rabbitmq as a message broker if requried. Hello everyone, I am trying to seprate monolithic DRF project into microservices, I am planing to make two microservices. one is user_auth project and another is post project. as i mentioned above i have already created project in monolithic approch and i seprate the user_auth project part while seprating the the post project, i have a problem with geting user details in post project from the user_auth project, for exmaple i want to make a post from the specific user who is login into the user_auth project but i am not able to get the user and its login status. can anyone over there help me to seprate those project into micro services also want to menthion that i do have a seprate database for two project which is postgres and i was planning to use rabbitmq as a message broker if needed. Thanks in Advance -
How Can I remove :8000 from the URL when I publish my Django project on Linode?
I have a project that has been developed using Django and is published to Linode cloud Hosting. By default each Django project is being run on localhost:8000 and for this reason now I can access my project using IP_Address:8000 or mydomain.com:8000. I want to access the project without mentioning the port number (:8000). I have added my IP address and domain name inside settings.py like below: ALLOWED_HOSTS = ['mydomain.com', '176.xx.xxx.xxx'] But I still need to specify the port number how can I solve this problem. By the way I used Linode's default python installation for the start point of my project then I changed some files and of course added new files and so on. How can I solve this problem? -
Use function for value input in html with ajax, jquery
I have an ajax function which is actually working good but I don't know how to use it on the html. What I need to achieve is that basically, attached to each checkbox there is a certain number of questions. They're all selected by default but, if I deselect one of them, the number of questions of that particular checkbox should be removed. The function I am using is working fine (in the console) but I couldn't find a way to use it on the HTML. I post some code for more clarity. let subjectId; $("#selection").on("change", function () { const selectSubjBtn = document.getElementById("select_subject"); subjectId = $(this).children(":selected").val(); let labelText = gettext( "Select the number of questions by moving the button to the right or left!" ); let title = gettext("Select Number of Questions"); let selectedQuestionsNum; $.ajax({ type: "GET", url: "/quiz/ajax_questions/" + subjectId, success: function (response) { let questions = response.questions; let topics = response.topics; let topicQuestionNum = response.question_num_list; if (topicQuestionNum != 0) { let topicsObj = topics.map(function (e, i) { return [e, topicQuestionNum[i]]; }); let subTopicHtml; // $("#sub_topic_box").append( // '<input class="form-check-input mt-0 ms-3" type="checkbox" value="" id="selectAll" checked aria-label="Checkbox for following text input">' // ); topicsObj.forEach((el) => { subTopicHtml = '<div class="row … -
Retrieve an Object using Multiple Parameters inside of an Url in Django-Rest-Framework
How to retrieve an object using multiple parameters in url? Example : 'customer/3/order/1/' or 'customer/<int:customer_pk>/order/<int:pk>/' Using shell i'm able to get the object like this but i can't seem to do it from the views. >>> from temp.models import Customer, Order >>> from temp.serializers import CustomerSerializer, OrderSerializer >>> q = Order.objects.filter(customer=1).get(order_number=2) >>> q.order_name 'fruit' views.py from rest_framework import generics, status from rest_framework.views import APIView from rest_framework.response import Response from django.shortcuts import get_object_or_404 from .models import * from .serializers import * class CustomerListView(generics.ListCreateAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class CustomerDetailView(generics.RetrieveDestroyAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class OrderListView(generics.ListCreateAPIView): def get_queryset(self): queryset = Order.objects.filter(customer_id=self.kwargs["pk"]) return queryset serializer_class = OrderSerializer class OrderDetailView(generics.RetrieveDestroyAPIView): serializer_class = OrderSerializer def get_queryset(self): queryset = Order.objects.filter(customer_id=self.kwargs["customer_pk"]).get(order_number=self.kwargs["pk"]) return queryset urls.py from django.urls import path from .views import * urlpatterns = [ path('', CustomerListView.as_view()), path('<int:pk>/', CustomerDetailView.as_view()), path('<int:pk>/orders/', OrderListView.as_view()), path('<int:customer_pk>/orders/<int:pk>/', OrderDetailView.as_view()), ] -
Monitoring more than one instance with Django Channels Websockets
I'm trying to make a monitoring app with Django and the Django-Channels websockets library. The idea is that, two players are playing a Tic-Tac-Toe game on my site. The third person as the admin is capable of monitoring whats going on on the board in real time. This means that the admin has in front of him the same board as the players and what players are playing. The question is, am I capable of monitoring two instances at the same time when two players are playing another game like Bingo? In this case the players have two other instances of the board, so could I replicate in real time two different boards on one page for the admin? Are there any articles, videos, tutorials to which I can refer to? Even for the monitoring part as a third person that can track a game of Tic-Tac-Toe. I'm trying to make this in Django for the backend and JavaScript/React for the frontend. Only help that I can find with websockets in Django are chat apps or some games like Tic-Tac-Toe but I would like to go a step further and add a third person that could monitor whats going on. -
ValueError at /form The view authentication.views.my_form didn't return an HttpResponse object. It returned None instead
I am trying to create a form but facing issues, any kind of help will be appreciated. Thanks in advance. Below is my views.py from django.contrib.auth import authenticate, login, logout from django.contrib.sites.shortcuts import get_current_site from django.core.mail import send_mail, EmailMessage from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.template.loader import render_to_string from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from . tokens import generate_token from Database import settings from django.shortcuts import render from .models import Inventory_Details from .forms import MyForm def my_form(request): if request.method == "POST": form = my_form(request.POST) if form.is_valid(): form.save() else: form = my_form() return render(request, "authentication/Inventory_details.html", {'form': form}) detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Inventory_details</title> </head> <body> <div class="container"> <form method="POST"> <fieldset> <legend>Form</legend> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Submit</button> </fieldset> </form> </div> </body> </html> Below is the error message: ValueError at /form The view authentication.views.my_form didn't return an HttpResponse object. It returned None instead. Thanks -
How to store dynamicly URLpatterns in databse with django
I want to store in a my database all the url of my web app and associate to them a page title and a tab title. I already have a ton of them that i want to store and i want to dynamical add them when i create a new path in UrlPattern. So far i used this command "python manage.py show_urls > urls.txt" to get the url in a file but they might be something easier than parse this file. -
Reason why reverse relation filtering fails when m2m field uses a string class?
I ran into a strange issue using Django 2.2 and trying to filter a reverse relation which was defined using a string reference to the class. The issue goes away if I pass the class itself, ie. This FAILS: class Whatever(models.Model): providers = models.ManyToManyField('Relation', related_name='dependants') This WORKS: from models import Relation class Whatever(models.Model): providers = models.ManyToManyField(Relation, related_name='dependants') Note the only difference is whatever the m2m field is declared using a string or a model class. When I have the foreign model as a string and I call: Relation.objects.filter(dependants=1) The error I get is: FieldError: Cannot resolve keyword 'dependants' into field. Choices are: ... None of the listed choices is dependants, basically it's not available. This does work though: r = Relation.objects.first() r.dependants Using an imported model class solves my specific issue but the advantage of using a string class to resolve circular dependencies is lost. In case this happens again can anybody shed light on why it might happen? Is it a known bug solved in later versions of Django or a known limitation of using strings to specify classes? Note, I tried the following to resolve this: Simplifying both models so there were no special managers or other queryset … -
Django - validating m2m relationship
I have the following models: class Question(Model): # ... class Choice(Model): question = ForeignKey(Question) # ... class AnswerToQuestion(Model): user = ForeignKey(User) question = ForeignKey(Question) selected_choices = ManyToManyField(Choice) What I would like to do is make sure that the values inside of selected_choices will always be choices belonging to the question stored in the question field. This is what I tried in the clean method of AnswerToQuestion: def clean(self): super().clean() if self.pk and self.selected_choices.exclude(question=self.question).exists(): raise ValidationError("Invalid choice(s)") However, this does not work as expected: since the m2m relationship is updated after the actual model save, if I try and associate an invalid choice, this will work fine, and then every subsequent save will fail because I already have an invalid associated choice. Is there another way to achieve what I'm trying to do? -
how can i run the live stream without hitting the API
I want to run the cv2.videocapture in a background thread. without hitting the API URL. Now I'm using the below code but it starts the stream only I hit the server http://10.11.20.85:8089/. from django.shortcuts import render from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 import threading @gzip.gzip_page def Home(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: pass return render(request, 'home.html') class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture() (self.grabbed, self.frame) = self.video.read() t = threading.Thread(target=self.update, args=()) t.daemon = True t.start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') -
How to require django's authentication on strawberry-graphql
I want to require django's user authentication in order to access the graphql view. My first attempt was to decorate the view with login_required: from django.contrib.auth.decorators import login_required from django.urls import path urlpatterns = [ path("graphql/sync", login_required(GraphQLView.as_view(schema=schema))), path("graphql", login_required(AsyncGraphQLView.as_view(schema=schema))), ] It work for the sync view but not for the async one since login_required does not async aware. For now I endend-up to write my own view which copy the login_required behavior: from urllib.parse import urlparse from asgiref.sync import sync_to_async from strawberry.django.views import AsyncGraphQLView from django.conf import settings from django.contrib.auth.views import redirect_to_login from django.shortcuts import resolve_url from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt class LoginRequiredAsyncGraphQLView(AsyncGraphQLView): @method_decorator(csrf_exempt) async def dispatch(self, request, *args, **kwargs): is_authenticated = await sync_to_async(lambda: request.user.is_authenticated)() if not is_authenticated: path = request.build_absolute_uri() resolved_login_url = resolve_url(settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if (not login_scheme or login_scheme == current_scheme) and ( not login_netloc or login_netloc == current_netloc ): path = request.get_full_path() return redirect_to_login(path, resolved_login_url) return await super().dispatch(request, *args, **kwargs) # urls.py urlpatterns = [ path("graphql", LoginRequiredAsyncGraphQLView.as_view(schema=schema)), ] But it seems to not be a nice … -
how can i use javascript variable inside django inclusion tag?
I want to pass post.id(ajax response variable) as a parameter of django inclusion tag <script> revBox.innerHTML += ` {% if request.user.is_authenticated %} {% has_useful user ${post.id} %} {% comment %} I want to pass post.id(ajax response variable) as a parameter of django inclusion tag {% endcomment %} {% else %} ... {% endif %} </span>` -
Django: Model needs to have a value for field "id" before this many-to-many relationship can be used
I'm trying to create a new model2 whenever a new model1 is created and link these two models. Model2 have many to many relation with model1 @admin.register(model1) class model1Admin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if not obj.id: obj.payments.add(model2.objects.create()) super().save_model(request, obj, form, change) After trying the code above I get this error: needs to have a value for field "id" before this many-to-many relationship can be used -
Django orm queries with left varaible is not certain
I want to make a query like this: Student.objects.filter(id= id).update(name=value) And the value comes from the user. But the problem is that I'm not only to update name but also update some other information like address or phone number. I don't want to create duplicated codes like: Student.objects.filter(id= id).update(address=value) Student.objects.filter(id= id).update(phone_number=value) I only want to have one line code like: Student.objects.filter(id= id).update(XXX=XXX_value) So I wonder if I can assign any variable to the left varaible inside update function or not. Thanks. -
wsgi request doesn't change on changing request.GET
I wanted to change the query params from the get request but the query dict of the request is changing but not the request I did: request.GET._mutable = True # to make it editable request.GET.pop("session_key") request.GET._mutable = False request I have <WSGIRequest: GET 'dashboard/auth/complete/activities-update/?session_key=abbccddeeff&state=GKW9z7ET AR&response_type=code&scope=update&show_login=true'> request I wanted: <WSGIRequest: GET 'dashboard/auth/complete/activities-update/?state=GKW9z7ET AR&response_type=code&scope=update&show_login=true'> however the session key is getting removed from request.Get but request is same -
Query only existing elements in an ArrayField
from django.contrib.postgres.fields import ArrayField from django.db import models class Post(models.Model): name = models.CharField(max_length=200) tags = ArrayField(models.CharField(max_length=200), blank=True) Post.objects.create(name='a', tags=['1']) Post.objects.create(name='b', tags=['1', '2']) Post.objects.create(name='c', tags=['1', '2','3']) How to query tags=[2,1]? Query tags contain only the results of 1 and 2 -
TemplateDoesNotExist after running app on Heroku, locally works fine
I can run my app locally and deployed the app to Heroku successfully. Here is my project structure: root folder env src app fund static staticfiles templates includes funds_table.html pagination.html about_me.html base.html index.html user_account manage.py requirements.txt Procfile .gitignore Here is my settings for templates: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR), 'templates'], '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', ], }, }, ] When I open the app, I receive the error: raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html, fund/fund_list.html "GET / HTTP/1.1" 500 145 "https://dashboard.heroku.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" What is interesting, I don't even have the fund/fund_list.html in my app. I tried to use Search Everywhere in Pycharm, and this file doesn't exist and even hasn't been mentioned anywhere. I'm not sure why Heroku tries to find it. What I'm doing wrong? -
FATAL: password authentication failed for user "admin" Running kubernetes and django
I am working with kubernetes manifest files and facing issue regarding postgres. I have tried running postgres independently on kubernetes but when I run with this project this error pops up. I have tried numerous solutions but no one working. apiVersion: apps/v1 kind: Deployment metadata: name: postgres # Sets Deployment name spec: replicas: 1 selector: matchLabels: app: postgres template: metadata: labels: app: postgres spec: containers: - name: postgres image: postgres:13 # Sets Image imagePullPolicy: "IfNotPresent" ports: - containerPort: 5432 # Exposes container port envFrom: - configMapRef: name: postgres-config volumeMounts: - mountPath: /var/lib/postgresql/data name: postgredb volumes: - name: postgredb persistentVolumeClaim: claimName: postgres-pv-claim Service for this deployment. apiVersion: v1 kind: Service metadata: name: postgres-service labels: app: postgres spec: ports: - port: 5432 selector: app: postgres Deployment for django, apiVersion: apps/v1 kind: Deployment metadata: name: lm-web spec: replicas: 1 selector: matchLabels: app: lm-web template: metadata: labels: app: lm-web spec: containers: - name: lm-web image: <Django_image of Code.> ports: - containerPort: 8000 envFrom: - secretRef: name: lm-db-secret env: - name: DB_HOST value: "postgres-service" command: - /bin/sh - -c - ./entrypoint.sh Service for django, apiVersion: v1 kind: Service metadata: name: lm-web-service spec: selector: app: lm-web type: LoadBalancer ports: - protocol: TCP port: 8000 targetPort: 8000 … -
Django: django-admin-lightweight-date-hierarchy to show today objects
I'm trying to use this django package: https://github.com/hakib/django-admin-lightweight-date-hierarchy to filter the objects by created dates. But now I want to display today's created objects by default and if no date is selected. Otherwise and after selecting any date this should display the objects for the selected date. class Test(models.Model): full_name = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) deleted_at = models.DateTimeField(null=True, blank=True) @admin.register(Test) class MyModelAdmin(admin.ModelAdmin): date_hierarchy = 'created_at' date_hierarchy_drilldown = False list_filter = ( RangeBasedDateHierarchyListFilter, ) def get_queryset(self, request): qs = super(ShareAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(owner=request.user) def get_date_hierarchy_drilldown(self, year_lookup, month_lookup): """Drill-down only on past dates.""" today = timezone.now().date() if year_lookup is None and month_lookup is None: # Past 3 years. return ( datetime.date(y, 1, 1) for y in range(today.year - 2, today.year + 1) ) elif year_lookup is not None and month_lookup is None: # Past months of selected year. this_month = today.replace(day=1) return ( month for month in ( datetime.date(int(year_lookup), month, 1) for month in range(1, 13) ) if month <= this_month ) elif year_lookup is not None and month_lookup is not None: # Past days of selected month. days_in_month = calendar.monthrange(year_lookup, month_lookup)[1] return ( day for day in ( datetime.date(year_lookup, month_lookup, i + 1) for … -
can someone say how to load webpage nice and smooth using javascript and css [closed]
kindly tell me how to smooth webpage using java script and CSS in simple way try to smooth our webpage but it doesn't work properly , think have done the method wrong -
Lock delete () function - Django
Is there an option to disable the delete function in the project object if a non-admin user tries to do this via delete function? For example: class Product(models.Model): name = models.CharField(max_lenght=200) show = models.BooleanField() logs = models.TextField() And now if we have in code of project product.delete() we block it through the model property and check if it is an admin, if it is not an admin add a reflection in the field.: class Product(models.Model): name = models.CharField(max_lenght=200) show = models.BooleanField(default=True) logs = models.TextField() def delete(self, *args, **kwargs): super().save(*args, **kwargs) if request.user.is_superuser Product.delete() else: show = False logs = 'ther user try remove this ads in time: 08.11 04.11.2022' save() -
How to programmatically create Django models and set their null attributes?
I have a spreadsheet of object types and their required attributes like this: |col 0|col 1|col 2|...|col n| type 0 | y | n | n |...| y | type 1 | y | y | y |...| y | type 2 | n | n | y |...| n | ...... | n | n | y |...| y | type n | y | n | n |...| n | How can I programmatically create these object models (and the corresponding forms), and set their null properties according to the spreadsheet? How can I then display the form objects with only required inputs? I saw this question but I think mine is different. I am not seeking to dynamically add model attributes.