Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'gamingispassion/settings.production' PYTHONANYWHERE
I'm trying to host my website on pythonanywhere but after lots of trying I'm gettings this error. This is the path of settings file: '/home/gamingispassion/django_project/src/gamingispassion/settings/production' I have tried 'gamingispassion.settings', 'gamingispassion/settings/production' but not any success. Please help me out with this problem. EDIT: I have tried '.gamingispassion/settings/production' and now i'm gettings this error TypeError: the 'package' argument is required to perform a relative import for '.gamingispassion/settings/production' -
How to update the database by getting the data from chart(created by using random number) using sqlite in django and stored that random no to database
I want to know that how to update the database by getting the data from the random value of temperature and humidity chart and that value will automatically update and store the database with timespan. view.py from django.contrib.auth import get_user_model from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from .models import * import random from rest_framework.views import APIView from rest_framework.response import Response User=get_user_model() class HomeView(View): def get(self,request,*args,**kwargs): return render(request,'charts.html',{}) def get_data(request,*args,**kwargs): data={ } return JsonResponse(data) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): qs_count=User.objects.all().count() labels=["0", "2", "4", "6", "8", "10","12","14","16","18"] default_items=[] for items in range(10): t=random.randint(0,50) default_items=default_items+[t] data={ "labels":labels, "default":default_items, } return Response(data)`` chart.html <meta http-equiv="refresh" content="2"> {% extends 'base.html' %} <script type="text/javascript"> {% block jquery %} var endpoint='/api/chart/data/' //{% url "api-data" %} var defaultData=[] var labels=[] $.ajax({ method:'GET', url:endpoint, success:function(data) { labels=data.labels defaultData=data.default setChart() }, error:function(error_data){ console.log(error) console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("Temp"); var ctx2 = document.getElementById("Hmdt"); var Hmdt = new Chart(ctx2, { type: 'bar', data: { labels: labels , datasets: [{ label: 'Max Humidity', data: defaultData, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, … -
KeyError when trying to publish some pages in django-cms 3.0 under python 2.7
After some moment on some pages, not all, such an error takes off: <div> <div> <div class="adm"> <div id="q_3471" class="ajR h4" data-tooltip="Скрыть развернутую часть" aria-label="Скрыть развернутую часть"> <div class="ajT"></div> </div> </div> <div class="im"> <h1>KeyError at /ru/admin/cms/page/6154/ru/<wbr>publish/</h1> <pre style="font-size:12pt">221273</pre> <br> <h2>Traceback</h2> </div> </div> <div style="font-size:10pt"> <ul> <div> <div class="adm"> <div id="q_3469" class="ajR h4" data-tooltip="Скрыть развернутую часть" aria-label="Скрыть развернутую часть"> <div class="ajT"></div> </div> </div> <div class="im"> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>django/core/handlers/base.py</code> in <b><i><code>get_response</code></i></b><br> <div> <ol start="112"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> response = wrapped_callback(request, *callback_args, **callback_kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>django/utils/decorators.py</code> in <b><i><code>_wrapped_view</code></i></b><br> <div> <ol start="99"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> response = view_func(request, *args, **kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>django/views/decorators/cache.<wbr>py</code> in <b><i><code>_wrapped_view_func</code></i></b><br> <div> <ol start="52"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> response = view_func(request, *args, **kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>django/contrib/admin/sites.py</code> in <b><i><code>inner</code></i></b><br> <div> <ol start="198"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> return view(request, *args, **kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>django/db/transaction.py</code> in <b><i><code>inner</code></i></b><br> <div> <ol start="431"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> return func(*args, **kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/<wbr>reversion/revisions.py</code> in <b><i><code>do_revision_context</code></i></b><br> <div> <ol start="300"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> return func(*args, **kwargs)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/cms/<wbr>admin/pageadmin.py</code> in <b><i><code>publish_page</code></i></b><br> <div> <ol start="1038"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> published = page.publish(language)</pre> </li> </ol> </div> </li> <li> <code>/home/web/{server}/env/local/lib/<wbr>python2.7/site-packages/cms/<wbr>models/pagemodel.py</code> in <b><i><code>publish</code></i></b><br> <div> <ol start="567"> <li> <pre style="margin-top:2px;margin-bottom:4px;background-color:silver"> … -
Multiple Models in Django-filter 1.1.0
I'd like to implement a filter for the end user of the site, so that they can filter by price, rating, gender and location. The problem here is that price and rating are stored in the models class "comment" and the location and gender in the models class "adventure". In the class "comment" the "adventure" is referenced by a foreign key. How can I use Django-filter 1.1.0 in my filters.py to address both models "comment" and "adventure" that reference each other, to filter according to the above mentioned arguments? Here is my code that works, but only filters the class "adventure". How can I extend this code to also filter by the foreign referenced arguments to return the matching adventures? filters.py import django_filters class AdventureFilter(django_filters.FilterSet): class Meta: model = Adventure fields = { 'gender', 'location', } models.py class Comment(models.Model): verfasser = models.ForeignKey(User, on_delete=models.CASCADE) related_adventure = models.ForeignKey(Adventure, on_delete=models.CASCADE, related_name='comments') rating_choices = ( (1, '1 Stern'), (2, '2 Sterne'), (3, '3 Sterne'), (4, '4 Sterne'), (5, '5 Sterne') ) Rating = models.PositiveIntegerField(null=True, choices=rating_choices,blank=False, default=0) verfasst_am = models.DateTimeField(default=timezone.now, blank=True, null=True) heading = models.CharField(max_length=100,blank=True,null=True, help_text="100 Zeichen") ratingtext= models.TextField(max_length=400, blank=True, null=True,help_text="400 Zeichen") price = models.PositiveIntegerField(null=True, help_text="Deine Ausgaben (pro Kopf) bei diesem Adventure", blank=True) class Adventure(models.Model): … -
How to save data to the same model from forms in different pages...Registration multiple fields? Django
i'm trying to make a user registration with multiple fields to save in the same model. The idea is have a form in the home page with username and password and when press button continue the user is redirected to another page with multiple fields to insert personal info for the user profile. I imagine i must have to different views for that, but i don't understand how put all this data together. Thanks! -
Update value of a column using existing column value in Django
how to perform following SQL operation using Django object: update table set column = column+x where column>5 -
How to make a simple ini of this uwsgi launch command
I would like to create a uwsgi_websocket.ini for a process that I launch using this command: uwsgi --http-socket web.socket --gevent 1000 --http-websockets --workers=2 --master --module main.wsgi_websocket So far my uwsgi file looks like this [uwsgi] # ----- Django-related settings ----- # the base directory (full path) chdir=/home/ec2-user/FooVenv/FooWeb/ module=main.wsgi_websocket # the virtualenv (full path) home=/home/ec2-user/FooVenv/ # pidfile=/path/to/site1.pid # master master=true # maximum number of worker processes processes=1 # the socket (use the full path to be safe) socket=/home/ec2-user/FooVenv/FooWeb/web.socket chmod-socket=664 # clear environment on exit vacuum=true My question is how do I specify the followings in my ini file --http-socket web.socket --gevent 1000 --http-websockets Also what is the purpose of specifying a pid file and what should that be ? -
Adding numbers from SQlite in django showing in WebApp
I'm trying to make a personal WebApp with Django/Python, all works out so far, just that i want to display: total ammount, balance ect...... in my WebApp and i can't figure it out how to do is. Can someone help me out here? Thanks! Models.py class Bills(models.Model): bank = models.CharField(max_length=40) name = models.CharField(max_length=40) ammount = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.bank Views.py def index(request): return render(request, 'budget/index.html') def bills(request): bills_list = Bills.objects.order_by('id') context = {'bills_list': bills_list} return render(request, 'budget/bills.html', context) -
Need to show User count other data count on Django admin interface
I've created custom index.html for django admin. Here is the ScreeenShot Here count of user or model 1 is static. I want to update from database. Is there any way to pass variable from admin.py to main Admin interface? -
How do i edit/delete data from the frontend in Django?
I would like to retrieve data from my backend (postgresql) to the frontend so i can edit/delete it. I have implemented this in views.py: def update(request, id): resp = Response.objects.get(pk = id) resp.response = request.POST.get('Response') resp.save() return render(request, 'app/update', { }) urls.py: url(r'update/(\d+)/$', views.update, name="update") How would i display it in my forms? update.html: <table class="dataTable"> {% for field in qform.visible_fields %} <tr> <th>{{ field.label_tag }}*</th> <td>{{ field }}</td> </tr> {% endfor %} <tr> <th>{{ rform.Response.label_tag }}*</th> <td>{{ rform.Response }}</td> </tr> <tr> <th>{{ rform.Topic.label_tag }}*</th> <td>{{ rform.Topic }}</td> </tr> <tr> <th>{{ rform.Client.label_tag }}*</th> <td>{{ rform.Client }}</td> </tr> <tr> <th>{{ rform.Planit_location.label_tag }}*</th> <td>{{ rform.Planit_location }}</td> </tr> <tr> <th>{{ rform.Date_added.label_tag }}</th> <td>{{ rform.Date_added }}</td> </tr> <tr> <th>{{ rform.Document.label_tag }}</th> <td>{{ rform.Document }}</td> </tr> Also I am getting an Assertion error "No exception message supplied" when i try to access the url .../update -
Django Admin multiple template inheritance
I thought it was a quite simple task but turns out it's not. So, I have two different mixins to use on a Django admin class. they both have some codes in it with templates. admin.py class AdminMixin01(admin.ModelAdmin): change_form_template = "change_form1.html" class AdminMixin02(admin.ModelAdmin): change_form_template = "change_form2.html" class ModalAdmin(AdminMixin01, AdminMixin02, admin.ModelAdmin): pass change_form1.html {% extends "change_form.html" %} {% block content %} {{ block.super }} Form 1 {% endblock content %} change_form2.html {% extends "change_form.html" %} {% block content %} {{ block.super }} Form 2 {% endblock content %} it's looks quite simple both python and html sides. The problem is Django renders only first mixin's template and ignores the second mixin's template. In this case only change_form1.html rendered into original change_form.html template and no traces from change_form2.html. The python codes in the both mixin are working except html codes. Any ideas ? -
Django 1.3: Is it possible to create a Listview from 2 or more objects?
I'm a newbie in Python and I'm struggling with syntax(and old usage of it). I need to make some changes to an existing Python app which is in Django 1.3. I have an existing Listview and I want to add a new column(contactDate) from another object. Is it possible at all? Thank you in a dvance! -
Library not loaded: @rpath/libmysqlclient.21.dylib Reason: image not found Django migrate error using mysqlclient DB driver and MySQL 8 with macOS
While changing to a MySQL database from the default SQLite one that Django uses by default, I ran into this tricky error while trying to run python manage.py migrate --database mysql: Traceback (most recent call last): File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> import _mysql ImportError: dlopen(/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line( sys.argv ) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 217, in all return [self[alias] for alias in self] File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 217, in <listcomp> return [self[alias] for alias in self] File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 202, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) … -
Static Files not getting loaded in Django Python
Here is the code I am trying to run: {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis path { display: none; } </style> <script src="http://d3js.org/d3.v3.js"></script> <script src="http://misoproject.com/js/d3.chart.js"></script> </head> <body> <script src="{% static 'stock-line.js' %}"></script> <script src="{% static 'stock-line-app.js' %}"></script> </body> </html> Reference Link for Js and sample data: Reference link My static path is: C:\Users\aims\Desktop\mysite\static I am getting the following error in the console log: GET http://127.0.0.1:8000/static/stock-line.js 404 (Not Found) GET http://127.0.0.1:8000/static/stock-line-app.js 404 (Not Found) Cross-Origin Read Blocking (CORB) blocked cross-origin response http://misoproject.com/js/d3.chart.js with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details. GET http://127.0.0.1:8000/static/stock-line.js 404 (Not Found) GET http://127.0.0.1:8000/static/stock-line-app.js 404 (Not Found) Pease do let me know what I have missed. I have placed the respective files in the static folder. Still file is not found. It is a mystery for me. Help me solve it. -
Django Serializers - Return the sum of values by filter
Following this post: Serializer - Django REST Framework - The serializer field might be named incorrectly and not match any attribute or key on the `str` instance I use this function: def get_month_hours(self): last_year = timezone.now() - datetime.timedelta(days=365) # for more accurate result, please use python-dateutil or similar tools return Timesheet.objects.annotate(total_hour=Sum('working_hour')).filter(owner=self.user, date__gte=last_year).order_by('date') I want to populate the chart who use exactly the same code: "data": [65, 59, 80, 81, 56, 55, 40], All values corresponding to the total working_hours (my models field) per month. So, I have 2 problems: The first, I receive this data: { "id": 3, "title": "Développement intranet", "date": "2018-11-19", "working_hour": 8.5, "week": 47, "owner": 1 }, { "id": 1, "title": "Développement intranet", "date": "2018-11-26", "working_hour": 8.5, "week": 48, "owner": 1 }, { "id": 2, "title": "Développement intranet", "date": "2018-11-27", "working_hour": 8.5, "week": 48, "owner": 1 }, { "id": 4, "title": "dev python", "date": "2018-11-28", "working_hour": 5.25, "week": 48, "owner": 1 }, { "id": 5, "title": "Développement intranet", "date": "2018-12-03", "working_hour": 8.5, "week": 49, "owner": 1 } But I want to receive only one value: the sum of working_hour per month. The second problme is: how to pass this values to my "data" ? I thinked like … -
DOCSTRING IN THE FUCNTION BASED VIEW
how to add docstring to function based view so that it can be visible in the swagger UI? I have created a manual schema for each my API and its working through swagger but I need to add docstring as well example responses in the Swagger UI. -
What is python datastream and why this us used for
I am not getting Python DataStream, What is python data stream and why this is used for? Can anyone tell me about it or give me link of a good article on this? TIA -
Import error after attempt at importing Class
I attempting to to run a python script inside another python script, upon entering a webpage using Django framework. This is my views script that is running the python script tech_scripts.py import subprocess from django.shortcuts import render from .models import ConfigInfo from .forms import ConfigInfoForm from .models import dhcp from .forms import dhcpForm def post_list_three(request): from .models import ConfigInfo ConfigInfo.objects.all().delete() if request.method =="POST": form =ConfigInfoForm(request.POST) if form.is_valid(): ConfigInfo=form.save(commit=False) ConfigInfo.save() subprocess.Popen(["python3", "/home/pi/tutorial/device_interfaces/device_interfaces/tech_scripts.py","-m"]) else: form=ConfigInfoForm() return render(request, 'device_interfaces/post_edit.html', {'form':form}) So, upon opening a webpage i want the function post_list_three to be executed. The subprocess manages to run the tech_scripts file which is below #!/usr/bin/env python3 import json import re import os.path import pathlib import uuid import subprocess from models.py import ConfigInfo def info(): creds=ConfigInfo.objects.first() SSID_name=creds.SSID psk_name=creds.psk sIP=creds.sIP netmask=creds.netmask gateway=creds.gateway netwrokIP=creds.networkIP broadcast=creds.broadcast dns_servers=creds.dns_servers config['ssid']=getattr(creds,SSID_name) config['password']=getattr(creds,psk_name) config['StatIP']=getattr(creds,sIP) config['Netmask']=getattr(creds,netmask) config['gateway']=getattr(creds,gateway) config['Network']=getattr(creds,networkIP) config['Broadcast']=getattr(creds,broadcast) config['DNS']=getattr(creds,dns_servers) jstring = json.dumps(config) with open("/home/techuser/config.json", "w+") as handle: handle.write(jstring) However, when going to my website after launching it using python3 manage.py rserver 192.168.1.150:8000 I get a traceback , [03/Dec/2018 09:51:24] "POST /post/new/static HTTP/1.1" 200 1884 Traceback (most recent call last): File "/home/pi/tutorial/device_interfaces/device_interfaces/tech_scripts.py", line 9, in <module> from models.py import ConfigInfo File "/home/pi/tutorial/device_interfaces/device_interfaces/models.py", line 7, in <module> class ConfigInfo(models.Model): File "/home/pi/tutorial/device_interfaces/myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 87, … -
Django not fetch the static file csv
I am trying to run the following example of D3 with the Django framework: {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /> <meta http-equiv="pragma" content="no-cache" /> <style> body { font: 10px sans-serif; background-color: #151512;; color: #FFF; } text { fill: white; } h1 { text-transform: uppercase; padding-left: 180px; } .axis path, .axis line { fill: none; stroke: #FFF; shape-rendering: crispEdges; } .line { stroke: #FFF; fill: none; stroke-width: 0.75px; } .line.close{ stroke: steelblue; } .summary.Close { color: steelblue; } .legend.Close { fill: steelblue; } .line.volume { stroke: indianred; } .summary.Volume { color: indianred; } .legend.Volume { fill: indianred; } .line.high { stroke: #aa81c5; } .summary.High { color: #aa81c5; } .legend.High { fill: #aa81c5; } .line.low { stroke: #7fc9bd; } .summary.Low { color: #7fc9bd; } .legend.Low { fill: #7fc9bd; } .invisible { fill: grey; } .overlay { pointer-events: all; } .focus line { stroke: white; stroke-dasharray: 3 3; opacity: .5; } .brush .extent { stroke: orange; fill: orange; fill-opacity: .125; shape-rendering: crispEdges; } #popup { left: 100px; top: 100px; width: 128px; background-color: rgba(255,255,255,0.2); font-size: 16px; position: absolute; padding: … -
How to get data from Django Many-Many relationship?
How to get all product for every order on Templates. Please help me Model.py class Order(models.Model): customer_id= models.ForeignKey(Customers ) delivery_add_id= models.ForeignKey(DeliveryAddresses) class OrderItem(models.Model): order_id = models.ForeignKey(Order, related_name='orderId') product_id = models.ForeignKey('Products', related_name='productId') class Products(models.Model): cat_id = models.ForeignKey('Categories') name = models.CharField(max_length=200) price = models.FloatField() Templates <tr> <th>Product ordered</th> <td> <ul> {% for prod in order.orderId.productId.product_set.all%} <li>{{pro}}</li> {% endfor %} </ul> {{order.orderId.productId.product_set.all}} </td> </tr> https://i.stack.imgur.com/XJ3zG.png Views.py class productList(ListView): model= Products context_object_name = 'product_list' def get_queryset(self): return Products.objects.all() class productDetail(DetailView): context_object_name = 'product' model = Products queryset = Products.objects.all() class orderList(ListView): model = Order context_object_name= 'order_list' def get_queryset(self): return Order.objects.all() class orderDetail(DetailView): context_object_name ='order' model = Order queryset= Order.objects.all() This is the general relationship I have set up.I'm trying to do is, in a templates, i want to show all product for every order. Order-product : many to many relationship. Please help me -
How can i show sub-category in category into data collapse, Using Djagno
I want to show subcategory in category into data collapse using django. As I am a noob developer that's why i can't understand the logic. Category and Sub-Category model is, category.py class Category(models.Model): category = models.CharField(max_length=120) timestamp = models.DateTimeField(auto_now_add=True) subcategory.py class SubCategory(models.Model): sub_category = models.CharField(max_length=120) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) I wanna show those value using generic.ListView views.py class PagetListView(ListView): model = ModelName template_name = 'template.html' context_object_name = 'main_content' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['category_list'] = Category.objects.all() # context['sub_category'] = return context I wanna show just like this, -
Google App Engine python37 build error error: `pip_download_wheels` returned code: 1
I am using Django REST based framework to deploy on Google App engine and my python pip req.txt file is as following asn1crypto==0.24.0 astroid==2.1.0 boto3==1.9.55 botocore==1.12.55 certifi==2018.8.13 cffi==1.11.5 chardet==3.0.4 colorama==0.4.1 coreapi==2.3.3 coreschema==0.0.4 cryptography==2.4.2 defusedxml==0.5.0 Django==2.1 django-allauth==0.36.0 django-filter==2.0.0 django-rest-auth==0.9.3 django-rest-swagger==2.0.7 djangorestframework==3.8.2 djangorestframework-jwt==1.11.0 docutils==0.14 idna==2.7 isort==4.3.4 itypes==1.1.0 Jinja2==2.10 jmespath==0.9.3 lazy-object-proxy==1.3.1 lxml==4.2.5 MarkupSafe==1.0 mccabe==0.6.1 oauthlib==2.1.0 openapi-codec==1.3.2 Pillow==5.3.0 pycparser==2.19 PyJWT==1.6.4 pylint==2.2.2 PyMySQL==0.9.2 python-dateutil==2.7.5 python-social-auth==0.3.6 python3-openid==3.1.0 pytz==2018.5 requests==2.19.1 requests-oauthlib==1.0.0 s3transfer==0.1.13 simplejson==3.16.0 six==1.11.0 social-auth-app-django==3.1.0 social-auth-core==2.0.0 typed-ast==1.1.0 uritemplate==3.0.0 urllib3==1.23 virtualenv==16.0.0 wrapt==1.10.11 Here is my app.yaml file and my project runs fine on local pip venv but when i # [START django_app] runtime: python37 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto # [END django_app] try to deploy it on google app engine using the following command i am getting following error on build time using following article https://cloud.google.com/python/django/appengine gcloud app deploy Error from Build log:- ERROR: build step … -
How to shuffle model also ArrayField values within each row in Django?
I have an MCQ model with an ArrayField. I want to shuffle or randomly sort the model data rows and the ArrayField values on each row while loading the page. ArrayField contains data in following formats- {{"London", "NYC", "Sydney", "CA"}} At present, I can only randomly sort the data rows without the ArrayField values. sorted(MCQ.objects.filter(), key=lambda x: random.random()) -
How to tag a comment with the blog post in django?
i am new to django and am currently working on the diy blog project to improve my understanding. I am trying to insert a comment form for my viewers using the CreateView template. Viewers will need to log in to type their comment. Their username will be tagged to the comment for the respective blog without them needing to indicate anything. However, i am only able to tag their comment with their username but not to the blog post. I am not sure why. Below is my code that is stored in the (view.py) class CommentCreate(LoginRequiredMixin,CreateView): model = Comment fields = ['comment','blog'] template_name = 'catalog/blog_comment.html' def get_context_data(self, **kwargs): context = super(CommentCreate, self).get_context_data(**kwargs) context['blog'] = get_object_or_404(Blog, pk = self.kwargs['pk']) return context def form_valid(self, form): form.instance.author = self.request.user return super(CommentCreate, self).form_valid(form) def get_success_url(self): return reverse('blog-detail', kwargs={'pk': self.kwargs['pk'],}) Any advice is appreciated. Thank you. -
Firebase FCM push notifications not show on iOS 12
I am using python 3 and Django framework with Firebase FCM to send push notifications from an iOS device. The push notifications did not show on device, until yesterday. When I now send a push notification, everything shows successful, but nothing is received on the device. If I send directly via a curl request, this is the response: {'failure': 0, 'canonical_ids': 0, 'success': 1, 'multicast_ids': [8348728835412078810], 'topic_message_id': None, 'results': [{'message_id': '0:1543820637538874%6467bacd6467abcd'}]} If I send from the Notification dashboard on the firebase console, it shows successfully completed. I have done the following with no success: Locked in pod for, 'Firebase/Core' and 'Firebase/Messaging'. Generated a new APN key on developer console and replaced the existing key on FCM setup in Firebase. Downloaded a fresh GoogleService-Info.plist and replaced existing Checked that bundle id's etc all match. Updated firebase pods to latest versions Turned message swizzling off in info.plist file (i.e. FirebaseAppDelegateProxyEnabled = No) Setting Messaging.messaging().shouldEstablishDirectChannel = true Made sure remote notification in Capabilities are still turned on