Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        Is PostgreSQL (via ElephantSQL) a much slower database than Django's SQLite, and what to do about it?I am building a Django webapp including a view, which can upload data into the database through a csv-import. Each import contains around 2,000 rows and 9 columns with DecimalFields and CharFields. So far I've been using Django's SQLite Database and each upload took me 1 min max. I switched to PostgreSQL (hosted via ElephantSQL) and now the upload takes at least 10 minutes. I've read in some posts that SQLite is faster than PostgreSQL but I was not expecting anything of this magnitude. Is there a way to speed up the upload process in PostgreSQL? I thought one reason for the low speed might be that I am using ElephantSQL's free Tiny Turtle Plan, but if i understand correctly the non-free plans differ only in terms of the max size of the database but not its speed? See also here https://www.elephantsql.com/plans.html Might it be a solution to have PostgreSQL installed locally instead of using a cloud provider? Is there anything else I can optimize to speed up the process? my model: class Testdata3(models.Model): key = models.CharField(max_length=100, primary_key=True) mnemonic = models.CharField(max_length=50) assetclass = models.CharField(max_length=50) value = models.DecimalField(max_digits=255, decimal_places=25) performance = models.DecimalField(max_digits=255, decimal_places=25) performance_exccy = models.DecimalField(max_digits=255, decimal_places=25) performance_abs = models.DecimalField(max_digits=255, decimal_places=25) …
- 
        Django - Relative ModelI have 2 models in my django app: Cats and Dogs, now I want to build a 3rd Model: Animals, that contains the same fields of the cats and dogs model. I want that the changes I make to the cats and dogs models will be saved in the animals model as well. Here is a short example of what I am trying to achieve: class Dogs(models.Model): avg_height = models.IntegerField() class Cats(models.Model): avg_height = models.IntegerField() class Animals(models.Model): avg_height_cats = models.IntegerField() avg_height_dogs = models.IntegerField() Thank you for any help
- 
        Django Can't find mysqlclientI am Django 2.2.8 python3.7 I made a virtual environment of Django,I installed mysqlclient, too This is all my bags,i have mysqlclient. Here is the error message
- 
        Django subquery/prefech_relatedFor example, I have models: class Location(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... class ControlPoint(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) location = models.ForeignKey(Location, related_name='+', on_delete=models.CASCADE, verbose_name='Локация') order = models.IntegerField(default=0) route = models.ForeignKey('Route', related_name='control_points', on_delete=models.CASCADE) ... class Route(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) @property def get_departure(self): return self.control_points.get(order=0) @property def get_arrival(self): return self.control_points.order_by('-order')[0] def clear_control_points(self): self.control_points.all().delete() class Trip(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) route = models.OneToOneField(Route, related_name='trips', null=True, on_delete=models.SET_NULL) user = models.ForeignKey(User, related_name='trips', on_delete=models.CASCADE) ... And I need to get all trips, which contains in route a control point with given location id. Can i do this with Subquery? I would be grateful for any help.
- 
        How to configure Celery with Django so that workers would received tasks properly?I installed RabbitMQ (systemd service) and configured Celery within my Django project. I started Celery workers, but currently, my task function (defined in my tasks.py within my application) is triggered but I don't see any "received" message within the worker process. Django project layout my_project │ ├── my_project │ ├── celery.py │ ├── settings.py │ ├── urls.py │ ├── wsgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── static │ └── templates ├── my_app │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── models.py │ ├── tasks.py │ ├── urls.py │ ├── views.py │ ├── migrations │ ├── __pycache__ │ └── templates └── venv settings.py # /foo/django/my_project/my_project/settings.py # ... INSTALLED_APPS = [ #... 'myapp", } # ... CELERY_BROKER_URL = 'amqp://localhost' __init__.py # /foo/django/my_project/my_project/__init__.py from .celery import app as celery_app __all__ = ('celery_app',) celery.py # /foo/django/my_project/my_project/celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE','my_project.settings') app = Celery('my_project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py # /foo/django/my_project/my_app/tasks.py import string from celery import shared_task from django.utils.crypto import get_random_string @shared_task def my_task(n): for c in range(n): result = get_random_string(20) print('Celery Task [' + str(c + 1) + '/' + str(n) + '] : ' + result) return '{} …
- 
        Stardardized way to save comments on a blog with Ajax and DjangoI'm building a comment system for a website i'm working on using Ajax as a way to send off the comments and Django as my backend. I've basically pieced together different tutorials to come up with a way to do it that fits my need. I'm just curious if: I'm doing this correctly? if there is any concern with this method? if it can be abused in anyway by users? if there is a better way of getting the Post's primary key? Javascript on blog page: <script type="text/javascript"> $("#comment_form").on('submit', function(event) { event.preventDefault(); var value = $("#comment").val(); $.ajax({ url: '{% url 'add-comment' %}', data: { comment_value: value, comment_pk: '{{ object.pk }}' }, dataType: 'json', success: function (data) { if (data.comment_saved) { alert('{{ object.pk }}') } else { alert("didn't save shit") } } }); }); </script> Django Class View: class AddCommentView(LoginRequiredMixin, View): def get(self, request): comment_value = request.GET.get("comment_value", None) print(f'request: {request}') data = { 'comment_saved': False } if comment_value: # save comment data['comment_saved'] = True return JsonResponse(data) return JsonResponse(data)
- 
        i have problem in django paypal integration payment**I face this problem in my project please help me.** **FieldError at /shop/process_payment/ Cannot resolve keyword 'id' into field. Choices are: address, amount, city, email, items_json, name, order_id, phone, state, zip_code** This is my checkout button code and use some javascript in my html file. def checkout(request): if request.method == "POST": items_json = request.POST.get('itemsjson', '') name = request.POST.get('name', '') amount = request.POST.get('amount', '') email = request.POST.get('email', '') address = request.POST.get('address1', '') + " " + request.POST.get('address2', '') city = request.POST.get('city', '') state = request.POST.get('state', '') zip_code = request.POST.get('zip_code', '') phone = request.POST.get('phone', '') order = Orders(items_json=items_json, name=name, amount=amount, email=email, address=address, city=city, state=state, zip_code=zip_code, phone=phone) order.save() update = OrderUpdate(order_id=order.order_id, update_desc="The order has been placed") update.save() thank = True id = order.order_id # What you want the button to do. request.get['id'] = order.order_id return redirect('process_payment') return render(request, 'shop/checkout.html', locals()) def process_payment(request): order_id = request.session.get('id') order = get_object_or_404(Orders, id=order_id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': '%.2f' % order.total_cost().quantize( Decimal('.01')), 'item_name': 'Orders {}'.format(order.id), 'invoice': str(order.id), 'currency_code': 'USD', "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('payment_done')), "cancel_return": request.build_absolute_uri(reverse('payment_cancelled')), } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render(request, "shop/process_payment.html", context)
- 
        Perpetual tasks in Celery?I'm building a django app where I use a camera to capture images, analyze them, store metadata and results of the analysis in a database, and finally present the data to users. I'm considering using Celery to handle to background process of capturing images and then processing them: app = Celery('myapp') @app.task def capture_and_process_images(camera): while True: image = camera.get_image() process_image(image) sleep(5000) @app.task def process_image(image): # do some calculations # django orm calls # etc... The first task will run perpetually, while the second should take ~20 seconds, so there will be multiple images being processed at once. I haven't found any examples online of using Celery in this way, so I'm not sure if this is bad practice or not. Can/should Celery be used to handle perpetually running tasks? Thank you.
- 
        Django: from request.GET to QuerySetI know how to create a html form with Django and I know how to access the values in request.GET. I know how to use the ORM: MyModel.objects.filter(...) Now I a missing how get from request.GET to a matching QuerySet I could not find this in the Django docs.
- 
        Django and keycloak; login console outputI have dockerized system: web container (Django 2.2) and Keycloak Auth container. It all works fine. When I login and watch docker-compose logs, I see this dict dump output, mostly logged by web container: web-container | [11/Dec/2019 14:36:45] "GET /login/keycloak/?next=/ HTTP/1.1" 302 0 keycloak-container | 13:36:45,420 WARN [org.keycloak.services] (default task-2) KC-SERVICES0091: Request is missing scope 'openid' so it's not treated as OIDC, but just pure OAuth2 request. web-container | ================================================================================ web-container | {'access_token': '<some token string>', web-container | 'acr': '1', web-container | 'allowed-origins': ['http://<my IP>:8000'], web-container | 'aud': ['<my client name>', 'account'], web-container | 'auth_time': 1576071415, web-container | 'azp': '<my client name>', web-container | 'email': '<my email>', web-container | 'email_verified': True, web-container | 'exp': 1576071715, web-container | 'expires_in': 300, web-container | 'family_name': '<my last name>', web-container | 'given_name': '<my first name>', web-container | 'iat': 1576071415, web-container | 'iss': 'http://<my IP>:8080/auth/realms/<my realm name>', web-container | 'jti': '<some uuid>', web-container | 'name': '<my full name>', web-container | 'nbf': 0, web-container | 'not-before-policy': 0, web-container | 'preferred_username': '<my isername>', web-container | 'realm_access': {'roles': ['offline_access', 'uma_authorization']}, web-container | 'refresh_expires_in': 1800, web-container | 'refresh_token': '<some token string>', web-container | 'resource_access': {'account': {'roles': ['manage-account', web-container | 'manage-account-links', web-container | 'view-profile']}}, web-container | 'scope': 'profile email', web-container …
- 
        Django : Multiple possible foreign keys for the same field in a modelI simplify the problem to make it clear, so it may sound stupid to set a product cost this way but i don't have the choice ! I have a product model. The pricing for this product is set by multiple conditions, depending of the type of the product. The different possibilities are stored in separated models for each case. Depending of the conditions the foreign key to set the pricing of the product must be one of the different pricing models. A simplified version of my models : class PricingA(models.Model): ... class PricingB(models.Model): ... class PricingC(models.Model): ... class Product(models.Model): fee1 = models.Foreignkey(xxx) fee2 = models.Foreignkey(xxx) # the foreignkey must be one of the 3 models (12 in the real case) in my views again a simplified version : def createproduct(request): product_app_form = ProductCreationForm() if request.method == 'POST': form_product = ProductCreationForm(request.POST, request.FILES) if form_product.is_valid(): product = form_product.save(commit=False) product.save() if product.type == 'xxx' product.fee1 = PricingB if product.type == 'yyy' product.fee2 = PricingA product.save() I'm kinda new into django so i have the feeling that i try to achieve something in a horrible way. If you have any idea to help me to solve this problem, you are more than welcome …
- 
        Variable in a Variable in Django TemplateI have global variable accesable from every html file. The variable is called "canAccessClients". Its a list of objects (clients) to which the logged user has access. It is mainly used in menu, so user can see only his clients. I can find client's logo (his url) by "canAccessClients.<some_index>.picture.url". Now, i have one page where are only some clients. I know ID of this clients. This ID of client is not obviously the same as index in list of canAccessClients. Because "canAccessClients" is only a list of client objects. Now i need to show logo for same client which i know his ID. I do it (maybe to bad idea, but works) by finding iterating through "canAccessClients" and looking for the needed ID. {% for client in canAccessClients %} {% if client.id == client_data.CLIENT_ID %} <img class="client-menu-logo" src="{{ canAccessClients.{{ forloop.counter }}.picture.url }}" alt="logo"> {% endif %} {% endfor %} Everything works and is ok, but... i need to pass "forloop.counter" variable into "canAccessClients.<some_id>.picture.url", this does not work. How can i use variable in some other variable in path like this?
- 
        For Loop Populate ID In URL DjangoI have a button on my template that says check progress, what the button does is takes you to another page for that user based on their user id. /points/student_progress/1000 <-- id What I'm trying to accomplish: When my for loop runs to populate the student names on my template, i want it also to populate the student ID on the button as well. /points/student_progress/{{student_id}} . Here is my code. How do i add this in ? Views.py @login_required def K8_Points_Classroom(request): #context_from_k8_points = request.session['k8_points_context'] if request.method == 'POST': form = K8Points_ClassroomForm(request.POST) if form.is_valid(): form.save(commit=False) form.save() class_name = form.cleaned_data.get('class_name') getstudents = Student.objects.filter(class_name = class_name) students = getstudents.all() form = K8Points_ClassroomForm() context = {'form': form ,'students' : students, 'class_name': class_name,} messages.success(request,("Points were successfully added for student !")) return render(request, 'points/k8_points_classroom.html', context ) if not form.is_valid(): messages.warning(request,(form._errors)) class_name = request.POST.get('class_name')[0] getstudents = Student.objects.filter(class_name = class_name) students = getstudents.all() context = {'form': form, 'students': students,} return render(request, 'points/k8_points_classroom.html', context ) else: form = K8Points_ClassroomForm() return render(request, 'points/k8_points_classroom.html', context) @login_required def K8_Points(request): if request.method == 'POST': form = K8PointsForm(request.POST) if form.is_valid(): form.save(commit=False) class_name = form.cleaned_data.get('class_name') getstudents = Student.objects.filter(class_name = class_name) students = getstudents.all() form = K8Points_ClassroomForm() context = {'form': form ,'students' : students, 'class_name': class_name,} …
- 
        Django reqired parameters in url queryIs there any chances to specify which parameters are required in url query and automatically pass them into view function? In urls.py I would like to have something like this: path('get_part_info?<part>', views.get_part_info, name='get_part_info'), And in views.py to have something like this: def get_part_info(request, part): # do something with part return JsonResponse({'result': part}) Idea is to avoid ugly construction like : part= request.GET.get('part') URL path is not a solution, because "part" value can have various extra characters like slashes etc.
- 
        Django: AllAuth login form doesnt send request?users/account/login.html: {% extends 'index.html' %} {% block 'head-title' %} <title>Вход</title> {% endblock %} {% block 'body' %} {% load i18n %} {% load account socialaccount %} {% block content %} <h1>Влез</h1> {% get_providers as socialaccount_providers %} {% if socialaccount_providers %} <p>{% blocktrans with site.name as site_name %}Ако все още нямате регистрация, можете да се <a href="{{ signup_url }}">регистрирате от тук!</a>{% endblocktrans %}</p> {% include "socialaccount/snippets/login_extra.html" %} <a href="{% provider_login_url "facebook" method="js_sdk" %}" class="btn btn-block btn-social btn-facebook" style="background-color:#3b5998;text-align:center"> <span class="fa fa-facebook"></span> Sign in with Facebook </a> {% else %} <p>{% blocktrans %}If you have not created an account yet, then please <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %}</p> {% endif %} <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> <button class="primaryAction" type="submit">{% trans "Sign In" %}</button> </form> {% endblock %} {% endblock %} users/urls.py: from django.urls import path, re_path, include from . import views urlpatterns = [ path('', include('allauth.urls')), ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'core', 'users', 'objects', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', …
- 
        Django channels, running server not workingHi i am trying to make a chat webapp with django and channels and now that i have intregrated channels into the project i am getting this trace back error Traceback Traceback (most recent call last): File ".\manage.py", line 21, in <module> main() File ".\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\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 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\site-packages\channels\apps.py", line 6, in <module> import daphne.server File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\site-packages\daphne\server.py", line 18, in <module> asyncioreactor.install() File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\site-packages\twisted\internet\asyncioreactor.py", line 320, in install PS C:\Users\abdsak11\OneDrive - Lärande\Dokument\GitHub\django-chat\djangoChat> py.exe .\manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\abdsak11\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File …
- 
        Django - Variations of product in shoppingcart empty / NoneHello I am very new to Django and am busy trying to learn how to make a webshop, but I have a problem. The product Canvasdoek should have two variants: 2cm and 4cm (thickness). I can select this option and then add it to the cart. The problem is that when I want to display in the shoppingcart which variant was chosen, it says Shopping.Variation.None but I cannot find the problem why it is not showing This is my code: Models Views Html How it displays on the site I hope someone can help me find the problem, any suggestions hardly appreciated!
- 
        Can Django admin lists / widgets be used outside admin pages?The admin lists are so powerful and have so many built in functionalities, so I'd like to display them outside on the standard http://site.url/admin/ urls. Is there a way to reuse the list widget on my own custom templates? For example, say I have a list of blog entries, that I just wanted non-logged in users to just view . I don't want them to have any access to the admin section, but want to just display the list that the admin site shows with all the sorting, pagination and automatic model related display functionality that comes with django admin out of the box. I know I can create my own templates to do this, but I just want to replicate the exact functionality provided by the admin module so am thinking there must be a way to reuse django's admin lists and include it in my own template since Django. I've googled this quite a bit but haven't had any luck yet finding a answer to this. Thanks in advance.
- 
        GETTING ITEM.Category from querysetI realized search method. And it works great views.py def get_queryset(request): queryset = Item.objects.all() search_query = request.GET.get('search_item','') if search_query: queryset = queryset.filter(title__icontains = search_query) context ={ 'queryset': queryset } print(request.GET) print(context) return render(request, 'search_results.html', context) So i want to filter my items by category like search method, but my queryqict is empty. i think because of it is not in input form like a search. how can i realize it. models.py CATEGORY_CHOICES = ( ('BP', 'BuildingProducts'), ('OT', 'OtherProducts'), ) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length = 2,) label = models.CharField(choices=LABEL_CHOICES, max_length = 1) slug = models.SlugField() description = models.TextField() image = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse('core:''product', kwargs={ 'slug': self.slug }) Here's the method get_cartegory: views.py def get_category(request): queryset = Item.objects.all() search_category = request.GET.get('search_item','') if search_category: queryset = queryset.filter(category__icontains = search_category) context ={ 'queryset': queryset } print(request.GET) print(context) return render(request, 'search_results.html', context) URLS.py urlpatterns = [ path('', HomeView.as_view(), name='home-page'), path('', products, name='products'), path('search/', get_queryset, name='get_queryset'), path('search/', get_category, name='get_category'), ] home-page.html here's the code for search which works <form action="{% url 'core:get_queryset' %}" class="form-inline" method="get"> <div class="md-form my-0"> <input name='search_item' type="text" placeholder="Search" aria-label="Search"> </div> </form> home-page.html here's the …
- 
        Django fails with Invalid column name 'deleted'I have a django app connecting to a mssql (2012) database using pyodbc, django-safedelete and django-mssql-backend. Previously this was working fine, but after a reinstallation of my development notebook i receive following error: ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'deleted'. (207) (SQLExecDirectW)") Connecting and querying the database directly with pyodbc only still works fine. Debug of django deliver following: C:\Users\XXXXXX\Documents\ipm\ipm\lib\site-packages\django\db\backends\utils.py in _execute return self.cursor.execute(sql, params) … ▼ Local vars Variable Value ignored_wrapper_args (False, {'connection': <sql_server.pyodbc.base.DatabaseWrapper object at 0x05713C10>, 'cursor': <django.db.backends.utils.CursorDebugWrapper object at 0x0578BED0>}) params () self <django.db.backends.utils.CursorDebugWrapper object at 0x0578BED0> sql ('SELECT COUNT_BIG(*) AS [__count] FROM [ipmt1] WHERE ' '[ipmt1].[deleted] IS NULL') I was not able to find out where this SQL statement is coming from, as my model does not contain a column called "deleted", so i can understand, why this is happening. But what i do not understand is, why this was working before with the same toolkit. First guess is, this is coming from a functionality of safedelete. Package Version -------------------- ------- Django 2.2.8 django-mssql-backend 2.4.2 django-safedelete 0.5.4 pip 19.3.1 pyodbc 4.0.27 pytz 2019.3 setuptools 42.0.2 sqlparse 0.3.0 wheel 0.33.6
- 
        Can I write to a database using Django models from async websocket client functions?For a continuous high volume data stream some other party has set up a websocket endpoint for me (and only me) to connect to. I've got my current models in Django so I would like to connect from that. I found two Python websocket client libraries: https://github.com/websocket-client/websocket-client https://github.com/aaugustin/websockets The first one (websocket-client) states that all functions are synchronous. Since the endpoint will have a continuous (fairly high volume) flow and I need to write the results to the (postgres) database, I would say I will need an async way of doing this. The second library called websockets has async ways of receiving stuff, but I'm unsure whether I can write to the DB using async functions. The reason I think that might be a problem is because in the Django Channels project this page has a note saying the following: any asynchronous consumer must be careful to avoid directly performing blocking operations, such as accessing a Django model. So my questions are: Can I write to the database using these async models? If so, what are the things I should be carefull for? Does anybody have any more tips on how to handle a large volume data stream over websockets?
- 
        How to count foreign key attribute values in DjangoGiven models set up like this: class Author(models.Model): name = models.CharField(max_length=255) class Genre(models.Model): name = models.CharField(max_length=255) class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author, on_delete=models.CASCADE) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) How can I count the number of genres each author has written for? I would ideally like a dictionary of genres and book counts for each author. [{id: author.id, genres: {genre.id: number_of_books}}] This can easily be achieved with a query to Author for each genre, however this would result in [number of authors]*[number of genres] queries. I would like to find a more efficient method if possible.
- 
        How to render a page with multiple parts progressively using django?I am developing a website using django. The website has a page which takes more than 1 seconds to be rendered. I want to load this page progressively like Google. Google first loads the input then after some moments loads search results. like this: I use StreamingHttpResponse (described here) to load page progressively. My views.py is here: import time from django.http.response import StreamingHttpResponse class TestStreamingLoading(View): def get(self, request): response = StreamingHttpResponse(streaming_content=self.generate_stream_response()) return response def generate_stream_response(self): yield 'data1 ' time.sleep(4) yield 'data2' My problem is the browser does not render anything till total page is downloaded. The browser shows nothing before 4 seconds and after that shows data1 data2. But I want to show data1 at the beginning and show data1 data2 after 4 seconds. How can I do this?
- 
        Django - Send/Receive Data from local machineHow would I go about sending data from a django app to a python app on a local machine? Do I need to create a http server and use that as a url endpoint? What else can I do? Basically, I want to start a program that is hosted locally from a django app. Thank you for any suggestions. Here is how far I got: Django - Bad request syntax or unsupported method
- 
        chaning FCM server in djangoI'm using push notification by fcm_django in my project and now I want to change FCM_SERVER to another URL instead fcm.googleapis.com/fcm/send (That's better to say I want setup reverse proxy for push notification). I tried in setting.py: ... FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": os.environ.get('HAMCLASSY_FCM_SERVER_KEY'), #"FCM_SERVER": "fcm.googleapis.com/fcm/send", "FCM_SERVER": "http://100.100.100.100:9000", # reverse proxy } ... and in the proxy server in 100.100.100.100 the nginx config in /etc/nginx/sites-enabled is: server { listen 9000; server_name 100.100.100.100; access_log /var/log/nginx/reverse-access.log; error_log /var/log/nginx/reverse-error.log; location / { proxy_pass https://fcm.googleapis.com/fcm/send; } } notice in when I go to 100.100.100.100:9000 from browser redirect to https://fcm.googleapis.com/fcm/send successfully.but in Nginx's log I can't see any access/error .it's seem that fcm_django doesn't check FCM_SERVER in settings.FCM_SETTING and still sending the request to the original FCM's server. my question is how I can change FCM server in the Django project to have a reverse proxy? thank you.