Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
bootstrapshuffle frontend add to django 3.0 project
I am building my CSS/JS/html basic site on https://bootstrapshuffle.com/ that I have exported and try to add to my Django 3.0 project. Requirements Django 3.0 python 3.7 macOS 10.12 Terminal Error Messages (after you start solving them it will show more error messages until you put everything to the right place) Not Found: /js/jquery/jquery.min.js [03/Mar/2020 14:31:28] "GET /js/jquery/jquery.min.js HTTP/1.1" 404 2568 Not Found: /placeholder/icons/check.svg [03/Mar/2020 14:31:28] "GET /placeholder/icons/check.svg HTTP/1.1" 404 2580 Not Found: /js/popper/popper.min.js Not Found: /js/bootstrap/bootstrap.min.js [03/Mar/2020 14:31:28] "GET /js/bootstrap/bootstrap.min.js HTTP/1.1" 404 2586 Not Found: /css/bootstrap/bootstrap.min.css [03/Mar/2020 14:31:28] "GET /css/bootstrap/bootstrap.min.css HTTP/1.1" 404 2592 [03/Mar/2020 14:31:28] "GET /js/popper/popper.min.js HTTP/1.1" 404 2568 Not Found: /js/popper/popper.min.js [03/Mar/2020 14:31:28] "GET /js/popper/popper.min.js HTTP/1.1" 404 2568 Not Found: /js/bootstrap/bootstrap.min.js [03/Mar/2020 14:31:28] "GET /js/bootstrap/bootstrap.min.js HTTP/1.1" 404 2586 -
Superuser account to dashboard in django
Is it possible that: I will login to admin/ using a superuser account but I will be redirected to my app. or I will login to my custom login form using my superuser account because I'm creating a system that only have one user. And only an admin. Thanks! -
How to give a dropdown a specific value after filling it with database values in Django?
I have in my Views.py a query which I'm using to populate a dropdown. It works well, except that I need it to show a specific value, stored in a variable that corresponds to the user's selection. Let's say we have a dropdown which is filled from a database ('world') using the following query: continents = world.objects.values_list("continents").distinct() So this fills my dropdown with continent names. If the user as previously selected 'Europe' (stored in sel_continent variable), how do I amend this query so it selects 'Europe' after having filled the dropdown? -
Django - Get raw request path
How do I get the raw request path (everything after the host name) in Django? I tried request.get_full_path(), but it doesn’t work for some URLs. For example, when the URL is http://localhost:8000/data/?, the result is /data/ instead of /data/?. I know that the server receives the full string because it show "GET /data/? HTTP/1.1" 200 642 in the terminal. -
Cache switching for django restframework
I set the cache with this in urls.py router = routers.DefaultRouter() router.register('mytexts',MyTextViewSet,basename='mytexts') in view.py class MyTextViewSet(viewsets.ModelViewSet): @method_decorator(cache_page(60*60*2)) @method_decorator(vary_on_cookie) def list(self,request,*args,**kwargs): It works for caching for api myapp.com/my_text/api/mytexts However I want to off the cache sometimes with query myapp.com/my_text/api/mytexts?cacheoff=1 Is it the good practice? if so where should I set?? -
403 Forbidden and can't understand why Angular Django
I'm pretty new to Django & Angular, i'm building a project with authentication. The authentication seems to work well, but when i'm connected, i only got a 403 error on every request i do. Everything in the frontend seems to work but i can't access my views or viewsets. My frontend code is as follows (players-list.component.ts): ngOnInit() { this.playerService.list().subscribe(response => { this.playerList = response.body; }); } Here is my players.service.ts : export class PlayersService { constructor(private http: RestService) {} public list(): Observable<any> { return this.http.list("players"); } } Now my list method in rest.service.ts : public list<T>(endpoint: string, getParams: any = {}): Observable<any> { const inline: string = this.getInlineGetParams(getParams); return this.http.get<T>(`${RestService.API_ROOT}/${endpoint}/${inline}`, { headers: { ...RestService.DEFAULT_HEADERS }, observe: "response" }); } Every console.log i do in this frontside code works. My django views are as follows : class PlayersViewSet(HasRoleMixin, ModelViewSet): queryset = Player.objects.all() serializer_class = PlayerSerializer def list(self, request, *args, **kwargs): print ('sdmlkfnqmfndn') #This doesn't print return super.list(request, *args, **kwargs) def get_queryset(self): return self.queryset.all().order_by("number") My print in my viewset doesn't print. So I guess the 403 error is raised before entering the viewset. Here is my urls.py : router = routers.DefaultRouter() router.register(r"players", PlayersViewSet) urlpatterns = [ url(r'^auth', AuthAPIView.as_view()), url(r'^admin/', admin.site.urls), ] urlpatterns … -
Always double plus link when go to next route Django
I make a dashboard from Django. When I click to change route it always adds more link. Example the link of the dashboard is 127.0.0.1:8000/dashboard, when I click change to another route example profile, the link become 127.0.0.1:8000/dashboard/pages/user-profile.html then when I go to next route it always plus pages/ look at my link in picture here are my code dashboard/urls.py from django.conf.urls import url, re_path from django.urls import path from . import views urlpatterns = [ url(r"^$", views.index, name="index"), re_path(r'^.*\.html', views.pages, name='pages'), ] dashboard/views.py from django.template.response import TemplateResponse from django.contrib.admin.views.decorators import ( staff_member_required as _staff_member_required ) from django.shortcuts import redirect from django.template import loader from django.http import HttpResponse def staff_member_required(f): return _staff_member_required(f, login_url="accounts:login") @staff_member_required def index(request): if request.user.is_superuser: context = {"active":"dashboard"} return TemplateResponse(request, "dashboard/index.html",context=context) else: return redirect("home") @staff_member_required def pages(request): context = {} try: load_template = request.path.split('/')[-1] print(request.path.split('/')) template = loader.get_template('dashboard/pages/' + load_template) print(template) return HttpResponse(template.render(context, request)) except: template = loader.get_template( 'dashboard/pages/error-404.html' ) return HttpResponse(template.render(context, request)) here are my template files templates/dashboard/includes/sidebar.html <aside class="main-sidebar col-12 col-md-3 col-lg-2 px-0"> <div class="main-navbar"> <nav class="navbar align-items-stretch navbar-light bg-white flex-md-nowrap border-bottom p-0"> <a class="navbar-brand w-100 mr-0" href="https://appseed.us/admin-dashboards/django-dashboard-shards" style="line-height: 25px;"> <div class="d-table m-auto"> <img id="main-logo" class="d-inline-block align-top mr-1" style="max-width: 25px;" src="/static/assets/img/shards-dashboards-logo.svg" alt="Shards Dashboard"> <span class="d-none … -
Django App to django-rest-framework ONLY BACKEND
I just created an app in Django that works nicely, but, since I am just a backend programmer, they asked me to migrate to django-rest-framework and leave someone expert the frontend work in VUE. Then I have to translate all of my code so that it could work using django-rest-framework and VUE. I learned Django by myself and I just watched a tutorial for django-rest-framework. I understand what I have to do is to create serializers instead of forms and use viewset, is that correct? How would you approach just the backend work monitoring that anything works fine? What is the fastest way to migrate everything? I'm sorry I seem stupid in yhis but at the moment I can't understand what is the best way to approach this problem... -
how can i save hmtl checkbox value to django database
i'm working on a subscription project that allows user select multiple services using checkbox and then calculate the total price for these services(something like selecting multiple mail from your mail account), I have these in the html and Js code but I wan to be able to store each selected services to the db, please how can i archieve this <form action="{% url 'sub:basic_starter' %}" id="subscription" method="post"> {% csrf_token %} <fieldset> <legend><h5><strong>Business Type: </strong> New Business </h5> </legend> <label>Brand Value Design: N6,180.00 <input type="checkbox" value=" 6179.50" name="services" id="bs1" onclick="subscribe())"> </label><br><br> <label>Business Development: N6,180.00 <input type="checkbox" value="6180.00" name="services" id="bs2" onclick="subscribe())"> </label><br><br> <label>Website Design & Dev: N6,180.00 <input type="checkbox" value=" 6180.00" name="services" id="bs3" onclick="subscribe())"> </label><br><br> <label>Mobile Application : N6,180.00 <input type="checkbox" value="6180.00" name="services" id="bs4" onclick="subscribe())"> </label><br><br> <label>Maintenance(Host & Domain): N5,450.00 <input type="checkbox" value="5450.00" name="services" id="bs5" onclick="subscribe())"> </label><br><br> <label>Social Media Management: <input type="checkbox" value="" name="services" id="bs6" onclick="subscribe())"> </label><br><br> <input type="text" readonly="readonly" id="total" value="N0.00" ><script>document.getElementById('total').innerHTML=price;</script><br><br> <input type="submit" value="Subscribe" class="btn btn-success"></a></button><br> </fieldset> </form> </div> JS function subscribe(){ let input = document.getElementsByName('services'), total = 0.00, form = document.getElementById('subscription'); for (let i = 0; i < input.length; i++) { if(input[i].checked){ total += parseFloat(input[i].value) let price = 'N' + total } } document.getElementById('total').value = total.toFixed(3) } document.getElementById('subscription').addEventListener('change', subscribe) -
Groups and channel layers make the process stop without raising exceptions
Starting with this very simple working code sample: from channels.generic.websocket import JsonWebsocketConsumer class IsacomptaManagementFeesConsumer(JsonWebsocketConsumer): pass When connecting to this websocket consumer from javascript, this works as expected. The connection is issued properly and I get the following logs: WebSocket HANDSHAKING /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38108] WebSocket CONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38108] WebSocket DISCONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38108] Now, if I change my code to the following code, to use groups: from channels.generic.websocket import JsonWebsocketConsumer class IsacomptaManagementFeesConsumer(JsonWebsocketConsumer): groups = ['foobar'] Then, the connection fails. JavaScript console tells me: Firefox can’t establish a connection to the server at ws://antoine.cocoonr.hq:3001/manager/accounting/isacompta/2020/03/management-fees.ws. error { target: WebSocket, isTrusted: true, srcElement: WebSocket, currentTarget: WebSocket, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, composed: false, timeStamp: 7804, … } And the server logs look like this: WebSocket HANDSHAKING /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38128] WebSocket DISCONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38128] No exception is raised on the server side though. I can also get a similar behavior without using groups. Let's take a bit bigger working code sample: from channels.generic.websocket import JsonWebsocketConsumer class IsacomptaManagementFeesConsumer(JsonWebsocketConsumer): def connect(self): print("one") self.accept() print("two") self.send_json({'text': "Foobar"}) print("three") This code works fine, the connection is issued properly and here are the server logs: WebSocket HANDSHAKING /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38168] one WebSocket CONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38168] two three WebSocket DISCONNECT /manager/accounting/isacompta/2020/03/management-fees.ws [192.168.96.1:38168] … -
Django does not send emails via smtp
hope someone can help me with this. i have 3 days in a row trying to fix this issue but i could not get anywhere and its making me crazy. this is the issue: im trying to send a email via smtp using django. when i try to send the email, i do not get any error, but my application does not respond and it keeps waiting on to send the email, but obviously it does not send nothing. i have tried with smtp gmail and smtp hotmail, but it is not working. i have already checked my windows firewall, and again it is not working. i have tried to send the email using python shell but it does not send nothing. i think that i have tried almost everything that i saw on the other posts here in stackoverflow, hope someone can help me. settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@hotmail.com' EMAIL_HOST_PASSWORD = 'mypassword' SERVER_EMAIL = EMAIL_HOST_USER -
Trying to link two models together in Django: challenges
Trying to work through linking two models or combining the two in a way that doesn't create an error. I have one model, which is just a FileField and accepts an uploaded file class FitFiles(models.Model): fitfiles=models.FileField(upload_to='PMC/fitfiles' null=False) I have another model that is populated under the same upload function and basically runs some calculations based on the file uploaded class RideSum(models.Model): fitfiles = models.OneToOneField(FitFiles, on_delete=models.CASCADE) ftp = models.IntegerField() norm_power = models.IntegerField() intensity = models.FloatField() tss = models.FloatField() date = models.DateField() Issue with the approach above is that I keep getting an error that fitfiles_id is not found. I've tried just putting everything under one model, but the issue there is that filefield 'fitfiles' returns a null value and I get a not-null constraint error. Was curious for advice on how to handle. At the moment I can do things just fine with these two models completely separated (i.e. not trying to link the two), but with the DetailView I need to make sure these always have the same pk and if for whatever reason the primary keys become misaligned between these models then the DetailView becomes a mess of different information. Happy to post and clarify -
How to strip the Prometheus response content in Django?
I'm trying to implement Prometheus client on Django App. But, the output I get is invalid which is why Prometheus server is unable to parse the metrics. Here is my Prometheus API View from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from prometheus_client import ( multiprocess, CollectorRegistry, generate_latest, CONTENT_TYPE_LATEST, ) class PrometheusAPIView(APIView): def get(self, request, format=None): registry = CollectorRegistry() multiprocess.MultiProcessCollector(registry) return ( Response( generate_latest(registry), status=status.HTTP_200_OK, content_type=CONTENT_TYPE_LATEST, ) ) and here is the URL Pattern urlpatterns = [ url(r'^metrics/', PrometheusAPIView.as_view()), ] When I curl the metrics/ endpoint, I get this ❯ curl localhost:8000/metrics/ "# HELP model_latency Multiprocess metric\n# TYPE model_latency histogram\nmodel_latency_bucket{app=\"app-name\",le=\"10.0\"} 4.0\nmodel_latency_bucket{app=\"app-name\",le=\"0.1\"} 0.0\nmodel_latency_bucket{app=\"app-name\",le=\"0.005\"} 0.0\nmodel_latency_sum{app=\"app-name\"} 7.6447835210005906\nmodel_latency_bucket{app=\"app-name\",le=\"0.25\"} 0.0\nmodel_latency_bucket{app=\"app-name\",le=\"0.75\"} 0.0\nmodel_latency_bucket{app=\"app-name\",le=\"7.5\"} 4.0\nmodel_latency_bucket{app=\"app-name\",le=\"5.0\"} 4.0\nmodel_latency_bucket{app=\"app-name\",le=\"0.5\"} 0.0\nmodel_latency_bucket{app=\"app-name\",le=\"2.5\"} 3.0\nmodel_latency_bucket{app=\"app-name\",le=\"0.075\"} 0.0\nmodel_latency_bucket{app=\"app-name\",le=\"0.01\"} 0.0\nmodel_latency_bucket{app=\"app-name\",le=\"0.05\"} 0.0\nmodel_latency_bucket{app=\"app-name\",le=\"+Inf\"} 4.0\nmodel_latency_bucket{app=\"app-name\",le=\"1.0\"} 0.0\nmodel_latency_bucket{app=\"app-name\",le=\"0.025\"} 0.0\nmodel_latency_count{app=\"app-name\"} 4.0\n# HELP log_count_total Multiprocess metric\n# TYPE log_count_total counter\nlog_count_total{app=\"app-name\",level=\"INFO\"} 8.0\n" But, what I expect is like below # HELP model_latency Multiprocess metric # TYPE model_latency histogram model_latency_bucket{app="app-name",le="10.0"} 2.0 model_latency_bucket{app="app-name",le="0.1"} 0.0 model_latency_bucket{app="app-name",le="0.005"} 0.0 model_latency_sum{app="app-name"} 4.431863597000756 model_latency_bucket{app="app-name",le="0.25"} 0.0 model_latency_bucket{app="app-name",le="0.75"} 0.0 model_latency_bucket{app="app-name",le="7.5"} 2.0 model_latency_bucket{app="app-name",le="5.0"} 2.0 model_latency_bucket{app="app-name",le="0.5"} 0.0 model_latency_bucket{app="app-name",le="2.5"} 1.0 model_latency_bucket{app="app-name",le="0.075"} 0.0 model_latency_bucket{app="app-name",le="0.01"} 0.0 model_latency_bucket{app="app-name",le="0.05"} 0.0 model_latency_bucket{app="app-name",le="+Inf"} 2.0 model_latency_bucket{app="app-name",le="1.0"} 0.0 model_latency_bucket{app="app-name",le="0.025"} 0.0 model_latency_count{app="app-name"} 2.0 # HELP log_count_total Multiprocess metric # TYPE log_count_total counter log_count_total{app="app-name",level="INFO"} 4.0 So, it's basically that I need to strip the output … -
Cant connect remote mongodb server with django/djongo
I try to connect to a remote database using Djongo, however I get an error - as I understand it, the connection is trying to connect to the local host. I use the following versions: Django==2.2.8 djongo==1.3.1 python3.6.3 My settings.py file contains: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'remote_db', 'HOST': 'mongodb://user:password@<remote_ip>:27017/remote_db', 'USER': 'user', 'PASSWORD': 'password', } } There is my 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 "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 48, in table_names return get_names(cursor) File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/djongo/introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "/home/dave/asr_project/asr_project/lib/python3.6/site-packages/pymongo/database.py", line 856, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File … -
How to fix Failed lookup for key when resolving the accessor in django project
I changed to python 3.5.2. I am using django_tables2 and I face the problem of Failed lookup for key [wholesale_product] in {'wholesale_product__code': '11500356', 'quantity': Decimal('1.00'), 'wholesale_product__description': 'ΜΕΤΡΟΤΑΙΝΙΑ IRWIN 5M SHORT', 'wholesale_product__id': 76970}, when resolving the accessor wholesale_product__id The problem has to do with wholesale product field which is a FK to my Warehouse_Order_Backorder model. my model class Warehouse_Order_Backorder(models.Model): woo_order = models.ForeignKey(Woo_Orders,verbose_name="Παραγγελία Χοντρικής",null=True,on_delete=models.CASCADE) wholesale_product=models.ForeignKey(Product,null=True,on_delete=models.CASCADE) warehouse=models.ForeignKey(Warehouse,verbose_name=u'Αποθήκη',blank=True, null=True,on_delete=models.CASCADE) quantity = models.DecimalField("Ποσότητα", max_digits=7, decimal_places=2, default=0) date = models.DateTimeField("Ημ/νία",null=True, blank=True, default=datetime.datetime.now) def __str__(self): return self.woo_order.oid+" "+self.wholesale_product.description my table class BackOrderTable(tables.Table): #description wholesale_product_name = tables.Column(accessor='wholesale_product__description',verbose_name= 'Προϊόν που έχει backorder') #sku wholesale_product_code = tables.Column(accessor='wholesale_product__code',verbose_name= 'Sku Προϊόντος') #product_id wholesale_product_id = tables.Column(accessor='wholesale_product__id',verbose_name= 'ID Προϊόντος') #details button details=tables.LinkColumn('backorder_details_list',args=[A('wholesale_product__id')],accessor='Backorder Details',orderable=False,empty_values=(),verbose_name = 'Λεπτομέρειες backorder') class Meta: #define the model model = Warehouse_Order_Backorder template_name = 'django_tables2/bootstrap4.html' exclude = ('id','date',"warehouse","woo_order",'wholesale_product') sequence = ('wholesale_product_name','wholesale_product_code', 'wholesale_product_id',"quantity",'details') def render_wholesale_product_id(self,record): return '%s' % (record.wholesale_product.id) def render_wholesale_product_name(self,record): return '%s' % (record.wholesale_product.description) def render_wholesale_product_code(self,record): return '%s' % (record.wholesale_product.code) def render_details(self,record): return format_html('<a href="/backorder_details/{}/"><button class="btn btn-primary btn-sm" type="">Details</button></a>',record['wholesale_product__id']) here is my Traceback Environment: Request Method: GET Request URL: http://backorders/ Django Version: 2.2.6 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'intranet', 'crispy_forms', 'fm', 'dal', 'dal_select2', 'django_crontab', 'django_tables2', 'django_filters', 'widget_tweaks', 'django_smtp_ssl', 'mathfilters', 'bootstrap4', 'bootstrap3', 'django.contrib.humanize'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
How do I properly configure the ini file uwsgi for a Django application?
Ubuntu 18.04 . Deploying site using Nginx and uwsgi. I see in my browser message Internal server error. Uwsgi now gives this status ● uwsgi.service - uWSGI Emperor service Loaded: loaded (/etc/systemd/system/uwsgi.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2020-03-03 12:24:17 UTC; 30s ago Process: 1475 ExecStartPre=/bin/bash -c mkdir -p /run/uwsgi; chown ubuntu:www-data /run/uwsgi (code=exited, status=0/SUCCESS) Main PID: 1489 (uwsgi) Status: "The Emperor is governing 1 vassals" Tasks: 7 (limit: 1151) CGroup: /system.slice/uwsgi.service ├─1489 /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites ├─1490 /usr/local/bin/uwsgi --ini spend.ini ├─1491 /usr/local/bin/uwsgi --ini spend.ini ├─1492 /usr/local/bin/uwsgi --ini spend.ini ├─1493 /usr/local/bin/uwsgi --ini spend.ini ├─1494 /usr/local/bin/uwsgi --ini spend.ini └─1495 /usr/local/bin/uwsgi --ini spend.ini Mar 03 12:24:17 ip-172-31-46-200 uwsgi[1489]: spawned uWSGI worker 1 (pid: 1491, cores: 1) Mar 03 12:24:17 ip-172-31-46-200 uwsgi[1489]: spawned uWSGI worker 2 (pid: 1492, cores: 1) Mar 03 12:24:17 ip-172-31-46-200 uwsgi[1489]: spawned uWSGI worker 3 (pid: 1493, cores: 1) Mar 03 12:24:17 ip-172-31-46-200 uwsgi[1489]: spawned uWSGI worker 4 (pid: 1494, cores: 1) Mar 03 12:24:17 ip-172-31-46-200 uwsgi[1489]: spawned uWSGI worker 5 (pid: 1495, cores: 1) Mar 03 12:24:17 ip-172-31-46-200 uwsgi[1489]: Tue Mar 3 12:24:17 2020 - [emperor] vassal spend.ini is ready to accept requests Mar 03 12:24:19 ip-172-31-46-200 uwsgi[1489]: --- no python application found, check your startup … -
Django creating table inside views.py
I have this code in my views.py, to create some table, students = StudentSubjectGrade.objects.filter( grading_Period=period).filter( Subjects=subject).order_by( 'Students_Enrollment_Records', 'Grading_Categories','id' ).values('id', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Middle_Initial', 'Grading_Categories', 'Average', 'Grading_Categories__PercentageWeight') Categories = list(cate.values_list('id', flat=True).order_by('id')) table = [] student_name = None table_row = None columns = len(Categories) + 1 table_header = ['Student Names'] table_header.extend(list(cate.values('CategoryName', 'PercentageWeight'))) table.append(table_header) for student in students: if not student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + \ student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + \ student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] table_row[0] = student_name id = student['id'] table_row.append(id) table_row[Categories.index(student['Grading_Categories']) + 1] = student['Average'] * student[ 'Grading_Categories__PercentageWeight'] / 100 table.append(table_row) this is the result, How to remove the extra ID under Average header? this is my html {% for row in table|slice:"1:" %} <tr class="tr2update"> <td><input type="text" value="{{ row.4 }}" name="studentname">{{ row.0 }}</td> <td class="tdupdate" hidden><input type="text" hidden></td> {% for c in row|slice:"1:" %} <td><input type="text" id="oldgrade" class="oldgrade" name="gradeupdate" value="{{c|floatformat:'2'}}" readonly></td> {% endfor %} <td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" readonly/></td> </tr> {% endfor %} please help me guys, this problem is almost a week now , till now i didn't solve it -
Django wrong amount of arguments in custom handler
Im trying to make a custom handler for page 404 but I've got this error. Ive tried numerous ways around it but my view just doesnt seem to work? handler404 = 'DEMOPROJECT.views.handler404' handler500 = 'DEMOPROJECT.views.handler500' def handler404(request, exception, template_name="404.html"): response = render_to_response('/not-found') response.status_code = 404 return render(request, response) ERRORS: ?: (urls.E007) The custom handler500 view 'DEMOPROJECT.views.handler500' does not take the correct number of arguments (request). System check identified 1 issue (0 silenced). -
Cron does not launch automatically
My cron on my django project does not work. I mean I have to launch it manually using the following instruction : python3 manage.py crontab run 1a909d1e0a17391270108c0591b73ed I tried this : python3 manage.py crontab add But it does not work automatically unfortunately ... Could you help me please ? Thank you very much ! -
Admin panel for user token management
I want to create custom admin panel. In admin panel having two main functionality. user management and token management I completed all things but I shrugged in token management. when admin user adding new user so it will generate token. and users_list view i can see all fields with token. please suggest me some idea how to do -
Django filter geometry given a coordinate
I want to get a polygon from a postgis table given a coordinate/point. With raw sql I do it with: SELECT * FROM parcelas WHERE fk_area=152 AND ST_contains(geometry,ST_SetSRID(ST_Point(342884.86705619487, 6539464.45201204),32721)); The query before returns one row. When I try to do this on django it doesn't return me any row: from django.contrib.gis.geos import GEOSGeometry class TestView(APIView): def get(self, request, format=None): pnt = GEOSGeometry('POINT(342884.86705619487 6539464.45201204)', srid=32721) parcelas = Parcelas.objects.filter(fk_area=152,geometry__contains=pnt) #Also tried this #parcelas = Parcelas.objects.filter(fk_area=pk,geometry__contains='SRID=32721;POINT(342884.86705619487 6539464.45201204)') serializer = ParcelasSerializer(parcelas, many=True) return Response(serializer.data) Even with django raw query it fails although in this case it returns me an internal server error (argument 3: : wrong type): class TestView(APIView): def get(self, request, format=None): parcelas = Parcelas.objects.raw('SELECT * FROM parcelas WHERE fk_area=152 AND ST_contains(geometry,ST_SetSRID(ST_Point(342884.86705619487, 6539464.45201204),32721))') for p in parcelas: #Internal server error print(p.id) return Response('Test') My model parcelas look like this: from django.contrib.gis.db import models class Parcelas(models.Model): id = models.BigAutoField(primary_key=True) fk_area = models.ForeignKey(Areas, models.DO_NOTHING, db_column='fk_area') geometry = models.GeometryField() class Meta: managed = False db_table = 'parcelas' I don't know what I'm doing wrongly if someone has any idea. -
Django(2.11) simultaneous (within 10ms) identical HTTP requests
Consider a POST/PUT REST API (using DRF). If the server receives request1 and within a couple of ms request2 with identical everything to request1 (duplicate request), is there a way to avoid the request2 to be executed using some Django way? Or Should I deal with it manually by some state? Any inputs would be much appreciated. -
Django : table minor_faculty has no column named user_id
Hi I am working on a Django version 2.2.4 application using sqlite3 database. I have a an extension to Django's User model, defined in my models.py as follows: from django.db import models from django.contrib.auth.models import User DEPARTMENT = ( ('CSE','Computer Science Engineering'), ('ECE','Electronics and Communication Engineering'), ('IT','Information Technology'), ('ME','Mechanical Engineering'), ('CE','Civil Engineering') ) YEAR = ( ('Third',3), ('Fourth',4) ) SECTION = ( ('1',1), ('2',2), ('3',3), ('4',4), ) # Create your models here. class Group(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) college = models.CharField(max_length = 300) department = models.CharField(choices = DEPARTMENT, max_length = 3) year = models.CharField(choices = YEAR, max_length = 5) section = models.CharField(choices = SECTION, max_length = 1) group_name = models.CharField( unique = True, max_length = 30) member_1_name = models.CharField( max_length = 100) member_2_name = models.CharField(max_length = 100) member_3_name = models.CharField(max_length = 100) member_1_enrollment = models.CharField( max_length = 20) member_2_enrollment = models.CharField(max_length = 20) member_3_enrollment = models.CharField(max_length = 20) email = models.EmailField(max_length = 256) contact = models.PositiveIntegerField() mentor = models.ForeignKey('Faculty', on_delete = models.PROTECT) def __str__(self): return self.group_name class Faculty(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) name = models.CharField( max_length = 100) email = models.EmailField( max_length = 256) contact = models.PositiveIntegerField() college = models.CharField( max_length = 300) department = models.CharField(choices … -
Download Button option in Django
I am working on a project which takes some files as input and then gives an output result file to the user. The output file is generated in the backend and takes significant time. I want to create a system where the download button appears only after the file has been generated. Do you have any suggestions? Thanks. :) -
error: "unsupported_grant_type" from django oauth2 server
Not sure why django won't accept my POST request for an access token. All my parameters are correct and I already have the authorization code, but a follow-up POST request for the access token gives me this error. Content-type is correct from what I read from others. If the pkce side was non-accurate it would give me a more specific error about that. HttpErrorResponse is { error: "unsupported_grant_type" } 400 bad request requestToken(code: string, state: string) { const clientState = sessionStorage.getItem('pkce-state'); if (clientState !== state) { console.error('States do not match!'); } const verifier = sessionStorage.getItem('pkce-verifier'); const params = new URLSearchParams({ grant_type: 'authorization_code', redirect_uri: 'http://localhost:4200/dashboard', client_id: 'client_id', code, state, verifier }); return this.http.post('http://localhost:8000/o/token/', { params }, { withCredentials: true, headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' } ) }); } Also tried this: requestToken(code: string, state: string) { const clientState = sessionStorage.getItem('pkce-state'); if (clientState !== state) { console.error('States do not match!'); } const verifier = sessionStorage.getItem('pkce-verifier'); return this.http.post('http://localhost:8000/o/token/', { grant_type: 'authorization_code', redirect_uri: 'http://localhost:4200/dashboard', client_id: 'client_id', code, state, verifier }, { withCredentials: true, headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' } ) }); }