Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django - pass dict from POST form
There is a from with various elements <input name='id' value='123'/> <input name='some_value' value='123'/> <!-- thing that i want--> <input name='array[key_1]' value='value_1'/> <input name='array[key_2]' value='value_2'/> <input name='array[key_3]' value='value_3'/> <input name='array[key_4]' value='value_4'/> </form> If i've been used PHP, array data will be collected in $_POST["array"] So the questions is, how to collect dict "array" in django views? -
Elastic Beanstalk fails on command 01_migrate
So basically, I transitioned from Heroku to AWS Beanstalk for my Django web application. I already had an existing database on Heroku Postgres and was able to use pg_restore to populate my AWS RDS Postgres Instance. Everything has worked fine until I made changes in Django which required me to run migrations (python manage.py migrate). So in my .ebextensions folder, I created a file called 01_django.config and put this information. option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "core.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: "core.wsgi:application" container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate --noinput" leader_only: true This gives me the error: 2022/11/04 03:32:33.664588 [INFO] Error occurred during build: Command 02_migrate failed 2022/11/04 03:32:33.666248 [ERROR] An error occurred during execution of command [app-deploy] - [PostBuildEbExtension]. Stop running the command. Error: container commands build failed. Please refer to /var/log/cfn-init.log for more details. In the error logs it tells me to look in cfn-init.log for more details, so I download the full logs from the AWS Console and open the file but it doesn't tell me more information. 2022-11-04 03:32:33,639 [ERROR] Unhandled exception during build: Command 02_migrate failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 176, in <module> worklog.build(metadata, configSets) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 137, in build Contractor(metadata).build(configSets, … -
django rest_framework using stored procedure
How can I use my stored procedure in django rest framework, let's say I have an add_item that insert product name and date_acquired select add_item(p_name,p_date_acquired) We have models.py # using RAW models Class Product(models.Model): name = models.CharField(blank=True, null=True) date_acquired = models.DateField(blank=True, null=True) What should I put in my serializer.py Something like this perhaps? what about my views class ClearanceItemSerialize(serializers.ModelSerializer): class Meta: model = Product fields = ['name', 'date_acquired' Please Help thank you -
Reverse for 'profile' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['profile/(?P<pk>[0-9]+)$'] n
this showing when i running server of django project i have try many thing but could not solve this -
Django Broken pipe when cluster version changed
I have the same API login code for my develop and stage versions. The staging server is with cluster 1.20 instead of 1.19 as like develop. I am not using Nginx we are using an HAProxy-based ingress controller. Django API can access the web without error using the ReactJS code but API shows 403 errors when accessing through postman. Here is the code: @csrf_protect @api_view(["POST"]) @authentication_classes((LoginAuthentication,)) @permission_classes((IsAuthenticated,)) def api_login(request): """Log in and retrieve tokens based on user name and password""" auth_header = request.META.get('HTTP_AUTHORIZATION') encoded_credentials = auth_header.split(' ')[1] # Removes "Basic " to isolate credentials decoded_credentials = base64.b64decode(encoded_credentials).decode("utf-8").split(':') username = decoded_credentials[0] password = decoded_credentials[1] user = authenticate(username=username,password=password) if user is not None: login(request,user) return _get_jwt_token(request.user) def _get_jwt_token(user): """Helper function to generate jwt tokens""" jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) exp_str = payload["exp"].isoformat() + "Z" token = jwt_encode_handler(payload) refreshToken = _get_refresh_token(user) return JsonResponse( {"token": token, "refreshToken": refreshToken, "exp": exp_str}, status=201 ) console output of develop [02/Nov/2022 10:41:06] "POST /accounts/api/login/ HTTP/1.1" 201 541 [02/Nov/2022 10:41:06] "POST /accounts/jwt_token/ HTTP/1.1" 201 541 [02/Nov/2022 10:41:06] "POST /accounts/get_csrf/ HTTP/1.1" 200 82 [02/Nov/2022 10:41:06] "POST /accounts/user_profile/ HTTP/1.1" 200 233 [02/Nov/2022 10:41:06] "POST /accounts/user_profile/ HTTP/1.1" 200 233 [02/Nov/2022 10:41:07] "POST /accounts/user_profile/ HTTP/1.1" 200 233 console output … -
Lazy page loading via Redis in Django project
There is a download page for about 5000 sql queries against a database (Postrgres). The team decided to apply the following algorithm to avoid 502 errors when multiple users load the page at the same time (using Redis): Create a task for an additional worker Connect via WebSocket to the page. (or use an AJAX request) While the request is running, the user sees the download window. When the worker completes the calculation, it will pass the result to the consumers The project uses django_rq. Are there ready-made solutions that perform this algorithm? Like a decorator? Also, if you have suggestions for optimizing such a number of requests, please suggest them. Used standard Django optimization tools to reduce the number of requests. -
How to cast django.db.models F to a String?
Note: working on expensive corporate legacy code and models that are not allowed to be changed What I'm trying to do: Combine two fields into one as a DateTime field. Model.py: from django.db import models class DateThing(models.Model): date = models.DateField() start_time = models.CharField("Start time", max_length=255) Viewset.py from datetime import datetime from django.db.models import F from django.db.models.functions import Concat from rest_framework import mixins, viewsets class ViewSet(viewsets.GenericViewSet, mixins.ListModelMixin): date_things = DateThing.objects.annotate( start=Concat( F("date"), Value(" "), datetime.strftime( datetime.strptime(str(F("start_time")), "%I:%M %p"), "%H:%M", ), Value("+00:00"), output_field=CharField(), ) ) ... Desired result: 2022-11-01 20:30:00+00:00 -
how to call a method in view.py from jinja2 template in Django
I am trying to execute a method which is views.py file a html template in django. beow is my views.py in an aplication def somemethod(**kwargs) #some stuff below is my template email.html {{somemethod(param1,param2,etc...)}} -
Django decorator throws error "object has no attribute 'session'"
I need a custom login check to be done, which looks at session attributes. However I am getting 'health_check' object has no attribute 'session'. The print inside health_check get method shows user object from session just fine. Here is the code def my_login_required(function): def wraper(request, *args, **kwargs): user = request.session.get('user') print(user) if user: return function(request, *args, **kwargs) else: return HttpResponseRedirect("/login") wraper.__doc__=function.__doc__ wraper.__name__=function.__name__ return wraper class health_check(APIView): @my_login_required def get(self, request): user = request.session.get('user') print(user) return JsonResponse({"status":"OK"})