Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update item status using other model in Django
I am creating purchase order app. I have difficulty to solve following issue. I have 2 models(request model & purchase update model) Once request model created(via form), with "update status button" admin can update follow up status to that specific selected item(via form-only can be access by staff) How I can create a function in views.py to generate task no.2? I could not find any solution in stackoverflow. It would be great if someone can point me to right solution if already discussed. p/s: I am not professional programmer :( Many thanks This is my model class OrderRequest(models.Model): user = models.ForeignKey(Customer, on_delete=models.CASCADE,null=True, blank=True) ref_code = models.CharField(max_length=100,blank=True, default='ABC') link = models.URLField(null=True, blank=True) image = models.ImageField(upload_to='media/images',null=True, blank=True) price = models.FloatField(null=True) draft = models.BooleanField(default=True) logistic_method = models.ForeignKey(Logistic, on_delete=models.CASCADE, null=True, blank=True) note = models.TextField(max_length=100) date_order = models.DateTimeField(auto_now=True) class PurchaseUpdate(models.Model): pu_item = models.OneToOneField(OrderRequest,on_delete=models.CASCADE,null=True, blank=True ) pu_itemprice = models.IntegerField(null=True, blank=True) pu_deliveryfee = models.IntegerField(null=True, blank=True) pu_intdeliveryfee = models.IntegerField(null=True, blank=True) pu_rank = models.IntegerField(null=True, blank=True) pu_complete =models.BooleanField(default=False, null=True, blank=True) Here is my views.py def purchase_update(request): form = PurchaseUpdateForm(request.POST) if request.method =='POST': form = PurchaseUpdateForm(request.POST) instance = form.save(commit=False) instance.pu_item = request.ref_code instance.save() context = { 'form':form } return render(request, 'commerce_autoparts/purchase_update.html', context) -
Method Not Allowed: /api/vote/
i trying to upvote some post but when i open the api page it doesn't upvote the post so what should i do ? and why it gives me method not allowed 405 class Addone(APIView): def post(self, request, *args, **kwargs): qs = Post.objects.filter(publisher=self.request.user) if qs.exists(): query = qs.first() query.votee += 1 query.save() return Response(status=HTTP_200_OK) return Response(status=HTTP_400_BAD_REQUEST) urls.py: path('api/vote/', Addone.as_view(), name='vote'), -
Hi I'm new to docker and I'm trying to run a docker compose file. I keep on getting the fallowing error
docker compose image version: '3.7' services: web: build: . command: python/code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 -
Remove chosen value of django-autocomplete using script
I have assigned a value to the foreign key element (which is an autocomplete in the form) using initial. Coming to the front-end if the category is changed I used script to hide and show fields accordingly. So if I change the category and the auto-complete goes to hidden state I just want to remove its initial value. I tried this: ... var category = $('#id_category').val(); if(category == 'customer'){ $('#id_customer').show(); ... } else { $('#id_customer').val('').hide(); ... } any other way -
(Django python) Using multiple 'for loop' for render
Hey guys I'm making English test system for education by using Django python. the system display one article and several(not fixed) questions about the article. and every question has selectable items which numbers are not fixed. for example { ---------- article -------------- } { ---------- question --------------} { ---------- item ------------------} { ---------- item ------------------} { ---------- item ------------------} { ---------- question --------------} { ---------- item ------------------} { ---------- item ------------------} { ---------- item ------------------} so I defined model like this : # Question DB class Article(models.Model): a_name = models.TextField(unique=True) a_con = models.TextField() #Article Contents class Question(models.Model): q_name = models.TextField(unique=True) q_a = models.ForeignKey(Article,on_delete=models.CASCADE) q_con = models.TextField() #Question Contents q_ans = models.TextField() #Question Correct Answer class Item(models.Model): i_q = models.ForeignKey(Question,on_delete=models.CASCADE) i_seq = models.PositiveIntegerField() #Item Sequence i_con = models.TextField() #Item Contents # Image DB class ArticleImage(models.Model): ai_name = models.TextField(unique=True) ai_a = models.ForeignKey(Article,on_delete=models.CASCADE) ai_src = models.TextField() class QuestionImage(models.Model): qi_name = models.TextField(unique=True) qi_q = models.ForeignKey(Question,on_delete=models.CASCADE) qi_src = models.TextField() class ItemImage(models.Model): ii_name = models.TextField(unique=True) ii_i = models.ForeignKey(Item,on_delete=models.CASCADE) ii_src = models.TextField() and I wrote view.py like this: def findQuestionbyArticle(article_name): _ARTICLE_ = Article.objects.filter(a_name = article_name) for a in _ARTICLE_: _ARTICLE_IMAGE_ = ArticleImage.objects.filter(ai_a = a) _QUESTION_ = Question.objects.filter(q_a = a) _ITEM_ = {} _ITEM_IMAGE_ = {} for q … -
How to Make API in Django?
I am completely new in django API.i dont know how to make API in django. in Other language like PHP, we Create an API file and We call that API file in our Application.is Django following same? i know structure of Django app. i Know how to make app and the crud operations as well.i don't know about API.How to make register API? for Example, i am having below fields in my database first_name last_name email password Then How to Make register API for above fields? -
AuthStateMissing at /complete/azuread-oauth2/ Session value state missing
I am using python social auth https://python-social-auth.readthedocs.io/en/latest/ and Azure backend https://python-social-auth.readthedocs.io/en/latest/backends/azuread.html for o365 login. However after entering all correct credentials i get session value state missing. My error trace is as follows: AuthStateMissing at /complete/azuread-oauth2/ Session value state missing. Request Method: GET Request URL: http://localhost:8000/complete/azuread-oauth2/?code=AQABAAIAAAAGV_bv21oQQ4ROqh0_1-tAd4a1-XSjMQv3OjWjqqpskGiNBkIYGujMLZsuB6QKXbTmFobZnhq6tT558B0grlCbN2xynEE86gQRKIJ91ScEKHLchQu329DKESMKyh2F8fydRn_L_ZBiZpU4QvBU_2r1XzZjo3vFyv6YF4Dh7xuJxMuE52ajXKwhbXoYlq9sZ1lvxOPCk6QjWDVQtRZ5X-WWLZwbwjE0czcEYTrPWE1GSy0D_gz6WfdBACs7AhZ_VNoUKaxdANmIBRaJT9PYGHKJZL-gr4WerbNpkyJ2lK-Qg9Lf75HtxXXXh7CRYLaSCAoypfGV1RggstrrV-JO-0S9cEgUy96yamuV82FfddCSSewfUy8dfASraqCo2ma7dTRr06FpL9gNqLEC2_2pMJVt5VEllmVp6eafTItE4VFqTLsty340QOaWI7yurgvWKpBnBVj5SwVZMv7nGrxOyv5ymEID99HbQm2-pteiPPc0g3BABSi9gWtaDsHD4EpdnS2vVUpEbccIJAfn90_jaCiJUWpjPzoI524Lbaz4xCLXQsMN25ZFDQfUo2Pvszr87E1JUTXSZuftjGszFvQ2UvuLUITp9y0btbs-YLIJvaPFG22yoDcyqFRYhG0H5BlWxcsgAA&state=DChfqXaiLVRCPivB503yqti6sWewqk7S&session_state=de25b1c3-906b-4dbd-a20f-4b0c18122cdb Django Version: 3.1.1 Exception Type: AuthStateMissing Exception Value: Session value state missing. Exception Location: /home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/social_core/backends/oauth.py, line 90, in validate_state Python Executable: /home/maz/ct/ct/.venv-ct/bin/python Python Version: 3.8.2 Python Path: ['/home/maz/ct/ct', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf', '/home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/odf'] Server time: Tue, 08 Sep 2020 14:49:52 +0200 Traceback Switch to copy-and-paste view /home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner response = await sync_to_async(response_for_exception)(request, exc) return response return inner else: @wraps(get_response) def inner(request): try: response = get_response(request) … except Exception as exc: response = response_for_exception(request, exc) return response return inner ▶ Local vars Variable Value exc AuthStateMissing('state') get_response <bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x7f3999792070>> request <WSGIRequest: GET '/complete/azuread-oauth2/?code=AQABAAIAAAAGV_bv21oQQ4ROqh0_1-tAd4a1-XSjMQv3OjWjqqpskGiNBkIYGujMLZsuB6QKXbTmFobZnhq6tT558B0grlCbN2xynEE86gQRKIJ91ScEKHLchQu329DKESMKyh2F8fydRn_L_ZBiZpU4QvBU_2r1XzZjo3vFyv6YF4Dh7xuJxMuE52ajXKwhbXoYlq9sZ1lvxOPCk6QjWDVQtRZ5X-WWLZwbwjE0czcEYTrPWE1GSy0D_gz6WfdBACs7AhZ_VNoUKaxdANmIBRaJT9PYGHKJZL-gr4WerbNpkyJ2lK-Qg9Lf75HtxXXXh7CRYLaSCAoypfGV1RggstrrV-JO-0S9cEgUy96yamuV82FfddCSSewfUy8dfASraqCo2ma7dTRr06FpL9gNqLEC2_2pMJVt5VEllmVp6eafTItE4VFqTLsty340QOaWI7yurgvWKpBnBVj5SwVZMv7nGrxOyv5ymEID99HbQm2-pteiPPc0g3BABSi9gWtaDsHD4EpdnS2vVUpEbccIJAfn90_jaCiJUWpjPzoI524Lbaz4xCLXQsMN25ZFDQfUo2Pvszr87E1JUTXSZuftjGszFvQ2UvuLUITp9y0btbs-YLIJvaPFG22yoDcyqFRYhG0H5BlWxcsgAA&state=DChfqXaiLVRCPivB503yqti6sWewqk7S&session_state=de25b1c3-906b-4dbd-a20f-4b0c18122cdb'> /home/maz/ct/ct/.venv-ct/lib/python3.8/site-packages/django/core/handlers/base.py, line 179, in _get_response if response is None: wrapped_callback = self.make_view_atomic(callback) # If it is an asynchronous view, run it in a subthread. if asyncio.iscoroutinefunction(wrapped_callback): wrapped_callback = async_to_sync(wrapped_callback) try: response = wrapped_callback(request, *callback_args, **callback_kwargs) … except Exception as e: response = self.process_exception_by_middleware(e, request) if response is None: … -
Retrieve User's input from Django
I'd like to retrieve the user's input and process them, then render a result page, but it keeps throwing me in Exception !! models.py class MultiStepFormModel(models.Model): headline1=models.CharField(max_length=255) headline2=models.CharField(max_length=255) headline3=models.CharField(max_length=255) views.py def ad_gen(request): context ={} if request.method!="POST": return render(request , 'gen.html' , context) else: headline1=request.POST.get("headline1") headline2=request.POST.get("headline2") headline3=request.POST.get("headline3") try: if form.is_valid (): multistepform=gen_form(request.POST or None) multistepform.save() return render(request , 'Ad result.html' , context) except: messages.error(request,"Error in Saving Data") return render(request , 'homepage.html' , context) forms.py class gen_form(forms.ModelForm): class Meta: model = MultiStepFormModel fields = "__all__" gen.html <form method="POST"> {% csrf_token%} <input type="text" id="fname" name="headline1" ><br> <input type="text" id="fname" name="headline2" ><br> <input type="text" id="fname" name="headline3" ><br> <input type="submit" value="Submit"> </form> -
Django reverse (on_delete) protection on a model instance
Is is possible to protect a model in a reverse relationship. For instance in the models below:- class Foo(models.Model): foo_field1 = models.CharField(max_length=56, unique=True) class Bar(models.Model): bar_field1 = models.ForeignKey(Foo, on_delete=models.PROTECT, blank=True) bar_field2 = models.CharField(max_length=56, unique=True) If an attempt is made to delete an instance of Foo, it wont be deleted as the on_delete attribute on Bar is set to models.PROTECT. So, is it possible to extend that protection both ways? That is, if an attempt is made to delete an instance of Bar, so can it be protected just like Foo, can someone suggest a solution?. -
How to integrate stripe 3D secure payments, with Strong Customer Authentication (SCA) in django-oscar?
I have followed these steps as mentioned here for setting up stripe in Django-oscar, used this link of this answer I have integrated everything and the payment and checkout functionality is working. I assume the above code is using the "Stripe Checkout" as a Stripe Payment Option to accept one-time payments with Stripe. (I am not sure, correct me if I am wrong). Now I want to integrate the 3D secure, Stripe integration due to Strong Customer Authentication (SCA). for integrating the SCA, I checked that I will have to use "Payment Intents API" which supports SCA. I have a few questions here: Do I need to remove the existing flow and use the "Payment Intents API" instead? If yes, the 3d secure, banks interface which appears before the final checkout page, will appear after 3rd step(Payment) in Django-oscar or after 4th step(Preview) in django-oscar ? Most importantly, how can I integrate 3D secure in this existing checkout flow that I currently have. I also have dj-stripe installed in my application. Please suggest me the steps and approach I need to follow step by step. Please, point me in the right direction, I just shared my understanding, I need to … -
Django 3.1 websockets chat [closed]
I'm trying to implement connection between users in django. I know i can do it with django channels but i found WebSockets in Django 3.1 and now I'm wondering how to implement something like group_send in django channels to that solution. I tried something like this: async def room(socket, id): await socket.accept() user = await socket.user if user.is_authenticated: while True: message = await socket.receive_text() message = json.loads(message) await socket.send_text(json.dumps(message)) else: await socket.close() but this doesn't work. -
Django - managing and accessing background processes
I'm looking for the cleanest way to serve data in Django 3.1 from background processes and to manage those processes "in" Django 3.1. Problem: I have couple sensors/cameras in my network which I want to monitor -- pull data and process each one of them (that I've already got). Now in Django I want to manage them (add new sensors / delete old ones / set alarms if something happens and saving it all to database) and present their current values thorugh views. So I need them (sensor processes and django) to communicate so I can pull data from those processes. I was thinking about some kind of global singleton manager of those processes that would be initialized on start of django app. I don't know where is the best place to do it so I could pull information about sensors from database to initialize on start of django app and access it later i.e. in views. Another solution would be to run this manager as app and django app independently and communicate through named pipes or other IPC method. But then I would have to store information about sensors in this manager app and django would serve just as … -
Adding permission based on the logged in user. Django
How can i deny a user who did not create a post an ability to delete the post of another user and also how can i display various edit functions for a post based on the user? Meaning that if you are the creator of the post, only you can have access to editing that post. (for example, if you are logged in as the creator of the post, the post-view displays more options to edit/delete your post). Can i create this permission through admin-groups or do i have to use another library? views.py def ViewPostMain(request, pk): post = Post.objects.get(id=pk) # where id is taken as the field name from the DB submissions = Submission.objects.filter(post_id = pk) # post_id is taken from db. context = {'post' : post, 'submissions' : submissions} return render(request, 'view-post.html', context) view-post.html template {% extends 'base.html' %} {% block content %} <h1><i> {{ post.title }} by {{post.author }}</i></h1> {{ post.post_creation_time }} {{ post.genre }} {{ post.stage }} {{ post.optional_notes }} <div> <hr> <a href="{% url 'delete_post' post.id %}">(Delete Post)</a> <hr> </div> <h3><i>Submissions</i></h3> <h6>{{ submissions.count }} submissions total </h6> <h3><i><a href="{% url 'create_submission' post.id %}">Create a submission</i></a></h3> {% for submission in submissions reversed %} <ul> <p> post_id: … -
A way to count objects in Django
I need to create a view in Django to count every vehicle on my DB. count=Vehicle.objects.all().count() count=Vehicle.objects.all().count() -
How can i make a voice recorder for my Django chat app like whatsapp?
I want to add a voice message to my chat app which is made by Django, for now, users can upload Audio from their devices, but how can I allow users to record the voice directly from my website and send it to the server-side with ajax or even refresh the page? Here is my models.py class GroupMessage(models.Model): group = models.ForeignKey( ChatGroup, related_name='chat_group', null=True, on_delete=models.CASCADE) message_sender = models.ForeignKey( User, related_name='group_message_sender', null=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) message = models.TextField(null=True, blank=True) # //////// Files file = models.FileField( upload_to='social/group_files', null=True, blank=True) video = models.FileField(upload_to='social/group_videos', null=True, blank=True) image = models.ImageField( upload_to='social/group_images', null=True, blank=True) audio = models.ImageField( upload_to='social/group_audio', null=True, blank=True) # Files //////// ... Here is my views.py that handles submitting group file def send_group_file_message(request, pk): group = get_object_or_404(ChatGroup, pk=pk) try: area = get_object_or_404(Area, pk=request.GET.get('area')) except: area = None message = GroupMessage( group=group, message_sender=request.user, file=request.FILES.get('file'), image=request.FILES.get('image'), video=request.FILES.get('video'), audio=request.FILES.get('audio'), area=area) message.save() return redirect('social:chat_group', pk=pk) I have been searching for this for about a week and I can't find anything, I would appreciate any help! -
DJANGO PYINSTALLER ISSUE
I'm trying to compile a Django (3) applications that uses pymongo and channels. I followed steps in a ticket in stackoverflow, I got the .exe file but when I try tu run it using app.exe runserver I got this error : \AppData\Local\Temp\_MEI149762\Test_Project\settings.pyc' Failed to execute script manage I've found nothing on the net discussing this issues. HELP PLEASE. -
Integrating java with django backend api
I am working on a project which uses django rest-framework as the rest-api and react as the frontend. While Python is a very good language and I was able to make most of my api work in django, there were a couple of features which I felt were lacking. I wanted to implement digital signature on a pdf in my api. I looked into Endesive which seemed like a good library in python for achieveing that. I would still like to prefer to use Java as a framework in my backend to implement this. So essentially I wanted to know if there is a compatibility of java and django to serve at the backend together? What I want to do is to: Get The data as a request in the rest api in django. Send the data to a java script for some processing and digital signature. From Java send the data back to django python which sends the data as a HTTPResponse to the client side. I have looked into Jython. But I was wondering if django would support such api calls or not.. Is there a library in django/python which would integrate java with Django Python? If, there … -
how to make a rows in column as a link in table created from djangotable2 and also apply django_filters
may i know how to get a link able column(particular,rest all will be normal table) in a table created from Django table 2 my previous html code was- {% for a in as %} <a href="{% url 'b' a.aid %}"><b>{{a.aname}}</b></a> {% endfor %} how will it work in a django table format my tables.py file class ATable(tables.Table): class Meta: model = A kindly help -
How to redirect to a dynamic url in django
I am working on a django project. in the project I have a dynamic url as follows app_name = 'test' urlpatterns = [ path('root', views.root, name='root'), path('output/<str:instance>', views.output_page, name='output_page'), ] There exists two pages in the application. In the root page there exists a form which when submitted should redirect to the output_page. But because the output_page is a dynamic url, I am not able to redirect. Here is my views file def root(request): if request.method == 'POST': name = request.POST.get('name') job = request.POST.get('job') return redirect("test:output_page") return render(request, 'test/root.html') def output_page(request, instance): record = Object.objects.all(Instance_id=instance) return render(request, 'test/output_page.html', {'record': record}) Here is the Model class Object(models.Model): Name = models.CharField(max_length=200, null=True, blank=True) Job = models.CharField(max_length=200, default="") Instance_id = models.CharField(max_length=200) When the redirect happens I want the url to be as follows http://127.0.0.1:8000/output/test-001 where test-001 is the instance_id in the model. The output_page should filter all the data in the model with instance_id test-001 -
Django {% translate %} does not work in project's base.html
I am internationalizing my app and need to translate nav links into their Italian counterparts. All the apps in my project share the same base.html file located in project_folder/templates/base.html. I also created a locale folder inside project_folder containing the .po file for base.html. Inside base.html I have the nav links I want to translate: {% load i18n %} <!doctype html> <html> <body> <nav> <a href="#">{% translate "Define" %}</a> <a href="#">{% translate "Profile" %}</a> ... </nav> </body> </html> Here is the corresponding portion of my .po file: #: project_folder/templates/base.html:32 msgid "Define" msgstr "Definisci" #: project_folder/templates/base.html:35 msgid "Profile" msgstr "Profilo" Despite this, when I switch the site to Italian, the links are all still in English. Other translations done similarly inside app folders in other parts of the website work perfectly. Also, in my settings.py I specified LOCALE_PATH = [ os.path.join(BASE_DIR, 'locale'), ] It seems that Django is not able to find the .po files at the project level, however, there is no error when I compile them and everything seems to be working until I render the nav. Can anybody help? -
Django Celery Tasks are not executed after an hour
I'm using celery to run some background tasks in django. Celery worker executes the tasks correctly for the first 45 minutes. After that tasks are not executed. I'm using Django==2.2.13 and Celery==4.4.7 And this is how i start the celery worker and beat. celery worker -A app_name --loglevel=info celery beat -A app_name --loglevel=info celery setting file is: CELERY_ACKS_LATE = True CELERYD_PREFETCH_MULTIPLIER = 1 CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' celery.py from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_name.settings') app = Celery('app_name') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.task_default_priority = 5 app.conf.beat_schedule = { 'parse_sources_manager_async': { 'task': 'parse_sources_manager_async', 'schedule': crontab(minute=0), } } Is there anyway to make it work , any help would be appreciated, thanks in advance. -
Django- user posting Errors
i am finding a problem in saving the user posts from my Django site. Whenever I try to run the submit form, it shows that the form has been submitted but I cant see the post being saved in the data base. def addPost(request): form = hacksform(request.POST or None, request.FILES or None) if request.method == 'POST': form = hacksform(request.POST or None, request.FILES or None) if form.is_valid(): try: newpost = form(commit= False) image = request.FILES['photo'] newpost.author = request.user newpost.post_image = image newpost.save() newpost.save_m2m() except: newposts = form(commit=False) newpost.author = request.user newposts.save() newposts.save_m2m() return HttpResponseRedirect('/tweaks/tweaks') return HttpResponseRedirect('/tweaks/tweaks') and here is my forms.py file class hacksform(forms.ModelForm): VIEW_CHOICES = ( ("Option", "Choose Option"), ("Public", "To Public"), ("Channels", "To Channels"), ) title = forms.CharField(widget=forms.TextInput(attrs={'class': 'user-title', 'placeholder': 'Title'}) ,required=True) content = forms.CharField(widget=forms.Textarea(attrs={'class': 'user-text', 'placeholder': 'Questions'}) ,required=False) tags = forms.CharField(widget=forms.TextInput(attrs={'class': 'input-tag', 'placeholder': 'Add Tag'}) ,required=False) audience_privacy = forms.CharField(widget=forms.Select(choices=VIEW_CHOICES,attrs={'id': 'selector'}) ,required=False) class Meta: model = hacks fields = [ 'title', 'author', 'tags', 'content', 'post_image', 'audience_privacy' ] any ideas why I cant post -
How to setup button on the home page for login Microsoft authentication in a django based project
I am using django-microsoft-auth in my Django project. I followed this guide. Now, I'm able to log in through Microsoft account(address: http://localhost:8000/admin ) but I don't know how to add a view that will say "Login using Microsoft" and how to link that view with the Microsoft authentication page. It will be great if someone can tell me how to do this. You can see this picture. Here Microsoft button is automatically added for login. How to set up a button like this on the home page for login? -
Django multiple annotations sum in one queryset
Models class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items') quantity = models.IntegerField(default=1) class OrderPlateRelation(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name='order_model_relations') plate = models.ForeignKey(EncryptedModel, on_delete=models.PROTECT, related_name='order_model_relation') quantity = models.PositiveSmallIntegerField() class OrderItemPlateRelation(models.Model): order_plate_relation = models.ForeignKey( OrderPlateRelation, on_delete=models.CASCADE, related_name='order_plate_relation', ) order_item = models.ForeignKey(OrderItem, on_delete=models.CASCADE, related_name='plate_relation') quantity_of_order_item = models.PositiveSmallIntegerField() Rest Framework Order Detail (Example) : { "id":70, "order_items":[ { "id":1313, "quantity":5 }, { "id":1311, "quantity":5 }, { "id":1310, "quantity":5 } ], "assigned_orders":[ { "order":70, "plate":15929, "quantity":1, "relations":[ { "order_item":1313, "quantity_of_order_item":5 } ] }, { "order":70, "plate":15930, "quantity":1, "relations":[ { "order_item":1310, "quantity_of_order_item":5 }, { "order_item":1311, "quantity_of_order_item":5 } ] } ] } Queryset : qs = ( Order.objects.filter(order_status__in=[Order.ORDER_STATUSSES.New, Order.ORDER_STATUSSES.Processing]) .filter(order_items_productowner_company=self.request.user.company) .distinct() .annotate( item_quantity=Sum('order_items__quantity'), assign_quantity=Sum( F('order_model_relations__quantity') * F('order_model_relations_order_plate_relation_quantity_of_order_item') ), ) .order_by('id') ) I have a order model at top. I'm building queryset from order. I need to sum order items quantity based on provider. Below item quantity part is working fine. item_quantity=Sum('order_items__quantity'), I want to check order_items quantity and sum of assigned_orders quantity. Let me give you a quick example from my JSON : sum of order_items quantity ( "id":1313,"quantity":5 + "id":1311,"quantity":5 + "id":1310, "quantity":5 ) is 15. sum of assigned_order (quantity * sum[quantity_of_order_item]) ==> ("plate":15929,"quantity":1,("quantity_of_order_item":5) 1 * 5 = 5 ("plate":15930,"quantity":1,("quantity_of_order_item":5,"quantity_of_order_item":5) 1 * ( 5 + 5 ) … -
Django Rest when i replace ModelSerializer with HyperlinkedModelSerializer, Raise this error
In my django rest project when I replace ModelSerializer with HyperlinkedModelSerializer, this error Raise below; ' Could not resolve URL for hyperlinked relationship using view name "product-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. ' # Views.py class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class CatView(viewsets.ModelViewSet): queryset = SubCategory.objects.all() serializer_class = CatSerializer class BrandView(viewsets.ModelViewSet): queryset = Brand.objects.all() serializer_class = BrandSerializer # Serializer.py class BrandSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Brand fields = '__all__' class CatSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SubCategory fields = '__all__' class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = '__all__' # urls.py app_name = 'api' router = routers.DefaultRouter() router.register('product', views.ProductView) router.register('category', views.CatView) router.register('brand', views.BrandView)