Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
not getting the data from Serializer
view.py @csrf_exempt def blog_list(request): if request.method == 'GET': post = Post.objects.all() serializer = BlogSerializer(post, many=True) return JsonResponse(serializer.data,safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = BlogSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) class BlogSerializer(serializers.Serializer): class Meta: model = Post fields = ['author', 'title', 'text', 'published_date'] class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
How can I dispay the data in django admin panel
I am creating an eCommerce website but I want to know how can I display a product_name or customer_name in the admin panel. The concept is that if a customer places an order that it will go to the admin panel. So the other details are displaying properly except product_name or customet_name. As shown in the below image: models.py class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) address = models.CharField(max_length=50, default='', blank=True) phone = models.CharField(max_length=50, default='', blank=True) price = models.IntegerField() date = models.DateField(default=datetime.datetime.today) status = models.BooleanField(default=False) admin.py class AdminOrders(admin.ModelAdmin): list_display = ['product', 'customer', 'quantity', 'address', 'phone', 'price', 'date', 'status'] -
How to add a list of numbers in a function?
I am trying to create a function which can add a list of numbers. I am using the for loop for that. Here is the code: I don't know where I am wrong but it gives me error. def add(amounts): for amount in amounts: total = add(amount) x= print(total) return x amounts= [1, 3, 5, 7, 8 ,9] add(amounts) here is error PS C:\Users\Lenovo\Documents\PP> & C:/Users/Lenovo/AppData/Local/Programs/Python/Python39/python.exe "c:/Users/Lenovo/Documents/PP/Advance python/class_method.py" Traceback (most recent call last): File "c:\Users\Lenovo\Documents\PP\Advance python\class_method.py", line 8, in <module> add(amounts) File "c:\Users\Lenovo\Documents\PP\Advance python\class_method.py", line 3, in add total = add(amount) File "c:\Users\Lenovo\Documents\PP\Advance python\class_method.py", line 2, in add for amount in amounts: TypeError: 'int' object is not iterable PS C:\Users\Lenovo\Documents\PP> -
Django Rest Framework: optimize nester serializers performance
I have problem with my endpoint performance which returns around 40 items and response takes around 17 seconds. I have model: class GameTask(models.Model): name= models.CharField() description = RichTextUploadingField() ... and another model like that: class TaskLevel(models.Model): master_task = models.ForeignKey(GameTask, related_name="sub_levels", on_delete-models.CASCADE) sub_tasks = models.ManyToManyField(GameTask, related_name="master_levels") ... So basicly I can have "normal" tasks, but when I create TaskLevel object I can add master_task as a task which gonna fasten other tasks added to sub_tasks field. My serializers look like: class TaskBaseSerializer(serializers.ModelSerializer): fields created by serializers.SerializerMethodField() ... class TaskLevelSerializer(serializers.ModelSerializer): sub_tasks = serializers.SerializerMethodField() class Meta: model = TaskLevel def get_sub_tasks(self, obj: TaskLevel): sub_tasks = get_sub_tasks(level=obj, user=self.context["request"].user) # method from other module return TaskBaseSerializer(sub_tasks, many=True, context=self.context).data class TaskSerializer(TaskBaseSerializer): levels_config = serializers.SerializerMethodField() class Meta: model = GameTask def get_levels_config(self, obj: GameTask): if is_mastertask(obj): return dict( sub_levels=TaskLevelSerializer( obj.sub_levels.all().order_by("number"), many=True, context=self.context ).data, progress=get_progress( master_task=obj, user=self.context["request"].user ), ) return None When I tried to measure time it turned out that get_levels_config method takes around 0.25 seconds for one multilevel-task (which contain 7 subtasks). Is there any way to improve this performance? If any more detailed methods are needed I will add them -
How to read a log file?
So I am new Django and using Django documentation regarding logging, I found how to get a log file, so I followed the steps and got my first log file. Now what? How do I read it?, I opened it in notepad to read but how to decode like what to look in those files? -
Django Many-to-Many query not returning related records
so this is my job records model that has a many to many relationship with employees model, but when I try to get the job records using {{ employee.jobs }} in my template it returns nothing I can successfully get the employee info, but not the jobs, it's as if they're not related (which they are I checked from database) Jobs Model class Jobs(models.Model): employee_id = models.ManyToManyField(Employee) department_id = models.ForeignKey(Departments,null=True,on_delete=models.SET_NULL) job_title_id = models.ManyToManyField(Job_titles) start_date = models.DateField(null=True) end_date = models.DateField(null=True) salary = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) primary = models.BooleanField(null=True) hire_date = models.DateField(null=True,blank=True) pay_schedule = models.ForeignKey(Pay_schedule,max_length=100,null=True,blank=True,on_delete=models.SET_NULL) pay_type = models.ForeignKey(Pay_type,max_length=100,null=True,blank=True,on_delete=models.SET_NULL) division = models.ForeignKey(Divisions,max_length=100,null=True,blank=True,on_delete=models.SET_NULL) My View def JobView(request,username): if request.user.is_authenticated: try: employee = Employee.objects.get(user__username=username) return render(request,'job.html',context={'employee':employee}) except: pass also , when I directly try to filter job records using jobs = Jobs.objects.filter(employee__id=1) I get a this : The view Employees.views.JobView didn't return an HttpResponse object. It returned None instead. -
Django, DRF: How to cache Pagination count
I think the official paginator uses @cached_property like this, but Even though the cache is used, the DB is accessed every time to get the COUNT. which can be a problem if the COUNT query is slow. Is there a way to cache the counts for a certain amount of time? class Paginator: ... @cached_property def count(self): """Return the total number of objects, across all pages.""" c = getattr(self.object_list, "count", None) if callable(c) and not inspect.isbuiltin(c) and method_has_no_args(c): return c() return len(self.object_list) ... -
pagination keep showing next page when filtered data didn't reach the minimal paginate_by
My first app get query from my second app with requests.get, the pagination works fine when I show all the data but when I use filter the pagination keep showing even when there is not enough data to paginate first app views.py : class Index(LoginRequiredMixin, ListView): model = Transaction template_name = 'transaction/transaction-list.html' paginate_by = 10 def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) status = self.request.GET.get("q", "all") if status != "all": get_data = requests.get(url).json() transaction_list = get_data["data"] context['transaction'] = transaction_list p = Paginator(context['transaction'], self.paginate_by) context['transaction'] = p.page(context['page_obj'].number) context['query'] = 'q='+status else: url = 'http://127.0.0.1:8005/api/transaction/' get_data = requests.get(url).json() transaction_list = get_data["data"] context['transaction'] = transaction_list p = Paginator(context['transaction'], self.paginate_by) context['transaction'] = p.page(context['page_obj'].number) return context second app views.py: def get(self, request, id=None, query=None): if query == 'Success' or query == 'Failed' or query == 'Approval' or query == 'Rejected' or query == 'Cancelled': items = Transaction.objects.filter(status__icontains=query) serializer = TransactionSerializer(items, many=True) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: if id: item = Transaction.objects.get(transaction_id=id) serializer = TransactionSerializer(item) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) items = Transaction.objects.all() counts = self.fetch_count_data() serializer = TransactionSerializer(items, many=True) return Response({"status": "success", "data": serializer.data, "counts":counts}, status=status.HTTP_200_OK) pagination html : <nav class="pagination"> <ul> {% if not page_obj.has_previous %} <li> <a href="#" class="btn btn--secondary … -
How to mock Django queryset which was got from related_name?
I want to unittest this function, which is service-function inside my Django app: from datetime import date, timedelta from account.models import Profile from lesson.models import Lesson, Question from repeat.models import RepetitionSession class QuestionService: @staticmethod def get_next_question_by_rep_session(rep_session: RepetitionSession) -> Question: today_date = date.today() questions_filter = rep_session.questions.filter(next_repeat_at=today_date) sorted_questions_filter = questions_filter.order_by('edited_at') next_question = sorted_questions_filter.first() return next_question It was like this, but I've separated it for 3 lines: next_question = rep_session.questions.filter(next_repeat_at=today_date).order_by('edited_at').first() Here is my unittest: from datetime import date, timedelta from random import randint from unittest.mock import patch, MagicMock from django.test import SimpleTestCase from lesson.services import QuestionService class QuestionServicesTest(SimpleTestCase): FILE_PATH = 'lesson.services.question_service' def test_get_next_question_by_rep_session(self): test_query = MagicMock() test_question = MagicMock() test_rep_session = MagicMock() test_rep_session.questions = test_query test_query.filter().return_value = test_query test_query.order_by().return_value = test_query test_query.first().return_value = test_question result = QuestionService.get_next_question_by_rep_session(test_rep_session) test_query.filter().assert_called_once_with(next_repeat_at=date.today()) I'm getting this fail https://i.stack.imgur.com/85Dzl.png AssertionError: Expected 'mock' to be called once. Called 0 times. Calls: [call.order_by('edited_at'), call.order_by().first()]. So if I want to test filter() I'm usually do this: @patch(f'{FILE_PATH}.Model_name.objects.filter') def test_example_func(self, patch_filter): test_attr = MagickMock() test_query = MagickMock() patch_filter.return_value = test_query result = example_func(test_attr) patch_filter.assert_called_once_with(test_attr) Please, help me find what I've missed. -
Python Django - swagger OPTIONS request problem
@swagger_auto_schema(method="OPTIONS",operation_description="options") @swagger_auto_schema(method="GET", operation_description="get", manual_parameters=[query_parameter]) @api_view(["GET", "OPTIONS"]) def status_get(request: WSGIRequest): if request.method == "GET": response_data = {"status": "OK"} parameter_value = request.query_params.get(PARAMETER_NAME) == "true" if parameter_value: response_data[PARAMETER_NAME] = "info" return JsonResponse(response_data) elif request.method == "OPTIONS": return JsonResponse({}) I'm testing Swagger for Django in a python app. I seem to have a problem with creating a doc for OPTIONS request. When I use Thunder in VSC OPTIONS route seems to be working, but i have no doc for it in my swagger. When using other types of requests it works ok. Thanks in advance for any advices -
Django: unset a user's password, but still allow password reset
I want to reset/unset the passwords of my users, they should be forced to use the "password reset", and set a new one, that validates with the new password validators. I found Django docs, so set_unusable_password() is not an option, as the reset is not allowed afterwards. I found that using user.password = '' works - user cannot login, and password reset is working. Still, this solution feels a bit awkward, and I cant find any real ressources on this topic - how is it security wise, etc.? -
Django open local image
I'm Try to Open local demo image and save to test.jpg but i getting error like this the local image open browser using url "http://127.0.0.1:8000/media/demo.jpg" Traceback (most recent call last): File "E:\django and flutter projects\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\django and flutter projects\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\django and flutter projects\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\django and flutter projects\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "E:\django and flutter projects\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\django and flutter projects\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "E:\django and flutter projects\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "E:\django and flutter projects\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "E:\django and flutter projects\rto\rc\views.py", line 20, in get img =Image.open('http://127.0.0.1:8000/media/demo.jpg',mode="r") File "E:\django and flutter projects\env\lib\site-packages\PIL\Image.py", line 2953, in open fp = builtins.open(filename, "rb") OSError: [Errno 22] Invalid argument: 'http://127.0.0.1:8000/media/demo.jpg' This is Simple view.py class PrintRC(APIView): def get(self,req): img =Image.open('http://127.0.0.1:8000/media/demo.jpg',mode="r") img.save('test.jpeg') print('Success') return Response('hello') -
Create an object that has a ForeignKey with another object
Assume that I have two models: class Category(models.Model): title = models.CharField(max_length=255) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=255) What I wanna accomplish is creating a Product object. Assume I'll receive category_id from the POST request >>> category = Category.objects.get(id=category_id) >>> Product.objects.create(category=category, title='Send the category object') >>> Product.objects.create(category_id=category_id, title='Send only category id') As you can see, there are two options, the first is to send category instance to create() method and the second is to send category_id, so my question is which approach is better for performance? I know that I need to check if that category exists in the DB or not but this is not the case that I'm talking about in the question. -
Why python file in virtual environment is carrying the same installation date after deleting the previous one?
I'm deleting the virtual environment and creating it again and again but in bin, the python and python3 file is not recreating. It's showing the installation time of those 2 files are the same as the first time it was installed. why is this happening? as I'm deleting it completely but again those 2 files carry the same installation time. It is causing problems in selecting interpreters. -
Django smart_select data to be saved in database
I have a model like the picture, but this model records the id in the database, and I want it to save the car_Code, how can I do it?İmage -
What will happen if I put project1's SECRET_KEY to project2
Sorry to bother you guys but I have a question about Django's SECRET_KEY. So I know these SECRET_KEY's are unique for every project. So I think what will happen if I change this SCECRET_KEY. Suppose I have created project1 and copied SECRET_KEY then paste it to project2's SECRET_KEY and after that I deleted project1. So what will happen? I searched a lot but I didn't get any clear answer about it. Thanks!!! -
Can you make an objects that deletes itself in Django?
So I made model VerificationToken class VerificationToken(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) code = models.CharField(max_length=4) date_created = models.DateTimeField(auto_now_add=True) @property def expiration(self): lifetime = timedelta(minutes=10) expire = self.date_created + lifetime return expire and this model have an expiration property. Is there a way to make this model delete itself after it expires? -
How to run two commands on Github Actions instance one after another?
So question seems easy but let me start with this, ";" "&" does not work. The two commands to be ran on Github actions instance in CI/CD pipeline : python3 manage.py runserver python3 abc.py After putting the command in the yaml file, only the first command runs and then the workflow is stuck there only and does not executes the second command. I have tried putting in two separate blocks in workflow yaml file but no luck. -
Run API urls file using management commands in django
In django project, I am creating a new file under management/commands folder named as api_tester.py There are other files as well inside commands folder. I am trying to run this file in pycharm by using configuration something like python /path/manage.py api_tester Working directory is also set to the directory where manage.py file exist. urls.py file content from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('sample_api/', views.sample_api_call), ] api_tester.py file from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): print("Inside api tester") Directory pattern - project_name/project_name/management/commands/api_tester.py project_name/project_name/urls.py project_name/project_name/views.py project_name/manage.py Now I want to run urls.py using api_tester.py file inside commands folder to test all the api's written inside urls.py file which is calling views functions to get api response. How to achieve this or is there any other way. Kindly guide. Any help is appreciated. -
How to use an existing DB for unit testing in Django?
I have created a REST-API application using Django Rest Framework. The API just converts the data from an existing Read-only Postgres DB to a REST- API to be consumed by the front-end. Now I need to write some unit tests to test the application. Since there are lots of tables and views involved, I cannot create mock data and test. Is there a way to run the tests in Django using the existing DB (Postgres) without creating any mock data ? Note: I have read a lot of SO posts related to my problem but none of them worked as they were for old versions of Django. -
Slow Django migrations on cloud spanner & Unable to run Django migrations on cloud spanner
I am trying to set up my Django project with Cloud Spanner. I came across this package django-google-spanner 3.0.1 which provide support to Django ORM. I did everything as told in the documentation like adding the app into INSTALLED_APPS = ['django_spanner',] list, database configuration after creating spanner instance & database. Then created a service account with the appropriate permissions & at last set the environment variables with the service account key & project id. export GOOGLE_APPLICATION_CREDENTIALS=/path/to/keyfile.json export GOOGLE_CLOUD_PROJECT=gcloud_project So far I am able to connect to the spanner instance when I spin up my project but when I run python manage.py migrate it takes like 10-20 mins to create 3-4 tables in the database. I waited long around 30 mins to see it could finish but unfortunately it failed with this error - Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK /usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py:242: UserWarning: This method is non-operational in autocommit mode return self.connection.commit() Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... … -
django models.ForeignKey("Tablename) or models.Foreignkey(Tablenamevariable)
Im looking at the django-generated model classes using inspectdb. I noticed that sometimes strings and sometimes variable names are called based on their "read from top to bottom" appearance in the file. here and example class AuthGroup(models.Model): name = models.CharField(unique=True, max_length=150) class Meta: managed = True db_table = 'auth_group' class AuthGroupPermissions(models.Model): id = models.BigAutoField(primary_key=True) group = models.ForeignKey(AuthGroup, models.DO_NOTHING) permission = models.ForeignKey('AuthPermission', models.DO_NOTHING) class Meta: managed = True db_table = 'auth_group_permissions' unique_together = (('group', 'permission'),) class AuthPermission(models.Model): name = models.CharField(max_length=255) content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING) codename = models.CharField(max_length=100) class Meta: managed = True db_table = 'auth_permission' unique_together = (('content_type', 'codename'),) Using a legacy db (mysql) in my case. Quesion is: Can i not just always use the string name of the table insead of sometimes string sometimes variable? That would be safer in my case Would... group = models.ForeignKey('AuthGroup', models.DO_NOTHING) permission = models.ForeignKey('AuthPermission', models.DO_NOTHING) ...not do the same thing? -
how to access the Json Responce dict value in the Html script
My django views def contact_otp(request): if request.method=="POST": data={} # return JsonResponse(data) .then((response) => response.json()) .then((data) => { console.log(data) const newVarPass = document.createElement("input") newVarPass.setAttribute('id','varPassID') newVarPass.setAttribute('value',`${data}`) newVarPass.value=`${data}` newVarPass.style.display="none" document.body.appendChild(newVarPass) alert("Check your Email We have send you the otp") console.log(data) }) x = document.getElementById("varPassID") console.log(x) console.log("Lets check") When i did that the value saved in the html element is object object [![enter image description here][1]][1] How to get the values of the json keypair i want to have [1]: https://i.stack.imgur.com/AMKQM.png -
unsupported operand type(s) for -: 'decimal.Decimal' and 'float' in Python 3
I am getting this issue unsupported operand type(s) for -: 'decimal.Decimal' and 'float' Here is my models.py def _convert(self,from_currency, to_currency, price): custom_rate_obj = self.quote.client.custom_rates.filter(currency=to_currency).first() if custom_rate_obj is None or custom_rate_obj.exchange_rate in (0, None): custom_rate_obj = ExchangeRates.objects.latest('created') return custom_rate_obj.convert(from_currency, to_currency, price) def get_margin(self): if self.cost_price: cost_price = self.cost_price unit_price = self._convert(self.currency, self.cost_currency, self.unit_price) if unit_price: return ((unit_price - float(cost_price))/unit_price) * 100 How can i solve my issue -
Zappa: No module named '_cffi_backend'
I recently uploaded an Django application with the use off Zappa, which was running perfectly fine. Now, I wanted to update this application, and It suddenly gives me this error: (The changes I made wasn't really that much, removed a blank=True in my models.py) ModuleNotFoundError: No module named '_cffi_backend' Traceback (most recent call last): File "/var/task/handler.py", line 657, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 251, in lambda_handler handler = cls() File "/var/task/handler.py", line 160, in __init__ wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 21, in get_django_wsgi return get_wsgi_application() File "/tmp/mysite/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/tmp/mysite/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/tmp/mysite/django/apps/registry.py", line 122, in populate app_config.ready() File "/tmp/mysite/core/apps.py", line 8, in ready from core import signals File "/tmp/mysite/core/signals.py", line 1, in <module> import cairosvg File "/tmp/mysite/cairosvg/__init__.py", line 26, in <module> from . import surface # noqa isort:skip File "/tmp/mysite/cairosvg/surface.py", line 9, in <module> import cairocffi as cairo File "/tmp/mysite/cairocffi/__init__.py", line 17, in <module> from ._generated.ffi import ffi File "/tmp/mysite/cairocffi/_generated/ffi.py", line 2, in <module> import _cffi_backend I use a package CairoSVG and when disabling this, my application works again. The weird thing is that I was using this package in previous version aswell without any problems. when …