Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Model Manager on queryset
In my admin panel i want to do some functions from my ModelManager. I have admin.py def change_status(modeladmin,request,queryset): status = queryset.change_value() return status model.py class ItemManager(models.Manager): @classmethod def change_value(cls): list = Item.objects.filter(value=5) list.update(value=6) return list.list_values("id", flat=True) class Item(models.Model): name = models.TextField() value = models.FloatField() objects = ItemManager() But i get QuerySet object has no attribute 'change_value'. But queryset is Item Queryset so why i cant use manager methods on it? -
What is the easy way to validate scheduling data in python
Well everyone. Honestly my head is about to explode on this situation. My whole day spent on this thing to solve it but i could not do that, so finally here i am on stackoverflow and asking for help from some of you experts. who can help me out in solving this problem. Well i have json object that contain the scheduling of a single day. and let me explain each part of this so you guys understand where i'm struggling so far. { "timings":{ "id":43, "partition":7, "day_name":"Tuesday", "full_day":false, "close_day":false, "start_time":"2022-12-20 00:00:00", "close_time":"2022-12-20 23:00:00" }, "pricings":[ { "partition":7, "day_name":"Tuesday", "peak_hours":true, "start_time":"2022-12-20 17:00:00", "close_time":"2022-12-20 23:00:00", "price":"1300" }, { "partition":7, "day_name":"Tuesday", "peak_hours":true, "start_time":"2022-12-20 00:00:00", "close_time":"2022-12-20 04:00:00", "price":"1300" }, { "id":54, "partition":7, "day_name":"Tuesday", "peak_hours":false, "start_time":"2022-12-20 04:00:00", "close_time":"2022-12-20 17:00:00", "price":2000 } ] } as you can see the first key is timings. Which contains the detail of shop when it will open and when it'll close. simple and nice. then we move on second key which is pricings. its a list of objects that contains that is it a peak hour or off_peak_hours or when they start and when they end. Now problem arise here : How can we validate all timing values such … -
How do I turn off CSRF checks with Django auth's PasswordResetView?
I'm using Django 3.1 with Django's auth application. I have the following middleware defined MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'directory.middleware.extend_token_response.ExtendTokenResponse' ] I would like to use Django auth's reset password functionality so I added this in my urls.py view path('reset_password', views.ResetPasswordView.as_view(), name='password_reset'), and in my views.py file I have defined from django.views.decorators.csrf import csrf_exempt ... class ResetPasswordView(SuccessMessageMixin, PasswordResetView): template_name = 'users/password_reset.html' email_template_name = 'users/password_reset_email.html' subject_template_name = 'users/password_reset_subject' success_message = "We've emailed you instructions for setting your password, " \ "if an account exists with the email you entered. You should receive them shortly." \ " If you don't receive an email, " \ "please make sure you've entered the address you registered with, and check your spam folder." success_url = reverse_lazy('users-home') @csrf_exempt def post(self, request, *args, **kwargs): email = request.data.get('email') try: if User.objects.get(email=email).active: print("email: %s " % email) return super(ResetPasswordView, self).post(request, *args, **kwargs) except: # this for if the email is not in the db of the system return super(ResetPasswordView, self).post(request, *args, **kwargs) However, the CSRF check doesn't seem to be getting checked for, because when I submit a request like the below curl 'http://127.0.0.1:8000/reset_password' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en;q=0.9' \ … -
How can I let my users watch Netflix, Prime video etc inside my webpage if they have accounts?
We are developing a website for users to be able to watch tv shows/movies together synchronously. We are aware of extensions such as Teleparty, Scener etc. We want to embed it within the site so that no one needs to install an extension. We have solely used Django because it was mandatory to use it. Is there a way to do it? Or should we just develop an extension as well? P.S: There is an app called Rave and they stream all of the aforementioned platforms and more through their apps (including Mac, Windows and Android). We are not sure how that is possible. -
Django Ecommerce View problem with incrementing a quantity up or down on products with same Product Id but different Option ID values
My issue is probably something simple but Ive been stuck on it. I am attempting to make my ecommerce shopping cart increment quantity up and down while deleting the instance when quantity gets to zero. The issue is that when you add options to a product that is in another cart_item instance with the same base Product_id its throwing an error. Im aware it is pulling different instances of the same product_id into the same get request but im not sure how to resolve it. MultipleObjectsReturned at /cart/add_cart/2/ get() returned more than one CartItem -- it returned 2! Request Method: GET Request URL: http://127.0.0.1:8000/cart/add_cart/2/ Django Version: 3.1 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one CartItem -- it returned 2! Exception Location: C:\Users\dave\Desktop\tnaecommerce\venv\Lib\site-packages\django\db\models\query.py, line 433, in get Python Executable: C:\Users\dave\Desktop\tnaecommerce\venv\Scripts\python.exe Python Version: 3.11.0 Python Path: ['C:\\Users\\dave\\Desktop\\tnaecommerce\\ecomwebsite\\tnaecom', 'C:\\Python311\\python311.zip', 'C:\\Python311\\DLLs', 'C:\\Python311\\Lib', 'C:\\Python311', 'C:\\Users\\dave\\Desktop\\tnaecommerce\\venv', 'C:\\Users\\dave\\Desktop\\tnaecommerce\\venv\\Lib\\site-packages'] Server time: Mon, 19 Dec 2022 16:19:11 +0000 views.py ` from django.shortcuts import render, redirect, get_object_or_404 from .models import Cart, CartItem from store.models import Product, ProductOption from django.core.exceptions import ObjectDoesNotExist from decimal import Decimal from django.http import HttpResponse from decimal import Decimal from django.views import View from django.views.generic.edit import DeleteView def _cart_id(request): cart = request.session.session_key if … -
How can I change the URL that points to a File on the FileInput widget in the Django Admin frontend to point to my view
In my django project I want the user to be able to upload files, that are only accessible to users from the same company and from users that are staff. The solution I found is, that I upload the Files to a custom FileSystemStorage with a base_url that is not in urls, so files are not accessible over that url, the only way to access them is through my view. The problem is, that in the django admin frontend on a FileInput widget, it links to the url that is not accessible. How can I link it to my view? This is my model: upload_storage = FileSystemStorage(location='/private/', base_url='/private/') class Datei(models.Model): datei = models.FileField(upload_to='vertraege', storage=upload_storage) ... This is my view: @login_required(login_url='/login/') def serve_file(request, file_id): file = Datei.objects.get(id=file_id) user = User.objects.get(id=request.user.id) if file.firma == user.firma or user.is_staff: return FileResponse(file.datei) else: return HttpResponseForbidden() -
How can a celery task accept a list of files as an argument?
Actually, I don't know how I could make the task have a list of files as an argument. files = {} for file in request.FILES.getlist('files'): files[file.name] = file.file.read() my_celery_task.apply_async( kwargs={ 'files': files, } ) This throws the error 'Object of type bytes is not JSON serializable'. I also tried to add these files to the constructor of a class, but it's still not good because the object cannot be serialized. If I use files[file.name] = file, throws InMemoryUploadedFile is not JSON serializable, or if I use files[file.name] = file.file.read().decode('utf-8') => 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte I actually have no idea how to solve it. I need that dictionary of the form name: content as an argument given to the task -
why does 'Django mssql connection error' happen?
i have an ready database and I wanna use it in django web project. but I have an error about connection. here is the error raise NotSupportedError('SQL Server v%d is not supported.' % ver) django.db.utils.NotSupportedError: SQL Server v16 is not supported. here is the packeges asgiref 3.5.2 Django 4.1.4 django-mssql-backend 2.8.1 django-pyodbc-azure 2.1.0.0 django-pyodbc-azure-2019 2.1.0.0 mssql-django 1.2 pip 22.0.4 pyodbc 4.0.35 pytz 2022.7 setuptools 58.1.0 sqlparse 0.4.3 tzdata 2022.6 and database settings DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME':'veritabanıProje2', 'USER': 'sa', 'PASSWORD':'**', 'HOST':'DESKTOP-MDLFE99', 'PORT':'', 'OPTIONS':{ 'driver':'ODBC Driver 17 for SQL Server', }, }, } I'm using SQL server 2022. also the db file's name DB.sql in project directory. but I write here the name that is written while I create database. (I tried with DB.sql also of course) I can understand the fault is about version but which one is wrong I dont know. -
How to get data from api and load site at same time
I am making a website in Django that gets all stock data for the previous day from API. My problem is that when we take that data we run a few calculations and save data in DB (that process takes about 4 hours to finish) in that time I can't load my home page because that's where part of getting, calculating, and saving data is. So basically is there any way to do all things that I mentioned and use the site normally while getting, calculating, and saving data is running in the background? -
Django sqlite3 deleting existing data in my Django sqlite3 after deployment/deploying to azure app service
the app was working just fine after deploying it to azure app service(ran to some issues but was later on fixed), and after that i decided to clear the data in the sqlite3 table and after i cleared the table, now every time i make some changes/deployment it clears the data in the sqlite3 table and the users of Django administration page. note : i didn't have this problem before clearing the table and everything was fine until i cleared it using flush in the terminal, and no error in the console it simply deletes all the data of the sqlite3 table and users. after deleting i expected it to only clear the table 1 time, and that's it but now it clears the data after every deployment, and only after every deployment. thanks in advance! -
Multitenancy architecture with test and real data
Now we are tasked with making a demo version of our project for potential clients with test data. The frontend is on React and the backend is on Django Rest Framework. The way I see it: Users log in to the demo version. We send a request (GET) to the backend. In the middleware we check the request: 3.1 If it is a demo query, user connects to the sql-lite database with the test data 3.2 Otherwise, we connect to the main database If it is PUT, PATCH, DELETE, then we just show a popup that the action has occurred Do you know of examples of this kind of functionality, or maybe see pitfalls along the way? -
How to solve this error deploying to render.com: django.db.utils.OperationalError: could not translate host name "***" to address?
What I'm trying to do: Deploy my django app to render.com with a postgres database. I'm following the render guide: Getting Started with Django on Render. Problem: I am getting a build failed log error saying the following: django.db.utils.OperationalError: could not translate host name "***" to address: Name or service not known (I have omitted the actual host name here). What research I have done: I have searched the error extensively, however all of the highly rated solutions I have encountered so far are based on using Docker like this which I am not using. settings.py (snippet): import dj_database_url DEBUG = 'RENDER' not in os.environ if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } if not DEBUG: DATABASES = { 'default': dj_database_url.config(default='DATABASE_URL', conn_max_age=600) } In my render.com environmental variables, DATABASE_URL is saved with the postgres URL given by render which includes the database name, hostname, username and password. It follows this format: postgres://USER:PASSWORD@INTERNAL_HOST:PORT/DATABASE -
How do I get rid of "Select a valid choice. That choice is not one of the available choices." error when using a ModelChoiceField?
I am trying to manually render options for a select filed in a django template. When I submit the form I get an error: "Select a valid choice. That choice is not one of the available choices." The error message also asks for required fields which I have provided. locations models.py class Location(models.Model): name = models.CharField(max_length=20) is_source = models.BooleanField(default=False) is_destination = models.BooleanField(default=False) def __str__(self): return self.name orders forms.py class OrderForm(ModelForm): source = forms.ModelChoiceField(queryset=Location.objects.filter(is_source=True)) destination = forms.ModelChoiceField(queryset=Location.objects.filter(is_destination=True)) class Meta: model = Order fields = ['source', 'destination', 'items'] def save(self, commit=True): instance = super().save(commit=False) instance.order_number = math.floor(time.time()) instance.type = 'Purchase' instance.customer = self.context.get('request').user instance.status = 'New' if commit: instance.save() return instance orders create.html <form class="" method="POST"> {% csrf_token %} <h1 class='text-center'>Make an order</h1> <div class='row'> <div class='col-md-6 px-2'> <span class="fw-bold mx-2">Buy from</span> <div class="control-container border-primary d-flex align-items-center"> <i class="fa fa-map"></i> <select class="control ms-1 flex-grow-1" type="text" name="{{form.source.html_name}}" required > {% for value,label in form.source.field.choices %} <option value="{{value}}">{{label}}</option> {% endfor %} </select> </div> </div> <div class='col-md-6 px-2'> <span class="fw-bold mx-2">Receive in</span> <div class="control-container border-primary d-flex align-items-center"> <i class="fa fa-map"></i> <select class="control ms-1 flex-grow-1" type="text" name="{{form.destination.html_name}}" required > {% for value,label in form.destination.field.choices %} <option value="{{value}}">{{label}}</option> {% endfor %} </select> </div> </div> </div> <div class='row'> … -
Does parser type conversion happen inside django tests?
I have defined a custom argument parser from dateutil.relativedelta import relativedelta def custom_parser(value): # Do some actions with value return relativedelta(...) I the use this in a management command as parser.add_argument( "--tes", help=("blablaaa"), type=custom_parser, required=False, default='15s', ) Inside the handler, tes is correctly converted If I call the management command from the terminal directly. def handle(self, *_args, **options): tes = options['tes'] This is correctly converted to relativedelta when I directly run the command. However, If I run this using call_command('mycommand', tes='20s') options['tes'] is always a string. Why is it not being converted? Can't seem to find something on the codebase that would explain it. -
how to check if the uploading file format is different with the file name extension in Python
I want to check the uploading file format is different with the file name extension without saving the file. I tried magic library -
api_view['POST', 'GET'] against SOLID principles?
It's not a problem I'm facing its just an open discussion. in Django Rest framework we declare a decorator @api_view[] and it take an argument like POST GET PUT DELETE in my case I'm allowed to put more than one argument in the decorator and make one function made more than one responsibility like @api_view['POST', 'GET] def fbv_list(request):` if request.method == 'POST': #do something if request.method == 'GET': #do something in this case fbv_list make more than one thing which is POST and GET isn't in this case this function is against the Single responsibility class which is from SOLID principles ???? That's my question and if yes what is supposed to do to avoid breaking the SOLID . Thanks in advance. -
TransactionManagementError An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. django project
I would like to add products or update them if they exist on the database. the data collected comes from an API, then I save it on my database that I created. models.py class Holl(models.Model): name=models.CharField(max_length=70,blank=True,null=True) service=models.CharField(max_length=255,blank=True,null=True) section=models.CharField(max_length=70,blank=True,null=True) class Meta: constraints=[ models.UniqueConstraint(fields=['name', 'section'], name='unique_rows') ] views.py url='http://myAPI/Holl/GetHoll' x=requests.get(url) contenu=x.json() all_holls=contenu['comm'] for holl in all_holls: ins, _ = Holl.objects.update_or_create(name=holl['name'],service=holl['service'], section=holl['section'],defaults={'name':holl['name'],'service':holl['service'],'section':holl['section']}) ins.save() After testing I get this error:An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. -
Rest-API post request fails with one-to-many in Django REST Framework
I want to add with my API the possibility to add a record with a foreign key. I don't want to create a new record in the related table. I just want to add the ID of the existing record to the relation and save the record. The relation is shown in the following graphic. Diagram For example, the Get request to an acronym returns the following response: { "acronym": "Commercial water large stock third letter. Democrat your goal run price. Record myself decision attorney give.\nBill around difficult west protect change every. Various history total particular painting. Mission himself car can of try ten.", "decleration": "Less.", "date": "1992-02-12", "scope": { "scope_id": 16 } }, On the other hand, I would like the post to be possible with the following format: { "acronym": "Hello", "decleration": "World", "date": "2010-07-05", "scope": {"scope_id" : 16} } The corresponding part of the view (view.py) looks like this: @api_view(['GET', 'POST']) def acronym_list(request): if request.method == 'GET': acronyms = Acronym.objects.all() serializer = AcronymSerializer(acronyms, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = AcronymSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In serialzier my idea was therefore to use a separate scope serializer for the post … -
How to trigger a function on user creation with django?
I'm new to django and I would like to know if it is possible to trigger a function after a user has been created? For user creation I use the django administration interface. I want to assign a default theme to a user and to do this I have the following class in my models.py file class Profile(models.Model): user = models.OneToOneField(User, null=False, on_delete=models.CASCADE) selected_theme = models.TextField(max_length=50, default="Clair") This class allows me to store the theme selected by the user I would like to use a function that assigns a theme to a user when creating it. -
Why can't I increment models.IntegerField?
I want to have a counter field in my user profile model to see how many requests each user has made. However I cannot figure out how to increment the count. I am trying to increment an integer field which is a associated with a model which looks like this: class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) request_count = models.IntegerField(default=0) Then in my views I want to increment the request_count every time the user makes a request like so: user = User.objects.get(email=pk) user_profile = Profile.objects.get(user=user) user_profile.request_count += 1 user_profile.save() For some reason every time I run this it sets the request_count to 1. I assume this is because it is defaulting to 0 (the default I set) and then adding 1 to that. But why doesn't the value increment? Help greatly appreciated. -
Is it possible to use "unique together" in Laravel, similarly to Django?
So in Django you can do this: unique_together = ('name', 'username',) so if you try to register people like this: name: John, username: blabla <---- this gets registered name: John, username: haha <---- this gets registered name: John, username: blabla <---- this won't get registered because the combination of John and blabla already exists. Is the something similar is Laravel I could use? The main goal is to check if the name with the username exists together, if it does, throw back a validation error, otherwise register the record to the database. edit #1: if I can get something like "unique together" in laravel, is it possible to modify the validation method based on a hidden field in the form? For example I want the user to write their name and email and submit it, and have a checkbox. The checkbox would enable/disable the 'unique' check of the name, so like if I do this: name: John Doe Corp. email: whatever, checkbox: Ticked then it would check the 'name' column for duplicates. Otherwise: name: Jane Doe. email: whatever, checkbox: Not Ticked then it would not check the name column for duplicates, allowing the record to be saved into the database. -
Django: Get Values from a ListSerializer
I have Serializer like this one: print(SubFoodSerializer(instance.sub_foods,many=True).food_images) Inside each sub_food we have some food_images. I want to get access to all food_images of the sub foods The error I get is: 'ListSerializer' object has no attribute 'title' print(SubFoodSerializer(instance.sub_foods,many=True).food_images) -
Scandics in django admin log
I'm using python 3.7/django 3.2/Mezzanine6.0 and due to use of Mezzanine the entries of django admin log become seen by users in the page history: All page history is ugly (compared what it used to be with python2.7/django 1.8/Mezzanine4.0 as there wasn't seen any unnecessary brackets, but there seem to be no answer in the whole net for that problem ), but it would be nice to have at least the scandics correctly written in the page history, i.e. "Däte of birth instead" of "D\u00e4te of birth". clip from models.py class Author(Page): dob = models.DateField("Däte of birth", null=True) Can anybody help with the scandics ? All program code is available in https://github.com/miettinj/mezzanine/tree/main/mezzanine_app/page_types. -
Django serializer returns enmpty list
I have a class-based view that returns all the data in the table. But while accessing the URL all I get is an empty list. models.py from django.db import models class EmployeeModel(models.Model): EmpID = models.IntegerField(primary_key=True) EmpName = models.CharField(max_length=100) Email = models.CharField(max_length=100) Salary = models.FloatField() class Meta: verbose_name = 'employeetable' views.py from .models import EmployeeModel from .serializers import EmployeeSerialize from rest_framework.views import APIView from rest_framework.response import Response class EmployeeTable(APIView): def get(self,request): emp_obj = EmployeeModel.objects.all() empserializer = EmployeeSerialize(emp_obj,many=True) return Response(empserializer.data) serializers.py from rest_framework import serializers from .models import EmployeeModel class EmployeeSerialize(serializers.ModelSerializer): class Meta: model = EmployeeModel fields = '__all__' The table has 5 rows. It is not empty. I want to serialize all 5 rows -
Django login fails after mail activation
Here's how a signup works: class SignUpView(FormView): template_name = 'center-form.html' form_class = SignUpForm def form_valid(self, form): if form.is_valid(): user = User.objects.create_user( first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password1'], is_active=False, ) activation_code = uuid.uuid4().hex Activation.objects.create(code=activation_code, user=user) activation_url = self.request.build_absolute_uri( reverse('activate', kwargs={'code': activation_code}) ) send_mail( 'Activate account', f'To activate your account, please follow the link below\n{activation_url}', 'Django', [form.cleaned_data['email']], fail_silently=False, ) messages.success( self.request, 'Please check your email for a message with the activation code.', ) return redirect('index') I eventually get a mail which contains some activation code. By clicking the link, I get a message indicating success as a result of: class ActivationView(View): @staticmethod def get(request, code): activation = get_object_or_404(Activation, code=code) activation.user.is_active = True login(request, activation.user) activation.user.save() activation.delete() messages.success(request, 'You have successfully activated your account') return redirect('index') However, when I try to sign in using the email and password used earlier, I get an error in the form: Please enter a correct username and password. Note that both fields may be case-sensitive. The form is AuthenticationForm and here's the view: class SignInView(LoginView): template_name = 'center-form.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data.update({'form_title': 'Sign in'}) return data