Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Aggregate return null values if queryset is none even if using Coalesce with default value
currently, I am trying to aggregate on queryset. it's working perfectly but the problem is if my queryset is none Coalesce function is not working so default value is set null rather than 0 . aggregated_data = queryset.aggregate( total_trips=Coalesce(Sum("total_trips"), 0, output_field=IntegerField()), total_orders=Coalesce(Sum("total_orders"), 0, output_field=IntegerField()), total_expense=Coalesce(Sum("total_expense"), 0, output_field=IntegerField()), total_payment=Coalesce(Sum("total_payment"), 0, output_field=IntegerField()), total_collected_payment=Coalesce(Sum("total_collected_payment"), 0, output_field=IntegerField()), total_driver=Coalesce(Sum("total_drivers"), 0, output_field=IntegerField()), total_utilized_driver=Coalesce(Sum("total_utilized_drivers"), 0, output_field=IntegerField()), total_vehicles=Coalesce(Sum("total_vehicles"), 0, output_field=IntegerField()), total_utilized_vehicles=Coalesce(Sum("total_utilized_vehicles"), 0, output_field=IntegerField()), ) current output if queryset is none : { "total_trips": null, "total_orders": null, "total_expense": null, "total_payment": null, "total_collected_payment": null, "total_driver": null, "total_utilized_driver": null, "total_vehicles": null, "total_utilized_vehicles": null } expected output : { "total_trips": 0, "total_orders": 0, "total_expense": 0, "total_payment": 0, "total_collected_payment": 0, "total_driver": 0, "total_utilized_driver": 0, "total_vehicles": 0, "total_utilized_vehicles": 0 } -
Django: how to save instance to a foreign key field based on the fields equally
So I have a user model that has a foreign key relation with class/room, I want a user to be able to press one button and all the users/students would be equally distributed throughout the class/room foreign key based on fields from the model like age, height and other fields. so if there are 4 students 2 with age 14 and 2 with age 15 and there are two classes, the function should put one 14-year-old and one 15-year-old in 1 class and the same in the other class as well, just iterate through the users and distribute them by the selected field values equally, any resource or code snippet would be highly appreciated. -
how to use AWS access keys in django?
I've currently configured my access keys as part of the environment variables and using that on the code: code However, when I host the application and someone tries using it, it will only work if they have the keys configured the same way. Is there any other way around this? -
Django Rest Framework and Group permissions [closed]
Is it possible to manage App level permissions using groups in DRF? My goal is to have different apps, and grant permissions to each of them based on group permission. So, each application has its own group, and only users in this group can access the app's endpoints. -
How to upload multiple images in django rest framework
I want to upload multiple images using image model not like a nested serializer Here is my serializer class ProjectImageSerializer(ModelSerializer): class Meta: model = ProjectImage fields = ( 'id', 'file', 'project', ) This is the model class ProjectImage(models.Model): file = models.ImageField( upload_to='apps/projects/ProjectImage/file/', ) user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, related_name='project_image_set', ) project = models.ForeignKey( 'Project', on_delete=models.CASCADE, related_name='image_set', ) created = CreatedField() last_modified = LastModifiedField() def __str__(self): return basename(self.file.name) and here is Views.py class ProjectImageViewSet(viewsets.ModelViewSet): parser_classes = [ MultiPartParser, ] queryset = ProjectImage.objects.all() serializer_class = ProjectImageSerializer can anyone help me when I try with postman its selecting multiple images but posting only one -
How does the Django setting of letting it know about your app really work?
I've been learning django for a few weeks , but i still cant fully understand how some of the settings really work,like the most basic one that when i create a new app called 'base' inside my django project then i should let django know about my app so i write like as most of the people do 'INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', ]' but if i write just only my app name 'base' , it still works , so can someone tell me what is the difference between this two? 'INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base', ]' -
I need to get the value of the field that we enter in the form and immediately take action on it
I need to get the value of the field that we enter in the form (in this case, these are the days of reservation) and immediately calculate the cost of the reservation based on it And the problem is that I don’t understand how to get the value of these very fields (so this is not QuerySet request, and not accessing the database) This is my views: def booking(request): error = '' if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.user = request.user booking.sum = #create sum function form.save() return redirect('account') else: error = 'Форма не корректна' form = BookingForm() context = { 'form': form, 'error': error } return render(request, 'bookings/booking.html', context) And this is models: class Booking(models.Model): startdate = models.DateField('Startgdate') finishdate = models.DateField('Finishdate') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) sum = models.PositiveIntegerField('Sum') fullname = models.CharField('Full name', max_length=50) pnumber = models.PositiveBigIntegerField('Phone number') def __str__(self): return self.fullname class Meta: verbose_name = 'Booking' verbose_name_plural = 'Bookings' thanks in advance -
How to return a folder in django views for using it in nginx proxy_pass?
I have 1 main server, where django and html with css, js located. While I am also have proxy server, that contains only nginx file that proxy_pass to django main server(by domain name) and receive site html code and another static. Here is my nginx file: server { server_name 11.111.111.111; index index.html location / { proxy_pass http://example.com/api/v1/render/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Photo $scheme; } } And after this I have 404 error. What I am need to do in django view /api/v1/render to return a folder with index.html, css and js scripts, that would be shown on 11.111.111.111 url? It also hasn't traces, that proxy_pass really works, because main server don't receive any requests. Thanks for help. -
how to use ccextractor with python?
I'm working on a django application to generate subtitles for videos. I'm required to use only ccextractor for this. I have figured out a way to use it using wsl: code However, it returns errors when I run it in other systems, since not everyone has ubuntu configured. Looking for a way to do this without using wsl. Any help is appreciated. -
Django admin file upload button not clickable
I was building an app and had the image upload section working previously, however, 2 weeks on in the project for some reason the upload file button in Django admin is no longer doing anything when clicked. I can't work out what is blocking it as it's in the admin, Any suggestions? This is for any of the apps in the project. This is the admin.py from django.contrib import admin from desire import models admin.site.register(models.Desire) admin.site.register(models.RelatedProduct) from django.contrib import admin from django.contrib.auth.admin import UserAdmin from account.models import Account class AccountAdmin(UserAdmin): list_display = ('email','username','date_joined', 'last_login', 'is_admin','is_staff') search_fields = ('email','username',) readonly_fields=('id', 'date_joined', 'last_login') filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ # my APPs 'personal', 'account', 'ckeditor', 'ckeditor_uploader', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'bootstrap4', 'fontawesome', 'cropperjs', 'django.contrib.humanize', ] AUTH_USER_MODEL = 'account.Account' # TODO: ADD THIS LINE. AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.AllowAllUsersModelBackend', 'account.backends.CaseInsensitiveModelBackend', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] DATA_UPLOAD_MAX_MEMORY_SIZE = 10485760 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'media'), ] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn') TEMP = os.path.join(BASE_DIR, 'media_cdn/temp') BASE_URL = "http://127.0.0.1:8000" -
Inline form validation based on Parentform - Django Admin
Below is my admin form Class RequestedAreaInilne(admin.StackedInline): model = RequestedArea fields = ("area", "building") class BuildingAdmin(admin.ModelAdmin): fields = ("special_access", "user_id", etc ....) inlines = (RequestedAreaInline,) While saving the BuildingAdmin form I need to validate inline form (ie RequestedAreaInilne). Validation should happen based on the value from the BuildingAdmin form field . To add more information , special_access of the BuildingAdmin is boolean field(True or False). If the user selection is True , I want to check if they have entered value for RequestedAreaInline. If it is not entered I need show them a message that "You should enter data for this" I tried doing the validation in save_formset(). But I am not getting inline field. How can I validate the inline formset based on parent form -
How SQL query Case and When works in django ORM?
I have a SQL query and when writing in Django ORM it returns an error. But the SQL query works perfectly on MySQL Command Line Client. Would anyone please explain the error or working of CASE and When in Django ORM? SQL query:- SELECT CASE WHEN LENGTH(au.first_name) < 1 THEN au.username ELSE concat(au.first_name,' ',au.last_name) END AS fullname FROM rewards_usercard ru RIGHT JOIN auth_user au ON ru.user_id = au.id; Django Models code:- queryset = UserCard.objects.annotate( full_name = models.Case( models.When(condition=models.Q( models.lookups.LessThan(models.functions.Length('user__first_name'),1) ), then='user__username'), default = models.functions.Concat('user__first_name', models.Value(' '), 'user__last_name'), output_field=models.CharField() ) ) Error:- cannot unpack non-iterable LessThan object -
Overriding create() method in the model manager doesn't do anything
I have a model employee, and while creating an instance I want to automatically set their email to "<first_name>.<last_name>@company.com". So, I wrote a manager to do the pre-processing: class EmployeeManager(models.Manager): def create(self, **kwargs): name = kwargs['first_name'] surname = kwargs['last_name'] kwargs['email'] = f'{name}.{surname}@company.com' return super(EmployeeManager, self).create(**kwargs) class Employee(models.Model): first_name = models.CharField(null=False, blank=False, default="employee", max_length=255) last_name = models.CharField(null=False, blank=False, default="employee", max_length=255) position = models.CharField(null=False, blank=False, default="SDE", max_length=255) email = models.EmailField(null=False, default="employee@company.com", unique=True) phone = models.CharField(null=False, blank=False, default='1234567890', max_length=10, validators=[MinLengthValidator]) slack_id = models.UUIDField(null=False, blank=True, default = uuid.uuid4) active = models.BooleanField(default=True) objects = EmployeeManager() def __str__(self) -> str: return self.email However, when I am creating an instance of this model using the admin interphase, the email is set to the default value (employee@company.com) and not what I am feeding it in the new create() method. Why is this happening? -
I this able to convert into dict of key:value pairs
current data [{'product_id': 446, 'available_stock': 959}, {'product_id': 447, 'available_stock': 1004}, {'product_id': 445, 'available_stock': 1021}, {'product_id': 396, 'available_stock': 6}] required output: {446:959, 447:1004, 445:1021,396:6} -
The view Manager.views.add_student_view didn't return an HttpResponse object. It returned None instead
I am trying my first Django project and practicing ORM. I am just trying to create a model form using Django's Model form framework. Somehow my form is not rendering and it is rendering as None. Can someone help? Here is the github link to my project: https://github.com/henselwilson/LibManager/tree/master Error Screenshot -
Cloudinary Private type for django
Cloudinary is working fine with Django but not sure how to change all the file types to private? Apparently i can define type but where do I do that? The default file storage is defined in setting DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' Thank you in advance. -
Django - how do i force a user to change password on their first login using the last_login field of django.contrib.auth
Im using the django.contrib.auth. The code below is the working login function in my views.py #function based def user_login(request): if request.method == "POST": username = request.POST['login-username'] password = request.POST['login-password'] user = authenticate(request, username = username, password = password) if user is not None: login(request, user) return redirect('dashboard') else: return render(request, 'authenticate/login.html', {}) else: return render(request, 'authenticate/login.html', {}) Below is my attempt to check whether if the last_login is NULL. If so, redirect the user to the change-password page. It logs the newly created user (with NULL in the last_login field) but it does not redirect to the change-password page. I have tried changing the placement of the if statement. How do i correctly do this? def user_login(request): if request.method == "POST": username = request.POST['login-username'] password = request.POST['login-password'] user = authenticate(request, username = username, password = password) if user is not None: if user.last_login == NULL: login(request, user) return redirect('change-password') else: login(request, user) return redirect('dashboard') else: return render(request, 'authenticate/login.html', {}) else: return render(request, 'authenticate/login.html', {}) -
Heroku Deployment Error: ModuleNotFoundError: No module named 'msilib'
Can someone please tell me how to resolve this error so I can deploy my app on Heroku? Here's my requirements.txt file: asgiref==3.5.2 dj-database-url==1.0.0 Django==4.1.1 django-extensions==3.2.1 django-on-heroku==1.1.2 gunicorn==20.1.0 psycopg2==2.9.4 psycopg2-binary==2.9.4 python-decouple==3.6 python-dotenv==0.21.0 sqlparse==0.4.2 tzdata==2022.2 whitenoise==6.2.0 When I run the instructions 'heroku run python manage.py migrate' at the command line I get the following error: from msilib.schema import AdminExecuteSequence ModuleNotFoundError: No module named 'msilib' -
nvim pyright issue with django BigAutoField
I am using nvim with pyright and I have this error, I use Coc picture -
I need to test this in django
this is my code, and already done testing others but this one, I do not know yet -
django 4.1.1 redirect is not working if request.method=='POST'
I have tried to implement redirect in django 4.1.1 views. Please find the following code. redirect is working def customer_registration(request): return redirect('customer_login') redirect not working def customer_registration(request): print("ASFADFAd") if request.method == 'POST': return redirect('customer_login') return render(request, 'registration/registration.html') Can anyone help what is the problem, I have already gone through the internet none of the solutions working. Please help me. -
Searching for JSON in Django
I was able to import my data.json into Django after some time. Right now when a request is sent, the view.py function spits out the whole data.json file. I want to create a view.py function that only returns the results of a search request that was submitted and not the whole data.json. If I search for apple, I want the definition for apple to be returned from within data.json. I don't even know what I need to do. Do I convert the data.json file into SQL or python dictionary? Do I convert data.json into a model? The data.json files doesn't specify keys or values. views.py def searchbar(request): if request.method == 'GET': file_path = os.path.join(os.environ.get('HOME'), 'data.json') with open(file_path, 'r') as f: context = {"file_path": f} return render(request, 'movies/searchbar.html', context) searchbar.html {%block content%} {% for i in file_path %} {{i}} {%empty%} There is nothing here {%endfor%} {%endblock content%} home.html <form action ="{% url 'searchbar' %}"method="get"> <input type="text" name="search"/> <button type="submit"> Search</button> </form> data.json contents in searchbar.html when search is pressed: -
Is there a way to disable django models and auth?
I newie in Django but I really like it and I have to work with raw SQL and I want to disable all django apps and use only with rest framework. I tried it but it doesnt work and I want to know if there is any way to disable Django models and auth and that things. -
Django forms not returning result or errors
I am trying to use a Django form for a login page, but the form is returning False whenever I call form.is_valid(). I tried to print the errors in the console and in the HTML file but there's nothing displaying. I tried to get data from the form with form["email"].value() and it's returning None, even when I input data into the email field. Here's views.py: def postlogin(request): form = BootstrapAuthenticationForm(request.POST) # This prints out None into the console print(form["email"].value()) if form.is_valid(): # This code never runs! Even when there are no errors in the form fields! return render(request, "app/home.html") # If form is invalid, return to login page # This always runs, meaning form.is_valid() keeps being false! return render(request,"app/login.html", {"form":form}) Here's my forms.py: from django import forms from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ class BootstrapAuthenticationForm(AuthenticationForm): """Authentication form which uses boostrap CSS.""" email = forms.CharField(max_length=254,label=('Email'), widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'Email'})) password = forms.CharField(label=("Password"), widget=forms.PasswordInput({ 'class': 'form-control', 'placeholder':'Password'})) Here's my login.html: {% extends "app/layout.html" %} {% block content %} <h2>{{ title }}</h2> <div class="row"> <div class="col-md-8"> <section id="loginForm"> <form action="/postlogin/" method="post" class="form-horizontal"> {% csrf_token %} <h4>Use a local account to log in.</h4> <hr /> <div class="form-group"> <label for="id_username" … -
Why Django Messages Won't Work for logout but it work for my sing up?
I wrote this code: my view: from django.contrib.auth.views import LoginView, LogoutView class CustomLogout(LogoutView): def post(self, request, *args, **kwargs): messages.success(request, 'Logout was successfully') return super(CustomLogout, self).get(request, *args, **kwargs) This is my url: urlpatterns = [ ... path('logout/', CustomLogout.as_view(template_name='core/index.html'), name='logout'), ] and I have this in my template: {% if messages %} <div class="alert alert-dismissible" role="alert"> {% for message in messages %} <div class="alert alert-{{ message.tags }}">{{ message }} </div> {% endfor %} </div> {% endif %} I write something like this for SignUp and it works well and show the messages but in this case for logout it won't show any message in template...