Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djano server vs apache2.4 not the same results
i have a weird problem in my django application is that im i have an application runs tools based on their scripts all scripts works fine but only one that works in django server but not in apache2 and the Unable to retrieve my generation from the parent im not sure if this is the issue but i need help on this Thank you o tried to change many things in setttings config and using the apache as admin but im not sure what causing the issue -
Hi. I'm a beginner programmer and I'm trying to write a Django website right now
The fact is that I have no experience at all and I use a tutorial from the Internet. This is a lesson: https://proglib-io.turbopages.org/proglib.io/s/p/django-s-nulya-chast-2-registraciya-avtorizaciya-ogranichenie-dostupa-2022-06-08 When I try to implement the user registration function and in fact just copy the actions of the teacher, my site gives the error: TemplateDoesNotExist at /register/ I don't understand why this is happening... I do not know what I am doing wrong, like I installed pipenv install django-crispy-forms, I only used the pip install django-crispy-forms command, because this command was not executed. I did everything according to the tutorial. -
How can we create authentication system in Django using MongoDB database?
I have a Django project where I am trying to set up authentication system with mongo db I followed various tutorials and documentation but still facing issues. I have tried with djongo module with django to connect mongo db. Also I have custom user. also tried custom authentication backend for mongo db -
Deployment: Procfile with Django Project Structure for more than one App
I need to know how you normally solve this issue. When you start a project, django creates a folder for the project and a second one inside it with the exact same name and the files like: settings.py, init.py, wsgi.py, etc. After Im done with the repo I delete one of the two folders with the same name in order to let Procfile find project.settings inside the wsgi.py. I want to be able to run the Procfile considering the original structure, because I want to learn how to create more than one app inside a project. My exact question is. How should I setup my procfile? right now is like this: web: gunicorn expenses.wsgi --log-file - But Then Procfile doesn't find expenses.wsgi This is my structure: v expenses v expenses > static __init.py asgi.py settings.py urls.py wsgi.py > finances manage.py Procfile requirements.txt runtime.txt I tried changing the Procfile from gunicorn expenses.wsgi to gunicorn expenses.expenses.wsgi but then I will tell my to change os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'expenses.settings') inside the wsgi.py I tried changing the wsgi.py from os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'expenses.settings') to os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'expenses.expenses.settings') but then it will tell me that it couldn't find the module finances. -
Djnamic checkbox, change and disabled or unhide when select
I have three columns named "passive", "discount" and "discountprice" in the rows coming from the database. I use checkbox. If the passive is full, when one of the data-x with the passive label is selected, the others will be disabled. If the discount is full, when one of the ones with the data-y discount tag is selected, the discount price of those with the same discount tag will replace the normal price. It cannot be both discounted and passive. There may be different discount groups or liability groups. I'm stuck. What I wrote was of no use. html {% for mal in mlazm %} <input class="form-check-input" type="checkbox" value="{{ mal.0 }}" name='mlzm{{ forloop.counter }}' data-price="{{ mal.3 }}" data-bprice="{{ mal.7|default:'0' }}" id="{{ mal.0 }}{{ mal.0 }}" {% if mal.4 %}disabled{% endif %}> {%endfor%} js var $checkboxes = $('.myCheckBox').change(function() { var $checked = $checkboxes.filter(':checked'); if ($checked.length >= 3) { $checkboxes.filter(':not(:checked)').prop('disabled', true); } else { $checkboxes.prop('disabled', false); } }); -
My context processor document is being a complete arse
I am literally going to scream. Why can I not get any bloody text to appear from my function in my contect-processor.py to work? I am going to scream so bloody loudly because I am fed up of Django not doing as it's told. PROJECT -|project -|careers -|models.py -|context_processor.py -|templates -|template.html #context_processors.py from .models import Careers def careers_exist(request): # Check if there are any active careers careers_available = Careers.objects.filter(active=True).exists() # Prepare the context dictionary based on availability if careers_available: header = {'header': 'Current vacancies'} else: header = {'header': 'No Vacancies'} return {'header' : header} #template.html <h2>{{ header.header }}</h2> Why is my template still blank despite doing everything correctly. What a stupid bloody thing. -
Which languange/framework should I use? [closed]
I'm getting ready to do my final project. It should be a web app that will show fitness progress by entering it into the system. The progress just given, which has to be written down by the user, will be shown in the form of a graph. I am mainly concerned about the look of the overall application, but at the same time a good backend of course with a database. The original idea was to use Python with Django and React for frontend. But recently I was recommended to use Next.js for both frontend and backend. What is your opinion on what you would use? Or do you have any other opinion? -
Photo upload app Using Flutter and Django
I want to make a (Photo Upload app ) using Flutter and Django Does anyone here have any experience using the Django / Django REST framework, as the backend for a mobile app built with Flutter which has the feature of uploading multiple photos? or anyone who built any apps like the feature of Facebook? If there are any please give me your GitHub repository link or teach me how to build this featured app or if there exists any course please suggest me. ..................... -
Choose which model manager to use when doing prefetch_related?
I have a Product model in my Django app, which uses a custom model manager where all the prefetch_related statements are made: class ProductManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .select_related("core_product") .prefetch_related("images") .prefetch_related("bundled_products") ) class Product(models.Model): _base_manager = ProductManager objects = ProductManager() # ... model fields This works fine; when I use the ORM and within the Admin the custom manager is used, preventing a whole bunch of duplicate queries. The problem is when I have another model that has a prefetch_related to the Product model: it now inherits all the prefetch_related from the Product, even though that's not necessary. It causes a whole bunch of unnecessary queries to be made. class OfferManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .select_related("flag") .prefetch_related("condition_products") .prefetch_related("limited_to_users") .order_by("-priority") ) Here the condition_products field is that Product model from above, and just by including this prefetch_related, all of its prefetch_related statements are also inherited. How can I prevent this from happening? Can I specify which object manager to use in the prefetch_related - so that is uses a "bare" manager? -
Django: how to filter based on custom field
I have a custom field in my extra action view that gets added by overriding to_representation() in serializer. I want to add a filter based on that value. How can I achieve that? views.py class MyFiltersetclass(filters.Filterset): name = filters.CharFilter(lookup_expr="exact", field_name="name") class Meta: model= MyModel fields = ["name"] class MyViewset(): .... @action(detail=True, method=["get"], queryset=MyModel.objects.filter(type=1), serilizer=MyModelSerializer, filterset_class=MyFiltersetclass) def action(self, request, *args, **kwargs): qs = self.get_object() queryset = obj.filter_queryset(queryset) page = obj.paginate_queryset(queryset) if page: serializer = obj.get_serializer(page, many=True) else: serializer = obj.get_serializer(queryset, many=True) return obj.get_paginated_response(serializer.data) model.py class MyModel(models.Model): name = models.TextField(blank=True, null=True) summaries = models.JSONField(blank=True, null=True) @property def summary(self): if not self.summaries: return {} return custom_func(self.summaries) class Meta: db_table = "model_view_1" managed = False serializer.py class MyModelSerializer(serializers.ModelSerializer): summary = serializers.ReadOnlyField() def to_representation(self, instance): data = super().to_representation(instance) summary = data.pop("summary") data["field_1"] = summary.get("field_1") return {**data} class Meta: model = MyModel exclude = ["summaries"] Now I want to add a filter that could filter based on field_1 just like how we have added filter for name in filterset class. -
How we can notify mobile app about messages (Django/React Native)?
What is the best implementation of notifications (about messages, new posts) to the client, Websockets, push notifications, or webhooks? The project consists of a server part in Django and React Native on the client. WebSockets, WebHooks, PUSH -
Extract the item image out of an RSS feed (multiple RSS feed types - feed parser/python)
Working on a project that pulls articles from 20+ rss feeds and the the variety of feed formats for where the articles image is, is driving me bonkers. I'm happy for the articles image to be missing in some cases, and I'll fall back to a set image but I don't want that happening more than 20% of the time. Using Python & Feedparser (DJANGO Project) I've gotten this far: # Try and get the image url try: # Looking for images embedded in enclosures post_image = sanitize_url(str(c.enclosures[0].href)) except: try: # Looking for images embedded in media content post_image = sanitize_url(str(c.media_content[0]["url"])) except: try: # Looking for images embedded in content post_image = sanitize_url(c.content[0]["value"]) except: post_image = "no image found" Had to build a sanitise URL function that does 3 things: Takes a string that extracts out a URL (in situations where the above pulls more than the URL) Trims URLS down to remove parameters that might cause problems i.e 342.jpg?w=25 Then does a final check of the string to make sure it has a mimetype in case the final url is not an image. I'm going in circles here, for every example of an RSS feed this does work on, … -
why i can not deploy python web app easily?
why I can not deploy the Python web application and put it in a folder like the WWW folder of the Apache server so I can access it immediately? like any server-side programming language like PHP? always I have to find a VPS service, of a Cloud computer to be accessed as root, put my files then run the server of python with another server like Nginx or Apache and I have to do a lot of configuration, why it is not like PHP I can through it in the folder of the server and install PHP and this is everything? -
allow locally hosted dockerized django app to be accessed from the interweb through a local dockerized traefik instance?
The problem: From a browser on my windows machine, I can access the default django page via: localhost:5000 192.168.1.100:5000 But, not via my domain example.com From the same windows machine: I can access the traefik dashboard via monitor.example.com So I know that the routing from the interweb to an internal docker container works. Note: django app is minimum required for django app to display django default page My home lab setup using Cloudflare to point example.com to my external IP address Local edge router port forwarding 80, 443 to docker-main server (x.x.x.165) docker-main server hosting traefik docker instance docker desktop on windows hosting simple django app (x.x.x.100) Note: using cloudflare origin certificates, rather than letsencrypt The traefik docker-compose.yml file is: networks: mynet: external: true services: traefik: image: docker.io/library/traefik:2.11.2 container_name: traefik ports: - 80:80 - 443:443 # -- (Optional) Enable Dashboard, don't do in production - 8080:8080 environment: - CF_DNS_API_TOKEN=[cloudflare token] - TZ=[local timezone] volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - ./config/traefik.yml:/etc/traefik/traefik.yml:ro # For the static configuration - ./config/config.yml:/etc/traefik/config.yml:ro # For any dynamic configuration you add - ./certs:/certs:ro # location for the certs - ./logs:/var/log/traefik labels: - "traefik.enable=true" - "traefik.http.middlewares.traefik-auth.basicauth.users=admin:[password]" - "traefik.http.middlewares.traefik-https-redirect.redirectscheme.scheme=https" - "traefik.http.middlewares.sslheader.headers.customrequestheaders.X-Forwarded-Proto=https" - "traefik.http.routers.traefik.entrypoints=web" - "traefik.http.routers.traefik.rule=Host(`monitor.example.com`)" - "traefik.http.routers.traefik.middlewares=traefik-https-redirect" - "traefik.http.routers.traefik-secure.entrypoints=websecure" - "traefik.http.routers.traefik-secure.rule=Host(`monitor.example.com`)" … -
I'm using Django and django-auth-ldap. How do I make all users to be staff?
I'm using django-auth-ldap for athentication. I want all new users to be assigned as staff. How do I do that? I know about AUTH_LDAP_USER_FLAGS_BY_GROUP, but I don't want to bother assigning people to a specific group. I know that there exists django_auth_ldap.backend, but I can't find a good working example of it. As a follow up (or combination?), I want to assign a set of default user permissions, for new users. Thanks. -
Unauthorized (401) while i sent a Post request to the server
when i try to add a post to my server i get 401 Unauthorized i sent my jwt in postman with Bearer jwt but nothing change . i think the probleme in the api where exactly i don't have any idea i use django as backend and react as frontend those are all my code urls.py : from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView urlpatterns = [ #path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path('', include('crm.urls')), ] urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] views.py : from django.shortcuts import render ,redirect ,get_object_or_404 from rest_framework.parsers import MultiPartParser, FormParser from .serializers import PostSerializer from rest_framework.viewsets import ModelViewSet, GenericViewSet from .forms import CreateUserForm, LoginForm from rest_framework.response import Response from rest_framework import status #, UploadForm from rest_framework.decorators import api_view, action from django.contrib.auth.decorators import login_required, user_passes_test from .models import Post, PostImage # - Authentication models and functions from django.contrib.auth.models import auth from django.contrib.auth import authenticate, login, logout def homepage(request): return render(request, 'crm/index.html') def register(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() return redirect("my-login") context = {'registerform':form} return render(request, 'crm/register.html', context=context) def my_login(request): form = LoginForm() if request.method == 'POST': form = LoginForm(request, data=request.POST) if form.is_valid(): username … -
Is there a way to annotate the count for all objects without grouping by another column?
I have code that looks like the following: filtered_queryset = Object.objects.filter(...misc filters) match time: case "year": qs = filtered_queryset.annotate(year=TruncYear("created_at")).values("year") case "month": qs = filtered_queryset.annotate(month=TruncMonth("created_at")).values("month") case "week": qs = filtered_queryset.annotate(week=TruncWeek("created_at")).values("week") case _: qs = filtered_queryset final_count = qs.annotate(count=Count("id")) In each case, I am expecting data that looks like the following # Each case { [{ "TIME": ... "count": ... }, ... ] } # Default { [{ "count": ... }] } I was under the impression that Count() was a terminal expression in django and that the queryset would be evaluated. However, the default case returns a queryset instead of evaluating. What am I missing here that causes it to not evaluate the queryset? I know that I can just call filtered_queryset.count() instead of trying to do this via annotate, but it causes extra code to check for the default case and adds code smell. -
Using Kerberos to authenticate Django Application in Corporate Environment
I am trying to use Kerberos and LDAP3 to authenticate my Django Application inside the corporate network. When I am logged in to my corporate computer, I want my application to be able to login without being able to again enter username and password again. I figured out it can be done with Kerberos but couldn't find the comprehensive document regarding this. I am using ldap3 authentication right now where the user has to enter username and password but I want to skip the process of entering username and password. How can I do that? -
Can't Log in in Django users
I am writing a site with a custom user model. I want to access the site via telegram. Everything works, but the authentication itself - the login function does nothing( I don't understand what's wrong, I've been trying different ways for 3 days now, but nothing works. I will be glad to any advice. And here is my code #users/views.py from django.http import JsonResponse from django.views import View from django.utils import timezone from django.shortcuts import render, redirect from users.models import AuthCode import uuid from django.utils.decorators import method_decorator from django.contrib.auth.models import User from django.views.decorators.csrf import csrf_exempt from backend import settings from django.contrib.auth import get_user_model from django.contrib.auth import authenticate, login User = get_user_model() class GenerateTelegramCodeView(View): def get(self, request, *args, **kwargs): # Устанавливаем время истечения кода на 5 минут в будущее expiry_time = timezone.now() + timezone.timedelta(minutes=5) # Создаём новый код с установленным временем истечения new_code = AuthCode.objects.create( session_id=request.session.session_key, expiry_time=expiry_time ) # Возвращаем созданный код как JSON return JsonResponse({"code": str(new_code.code)}) @method_decorator(csrf_exempt, name="dispatch") class TelegramAuthView(View): def post(self, request, *args, **kwargs): telegram_id = request.POST.get("telegram_id") code = request.POST.get("code") try: auth_code = AuthCode.objects.get(code=code, expiry_time__gt=timezone.now()) if auth_code: auth_code.is_used = True user = authenticate(request, telegram_id=telegram_id) if user is None: user = User.objects.create_user(telegram_id=telegram_id) user = authenticate(request, telegram_id=telegram_id) if user: auth_code.telegram_id = … -
Problem with patient profile and auth system in Django
Today i met very difficult problem in my project. Idea is simple, in my Doctor model i have a unique_connect_token, which needs for link Patient to the specific Doctor. In my patient profile template i created a simple POST method form to obtain this token from Patient. Patient see this form in his profile if he have no linked Doctor and authenticate. I have problem with my post method in this class: class PatientProfile(generic.DetailView): model = Patient template_name = 'patient_profile.html' context_object_name = 'patient' @staticmethod def users_role(request): user = request.user is_patient = user.groups.filter(name='Patients').exists() is_doctor = user.groups.filter(name='Doctors').exists() return is_patient, is_doctor def get_context_data(self, **kwargs): self.object = self.get_object() context = super().get_context_data(**kwargs) is_patient, is_doctor = self.users_role(self.request) context['is_patient'] = is_patient context['is_doctor'] = is_doctor context['link_form'] = DoctorLinkForm() return context def get_object(self, queryset=None): if not hasattr(self, 'object'): self.object = super().get_object(queryset) return self.object def post(self, request, *args, **kwargs): patient_id = request.user.id link_form = DoctorLinkForm(request.POST) if link_form.is_valid(): token = link_form.cleaned_data['doctor_unique_token'] doctor = Doctor.objects.get(unique_connect_token = token) patient = Patient.objects.get(pk = patient_id) patient.doctor_id = doctor patient.save() return redirect('patient_profile', pk=request.user.id) return self.render_to_response(self.get_context_data(link_form = link_form)) When POST method works succesfully, my patient redirecting on the same page but UNLOG from site. And when im trying to login again, I get a message that the … -
Is there a way to filter django submodel dropdowns to only appear for the current user?
I have a main model named Event. This event has a submodel named Pogram, and the Program model has a submodel called DetailedProgram. I have been able to filter the app to make sure that only the logged in user can post for themself. Also, I have managed to make the user only access Events created by the loged in user. However, I am struggling to find a way to make the user logged in only access the submodel Program's objects as all the object's are being displayed. Please advise. I tried using the very filter (user filter) used on the Program model but to no avail -
django object filter using AND,between date
pls my below code not working but i noticed if i remove statu='Approved' it worked fine but i want it to be part ofthe condition statment. pls help sdate = request.POST['sdate'] edate = request.POST['edate'] acct =int(request.POST['acct']) actyp = request.POST['actyp'] d1 = datetime.strptime(sdate, "%Y-%m-%d") d2 = datetime.strptime(edate, "%Y-%m-%d") now = datetime.now() dte = now.strftime("%Y-%m-%d") stmtacct = Tbltrn.objects.filter(accountno=acct,statu='APPROVED',date__gte=d1,date__lte=d2) context={ 'mysere': stmtacct, 'strdate': sdate, 'endate': edate, 'fname': fname, 'acct': acct, 'actyp': actyp } -
How to serve static files from different locations in NGINX
I want to serve static files from different two Django apps. one static files for the admin app and other static files for the pages app. Note: I am aware of collectstatic command. What I would like to know is that, if there is a way to serve static files from two different directories under /static/ location. If one location failed, check the other location. Locations for static files: /webapps/project/admin/static and /webapps/project/pages/static location /static/ { alias /webapps/project/admin/static/; alias /webapps/project/pages/static/; } This raise an error of duplicate alias directive Here is what I wish to have. To check the files in @static, if file not found check in the @static2 block. server { server_name x.x.x.x; client_max_body_size 8M; access_log /webapps/logs/project/nginx-access.log; error_log /webapps/logs/project/nginx-error.log; location /static/ { try_files $uri @static @static2; } location @static { root /webapps/project/pages/; } location @static2 { root /webapps/project/admin/; } } How should I serve both static files from two directories. -
Trouble deploying Django app to AWS Elastic Beanstalk
I'm having the following issues when running eb deploy: 2024/04/29 18:00:10 [warn] 28747#28747: could not build optimal types_hash, you should increase either types_hash_max_size: 1024 or types_hash_bucket_size: 64; ignoring types_hash_bucket_size Apr 29 18:00:15 ip-172-31-85-53 web[28824]: ModuleNotFoundError: No module named 'authentication' authentication is a Django app. These are the two main errors found from the logs provided after updating the environment from eb deploy. I'm following this tutorial I found: https://testdriven.io/blog/django-elastic-beanstalk/ I've had to change a couple things obviously due to different project structure/details but I'm not understanding why these errors are coming up. I have not yet set up AWS RDS for PSQL, but I plan on doing that once I fix these errors. I am also using React as a frontend but I have not yet configured the environment for that either. Here are some of my config files: # .ebextensions/01_django.config option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "campusconnect.campusconnect.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: "campusconnect.campusconnect.wsgi:application" # .elasticbeanstalk/config.yml branch-defaults: aws-psql: environment: SE-Dev-Project-dev group_suffix: null global: application_name: SE-Dev_Project branch: null default_platform: Python 3.11 running on 64bit Amazon Linux 2023 default_region: us-east-1 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: git workspace_type: Application And my project structure: . ├── .ebextensions │ ├── 01_django.config … -
Nginx configuration not working correctly with gunicorn
I have a Django app hosted on a GCP instance that has an external IP, the Django is running using Gunicorn on port 8000, when accessing the Django using EXTERNAL_IP:8000 the site works perfectly, but when trying to access the Django using EXTERNAL_IP:18000 the site doesn't work(This site can’t be reached), how to fix the Nginx configuration? All the IPs will be replaced with the domain once testing is done. In Django settings: ALLOWED_HOSTS = ['*'] gunicorn_config.py command = "/home/path/venv/bin/gunicorn" pythonpath = "/home/path/venv/bin/python" bind = "127.0.0.1:8000" workers = 3 supervisor.conf [program: procurement] directory = /home/path/ command = /home/path/venv/bin/gunicorn namet_system.wsgi:application --bind 0.0.0.0:8000 user = user stdout_logfile = /home/path/logs/gunicorn_supervisor.log redirect_stderr = true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 nginx_config upstream procurement_server { server 127.0.0.1:8000 fail_timeout=0; } map $http_origin $cors_origin { default "null"; } server { server_name LB_IP1 LB_IP2 EXTERNAL_IP; listen 18000 ; if ($http_x_forwarded_proto = "http") { set $do_redirect_to_https "true"; } if ($do_redirect_to_https = "true") { return 301 https://$host$request_uri; } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; proxy_set_header X-Forwarded-Port $http_x_forwarded_port; proxy_set_header X-Forwarded-For $http_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://procurement_server; } }