Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'alunos_por_ano' with arguments '('',)' not found. 1 pattern(s) tried: ['escola/ano/(?P<ano_lectivo_id>\\d+)/$']
Sou novo e estou aprendendo Django. estou criando um projecto de gestao de mensalidades, e as views funcioanam perfeitamente, mas quando adiciono o link no templete (linha 56) da o seguinte erro: enter image description here views: enter image description here urls: enter image description here models: enter image description here espero que me ajudem. -
I need to convert string to byte string but am unable to do so, please assist me
def application(environ,start_response): status = '200 OK' html = '<html>\n' \ '<body>\n' \ '<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \ 'mod wsgi Test Page\n' \ '</div>\n' \ '</body>\n' \ '</html>\n' response_header = [('Content-type','text/html')] start_response(status,response_header) return [html] This causes an error saying: TypeError: sequence of byte string values expected, value of type str found -
How to save newline (\n) or escape character using Django rest famework serializer
I'm following the tutorial(link) There are two methods to save data (1) direct save(without serializer) from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser snippet = Snippet(code='foo = "bar"\n') snippet.save() (2) with serializer 'PUT' method def snippet_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = SnippetSerializer(snippet) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = SnippetSerializer(snippet, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': snippet.delete() return HttpResponse(status=204) With the first method, I can save newline character('\n') without any problem. But, with the second mehtod, I fail to save. I tested two cases. (1) one backslash { "title": "", "code": "foo = "bar"\n", "linenos": false, "language": "python", "style": "friendly" } (2) two backslashes { "title": "", "code": "foo = "bar"\\n", "linenos": false, "language": "python", "style": "friendly" } The results are: (1) no newline character { "id": 6, "title": "", "code": "foo = "bar"", "linenos": false, "language": "python", "style": "friendly" } (2) backslash character ('') before 'n' { "id": 6, "title": "", "code": "foo = "bar"\\n", "linenos": false, "language": "python", "style": "friendly" … -
AttributeError: 'WSGIRequest' object has no attribute 'get_raw_uri'
I got an AttributeError: 'WSGIRequest' object has no attribute 'get_raw_uri' when I am trying to update my code from python3.3 to 3.9 and django1.10 to 4.0.8. When I try to call update API I got this error -
django multilevel nested formsets
can't find any solution to my needs. django provide inline formset which allow to 3rd level of nesting, but I need much more complex nesting. It should be fully dynamic, so I can go one to one on each level, but it could be one to many on each level. So far I have this only, but could be expanded for additional sublevels. class Srts(models.Model): data = models.CharField(max_length=10, blank=True, null=True) class Volume(models.Model): srts = models.ForeignKey('Srts', on_delete=models.CASCADE) name = models.CharField(max_length=120, blank=True, null=True) class Qtree(models.Model): volume = models.ForeignKey('Volume', on_delete=models.CASCADE) name = models.CharField(max_length=120) class Server(models.Model): qtree = models.ForeignKey('Qtree', on_delete=models.CASCADE) hostname = models.CharField(max_length=120, blank=True, null=True) class CifsPermission(models.Model): qtree = models.ForeignKey('Qtree', on_delete=models.CASCADE) group = models.CharField(max_length=30, blank=True, null=True, default='None') permission = models.CharField(max_length=30, blank=True, null=True, default='None') I have been googling a lot last days, but there is not much. Some examples django-nested-inline-formsets-example -that basic only 3rd level Django-better forms -could handle mltiple forms on one submin, but not formsets django-nested-inline -only for admin page Soudl be the way to do not model related for , then do some separation and appropriate logic to save it in order to my models? -
Schedule a task with celery to run only once in Django
How can I schedule a task with celery to run only once in my Django app. Lets say I'm writing a reminder app where user can login to the system and say "Please remind me 10 minutes earlier that I have a meeting by 10:00am". Then the celery task will run by 9:50am and after that, it would never run again. Not a recurring task. -
Template used by multiple apps requires a specific variable
When one uses a template, used by various apps, that requires a specific variable <a href="{% url 'blog:blog-detail' user_blog %}">My blog</a> we want to ensure that the template will always be aware of the variable user_blog. Also, we don't want to hammer the logic in every view. In such cases, the question popping up is usually within the lines of "How to make a variable available to all templates?" and so we are redirected to Template context processors. Since what we want is dependent on a user instance, we wouldn't be able to use a context processor for something like this user_blog = self.request.user.blog return {'user_blog': user_blog} because, as noted by Willem Van Onsem A contextprocessor only passes extra variables to the template render engine, so it returns a dictionary, and does not take any parameters (except for the request). What do we then do in such cases? -
Str object has no attribute read with django
I have these two codes, i'm working with django, it's a request that asks for a specific project, and the python is supposed to give it back with the return function def project(request): request_body = json.loads(request.body.decode('utf-8')) queryID = request_body['queryID'] with open(os.path.join(BASE_DIR, 'projects//') + queryID + ".json", 'r') as f: response = json.load(f.read()) return response const url = "/project" let id_request = {"queryID":projectID} let data = fetch(url, { method: 'POST', mode: "same-origin", headers: { "Accept": "network/json", "Content-Type": "network/json", "X-CSRFToken": csrftoken, }, body: JSON.stringify(id_request) } ) .then(response=>response.text()) .then(data=>{ console.log(data); }) But when reading the json file I want to return, it throws an error AttributeError: 'str' object has no attribute 'read' -
Django/ Cannot upload image to server (multipart)
I just started with Django and server programming, is there any thing I should know, please kindly give advise. Question: I am trying to upload image to the server. I received Imagename (string) and Imagefile (multipart) from android, Imagename is successfully saved with below algorithm but Imagefile wasn't. I think the problem is the column name of image figure is not imgfigure but "Character". What should I do? Here is the code below, @view.py @api_view(['POST']) def Createtest(request): if request.method == "POST": serializer = FullSerializer(request.POST, request.FILES) if serializer.is_valid(): serializer.save() return JsonResponse({'code':'0000', 'msg': 'saved'}, status=200) return JsonResponse({'code':'1001', 'msg': 'failed'}, status=200) @serializer.py class FullSerializer(forms.ModelForm): class Meta: model = Character fields = ('imgname','imgfigure') @model.py class Character(models.Model): imgname = models.TextField(max_length=20) imgfigure = models.ImageField(upload_to='Image/',blank=True, null=True) Here is the request data in Django //The result of request.POST = <QueryDict: {'imgname': ['"session1"']}> //The result of request.FILES = <MultiValueDict: {'character': [<InMemoryUploadedFile: haruRoll.jpg (image/*)>]}> Here is Retrofit service from Kotlin interface SessionCreateService { @Multipart @POST ("/character/create/") fun SessCreate( @Part("imgname") imgname:String, @Part imgfigure : MultipartBody.Part, ):Call<SessionCreate_o> //output } -
django websocket send messages async in a loop
I'm trying to create a websocket channel using the AsyncJsonWebsocketConsumer class. I want to send messages in a loop after every 5 seconds and my consumer of the websocket channel (ReactJS App Client) should also receive the messages after every 5 seconds. Though my consumer app receives all the messages at once after the final message is sent or when the receive_json function is completed. I cannot seem to fix this. Need help. Thanks test.py from channels.generic.websocket import AsyncJsonWebsocketConsumer class TestController(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() async def receive_json(self, content: dict): for i in range(0, 5): await self.send_json({ "text": f"Loop - {i + 1}" }) sleep(5) await self.send_json({ "text": { "type": "finished" } }) async def disconnect(self, close_code): print() print("DISCONNECTED") print(close_code) print() routing.py from django.urls import path from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from app.test import TestController channel_routing = ProtocolTypeRouter({ "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path("websocket/test", TestController.as_asgi()) ]) ) ) }) -
Use like in MongoDB
I'm trying to write a query in mongo previously I have written in MySQL I'm trying to implement a search on multiple fields using the query collection = get_connection(settings.DATABASE_NAME, settings.FARM_COLLECTION) result = list(collection.find( {'$or': [{'farm_name': "Test_Farm_26"}]} ).limit(filter['limit']).skip(filter['skip'])) print(result) then I am getting this output [{'_id': ObjectId('6331920021a8c44f7e95ea4e'), 'farm_id': 1, 'farm_acreage': 50, 'farm_name': 'Test_Farm_26', 'assignee_id': 1, 'is_active': True, 'farm_location': {'lgd_state_id': 9, 'district_code': 119, 'sub_district_code': 755, 'village_code': 122028, 'lat': 27.934293908219843, 'lng': 78.0054819610702}, 'area_latest_id': 1, 'zone_latest_id': 0, 'created_at': datetime.datetime(2022, 9, 26, 11, 50, 24, 138000), 'updated_at': datetime.datetime(2022, 9, 26, 11, 59, 50, 289000), 'created_by_id': 0, 'updated_by_id': 0, 'farm_area': [{'area_id': 1, 'area_acerage': 3, 'area_structure_type': 'polyhouse'}], 'farm_area_count': 1}] as you see that the column name "farm_name" search filter is working when I am passing its total value but when I am giving its half value and trying to use the LIKE statement in MongoDB I'm getting a blank list as an output collection = get_connection(settings.DATABASE_NAME, settings.FARM_COLLECTION) result = list(collection.find( {'$or': [{'farm_name': "/26/"}]} ).limit(filter['limit']).skip(filter['skip'])) print(result) -
Django Admin prevent overriding of changes by other user submitting the same page
I would like to detect on submit (or maybe even live) that some Django Admin page has been changed and thus what the user sees is stale and the submit will override changes made by other user. My idea would be to create some unique hash of the context_data displayed which would then be compared to the actual hash of the view on submit. Are there any better solutions? -
Autocomplete - Multifill Tag Field at Django Form
Hi! I want to use a tagfield like it is depicted here within django framework: https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/ For the moment I followed the suggestion to use: taggit (https://django-taggit.readthedocs.io/en/latest/) and dal (https://django-autocomplete-light.readthedocs.io/en/master/) extension. I want to have a multipinput field, getting the tags from json-data, allowing autocomplete, using bootstrap design. I just got crazy over the last 5 days, to get this properly working, testing different approaches... !!!!grmxchl!!!! Is somebody out there, able to help me out and suggest a principal solution for that. My current implementation does showing the objects instead the values and furthermore seems to somehow destroy the values on certain cases. However it looks like so. And should look like so. My code: Model class SrsReqs(models.Model): uid_req = models.AutoField(db_column='uid_Req', primary_key=True) # Field name made lowercase. req_title = models.TextField(db_column='Req_title', blank=True, null=True) # Field name made lowercase. req_userstory = models.TextField(db_column='Req_userstory', blank=True, null=True) # Field name made lowercase. req_tags = models.ManyToManyField(SrsTags) req_issues = models.ManyToManyField(SrsWsIssues, related_name='req') # through='ReqIssues', tags = TaggableManager() class Meta: db_table = 'SRS_Reqs' ordering = ['uid_req'] def __str__(self): return self.req_userstory View from django.shortcuts import render, get_object_or_404 from .models import SrsReqs from taggit.models import Tag from .forms import UpdateReq class ModifyRequ(TemplateView): template_name = 'requirements/change_req.html' def __init__(self, *args, **kwargs): super(ModifyRequ, self).__init__() … -
allauth registeration request is returning 500 smallint out of range
I recently migrated my database to PostgreSQL, and up until then, everything was working fine. now when I send a registration request the server is returning the following error (Although the user is being created in the database just fine). I am getting 500 error smallint out of range although none of the posted data has integer as dataType DataError at /authentication/registeration/ smallint out of range Request Method: POST Request URL: http://127.0.0.1:8000/authentication/registeration/ Django Version: 4.0.4 Exception Type: DataError Exception Value: smallint out of range Exception Location: C:\Users\Saad\OneDrive\Documents\Scripts\python\venv\lib\site- packages\django\db\backends\utils.py, line 89, in _execute Python Executable: C:\Users\Saad\OneDrive\Documents\Scripts\python\venv\Scripts\python.exe Python Version: 3.10.7 Python Path: ['C:\\Users\\Saad\\OneDrive\\Documents\\Scripts\\python\\motanafisoun-backend', 'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\Saad\\OneDrive\\Documents\\Scripts\\python\\venv', 'C:\\Users\\Saad\\OneDrive\\Documents\\Scripts\\python\\venv\\lib\\site-packages'] Server time: Wed, 12 Oct 2022 13:05:57 +0300 my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext as _ from django.utils import timezone from PIL import Image from io import BytesIO import random GERNDER_CHOICES = (("male", "Male"), ("female", "Female"), ("unknown", "Unknown")) class UserManager(BaseUserManager): use_in_migrations: True def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) if not email: raise ValueError("The given email must be set") user = self.model( email=self.normalize_email(email), **extra_fields, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) … -
Django update initialized model with get from DB one
I am trying to change the existing initialized and not saved model instance to a one that exist in database. Is this doable? # models.py from django.db import models class Book(models.Model): def cache_or_get(self, some_value): # ... do some cache stuff if not cached: try: from_db = Book.objects.get(some_value=some_value) self.__dict__.update(from_db) # or self = from_db except Book.DoesNotExist: # do some other stuff -
Django Rest Framework not pulling through data
I'm trying to get my data to pull through from my model using DRF. It's my first time using it so I'm trying to work out what I'm doing wrong, the below view pulls through a blank list in the API for "chartdata". Can anyone help with what I'm doing wrong? I would like to get the data pulling through first, and my ultimate goal is to pull through my data and display it on a chart with chart.js on the 'health_hub_tracker' view. One step at a time! Any help would be appreciated! views.py: class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): labels = "weight (lbs)" chartLabel = "weight (lbs)" serialized_stats = [] for stats in HealthStats.objects.filter(user=request.user.id): serialized_stats.append({ "weight": stats.weight, }) data = { "labels": labels, "chartLabel": chartLabel, "chartdata": serialized_stats, } return Response(data) models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse from cloudinary.models import CloudinaryField class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.DecimalField(max_digits=5, decimal_places=2) run_time = models.DurationField() class Meta: db_table = 'health_stats' ordering = ['-date'] def get_absolute_url(self): return reverse('HealthHub:health_hub_history') def __str__(self): return f"{self.user} | {self.date}" class Article(models.Model): title = models.CharField(max_length=200, unique=True) topic = … -
how to add data to jsonfield django from views in django
I have a model with field jsonfield where I store if a shop is opened or not throughout the week I got data from form, and made the data into a json and tried to save, but I got error saying field is required why? working_days['friday'] = True if request.POST.get('friday') is not None else False working_days['saturday'] = True if request.POST.get('saturday') is not None else False form.working_days = json.dumps(working_days) if form.is_valid(): form.save() if I print form.working_days, I get correct json data but yet it is not saved, why? -
How can I add file manager
I'm making a basic panel with Django, I add sidebar, navbar some process but I need to add a file manager but idk how and I searched but couldn't find anything. I ask this question before but didn't worked. Can you help me?? -
Django RestFramework Create Object Without Serializer
i am trying to create an API using POST method in REST that receives the information of a new product and uses them to create a new product. here is an example of what the output should look like after sending POST request: { "message": "new product added successfully", "product": { "name": "chips", "price": 5000 } } this is my code: @api_view(['POST']) def create_product(request): name = request.data['name'] price = request.data['price'] return Response({ "message": "new product added successfully", "product": { "name": name, "price": price } }, status=status.HTTP_201_CREATED) and this is the error i get when i send post request: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" } what do i have to change in my code? thanks for helping :3 -
Mobe Groups model in Django Admin to custom app
I created UserProfiles model in Django in my users app. What I want is to put Group model to the same group in Django admin as UsersProfiles. I tried to implement this solution: Get Django Custom user model listed under admin app `Authentication and Authorization` however I am getting such error: <class 'filer.admin.permissionadmin.PermissionAdmin'>: (admin.E039) An admin for model "Group" has to be registered to be referenced by PermissionAdmin.autocomplete_fields. The code from the solution is below: class Group(DjangoGroup): """Instead of trying to get new user under existing `Aunthentication and Authorization` banner, create a proxy group model under our Accounts app label. Refer to: https://github.com/tmm/django-username-email/blob/master/cuser/admin.py """ class Meta: verbose_name = _('group') verbose_name_plural = _('groups') proxy = True admin.site.unregister(DjangoGroup) @admin.register(Group) class GroupAdmin(BaseGroupAdmin): pass How can I fix it? My UserProfiles model is placed in user app. The only thing I want is to move Groups from auth to user app. -
Get common values in django queryset
I am building a Quiz Application. I have a simple queryset, where I want to filter all the right answers given by the user. So far so good. After that, I would like to obtain the results, divided per subject, si I am trying to figure a way to filter even more. I post some code for better understanding: models.py class QuestionDraft(models.Model): quiz_profile = models.ForeignKey(QuizProfile, on_delete=models.CASCADE, blank=True, null=True) question = models.ForeignKey(Question, on_delete=models.CASCADE, blank=True, null=True) text = models.TextField() is_answered = models.BooleanField(blank=True, null=True) is_correct = models.BooleanField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Question(models.Model): id = models.CharField(max_length=7, default=generate_question_id, unique=True, primary_key=True, editable=False) question_subject = models.ForeignKey( QuestionSubject, on_delete=models.CASCADE) text = models.TextField() mark = models.IntegerField(default=1) is_published = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class QuestionSubject(models.Model): quiz_course = models.ForeignKey(QuizTheoryCourse, on_delete=models.CASCADE) name = models.CharField(max_length=200) exam_questions_num = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) In my views I am trying, initially to filter the correct answers (which I am getting right) and after that to group the right answers per subject. Let's say, I have 10 different subjects views.py def test_report(request, pk): quiz_profile = QuizProfile.objects.get(id=pk) question_drafts = QuestionDraft.objects.filter(quiz_profile=quiz_profile) total_questions = question_drafts.count() right_answers = quiz_profile.right_answer quiz_percentage = ((right_answers * 100) / total_questions) wrong_answers = total_questions - … -
gunicorn - ModuleNotFoundError: No module named 'environ'
I am running the Django project with gunicorn: gunicorn --bind 0.0.0.0:8000 project.wsgi but I am getting the error below : [2022-10-12 12:05:11 +0300] [33444] [INFO] Starting gunicorn 20.1.0 [2022-10-12 12:05:11 +0300] [33444] [INFO] Listening at: http://0.0.0.0:8000 (33444) [2022-10-12 12:05:11 +0300] [33444] [INFO] Using worker: sync [2022-10-12 12:05:11 +0300] [33446] [INFO] Booting worker with pid: 33446 [2022-10-12 12:05:12 +0300] [33446] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/idris/.local/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/idris/Documents/workspace_captiq/venv/captiq/captiq/wsgi.py", line 8, in <module> application = get_wsgi_application() File "/home/idris/.local/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/idris/.local/lib/python3.8/site-packages/django/__init__.py", line 19, in setup … -
How to make Django values() exclude some fields?
I have multiple models which has fields like "created_at" "updated_at" which I don't want to get with objects.values() Does Django has any way to exclude fields in values(). I know people refer to defer(), but it doesn't return QuerySet<Dict> like values() instead returns QuerySet<Model>. I tried objects.defer("created_at", "updated_at").values(), but it includes those 2 deferred fields in the resulting Dict. I see defer().query only selecting the non-exluded fields in the SQL, but using defer(..).values() resets the deferred fields and selects all fields. I cannot specify which field I want, since different model has different fields, I can only specity which fields I don't want. So I cannot use values('name', 'age', ...) I'm planning to use a CustomeManager, which I can use in all model. Eg: class CustomManager(models.Manager): def values_excluded(self): return self.values() # somehow exlude the fields and return QuerySet<Dict> class ExampleModel(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() created_at = models.DateTimeField() updated_at = models.DateTimeField() objects = CustomManager() ExampleModel.objects.values_excluded() Is there any way in Django or do I have to manually delete those keys from the resulting Dict from values()? -
Django -- concatenate filter on a many_to_many relation create unexpected join
class ProductionOrderProductionOrderStatus(sf_models.BaseModel): production_order = models.ForeignKey(ProductionOrder, on_delete=models.CASCADE) production_order_status = models.ForeignKey(ProductionOrderStatus, on_delete=models.CASCADE) class ProductionOrderStatus(sf_models.BaseModel): status = models.IntegerField(null=False) begin_datetime = models.DateTimeField(default=timezone.now) end_datetime = models.DateTimeField(null=True, blank=True) class ProductionOrder(sf_models.BaseModel): statuses = models.ManyToManyField(ProductionOrderStatus, through='ProductionOrderProductionOrderStatus', related_name='production_orders') if i concatenate 2 filter like this -> ProductionOrder.objects.filter(statuses__status=2).filter(statuses__end_datetime=None) i get this sql: 'SELECT ... FROM "production_order_productionorder" INNER JOIN "production_order_productionorderproductionorderstatus" ON ("production_order_productionorder"."id" = "production_order_productionorderproductionorderstatus"."production_order_id") INNER JOIN "production_order_productionorderstatus" ON ("production_order_productionorderproductionorderstatus"."production_order_status_id" = "production_order_productionorderstatus"."id") LEFT OUTER JOIN "production_order_productionorderproductionorderstatus" T4 ON ("production_order_productionorder"."id" = T4."production_order_id") LEFT OUTER JOIN "production_order_productionorderstatus" T5 ON (T4."production_order_status_id" = T5."id") WHERE ("production_order_productionorderstatus"."status" = 2 AND T5."end_datetime" IS NULL)' if i put on the same filter like this -> ProductionOrder.objects.filter(statuses__status=2, statuses__end_datetime=None) i get this sql: 'SELECT ... FROM "production_order_productionorder" INNER JOIN "production_order_productionorderproductionorderstatus" ON ("production_order_productionorder"."id" = "production_order_productionorderproductionorderstatus"."production_order_id") INNER JOIN "production_order_productionorderstatus" ON ("production_order_productionorderproductionorderstatus"."production_order_status_id" = "production_order_productionorderstatus"."id") WHERE ("production_order_productionorderstatus"."end_datetime" IS NULL AND "production_order_productionorderstatus"."status" = 2)' if i have a queryset created with this condition: ProductionOrder.objects.filter(statuses__status=2) how can i concatenate the second condition? is there a solution to get a dict of the already filtered condition? (to get for example {'statuses__status':2}, so i can concatenate the second condition and recreate the query) -
Django error ValueError: Field 'id' expected a number but got ''
I create django model for keep api_key as char like this. class DeviceKey(models.Model): api_key=models.CharField(max_length=100,unique=True) limit_device=models.IntegerField() created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def __str__(self): return self.api_key class Meta: ordering=('api_key',) verbose_name='DEVICE KEY' verbose_name_plural='DEVICE KEY' class Device(models.Model): api_key=models.ForeignKey(DeviceKey,on_delete=models.CASCADE) name = models.CharField(max_length=100) status=models.BooleanField() switch=models.BooleanField(default=False) timer=models.BooleanField(default=False) category=models.ForeignKey(Category,on_delete=models.CASCADE) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: ordering=('api_key',) I create function device() in views.py for get data by using api_key like this. def device(request): key = request.GET.getlist('key') data=Device.objects.filter(api_key__in=key).values_list('name','status') return JsonResponse(list(data), safe=False) In admin page I create sample api_key as 2eaWe. when I run and send api_key to function device() it show error like this. ValueError: Field 'id' expected a number but got '2eaWe'.