Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form validation/saving for a template with varying quantity and order of text, images, and forms
I am trying to create a Django app where a user (say a researcher or a teacher) can create content for other users (participants or students) where any given page may include any number of content items (such as surveys questions, text, and/or images), and these items can be arranged by the teacher in any order on a page. I'm taking an approach similar to the last chapters (10-12) of the book Django by Example. The app from those chapters comes very close to giving an example of my case using an e-Learning platform app, but they only allow teachers to create Content like Text and Images, they do not allow teachers to create survey questions for students. Here is the general approach that I am following. The book models content for text and images for a given page like so: class Content(models.Model): page = models.ForeignKey(Page, related_name='contents') content_type = models.ForeignKey(ContentType, limit_choices_to={'model__in':('text', 'image')}) object_id = models.PositiveIntegerField() item = GenericForeignKey('content_type', 'object_id') order = OrderField(blank=True, for_fields=['page']) class Meta: ordering = ['order'] class ItemBase(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True def render(self): return render_to_string('courses/content/{}.html'.format( self._meta.model_name), {'item': self}) class Text(ItemBase): content = models.TextField() class Image(ItemBase): file = models.FileField(upload_to='images') There's an … -
Facebook Login "Use Strict Mode for Redirect URIs" with Social Django after March 2018 restrictions
After Facebook security restrictions from March 2018, my Facebook Login feature stopped working. After proper configuration in Facebook API panel and setting "https://{my_domain}/oauth/complete/facebook/" as a "Valid OAuth Redirect URI", I am getting error: "Can’t Load URL: The domain of this URL isn’t included in the app’s domains". I realized that problem is caused by link generated by social-django, which is including redirect_state in the end: "/oauth/complete/facebook/?redirect_state={some_characters}" and this is making mismatch to Valid OAuth Redirect URI. My question is, how can I disable adding redirect_state to the url in Django, using social-django? urls.py: url(r'^account/login/oauth/', include('social_django.urls', namespace='social')) -
What is the best integration of reactjs and django
I am using reactjs for frontend and Django REST API for the backened. What is the best possible way to integrate both? which of these two is a good option? Running two servers for frontend and backend? or replacing django templates with reactjs? Your help is highly appreciated. -
Why does Celery give No such file or directory error?
I generate a PDF and send it through email as attachment. Whenever I run celery multi start worker -A erp -l info and try to send the email it works. But whenever I do it with the daemonized Celery it shows the following error. [2018-05-11 20:53:47,131: ERROR/ForkPoolWorker-6] Task europarts.tasks.generate_pdf_and_send_email[fd80843b-647c-412e-b847-f35cbf157fae] raised unexpected: OSError(2, 'No such file or directory') Traceback (most recent call last): File "/home/michel/erp/venv/lib/python2.7/site-packages/celery/app/trace.py", line 374, in trace_task R = retval = fun(*args, **kwargs) File "/home/michel/erp/venv/lib/python2.7/site-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "europarts/tasks.py", line 58, in generate_pdf_and_send_email email.attach(file_name, response.rendered_content, 'application/pdf') File "/home/michel/erp/venv/lib/python2.7/site-packages/wkhtmltopdf/views.py", line 78, in rendered_content cmd_options=cmd_options File "/home/michel/erp/venv/lib/python2.7/site-packages/wkhtmltopdf/utils.py", line 186, in render_pdf_from_template cmd_options=cmd_options) File "/home/michel/erp/venv/lib/python2.7/site-packages/wkhtmltopdf/utils.py", line 124, in convert_to_pdf return wkhtmltopdf(pages=filename, **cmd_options) File "/home/michel/erp/venv/lib/python2.7/site-packages/wkhtmltopdf/utils.py", line 110, in wkhtmltopdf return check_output(ck_args, **ck_kwargs) File "/usr/lib64/python2.7/subprocess.py", line 568, in check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__ errread, errwrite) File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I can see that on line 58 I have and error in my function. But that function does not write a file to disk, just creates the PDF and attaches it to email before sending. Here is the code: def generate_pdf_and_send_email(template, … -
Django ChoiceField - how to access variable from tuple?
I have following code for my web application. forms.py from . import choices class Find2PlacesForm(forms.Form): category_place_1 = forms.ChoiceField( choices=choices.place_types, label='Category for place 1', widget=forms.Select(attrs={ 'class': 'form-control', })) choices.py place_types = ( (1,'None'), (2,'accounting'), (3,'airport'), (4,'amusement_park')) In views.py I need to pass value from ChoiceField to function. But when I'm using this code: some_function(form.cleaned_data['category_place_1']) Only integer from place_types tuple is passed. For example, if I select from the choice field "airport" then number '3' is passed to function as a value. How can I pass second value from tuple? -
Can I use some client-side cache for 'Big Datas' dynamic visualisation on a Dashboard?
Programming language : Python. Web Framework : Django. Graphic framework : Bokeh. Trying to set up a Dashboard-like application for my company where each factory would be able to upload their own csv-like data and have dynamic results presentation after data cleaning and processing, and some predictions from machine-learning if enough data is provided. The dynamic part is mostly using widgets to let them choose how to visualize, what to visualize, different parts of the data analysis process etc... with either JS Callbacks of the Bokeh server functionality. Until now I decided not to use DataBase Storage but server-side storage in different big CSV, it seems like I have faster access to those on server-side than filtering each time my tables for a given factory upload. Also thought about creating temporary tables/models but didn't feel it right. Before getting into any hard time programming that, I'd like to know if there is any easy answer to my questions, didn't find suitable solution online regarding this, considering the fact that they might upload a bunch of CSV at once. Is there anyway to save all the data (after cleaned on the server) in client-side cache so I have to send it … -
Django looks for templates in my .envs folder (+ Django Admin)
I have my folders set up like this: ~/projects/myproject/ ~/.envs/myproject/ My app folders look like this: myapp/ ├── __init__.py ├── admin.py ├── forms.py ├── migrations/ ├── models.py ├── tests/ ├── templates/ ├── urls.py ├── views.py I just implemented a custom password reset view, because I wanted to use my own templates. The problem is, that the password reset view does not find my template. Here is my view: class CustomPasswordResetConfirmView(views.PasswordResetConfirmView): success_url = reverse_lazy("accounts:password_reset_complete") template_name = "accounts/registration/password_reset_confirm.html." And here is the error message that I get: TemplateDoesNotExist at /auth/reset/MQ/set-password/ accounts/registration/password_reset_confirm.html. Request Method: GET Request URL: http://localhost:8000/auth/reset/MQ/set-password/ Django Version: 1.11.13 Exception Type: TemplateDoesNotExist Exception Value: accounts/registration/password_reset_confirm.html. Exception Location: /Users/jan/.envs/myproject/lib/python3.6/site-packages/django/template/loader.py in select_template, line 53 Python Executable: /Users/jan/.envs/myproject/bin/python Python Version: 3.6.5 Python Path: ['/Users/jan/Dev/Misc Tutorial/myproject', '/Users/jan/.envs/myproject/lib/python36.zip', '/Users/jan/.envs/myproject/lib/python3.6', '/Users/jan/.envs/myproject/lib/python3.6/lib-dynload', '/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/jan/.envs/myproject/lib/python3.6/site-packages'] How can I get Django to find my custom templates? From the error I can tell that he looks in my virtual environments. I tried specifying the templates path like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ [os.path.join(BASE_DIR, 'templates')] ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] The code for this I got from the Django documentation. Unfortunately this doesn't help. If … -
Declaration group closing '}' not found using xhtmltopdf
I am getting below error while converting html to pdf. Declaration group closing '}' not found:: (u'{\n 0', u'% { -webkit-transfor') Code: @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } -
Django: How to use AJAX to dynamically generate form values, based on other form dropdown options?
I want to autopopulate a couple of forms based on other form dropdown values selected. I can find several Django AJAX tutorials which show you how to send and post a form using AJAX, but I don't want to do that. I'd like to submit my form post data without AJAX. So I suppose I need to send post data on specific onclick actions, send that post data to my view/form with AJAX, and then do something (i.e. set ModelChoiceField value) with that post data in the view/form. How would I go about doing this? The dynamic values I want in the form: Trade Price populates based on Coin selected. Coin populates a queryset (based on user's coins) when Sell is selected on "Buysell". if Sell is selected on "Buysell" a) Amount defaults to a value (set to a GetCoinPrice function) and b) whenever a coin is selected that amount is calculated i.e. (on select "Litecoin" value = GetCoinPrice("Litecoin") models.py class Transactions(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) coin = models.CharField(max_length = 64) # is coin a current holding? buysell = models.CharField(default = 'buy', max_length = 4) amount = models.DecimalField(max_digits = 13, decimal_places = 7) trade_price = models.DecimalField(max_digits = 10, … -
Django formset : Add a unique field
I try to use Django 2.0 and formset to make a way to do an inventory of the products in a shop. In the working previous version, i could add products in my inventory, with some data. Now, i would like to add a unique field, for a general info about the inventory (a boolean for full inventory, or not). I first thought that i should use a BaseFormSet with the add_fields method, but it adds a field for each product, and i would like a single one for the global form. What is the best way to do it ? Should I use another form, or can I manipulate the BaseFormSet to do it ? Thanks in advance ! See some of my code below : forms.py class InventoryProductForm(forms.Form): def __init__(self, *args, **kwargs): shop = kwargs.pop('shop') super(InventoryProductForm, self).__init__(*args, **kwargs) product_choice = ([(None, 'Sélectionner un produit')] + [(str(product.pk)+'/'+str(product.get_unit_display()), product.__str__()) for product in Product.objects.filter(shop=shop, is_removed=False)] ) self.fields['product'].choices = product_choice product = forms.ChoiceField(label='Produit', widget=forms.Select( attrs={'class': 'form-control selectpicker', 'data-live-search': 'True', 'required':'required'}) ) quantity = forms.IntegerField( label='En vente', required=False, widget=forms.NumberInput( attrs={'class': 'form-control centered_input quantity', 'placeholder': 'Quantité', 'min':0, 'required':'required'} ) ) unit_quantity = forms.ChoiceField( label='Unité quantité', choices=([('UNIT', 'produits'), ('CL', 'cl'), ('L', 'L'), ('G', 'g'), ('KG', … -
Call URL Name From Another App In Django using Pattern Name + RedirectVew
I'm working on some redirects for a few URL paths. I ended up needing to move a few of my paths to another APP. I'm having an issue calling the pattern name to reference the other URL in my RedirectView. Here's the url i'm trying to redirect which resides in a 'deals' app: path('<slug:slug>/', RedirectView.as_view(pattern_name='deal_detail', permanent=False)) Note i'm also importing the views from the referenced app like so: from dealmazing.urls import * The new url that I want it to redirect to is in my core app directory and looks like this: path('<slug:slug>/', deal_by_detail, name='deal_detail'), Issue is that I'm getting this error: Reverse for 'deal_detail' not found. 'deal_detail' is not a valid view function or pattern name. Is it not possible to reference an external pattern_name? -
Django template block from within template tag template
I have a template called base.html. This template contains a block called pagescripts at the bottom after jQuery has been loaded, like this: <div class="container-fluid"> {% block content %} {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script> <script defer src="https://use.fontawesome.com/releases/v5.0.10/js/all.js" integrity="sha384-slN8GvtUJGnv6ca26v8EzVaR9DC58QEwsIk9q1QXdCU8Yu8ck/tL/5szYlBbqmS+" crossorigin="anonymous"></script> {% block pagescripts %} {% endblock %} Next, I have a template tag that is an inclusion tag for displaying a fancy-looking boostrap 4 card for a particular news article, like this: @register.inclusion_tag('long_article_card.html', takes_context=True) def show_long_card(context, article): try: contextForm = context['form'] except KeyError: contextForm = None return {'article':article, 'form': contextForm} Now, within that long_article_card.html, I want to add a script to the pagescripts block from base.html. So, in long_article_card.html, I have this: <div class="target">TARGET HERE</div> <a class="dropdown-item" id="lean-vote-xl" href="#">Extreme Left</a> {% block pagescripts %} <script> $(document).ready(function(){ $("#lean-vote-xl").on('click', function(){ $.ajax({ url:'/webproxy/v/?i=a&pk={{article.id}}&t=1&v=3', type:'get', dataType:'html', crossDomain:true, success:function(data) { var outputCard = "<div class=\"target\"><br><h2>That worked</h2></div>"; $(".target").html(outputCard); }, error: function(data) { var outputCard = "<div class=\"target\"><br><h2>Load Error</h2></div>"; $(".target").html(outputCard); } }); }); // end id_url_text }); </script> {% endblock %} That template tag is then called from an article detail template called article/detail.html, which extends base.html. {% extends 'base/base.html' %} <div class="row"> {% show_long_card article %} </div> … -
Django use a context_processors.py with settings in Separate Settings Files
I use a context_processors.py based on this example: https://hackernoon.com/5-ways-to-make-django-admin-safer-eb7753698ac8 to Visually distinguish environments between local / internal / prod Ex: def from_settings(request): return { 'ENVIRONMENT_NAME': settings.ENVIRONMENT_NAME, 'ENVIRONMENT_COLOR': settings.ENVIRONMENT_COLOR, } Like that I can use this variable in my template for example here in the admin page {% extends "admin/base_site.html" %} {% block extrastyle %} <style type="text/css"> body:before { display: block; line-height: 35px; text-align: center; font-weight: bold; text-transform: uppercase; color: white; content: "{{ ENVIRONMENT_NAME }}"; background-color: {{ ENVIRONMENT_COLOR }}; } </style> {% endblock %} BUt I also introduce : multiple settings file in order to separate my configuration https://simpleisbetterthancomplex.com/tips/2017/07/03/django-tip-20-working-with-multiple-settings-modules.html Problem now I am no more able to display a variable in my template based on the settings file: can you explain me or give me an example about context_processors based on several settings? Thanks in advance -
django.forms - Getting formset_factory to process initial data, untouched by a user, through POST
I'm using formset_factory to generate a bunch of forms, but I'd also like some HTML to be displayed with these forms, specific to the objects that they will eventually save. Say: Name: Chris Color: Blue Shoesize: [user input] Name: Bologna Color: Pink Shoesize: [user input] Where Name and Color are presented in HTML and Shoesize is a field of some sort. I've tried adding hidden fields with an initial value (initialized when the formset_factory is being created, using the initial argument), but when one tries to POST these forms, if they don't pass validation, the initial values go away and the hidden fields are empty (some of which are required). I could include more than just the formset in the dictionary sent to my template, but I don't have a way of associating information w/ each form in the formset (except through an attribute in the form itself, which doesn't get passed during POST). I've tried actual form fields with the "disabled" attribute, but that doesn't send through validation, either. Can I override the __init__ method to include some variables (but then how would you pass these through to the formset_factory call?) Is there a way of doing this, or … -
download PDF with header and footer with Django
I just started to use Django, and I want to create a button that will initiate a PDF download with a header and a footer. for the PDF I use Reportlab. In the Django documentation, they say to use the Canvas object, but I cannot add a footer and a header with canvas. Can anyone give me a piece of code that will return a response from a view in Django with a PDF download with footer and header? thank you! -
`with` template tag with logical comparison result as value
Is there a way to assign a logical value from a comparison to a variable in the current context? I tried : {% with hidden=forloop.counter > 4 %} {% include "path/to/template.html" %} {% endwith %} And it didn't work. But perhaps there is just a syntax I don't know? So far I do something like this : {% if forloop.counter > 4 %} {% with hidden=True %} {% include "path/to/template.html" %} {% endwith %} {% else %} {% include "path/to/template.html" %} {% endif %} And it works, But it looks dirty to me. -
django models/forms filename one more time
I need some simple help with filename in models. I think the solution can be really simple but i'm stucked and tired allready. For example i have some model as shown below: class Change(models.Model): author=models.CharField(max_length=20) def upload_to(instance,filename): now=datetime.datetime.now().strftime("%y-%m-%d_%H:%M") return 'documents/%s/%s' % (instance.change.author+'/'+now,filename) class File(models.Model): file=FileField(upload_to=upload_to) So now i want to display in template only filename not the whole path given by 'upload_to' or 'variable_in_template.url'. Any ideas would be very helpfull. -
django form ForeignKey as ForeignKey.name not an ForeignKey.id
models.py class Employee(models.Model): name = models.CharField(max_length=100) company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL, related_name='company') views.py class Employee(CreateView): fields = ('name','company') model = models.Employee def form_valid(self, form): self.object = form.save(commit=False) comp_name = self.request.POST.get("company", "") shop_id = "" for word in dept_name.split(" "): shop_id += word[:1] self.object.nik = shop_id[-3:] self.object.save() return super(ModelFormMixin, self).form_valid(form) iam trying to get value from ForeignKey on my code self.request.POST.get("company", "") is return id of the company, i need its return the company.name. how do that?... -
Django 2.0 ordering multiple forms dynamically
I am wondering how I might be able to implement dynamic ordering(via mouse dragging or other method) of forms on a page for Django 2.0. Specifically a user would be able to order 'mini form modules' around in a container which would dictate their priority which is a sort of hidden field for each 'mini form module'. I know the approach to making standard forms however I am unable to find any resources explaining how to do something remotely close to what I require. If anyone has any resources or small examples I would be very appreciative, thanks! -
Django Framework: Object does not display on web page for specific pk
I am trying to import specific items from a database into a web page using Django Framework. I have managed to do this when I pull all the records but not when I try to pick individual records by their primary key. Here is the html to display the page and database fields: {% extends "base.html" %} {% load static %} {% block content %} <br> <h3>Adherence agreement for authorized access to data and biospecimens in the RD-Connect Genome-Phenome Analysis Platform (RDC-GPAP)<sup><a href="#fn1" id="ref1">1</a></sup><small class="text-muted"> to be used together with the <span class="text-info">Code of Conduct</span> for integrated user access to RDC-GPAP for health-related information and human biological samples.</small></h3> <hr> {% for item in items %} <p>I, <span class="text-success">{{ item.first_name }} {{ item.last_name }}</span>, acting on behalf of the <span class="text-success">{{ item.department }}</span>, and holding the position <span class="text-success">{{ item.job_title }}</span>, herewith declare:</p> <ol type="1"> <li>I have the authority to represent and engage the <span class="text-success">{{ item.department }}</span> for the purpose of the project, <span class="text-success">[project name]</span>. For this project we ask for access to data and/or biospecimens in accordance with our research interests as set out in our completed <span class="text-info">User Verification Form</span> (previous page).</li> <br> <li>The <span class="text-success">{{ item.department … -
How to optimize serializing models data in Django Rest Framework?
I need an advice. Sometimes I have situations when in an API I need to retrive a lot of data from some db tables. And when I try to get all data - it takes a lot of time. So I use a little bicycle for retrieving data in a single query. Example: class SomeModelSerializer(serializers.ModelSerializer): related_name1 = serializers.SerializerMethodField() related_name2 = serializers.SerializerMethodField() related_name3 = serializers.SerializerMethodField() def get_related_name1(self, obj): return self.values[obj.id].get('related_table1__name') def get_related_name2(self, obj): return self.values[obj.id].get('related_table1__related_table2__name') def get_related_name3(self, obj): return self.values[obj.id].get('related_table3__name') def __init__(self, *args, **kwargs): super(SomeModelSerializer, self).__init__(*args, **kwargs) # Collect all necessary data from BD. self.values = {} if self.instance: for some_model_values in self.instance.values( 'id', 'related_table1__name', 'related_table1__related_table2__name', 'related_table3__name' ).iterator(): self.values[some_model_values['id']] = some_model_values class Meta: model = SomeModel fields = ('id', 'related_name1', 'related_name2', 'related_name3') It works fine for situations when need to retrive a lot of data, but it takes more time in coding than simple serializer. Is this a good idea to optimize data retrieving, or you have other solutions for this situation? -
Django - How to filter a query, through an attribute of a foreingkey, which is also a foreingkey
I need to filter a query using a foreingkey attribute, but this attribute is a foreignkey too. I have to filter a list of OrderItems, filtering by the Supplier of the product in the order item. OrderItem -> Product -> Supplier is the hierarchy These are the models class OrderItem(models.Model): # Relations order = models.ForeignKey( Order, related_name='items', verbose_name=_('order'), on_delete=CASCADE, ) product = models.ForeignKey( Product, related_name='order_items', verbose_name=_('product'), on_delete=CASCADE, ) # Attributes - Mandatory quantity = models.PositiveIntegerField(default=1) class Product(models.Model): # Relations supplier = models.ForeignKey( Supplier, verbose_name=_('supplier'), on_delete=CASCADE, ) manufacturer = models.ForeignKey( Manufacturer, verbose_name=_('manufacturer'), on_delete=CASCADE, ) family = models.ForeignKey( Family, verbose_name=_('family'), on_delete=CASCADE, ) ... class Supplier(models.Model): # Relations # Attributes - Mandatory name = models.CharField( max_length=50, verbose_name=_('name'), ) corporate_name = models.CharField( max_length=50, verbose_name=_('corporate name'), ) cuit = models.CharField( max_length=11, verbose_name=_('cuit'), ) ... Well, i can filter using the product name, etc, but i need to filter the OrderItems by the Supplier of the Product. Thanks very much! -
using social django package login as google showing url missmatch?
Error: redirect_uri_mismatch The redirect URI in the request, http://localhost:8000/^oauth/complete/google-oauth2/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/300857016299-omtn7s93vsuml8f3ja0v0aiacr41e4sf.apps.googleusercontent.com?project=300857016299 settings.py LOGIN_URL = 'login:log' LOGOUT_URL = 'login:logout' LOGIN_REDIRECT_URL = 'login:success' -
Throwing exception used string object is not callable,django
Getting ERROR:TypeError at /test/ 'str' object is not callable form view: class Test(FormView): template_name = "pkm_templates/main.html" form_class = "Testform" success_url = '/thanks/' def form_valid(self,form): title = form.cleaned_data.get("title") fkey = form.cleaned_data.get("fkey") instance = Buildkb.objects.create(title=title,fkey=fkey) for user in fkey: instance.fkey.add(user) instance.save() return redirect("/") URL: path('test/',views.Test.as_view(),name="test") for another model i used approch formview , modelform and url same has this one no exception. -
join records multiple tables
I have 3 models. i am using billmanagment for date. and customerproductbill table save record of product sale that how many products sale. iam using ORM django query and get record correctly but i need also those product which is not sale and in my customerproduct just save sale product record. i need sale and not sale product, becuase i am developing Ladger of inventory where show all record.Here is my queries products = Product.objects.all().order_by('id') --------------------------------------------------- product_sale_history = BillManagement.objects.filter(Q(creation_date__gte=from_date) & Q(creation_date__lte=to_date) & Q(product__in=products) ).exclude( Q(customer_id=1248)).values('customerproductbill__product_id')\ .annotate(sale_quantity = Coalesce(Sum('customerproductbill__product_qty'), 0)).order_by('customerproductbill__product_id') class Product(models.Model): """ Represent an Inventory Product entity """ product_name = models.CharField(max_length=512, null=True, blank=True) reference_number = models.CharField(max_length=20, null=True, blank= True, unique=True) class Meta: verbose_name_plural = 'Inventory Products' def __unicode__(self): return self.product_name ------------------------------------------------------- class BillManagement(models.Model): """ Represent a Bill entity """ bill_number = models.CharField(max_length=250, null=True, blank=True) creation_date = models.DateField(auto_now_add=True) product = models.ManyToManyField(Product,through='CustomerProductBill', related_name='customer_product_bill') class Meta: verbose_name_plural = 'BillManagements' ordering = ['creation_date'] def __unicode__(self): return self.creation_date ------------------------------------------------ class CustomerProductBill(models.Model): """ Represent a CustomerProductBill entity """ bill = models.ForeignKey(BillManagement, null=True, blank=True) product = models.ForeignKey(Product, null=True, blank=True) product_qty = models.IntegerField(null=False, blank=False, default=0) class Meta: verbose_name_plural = 'CustomerProductBill' ordering = ['product'] def __unicode__(self): return self.product.product_name Can some one modify my query how can i get sale …