Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Access-Control-Allow-Origin' in Django app with Django-cors-headers
So I am getting the following error in one of my web pages. XMLHttpRequest cannot load http://coolkites.com/static/modelling/models/parented.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.coolkites.com' is therefore not allowed access. After researching this issue I came across Django-cors-Headers. After pip installing it. I added the following to Middleware and also set CORS_ORIGIN_ALLOW_ALL to True MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', #'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # CORS Config CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True However I am still getting this issue. Any suggestions ? -
Error configuring postgresql and sqlitedb3
Iam working on a django project and I am configuring preconfigured database in sqlite3 to postgress locally .First i have done all my migrations to sqlite3 database all was working fine .. After that i want to migrate to postgressql so i created a local database and connected to it ... The model iam migrating is :: class State(models.Model): statename = models.CharField(db_column='statename',max_length=26,unique=True) def __str__(self): return self.statename class College(models.Model): statename= models.ForeignKey(State,db_column='statename',on_delete=models.CASCADE,to_field='statename')#used to_field to convert int to text must set unique to true for operation collegename = models.CharField(db_column='collegename',max_length=30,unique=True) def __str__(self): return self.collegename This are the two databases DDL generated by Django :: sqlite3 working fine ----- CREATE TABLE api_state ( id integer PRIMARY KEY AUTOINCREMENT NOT NULL, statename varchar(25) NOT NULL ); CREATE UNIQUE INDEX sqlite_autoindex_api_state_1 ON api_state (statename); CREATE TABLE api_college ( id integer PRIMARY KEY AUTOINCREMENT NOT NULL, collegename varchar(30) NOT NULL, state varchar(25) NOT NULL, FOREIGN KEY (state) REFERENCES api_state (statename) ); CREATE UNIQUE INDEX sqlite_autoindex_api_college_1 ON api_college (collegename); CREATE INDEX api_college_9ed39e2e ON api_college (state) postgress ddl changed after generation with Django:: create table api_college ( id serial not null constraint api_college_pkey primary key, collegename varchar(30) not null, statename_id integer not null ) ; create index api_college_b291eb83 on api_college … -
django rest framework api and angular 2 integration
I'm developing back-end API with Django Rest Framework and front-end with Angular 2. The django server runs on localhost:8000 and the angular server runs on localhost:3000. When I try to access API using angular 2, it gives me the following error: customerregister:1 XMLHttpRequest cannot load http://127.0.0.1:8000/user/signup. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. What I want to ask is how to integrate the development of Django Rest API and angular 2 project. -
how to extend to a lot of template along with its view function?
What i am trying to do is that my base.html to have a Cart.html that extends to it while other child html can extend to base.html and have the Cart.html available in the base.html something like this Catalogue.html----> base.html with Cart.html Catagories.html------^ i tried include in base.html, the form and button did appear but it doesn't pass the class and function from the Cart.html class CartFormView(generic.ListView, ModelFormMixin): template_name = 'Shop/Cart.html' def get(self, request, *args, **kwargs): #bla bla bla def post(self, request, *args, **kwargs): #bla bla bla tried double extending but it is not allowed in Cart.html {% extends 'Shop/Catalogue.html', 'Shop/Catagories.html' %} or {% extends 'Shop/Catalogue.html' %} {% extends 'Shop/Catagories.html' %} Thanks -
Returning empty queryset in Django managers
How do you return an empty queryset in a Django manager? class EventDateRangeManager(models.Manager): def occurring_in_day(self, year, month, day): try: picked_date = datetime.date(int(year), int(month), int(day)) except (TypeError, ValueError): return an empty query set here return super(EventDateRangeManager, self).get_queryset().filter( start_day__lte=picked_date, end_day__gte=picked_date, ) -
Flow map on the web application
I am working on the web application which on Home page should have the map of the servers and connections between them, also I need to see the additional data on those connections, like Lag (Kafka), status of health checks etc.What is the best javascript framework to implement it? -
HttpResponse Django does not change file name
I had followed 3 of answers Generating file to download with Django Make Django return response as a "different filename" Adding a variable in Content disposition response file name-python/django My POSTMAN is v4.10.3 class SBrandJobRawDataView(APIView): permission_classes = [] authentication_classes = (TokenAuthentication,) def get(self, request, format=None): data = { "message": _("GET method is not allowed"), } return Response(data=data, status=status.HTTP_400_BAD_REQUEST, ) def post(self, request, format=None): from_date = request.data.get('from_date') to_date = request.data.get('to_date') queryset = get_raw_sbrand_record(from_date, to_date) filename = f"From_{from_date.get('year')}-{from_date.get('month')}-{from_date.get('day')}_to_" \ f"{to_date.get('year')}-{to_date.get('month')}-{to_date.get('day')}.xlsx" # Allow only last file stay in the server. clean_dir("xlsx") # Create Excel report gen_sbrand_report(queryset, filename) # Open file abs_file = os.getcwd() + '/' + filename xls_file = open(abs_file, 'rb') # Response with attachment response = HttpResponse(xls_file, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f"attachment; filename={filename}" import pdb; pdb.set_trace() return response I am aware that I am mixing Django and Django REST response. If I use from rest_framework.response import Response I get error Internal Server Error: /api/sbrand-jobs/reports Traceback (most recent call last): File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/django/template/response.py", line 109, in render self.content = self.rendered_content File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content ret … -
Creating a Table of Old Passwords in Django 1.9
What I am trying to do: Create a database table of 2 most recently used passwords (not including current). What have I discovered so far? I have discovered the check_password('123') function To my knowledge, this compares newly entered password to the current password before running User.set_password() I have created a table to store a username with the two previously used (not including current) passwords. I have discovered two different hash numbers User.get_session_hash() Not sure if this is used for the password hashing? User.set_password.hash() Again, not sure if this is used for the password hashing? My Issue: In my python shell (under my project), I use User.set_password() and set the same current password after running User.password. Then when I run User.password again and see that there is a different hash. How do I save the previous password hashing method and re-use it to re-hash the password in order to compare it to the previously hashed password?? My research amongst this sight brought me to this post: How to implement password change form in django 1.9 -
Django Queryset Annotate function Rails equivalent
So I'm rewriting my app from Django to Rails, & I'm current stuck on this piece of code conversations = Message.objects.filter( user=user).values('conversation').annotate( last=Max('date')).order_by('-last') users = [] for conversation in conversations: users.append({ 'user': User.objects.get(pk=conversation['conversation']), 'last': conversation['last'], 'unread': Message.objects.filter(user=user, conversation__pk=conversation[ 'conversation'], is_read=False).count(), }) How would I rewrite this in Rails? More specifically, the values('conversation').annotate() part. I've tried this, but still nothing: conversations = Message.where(user: user).select(:conversation, :created_at).distinct(false).order(created_at: :desc) Thank you. -
Django Bad Request (400) on a Digital Ocean Ubuntu 16.04 Server Running Nginx and Gunicorn
I have a dozen Digital Ocean droplets setup with this same configuration with no issues, but for some reason I cannot get this one site to load - I keep getting a Bad Request (400) error when visiting the ip address of my server. The site works fine on localhost though. At this point I am not sure what and how much info to include here, so I've included the basics. I am at my wits end..please help! Nginx Error Log 2017/03/26 04:37:14 [error] 1626#1626: *129 readv() failed (104: Connection reset by peer) while reading upstream, client: 82.113.98.143, server: 138.197.70.81, request: "POST / HTTP/1.1", upstream: "http://unix:/home/rooster/corbett/corbett.sock:/", host: "138.197.70.81:80" 2017/03/26 04:41:51 [error] 1626#1626: *325 readv() failed (104: Connection reset by peer) while reading upstream, client: 50.118.145.87, server: 138.197.70.81, request: "POST / HTTP/1.1", upstream: "http://unix:/home/rooster/corbett/corbett.sock:/", host: "138.197.70.81" 2017/03/26 04:43:29 [error] 1626#1626: *409 readv() failed (104: Connection reset by peer) while reading upstream, client: 31.29.63.51, server: 138.197.70.81, request: "POST / HTTP/1.1", upstream: "http://unix:/home/rooster/corbett/corbett.sock:/", host: "138.197.70.81" 2017/03/26 04:46:45 [error] 1626#1626: *581 readv() failed (104: Connection reset by peer) while reading upstream, client: 124.160.153.143, server: 138.197.70.81, request: "POST / HTTP/1.1", upstream: "http://unix:/home/rooster/corbett/corbett.sock:/", host: "138.197.70.81" Simple Site File server { listen 80; server_name 138.197.70.81; location = … -
UpdateView without a PK or Slug
Having trouble with an UpdateView. I've tried over writing the get_object but I am getting AttributeError at /companydata/update/ 'User' object has no attribute 'get_companydata' The CompanyData Model has a OneToOne relationship with User. Here's my code: urls.py ### Omitted ### url(r'^update/$', CompanyDataUpdateView.as_view(), name='companydataupdate') ### Omitted ### views.py class CompanyDataUpdateView(UpdateView): model = CompanyData fields = ['arr', 'num_cust'] template_name = 'company_data/companydata_form.html' def get_object(self): return self.request.user.get_companydata() models.py class CompanyData(models.Model): user = models.OneToOneField(User) arr = models.DecimalField(max_digits=20, decimal_places=2, validators=[MinValueValidator(1)]) num_cust = models.IntegerField(validators=[MinValueValidator(1)]) def get_absolute_url(self): return reverse('companyrevenue') Any help would be greatly apprecaited! -
How to set class name in table cell in python django?
I am learning django. I have a simple model named customer. Here is my model: class Year(models.Model): year = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) def __unicode__(self): return self.year def __str__(self): return self.year class Customer(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) def __unicode__(self): return self.name def __str__(self): return self.name class Product(models.Model): customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.CharField(max_length=255) year = models.ForeignKey(Year, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) def __unicode__(self): return self.score def __str__(self): return self.score and view is: from django.shortcuts import render, get_object_or_404, redirect from .models import Customer, Product, Year views.py def home(request): customers = Customer.objects.all() years = Year.objects.all().values_list('year', flat=True).asc() # List of year name rows = [] for year in years: row = [year] + [None] * len(customers) # Row with year in first column, and the rest init with same size of customers list for idx, customer in enumerate(customers): quantities = customer.product_set.filter(year__year=year).valu e_list('quantity', flat=True) # filter product by year. That can return multiple product !!! row[idx + 1] = ' ,'.join(quantities) # create a string of quantities rows.append(row) # Add new row in our rows list context = {'customers': customer, 'rows': rows} return render(request, 'customer.html', context) template: … -
Target WSGI script '/opt/python/current/app/ ... /wsgi.py' cannot be loaded as Python module
I am trying to deploy a django app on aws beanstalk but I get a 500. I get the ImportError and I have tried all what the web has suggested, I think, to no end. The trace from the aws server log: ------------------------------------- /var/log/httpd/error_log ------------------------------------- [Sun Mar 26 02:55:17.126990 2017] [:error] [pid 11381] [remote 127.0.0.1:45055] mod_wsgi (pid=11381): Target WSGI script '/opt/python/current/app/src/kirr/wsgi.py' cannot be loaded as Python module. [Sun Mar 26 02:55:17.127048 2017] [:error] [pid 11381] [remote 127.0.0.1:45055] mod_wsgi (pid=11381): Exception occurred processing WSGI script '/opt/python/current/app/src/kirr/wsgi.py'. [Sun Mar 26 02:55:17.127087 2017] [:error] [pid 11381] [remote 127.0.0.1:45055] Traceback (most recent call last): [Sun Mar 26 02:55:17.127244 2017] [:error] [pid 11381] [remote 127.0.0.1:45055] File "/opt/python/current/app/src/kirr/wsgi.py", line 7, in <module> [Sun Mar 26 02:55:17.127252 2017] [:error] [pid 11381] [remote 127.0.0.1:45055] application = get_wsgi_application() [Sun Mar 26 02:55:17.127347 2017] [:error] [pid 11381] [remote 127.0.0.1:45055] File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Sun Mar 26 02:55:17.127354 2017] [:error] [pid 11381] [remote 127.0.0.1:45055] django.setup(set_prefix=False) [Sun Mar 26 02:55:17.127446 2017] [:error] [pid 11381] [remote 127.0.0.1:45055] File "/opt/python/run/venv/lib/python3.4/site-packages/django/__init__.py", line 22, in setup [Sun Mar 26 02:55:17.127453 2017] [:error] [pid 11381] [remote 127.0.0.1:45055] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Sun Mar 26 02:55:17.127584 2017] [:error] [pid 11381] [remote 127.0.0.1:45055] File "/opt/python/run/venv/lib/python3.4/site-packages/django/conf/__init__.py", line 53, in __getattr__ … -
Django DRF - ListCreateAPIView POST Failing with depth=2
I have a ListCreateAPIViewfor showing a list of contacts, as well as for creating new contacts which uses this serializer: class ContactPostSerializer(serializers.ModelSerializer): class Meta: model = Contact exclude = ('id',) For POSTing new records, I have to specifically exclude id so that DRF doesn't complain about a null id. But, for listing records with this serializer, the serializer doesn't return the objects in ForeignKey fields. To get these objects, I add depth = 2. So now the serializer looks like this: class ContactPostSerializer(serializers.ModelSerializer): class Meta: model = Contact exclude = ('id',) depth = 2 However, now, with depth = 2, I can't do POSTs anymore. It complains again of null id values. Edit: I should add that the errors that come up with I have depth=2 are specific to the models of the Foreign Key objects, not the new record I'm creating. What am I missing here? -
Issues with filtering by foreign key and product id
I am trying to filter products added by the person that created them. And then do a separate section that excludes the same person. Ie right now i have something like {{i.product.filter.creator_id}} but its not showing me so i think i have the format either wrong or wrong key words. If i just do i.product I get all the products I need to edit it in the html. I have included the html in question as well as the model. The views is set to show all the database. html in questinon <table class="table"> <tr> <th>Name</th> <th>Added by</th> <th>Date Added</th> <th>Remove From my Wishlist</th> <th>Delete</th> </tr> {% for i in info%} <tr> <td><a href="{% url 'blackbelt:show' i.id %}">{{i.product.filter.creator_id}}</a></a></td> <td>{{i.creator.name}}</td> <td>{{i.created_at}}</td> <td><a href="{% url 'blackbelt:show' i.id %}">Remove From my Wishlist</a></td> <td><form action="{% url 'blackbelt:destroy' id=i.id %}" method="post">{% csrf_token %}<input class="btn btn-default" type="submit" value="Remove"></form></td> {% endfor%} </tr> </table> model.py from __future__ import unicode_literals from django.db import models from ..logReg.models import User class ProductManager(models.Manager): def add_product(self, postData, user): product = postData.get('product', None) if product is not None and user: Myblackbelt = self.create(product=product, creator=user) class Myblackbelt(models.Model): product = models.CharField(max_length = 70) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) loguser = models.ManyToManyField(User, … -
Django REST Framework: require login to view API
I am working through this series on the Django REST Framework and have a few videos left: https://www.youtube.com/playlist?list=PLEsfXFp6DpzTOcOVdZF-th7BS_GYGguAS Unless I missed it somehow, I haven't seen anything on how to require login to view the API. I Googled such things as "Django REST require login", but didn't see anything other than creating authorization in general using Django REST API. I imagine there is a way to do it and would like to implement it because having a wide open API wouldn't work for my project. Can someone point me in the right direction for setting login required for the API? -
Switching from SQL to postgres in Django
I am switching from SQL to postgres in django will this lead to a data loss in my existing database -
TypeError: unbound method set_rank() must be called with Link instance as first argument (got nothing instead)
when i run (nohup python -u rerank.py&) I have the following : Traceback (most recent call last): File "rerank.py", line 24, in <module> rank_all() File "rerank.py", line 11, in rank_all Link.set_rank() TypeError: unbound method set_rank() must be called with Link instance as first argument (got nothing instead) my file rerank.py looks like this and I don't find any gem #!/usr/bin/env python import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "news_factory.settings") django.setup() from news.models import Link def rank_all(): for link in Link.with_votes.all(): Link.set_rank() import time def show_all(): print "\n".join("%10s %0.2f" % (l.title, l.rank_score,) for l in Link.with_votes.all()) print "----\n\n\n" if __name__ == "__main__": while 1: print "---" rank_all() show_all() time.sleep(5) I really thank you for your help -
Django rest framework and iOS authentication using id token from Google
I was wondering if there are any packages out there that I can use to authenticate a user based on the id token that a user receives from Google Auth on iOS. Here is the link to Google's documentation on id token based authentication. I've read about it and searched for a simple package to use for handling the authentication but I could not find one that accepts the id token. So far I have tried and implemented django-rest-auth but it requires either an access token or code both of which do not work if I pass in the id token. I believe django-rest-auth is useful if server-side access is required, which is not my case. I appreciate any help, thanks! -
Python stops working on manage.py runserver
I am new to stackoverflow, very new to Python and trying to learn Django. I am on Windows 10 and running commands from powershell (as administrator). I am in a virtual environment. I am trying to set up Django. I have run the following commands "pip install Django" "django-admin.py startproject learning_log ." "python manage.py migrate" All of the above seemed to work okay, however, when I then try to run the command "python manage.py runserver" I get a popup error box that says: Python has stopped working A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available. Can someone tell me how to resolve this issue or where to look for any error messages that might clue me in as to what is causing the problem? -
Django admin: Access choices from overidden save function
This is a admin poll app in django. admin.py: class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class BallotAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['ballot_name']}), (None, {'fields': ['ballot_address']}), ('Date information', {'fields': ['pub_date'], 'classes': ['expand']}), ('Date information', {'fields': ['end_date'], 'classes': ['expand']}), ] inlines = [ChoiceInline] # include a list filter list_filter = ['pub_date'] list_display = ('ballot_name', 'ballot_address', 'pub_date', 'end_date', 'was_published_recently') # include a ballot search search_fields = ['ballot_name'] def save_model(self, request, obj, form, change): print("***************************************SANDEEPPP*****************************************") print('Ballot address is: ', obj.ballot_address) super().save_model(request, obj, form, change) admin.site.register(Ballot, BallotAdmin) and my models.py is class Ballot(models.Model): ballot_name = models.CharField(max_length=200) ballot_address = models.CharField(max_length=36) pub_date = models.DateTimeField('date published') end_date = models.DateTimeField('end date') def __str__(self): return self.ballot_name def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): ballot = models.ForeignKey(Ballot, on_delete=models.CASCADE) voter_text = models.CharField(max_length=200) voter_address = models.CharField(max_length=36) #votes = models.IntegerField(default=0) def __str__(self): return self.voter_text I am able to access ballot details from obj but how I can access choices? Choices are variable as per the number user provides, so how I can access variable number of choices in Save function? -
Django and jQuery Quiz Use Model in script
I'm trying to use jQuery with model objects in my template. I want to see if the radio button they chose is equal to the correct answer attribute. My code runs, but it doesn't do anything. For example, "if {answerA} equals {correctAnswer} then add a point' {% extends "mainpage/base.html" %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <title>Multiple Choice</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script> // $(function() // { // $('#quiz').on('change', function(){ // alert($('input[name=optradio]:checked','#quiz').val()); // }) // }) // $(document).ready(function(){ // // $("#A").click(function(event){ // if ($('input[name=A]:checked').val() == correctAnswer) { // alert($('input[name=optradio]:checked','#quiz').val()); // } // // }) // }) $(document).ready(function(){ $('#quiz').on('change', function(){ // if the id of a button equals the correct answer if($('input[name=optradio]:checked', '#quiz').val() === '4'){ alert($('input[name=optradio]:checked','#quiz').val()); } }) }) </script> </head> {% csrf_token %} <html> <p>{{ title }}</p> <div class="container"> <form method="GET" class="QuestionForm" id="quiz"> <div class="radio"> <label><input type="radio" name="optradio" id="A">{{answerA}}</label> </div> <div class="radio"> <label><input type="radio" name="optradio" id="B">{{answerB}}</label> </div> <div class="radio"> <label><input type="radio" name="optradio" id="C">{{answerC}}</label> </div> <div class="radio"> <label><input type="radio" name="optradio" id="D">{{answerD}}</label> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> </html> {% endblock %} -
How to shorten Pagination in Django
I have a Django project with 600 listings. I get an extremely long pagination and I would like to know how I would shorten the pagination. Maybe not show all the page numbers and replace some with ... I am using bootstrap v4 and django 1.10. I know there are modules out there I could use but I want to learn. template {% if product.has_other_pages %} <div class="col-md-12 text-center"> <nav aria-label=""> <ul class="pagination"> {% if product.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ product.previous_page_number }}">&laquo;</a> </li> {% else %} <li class="page-item disabled"><a class="page-link"><span>&laquo;</span></a></li> {% endif %} {% for i in product.paginator.page_range %} {% if product.number == i %} <li class="page-item active"><a class="page-link" href="#">{{ i }} <span class="sr-only">(current)</span></a></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if product.has_next %} <li class="page-item"><a class="page-link" aria-label="Next" href="?page={{ product.next_page_number }}">&raquo;</a></li> {% else %} <li class="page-item disabled"><a class="page-link"><span>&raquo;</span></a></li> {% endif %} </ul> </nav> </div> {% endif %} views def products_all(request): products = Product.objects.order_by("-date_added") product_count = Category.objects.annotate(num_products=Count('product')).order_by('-num_products')[:5] company_count = Company.objects.annotate(num_products=Count('product')).order_by('-num_products')[:5] manufacturer_count = Manufacturer.objects.annotate(num_products=Count('product')).order_by('-num_products')[:5] total_manufacturer = Manufacturer.objects.count() total_company = Company.objects.count() total_categories = Category.objects.count() paginator = Paginator(products, 50) page = request.GET.get('page') try: product = paginator.page(page) except PageNotAnInteger: product = paginator.page(1) except … -
Django Ajax Return Multiple json Objects
I have a simple Ajax method: $.ajax({ type:'GET', url: '/getNotifications', success: function (data) { console.log(data); $('#event_invites li').empty(); $('#team_invites li').empty(); $.each(data, function(key, value){ var type = value.model; if(type == "prof.teaminvite"){ $('#team_invites').append("<li>" + value.fields.Invitee + "</li>"); } else if (type == "fullcalendar.eventinvite"){ $('#event_invites').append("<li>" + value.fields.Invitee + "</li>"); } }); } }); My getNotifications: def getNotifications(request): notifications = [] team_invites = serializers.serialize('json',TeamInvite.objects.filter(Invitee=request.user.id)) team_data = json.loads(team_invites) json_team_data = json.dumps(team_data) event_invites = serializers.serialize('json',EventInvite.objects.filter(Invitee_id=request.user.id)) event_data = json.loads(event_invites) json_event_data = json.dumps(event_data) notifications={ 'team_invite':json_team_data, 'event_invite': json_event_data } print(notifications) return HttpResponse(json_team_data, content_type='json') # Multiple objects, single model As you can see I want to return multiple objects from multiple models. I am able to return multiple objects from a single model so far from the above code. I return the TeamInvite objects using json but I also want to pass in the EventInvite objects as well. As you can see, I have tried creating a dict and storing the json objects with the appropriate keys. The data gets passed through, however, I don't know how to retrieve the data in the ajax function. I want something like this: data['team_invite'].model // Gets model type data[team_invite].field.Invitee // Gets the invitee data[event_invite].field.id // Gets event id Is this possible? Thanks -
Access django poll admin fields from python code
I want to access the fields from admin page of ballot from overridden save method. I have created a overridden method for SAVE button on this admin new ballot creation page. But in that method I would like to access ballot address and choice options like Voter text and voter address for each voter. Is it possible to access the user entered data on the save_model method?