Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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; } } -
How do I create/update/retrieve multiple Models in one View in Django Rest Framework
I have a Business model and Order model. Businesses can order furniture in our website. A user creates an account and makes an order. Since he is a new user, he is not associated to any Business. In the order form, he will give the information about his business and some information related to current order. A new Business record and Order record will be created with the given info. There's a foreign key for Business in Order table. If he wants to create a second order, since he has already a business, he will have the business info pre-filled in his form. When he gives the order data and submits, backend won't create a new Business record. It only creates Order record and store the Business reference. How do I achieve this in single endpoint to create update and retrieve? # serializers.py import time class BusinessSerializer(serializers.ModelSerializer): class Meta: model = Business fields = '__all__' def create(self, validated_data): timestamp = int(time.time()) random_number = random.randint(100,999) validated_data['code'] = f'BUSINESS-{timestamp}' validated_data['status'] = 'CREATED' return super().create(validated_data) class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' def create(self, validated_data): timestamp = int(time.time()) random_number = random.randint(100,999) validated_data['code'] = f'ORDER-{timestamp}' validated_data['status'] = 'CREATED' return super().create(validated_data) # … -
Django request process data saving
I have django asgi app. And I want to have POST /routes handling, that would be something like: async def routes(request): if is_first_request_from_user(request): generator = RouteGenerator() save_generator_for_user(request, generator) return await generator.first_generate() else: generator = get_generator_for_user(request) return await generator.further_generate() And RouteGenerator object has state and stores some complex data like heap, maps, sets etc. and it is attached to each user and should be stored in local memory. So how to implement it in django? Should I use some kind of django cache? I'm not really good at python, especially django, and for me the most straightforward solution would be to store some global map {request_id: route_generator}, however while googling nowhere was mentioned such a simple approach -
How to build single query in Django with related models and count
I did not use the Django for a years and tried to modify some old codebase today. I have models: class MetaTemplate(CreatedModifiedBase): type = models.CharField(max_length=200) class Project(CreatedModifiedBase): name = models.CharField(max_length=200, unique=True) members = models.ManyToManyField( User, through=ProjectMembership, related_name="annotation_projects_as_member", blank=True, ) metatemplate = models.ForeignKey( MetaTemplate, on_delete=models.SET_NULL, related_name="project", null=True ) class Dataset(CreatedModifiedBase): name = models.CharField(max_length=200) project = models.ForeignKey( Project, related_name="datasets", on_delete=models.CASCADE ) class Task(CreatedModifiedBase): dataset = models.ForeignKey( Dataset, related_name="tasks", on_delete=models.CASCADE, null=True ) class Completion(CreatedModifiedBase): task = models.ForeignKey(Task, related_name="completions", on_delete=models.CASCADE) annotator = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="annotation_completions", null=True, ) I have a method which returns number of incomplete Tasks. def get_incomplete_tasks(self, user, project_id, target_completion_count) -> int: return ( Task.objects.annotate(counts=Count("completions")) .filter( counts__lt=target_completion_count, dataset__project=project_id, ) .exclude(completions__annotator=user) .prefetch_related( "completions", "completions__annotator", "dataset__project" ) .count() ) Now I want to rework this method and return the number of incomplete Tasks for each of the projects in single query without project_id and target_completion_count passed by user. So basically the same logic but per in one query per Project. I wrote this code: t = Task.objects.filter( dataset__project=OuterRef('id') ) completion_count_subquery = t.exclude(completions__annotator=user).prefetch_related( "completions", "completions__annotator").order_by().annotate( counts=Func(F('id'), function='Count')).values('counts') objects = Project.objects.all().annotate(task_count=Subquery(completion_count_subquery)).prefetch_related("members", "metatemplate") But I am not able to include counts__lt=target_completion_count part in the proper way. Also tried this query t = Task.objects.all().annotate(counts=Count("completions")).filter(dataset__project = OuterRef('id'), counts__lt=OuterRef("target_completion_count")).order_by().values("completions") … -
Google provider not showing up in Django admin and getting ImproperlyConfigured error after setting up django-allauth
I'm encountering two issues after setting up Django Allauth for authentication in my Django project: 1. The Google provider option is not showing up in the dropdown list when navigating to the "Add social application" section of the Django admin panel. 2. When attempting to access the sign-in page (/enrolled/sign-in/), I'm getting an "ImproperlyConfigured" error with the message "unknown provider: google". I followed the setup instructions provided in the Django Allauth documentation and added the necessary configuration for the Google provider in my settings file. Despite this, I'm facing these issues. Here is my settings.py file: """ Django settings for temp project. Generated by 'django-admin startproject' using Django 4.2.11. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-x5242^+u0mit3om8z)e=8i$(vi!o@7$ks1om9*@7r(lo(=!3y!' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
problem not loading image with name persian in django
problem not loading image with name persian in django enter image description here enter image description here I added these two to the setting file FILE_CHARSET = 'utf-8' DEFAULT_CHARSET = 'utf-8'enter image description here -
Django widget tweaks manually set input field value?
I am looking for an easy way to manually set a form field (ModelForm) value in a Django Template. I've tried this {% render_field my_form.my_field value=200 %} (tried with and without quotes) but it doesn't work, field is still displaying 0. I can't populate those fields in advance (overwriting form initialization in a ModelForm, or similar), because I will need to change input values dynamically later on, based on other input fields (using HTMX). -
how to attach a file, uploaded by customer, to email in Django?
i'm trying to make a form where customer can add a file and send it via page. No file save in database just attach it and send to company email. Here are the details forms.py class ContactForm(forms.Form): name = forms.CharField(max_length=120, widget=forms.TextInput(attrs={'placeholder': 'Your name'})) phone_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Phone number'})) email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'example@example.com'})) customer_details = forms.FileField(required=False, widget=forms.ClearableFileInput( attrs={'multiple': False, 'allow_empty_file': True})) message = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Your message'})) emailsender.py from django.core.mail import send_mail class EmailSender: def __send_email(self, subject, message, recipient_list): send_mail( subject=subject, message=message, from_email=EMAIL_HOST_USER, auth_password=EMAIL_HOST_PASSWORD, recipient_list=recipient_list ) def send_submitted_order(self, request, offers): subject = f'Order {datetime.now().strftime("%Y-%m-%d %H:%M:%S.")}' recipient_list = [RECIPIENT_EMAIL] form = ContactForm(request.POST, request.FILES or None) if form.is_valid(): customer_email = form.cleaned_data['email'] customer_phone = form.cleaned_data['phone_number'] customer_message = form.cleaned_data['message'] **customer_details = form.cleaned_data['customer_details']** message = render_to_string( 'cart/message_for_company.html', {'customer_message': customer_message, 'customer_email': customer_email, 'customer_phone': customer_phone, 'offers': offers} ) self.__send_email(subject, message, recipient_list) def send_message_to_customer(self, request, offers): form = ContactForm(request.POST, request.FILES or None) subject = f'Order {datetime.now().strftime("%Y-%m-%d %H:%M:%S.")}' if form.is_valid(): customer_email = form.cleaned_data['email'] customer_phone = form.cleaned_data['phone_number'] customer_message = form.cleaned_data['message'] **customer_details = form.cleaned_data['customer_details']** message = render_to_string( 'cart/message_for_customer.html', {'customer_message': customer_message, 'customer_email': customer_email, 'customer_phone': customer_phone, 'offers': offers} ) recipient_list = [customer_email] self.__send_email(subject, message, recipient_list) and minimalistic template for render_to_string <h1>Order</h1> {% for offer in offers %} {{ offer.name }} - {{ offer.quantity }} {% … -
I cannot upload multiple files in my html template
I am making a site where you can send your game with multiple additional images. I upload images and they are send to API. Then when you open the game page there is a request to API and it returns the image. The problem is that when I try to upload multiple images only last one uploads. This is my html form {% extends "base.html" %} {% block body %} <form id="chloroform" action="/senddata" method="post" enctype=multipart/form-data > <h2>Загрузить игру</h2> <fieldset> <legend>Основные данные</legend> <label for="title">Название игры:</label> <input type="text" name="title" id="title" maxlength="24" required> </fieldset> <div class="container col-md-6" style="float:right; position: relative; top: -100px; left: 20px"> <p style="outline:2px solid #555; border-radius:5px; width: 300px; height: 300px;"> <img id="frame" src="" class="img-fluid" style="max-width: 300px; max-height: 300px; " /> </p> <div class="mb-5"> <input class="form-control" name="prev" type="file" id="formFile" onchange="preview()" accept="image/png" required> </div> </div> <script> function checkImage(file) { return new Promise((resolve, reject) => { if (file.type === 'image/png') { const img = new Image(); img.onload = () => { if (img.width === img.height) { resolve(); } else { reject(new Error('Изображение должно быть квадратным!')); } }; img.src = URL.createObjectURL(file); } else { reject(new Error('Изображение должно быть в формате PNG!')); } }); } function preview() { const file = event.target.files[0]; checkImage(file) .then(() => … -
Why dropdown field is disappeared in Django Rest Framework when using custom serializer for a field?
I am trying to use Django, DRF, ViewSet and Serializers to build a simple weblog. I have a main app and inside it: main\models.py: from django.db import models from django.contrib.auth.models import User class TimeStampMixin(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Category(TimeStampMixin): name=models.CharField(max_length=255) parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name class PostStatus(models.Model): status = models.CharField(max_length=50) def __str__(self): return self.status def get_draft_status(): return PostStatus.objects.get_or_create(status='draft')[0].id class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=200) description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) status = models.ForeignKey(PostStatus, on_delete=models.CASCADE, default=get_draft_status) def __str__(self): return self.title class RelatedPost(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='related_posts') related_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='related_to') def __str__(self): return f"{self.post.title} related to {self.related_post.title}" main\serializers.py: from rest_framework import serializers, status from rest_framework.response import Response from .models import Post, RelatedPost, PostStatus, Category class PostStatusSerializer(serializers.ModelSerializer): class Meta: model = PostStatus fields = '__all__' class RelatedPostSerializer(serializers.ModelSerializer): class Meta: model = RelatedPost fields = '__all__' class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class PostSerializer(serializers.ModelSerializer): related_posts = serializers.SerializerMethodField() category = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' def get_related_posts(self, obj): related_posts = obj.related_posts.all() return [{'id': rp.related_post.id, 'title': rp.related_post.title} for rp in related_posts] def get_category(self, obj): if obj.category: … -
How can I display product photos from the database in Django?
I am putting the project on the Python host for the first time, which is written with Django, but when I try to fetch the photos of the products from the database, when I look at it with inspect, it shows the photo address correctly, but still nothing.I also set media root.The main folder of the project is not in public_html and I considered root, but the photos folder is in public_html These are media root and media url... MEDIA_ROOT = '/home/pythoni1/public_html/medias/' MEDIA_URL = '/media/' urlpatterns = [ path('admin/', admin.site.urls), path('',include('home_module.urls')), path('', include('account_module.urls')), path('products/',include('product_module.urls')), path('user-account/',include('user_module.urls')), path('contact-us/',include('contact_us_module.urls')), path('articles/',include('article_module.urls')), path('order/',include('order_module.urls')) ] urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root =settings.MEDIA_ROOT) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydatabasename', 'USER': 'mydatabaseuser', 'PASSWORD': 'mydatabase password', 'OPTIONS':{ 'autocommit':True } } } -
Django Rest Framework authentification in viewsets.ViewSet - need different permissions for each method
I'm facing an issue with Django REST Framework and viewsets.ViewSet. I'm trying to use the @permission_classes decorator to secure specific methods within a ViewSet, but it doesn't seem to be working as expected. When I apply the decorator, all methods require authentication, even when I specify different permissions for other methods. However, if I set the permission_classes attribute at the top of the ViewSet, it works as expected, but I need different permissions for each method. Do you have any advice on how I can achieve method-level permissions within a ViewSet? from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.decorators import action, permission_classes from rest_framework.response import Response class ProjectViewSet(viewsets.ViewSet): # Works as expected: all methods require authentication permission_classes = (IsAuthenticated,) @action(detail=False, methods=['get'], url_path='my') def list_investors_projects(self, request): # This method should be protected but allows access without authentication data = { 'message': "This is a custom GET method!", 'status': 'success' } return Response(data) @action(detail=False, methods=['get'], url_path='public', permission_classes=[AllowAny]) def public_projects(self, request): # This method allows public access data = { 'message': "Public projects", 'status': 'success' } return Response(data) I tried using the @permission_classes decorator above the list_investors_projects method to require authentication and custom permissions. I expected that this specific method … -
Mapping DRF GenericViewSet to http verbs via DefaultRouter
My goal is to implement adding a recipe to current user favorites list and removing it using Django Rest Framework 3.12.x. POST api/recipes/{int:recipe_id}/favorite DELETE api/recipes/{int:recipe_id}/favorite Request body is empty. User_id is got from self.context['request'].user.id. I.e. I need to serve POST and DELETE on the same URL. I implemented that against DefaultRouter in conjunction with GenericViewSet, but can't get this implementation serving DELETE. Only POST is served properly. The quesrtion is: what's wrong in the configuration? Why DRF returns 405 "Method Not Allowed" on DELETE calls and returns Http header Allow: POST, OPTIONS? Router configuration: from rest_framework import routers from api.views import FavoriteViewSet _v1_router = routers.DefaultRouter() _v1_router.register( r'recipes/(?P<recipe_id>\d+)/favorite', FavoriteViewSet, basename='favorite') View: class FavoriteViewSet( mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) http_method_names = ('post', 'delete', 'head', 'options',) queryset = Favorite.objects.all() serializer_class = FavoriteSerializer pagination_class = None def get_permissions(self): return super().get_permissions() def get_object(self): return super().get_object() def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response(serializer.data) def destroy(self, request, *args, **kwargs): super().destroy(request, *args, **kwargs) def get_serializer_class(self): return super().get_serializer_class() def dispatch(self, request, *args, **kwargs): p1 = hasattr(self, 'get') p2 = hasattr(self, 'post') p3 = hasattr(self, 'delete') p4 = hasattr(self, 'options') return super().dispatch(request, *args, **kwargs) Having spent some time in the Debugger, I figured … -
DjangoAdmin: Use InlineModels without a parent model
I have a model (e.g. Contact with two fields, email and name). I'd like to add a custom view to Django Admin that allows for batch creation of multiple contacts. As they do not have a m2m-relationship, there is no way for me to add them as a InlineModelAdmin into another object. Is there a way to reuse the inline-code from Django admin to add a custom view for batch adding multiple contacts? As a strating point for adding custom views I'm currently at (which simply adds a add-page under the /add/multiple path). class ContactAdmin(admin.ModelAdmin): def get_urls(self): info = self.opts.app_label, self.opts.model_name urls = [ path( "add/multiple/", self.admin_site.admin_view(self.add_multiple_view), name="%s_%s_add_multiple" % info, ) ] return urls + super().get_urls() def add_multiple_view(self, request, form_url="", extra_context=None): return self.changeform_view(request, None, form_url, extra_context) -
Django formset queryset
I have two apps: accounting and projects. Every consumption item has a fk to project. Every production has a fk to a project. Production order has fk to production. produced product has fk to production order. consumption item has fk to produced product. While creating produced line, I want to create consumption line as formset. However, consumptionitemline_to_consume field should show instances from the related project, not all instances.. Below I tried to filter the dropdown however, it just does not work. here is forms class ProductionProducedLineConsumptionLineForm(forms.ModelForm): class Meta: model = ProductionProducedLineConsumptionLine fields = '__all__' widgets = { 'productionproducedline': forms.HiddenInput(), 'produced_kg_scrap': forms.NumberInput(attrs={'class': 'w-full input rounded-md'}), 'produced_kg_wastage': forms.NumberInput(attrs={'class': 'w-full input rounded-md'}), } def __init__(self, *args, **kwargs): production_id = kwargs.pop('production_id', None) # We'll pass this when initializing the formset in the view super(ProductionProducedLineConsumptionLineForm, self).__init__(*args, **kwargs) if production_id: production = ProductionProducedLine.objects.get(id=production_id) project = production.productionorderline.production.project self.fields['consumptionitemline_to_consume'].queryset = ConsumptionItemLine.objects.filter(project=project) # This does not work? ProductionProducedLineConsumptionLineFormSet = inlineformset_factory( ProductionProducedLine, ProductionProducedLineConsumptionLine, fk_name='productionproducedline', form=ProductionProducedLineConsumptionLineForm, # Use the custom form fields=('productionproducedline','productionproducedline_to_consume', 'consumptionitemline_to_consume','consumed_kg_product','produced_kg_scrap', 'produced_kg_wastage','wastage_return_customer'), extra=1, can_delete=True ) Here is view class ProductionProducedLineCreateView(CreateView): model = ProductionProducedLine form_class = ProductionProducedLineForm template_name = 'projects/produced_create.html' def get_form_kwargs(self): """Ensure the form is initialized with necessary kwargs.""" kwargs = super(ProductionProducedLineCreateView, self).get_form_kwargs() if self.kwargs.get('order_line_id'): kwargs['order_line_id'] = self.kwargs['order_line_id'] return …