Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dont know how to use and work href on form ON Django python
Hey I am beginner in Django.I dont know how can I use href on form in django This is my url.py on my Django project name albert(folder) This is my views.py This is my urls on my django APP name (folder)home but it name with login cause it login url.py -
Google API key not working on server but working fine on local server
I am really new to Google API key. When am I testing my code on the local system, it is working fine but on an actual server it giving me SSLHandshakeError. SSLHandshakeError at 'url' [Errno 1] _ssl.c:510: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed -
Django Custom Command with supervisorctl
I have a django custom management command named Stream that when run in a virtual environment or run using /webapps/senticle50/brexit/python-virtualenv/bin/python /webapps/senticle50/brexit/manage.py Stream --settings=brexit.settings.production works but when I put the exact command into a supervisord .conf file and after running: supervisorctl reread && supervisorctl update followed by supervisorctl restart stream it starts the process but the django command is never actually executed as no output is printed to the log file amongst other end goals of the custom django command not being met. stream.conf: [program:stream] command=/webapps/senticle50/brexit/python-virtualenv/bin/python /webapps/senticle50/brexit/manage.py Stream --settings=brexit.settings.production user=senticle50 stdout_logfile = /webapps/senticle50/logs/stream.log ; Where to write log messages stderr_logfile = /webapps/senticle50/logs/stream.log environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 TLDR; the command works outside of supervisor but when run through supervisor the process starts but the command is never run. -
using python Django and Mysql. Data won't insert due to Binlog
When I use django to design a website and delopy, I find I have some trouble if I using MySQL that turn on the Binlog( mode:STATEMENT). Traceback like this: django.db.utils.OperationalError: (1665, 'Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = STATEMENT and at least one table uses a storage engine limited to row-based logging. InnoDB is limited to row- logging when transaction isolation level is READ COMMITTED or READ UNCOMMITTED.') -
Get every folder inside path
I just want to tell my Django project that the .html file it want can be find in any folder inside "/templates". I know this can be done with a simple pattern like allfolders = "/templates/*" or allfolders '/templates/$' or allfolders = 'templates/^$' I really can't remember the correct way of doing it, its just a simple string manipulation that can tell "The file is inside any folder inside the folder '/templates' without any imports being needed. Thats because i want to organize my templates folder so i can have different folders inside it to point me what type of html is this or from what project, things like that, organization propose. Thanks for your attention and sorry for the lack of code. -
SQL Count Optimisations
I have been using the Django Rest Framework, and part of the ORM does the following query as part of a generic object list endpoint: `SELECT COUNT(*) AS `__count` FROM `album` INNER JOIN `tracks` ON (`album`.`id` = `tracks`.`album_id`) WHERE `tracks`.`viewable` = 1` The API is supposed to only display albums with tracks that are set to viewable, but with a tracks table containing 50 million rows this is query never seem to complete and hangs the endpoint's execution. All columns referenced are indexed, so I do not know why this is taking so long to execute. If there are any potential optimisations that I might have not considered please let me know. -
Travis.yml file not being found in Django project
I have a Django project that needs to be built using TravisCI. Originally, I put the travis.yml file in the root of the project (where the virtual environment would be) and then built it but for some reason, Travis is using default settings since it can't find the yml file. I then moved the file into the src directory and rerun, but the build still wasn't finding the file. Where does the file need to be placed in order for Travis to find it? Travis.yml: language: python python: - "2.7" # setup environment env: - DJANGO_VERSION=1.11.2 - DJANGO_SETTINGS_MODULE='di_photouploader.settings.production' # install dependencies install: - pip install -r requirements.txt # run test scripts script: - python manage.py test -
How do I make a model with a datetime field that does NOT save the time zone?
I have a model that looks like this: class IPLog(models.Model): last_click = models.DateTimeField() When I save an IPLog instance, the time zone gets saved with it. This is a problem for me since I want to compare last_click to a datetime.now() instance, but it throws me an error since the model instance's last_click has a time zone: TypeError: can't subtract offset-naive and offset-aware datetimes. The difference tends to look like this: 2018-03-16 00:24:35.619424 # datetime.now() 2018-03-15 23:55:07.006190+00:00 # last_click How do I stop my model from saving new instances with a time zone? -
Django middleware advised not to use request.POST why?
"Accessing request.POST inside middleware before the view runs or in process_view() will prevent any view running after the middleware from being able to modify the upload handlers for the request, and should normally be avoided." This is from the django documentation. First of all, if I just read the POST, without changing that, how does it even know and how does it prevent the view from doing it's business and second, how is a CsrfViewMiddleware different in that sense? -
How do I print a url path in an `a` tag using the url's name attribute?
In my urls.py I have url("^login-register/$", views.login_register, name="login_register"),. In a template, I can do {% url "login_register" %}. How do I print that value in views.py? -
django rest patch, how do I save with updated data?
For a REST PATCH, I want to update some values in the model that already exists and save it back out. However, I'm obviously missing some step here: Find the item to update Update the the value(s) Save it out Seems simple enough: def patch( self, request, serialnumber, format = None ): try: r = Rack.objects.get( serialNumber = serialnumber ) except Rack.DoesNotExist: data = { 'error' : 'item not found' } return Response( data, status = status.HTTP_404_NOT_FOUND ) s = RackSerializer( r ) token = "New value for token" s.save( token = token, serialNumber = serialnumber ) data = { 'serialNumber' : serialnumber, 'token' : token } return Response( data, status = status.HTTP_200_OK ) This gives "AssertionError: You must call '.is_valid()' before calling '.save().'" If I add the s.is_valid() call, I get "Cannot call '.is_valid()' as no 'data=' keyword argument was passed when instantiating the serializer instance." Can someone point me at how to untie this knot? -
parse uploaded file to another format before saving it in django
I am trying to upload csv file and then parse to xml format but before saving it "import csv file and save it as xml file" I have got the uploading functionality working fine and be saved correctly; however, my issue is how to pass the uploaded file to the function where it is parsed to xml format. I am using django python Model.py from django.db import models from django.urls import reverse from .validators import validate_file_extension # Create your models here. class DataFile(models.Model): title = models.CharField(max_length=250) description = models.CharField(max_length=1000) file = models.FileField() def __str__(self): return self.title + ' - ' + self.description + ' - ' + self.file and here is my form.py from django import forms from .models import DataFile class FileForm(forms.ModelForm): class Meta: model = DataFile fields = ['title', 'description', 'file' ] here is my view.py def importing(request): form = FileForm(request.POST or None) if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): #here is where the passing supose to be form = csv2xml(request.FILES['file']) form.save() return HttpResponseRedirect('http://127.0.0.1:8000') return render(request, 'import.html', { 'form': form }) function that i want to pass my uploaded file to: def csv2xml(csv_file): csv_data = csv.reader(csv_file) for row in csv_data: print(row) xml = '<?xml version="1.0"?>\n' … -
Django Ajax post failed with Gunicorn and Nginx
I am writing a app using AJAX deployed by gunicorn and nginx on AWS. It works very well when I am using python3 manage.py runserver. But after I used gunicorn, the AJAX post doesn't work. I get a Failed to load resource: the server responded with a status of 404 (Not Found). What I did is a very simple AJAX post $.ajax({ type: 'POST', url: '/analytical-tools/getData/', data: { 'somedata':somedata csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: 'json', success: function (data) { /*do something*/ } }); First I want to ask is is there any difference on AJAX when deployed on Gunicorn? And I want to ask how to debug on gunicorn. The gunicorn runs in the background and I can't see any debug information or print something when it is running. -
Django's template tag inside javascript
My app's urls.py is: from django.urls import path from . import views app_name = 'javascript' urlpatterns = [ path('create_table', views.create_table, name='create_table') My views.py is: def create_table(request): row_data = "this is row data" context = {'row_data': row_data} return render(request, 'javascript/create_table.html', context) My create_table.html is: {% load static %} <button id="create_table">Get data</button> <div id="place_for_table"></div></div> <script src="{% static 'javascript/scripts/create_table.js' %}"></script> And my create_table.js is: function create_table() { document.getElementById("place_for_table").innerHTML = '{{ row_data }}'; } document.getElementById("create_table").onclick = function() { create_table() } What I am trying to do is to run the create_table.js script on the click of the create_table button which should display "this is row data" text in place for table div element. However, what gets diplayed is just {{ row_data )). I have read other similar questions on using Django's variables inside Javascript but as per my understanding they all suggest to do the way I did it, so I am not sure what I am doing wrong. -
Django custom tag
i am trying to get value loop but it does not work , i created custom tag to get sections from database it works but when i am trying to display values in html code it does not appear any thing @register.simple_tag def section(): return {'val': models.section.objects.all()} header.html {% load tags%} {% section as sections %} {% for sect in sections.val %} <li class="nav-item"> <a class="nav-link" href="#">{{sec.name}}</a> </li> {% endfor%} -
NameError: name 'django_filters' is not defined
I am trying to use the Django package: Django Filter I installed it via Pip, made sure I was running supported versions of Python(3.6), and Django(2.0), but whenever I try to run my application, I get the following error: class Table1(models.Model, django_filters.FilterSet): NameError: name 'django_filters' is not defined Here's a sample of my code, with the names changed to protect my work. models.py: from django.db import models from django.contrib.postgres.search import SearchVectorField, SearchQuery from django_filters import FilterSet class Msysaces1(models.Model, django_filters.FilterSet): field1 = models.IntegerField(db_column='field1', blank=True, null=True) field2 = models.NullBooleanField(db_column='field2') field3= models.IntegerField(db_column='field3', blank=True, null=True) field4= models.TextField(db_column='field4', blank=True, null=False, primary_key=True) #def __str__(self): # return self.sid class Meta: managed = False db_table = 'Table1' unique_together = (('field1', 'field2', 'field3', 'field4'),) filters.py: from .models import Table1 import django_filters class Table1Filter(django_filters.FilterSet): class Meta: model = Table1 fields = ['field1', 'field2', 'field3', 'field4'] views.py: from django.shortcuts import render from django_tables2 import RequestConfig from django_tables2.export.export import TableExport from django.contrib.postgres.search import SearchQuery, SearchRank from django.template import RequestContext from django.views.generic import * from .models import * from .tables import * from .forms import * from .filters import Table1Filter def table1(request): filter = Table1Filter(request.GET, queryset=Table1.objects.all()) return render(request, 'table1.html', {'filter': filter}) I wrote some basic filtering stuff manually and then realized that Django … -
Implement multiple table joins in Django using ORM
How to implement multiple table joins in Django ORM? Table1 join Table2, Table2 join Table3, Table3 join table4? I tried but I was able to join only first two tables. -
Django manage.py runserver command returns an error
I could use some help figuring out what's the problem with running the development server for one of my django projects. When I run python managy.py runserver, I get an error that ends with this: OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Never before has anything like this happened to me while working with Django, so I will be very thankful for every possible solution. -
Setting up node-http-proxy for Django/NodeJS app on heroku
I am deploying a Django app that makes use also of nodeJS With that, I have stumbled upon https://blog.heroku.com/heroku-django-node I was able to setup the buildpacks and procfiles but I'm having problems with setting up node-http-proxy Saying so because the error I am getting is Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch So I guess this part confuses me (from the link above): Of course, still only 1 process on the web dyno can bind to PORT. By adding an environment variable (we called it DJANGO_PORT) and adding node-http-proxy to our node script, we were able to bind node to PORT and proxy all normal web traffic through to Django over 127.0.0.1. The resulting Procfiles look something like this: I have already added the env variable to my heroku app. 2 Questions How do you bind PORT to node? Do I create a proxyserver that targets my app on DJANGO_PORT only? 1st questions seems to be the most blurry to me Thanks in advanced -
NoReverseMatch error integrating Django forms and HTML with django-s3direct
I'm trying to add functionality to my Django site to upload files to an AWS S3 bucket. I found django-s3direct, which seems perfectly suited. After following the setup instructions, though, I'm getting an error rendering the very basic HTML template: <html> <head> <meta charset="utf-8"> <title>s3direct</title> {{ form.media }} </head> <body> <form action="" method="post">{% csrf_token %} {{ form.as_p }} </form> </body> </html> I get the error Reverse for 's3direct' not found. 's3direct' is not a valid view function or pattern name. on the line with {{ form.as_p }}. In my urls.py I have (as specified in the s3direct docs): from django.conf.urls import url from .views import get_upload_params, generate_aws_v4_signature, MyView app_name = 's3direct' urlpatterns = [ url(r'^$', MyView.as_view(), name='form'), url('^get_upload_params/', get_upload_params, name='s3direct'), url('^get_aws_v4_signature/', generate_aws_v4_signature, name='s3direct-signing'), ] In forms.py: from django import forms from s3direct.widgets import S3DirectWidget class S3DirectUploadForm(forms.Form): csv = forms.URLField(widget=S3DirectWidget(dest='csv_destination')) And in views.py (along with a couple other long functions from s3direct): from django.views.generic import FormView from .forms import S3DirectUploadForm class MyView(FormView): template_name = 'form.html' form_class = S3DirectUploadForm I've configured an IAM policy and added keys to my Django settings file, as well as made a CORS policy for my S3 bucket. I'm using Django 2.0. I'm stuck on this reverse … -
Assignment Submission System (Practical Base)
Is it possible to design an Online Assignment Submission System (Practical Base). In which the students have to fill in the gaps and label diagram online which will be mark systematically?.... My question is basically on labeling diagram online. Can Django handle this and how? -
Django - global setting to specify all models as non-managed
I'm writing a Django app, but have a separate process for creating / managing the tables. In other words, I don't want Django to manage any of the DB tables. To accomplish this, I use managed = False in the Meta class, like: class School(models.Model): schoolid = models.IntegerField(primary_key=True) schooldisplayname = models.CharField(max_length=100) address = models.CharField(max_length=100) city = models.CharField(max_length=100) department = models.CharField(max_length=100) class Meta: managed = False But it's annoying to have to always specify this for each model. Is there a way to apply this as a global setting to all my models by default? Thanks. -
Update Value dynamically using repeated Ajax calls from DJango template
I wanted to show my sound sensor readings from a django site (original code as posted in the link). Now as per the situation 2 of the accepted answer, I wanted to make a Javascript function which repeatedly calls the ajax_data function from views template. But it seems that no repeated calls are being made. And no update in reading reflects either. My django template till now: <!doctype html> <html> <head> <title>Noise measurement site</title> <script src="http://code.jquery.com/jquery-3.0.0.js" integrity="sha256-jrPLZ+8vDxt2FnE1zvZXCkCcebI/C8Dt5xyaQBjxQIo=" crossorigin="anonymous"></script> <script language="javascript" type="text/javascript"> function updateValue() { $.ajax({ url:"D:/Python programs/django_projects/Noise_Measurement/noise_m/views.py/ajax_data/", //success: updateValue(), for experimenting with a recursive call... }); } $(document).ready(function(){ var v = setInterval(updateValue,2000); }); </script> </head> <body> <p>Hello there</p> <p>Present noise level : {{noise_level}} dB</p> </body> </html> (I have mentioned rest of the code in my previously asked question. I have read some of the answers on the platform but I'm not getting much results.) Output till now... (and after some seconds...) How should I make the calls to refresh the shown value without whole page reload? -
Django Template Value Passed to Javascript
I am working on a turn-based game where players can, but don't have to, gain ownership of certain spaces on the game board. My detail view in shows the spaces owned by each player, and I use a loop to display all owned spaces: <small class="text-muted">Spaces Owned</small> <div class="list-group list-group-flush"> {% for space in player.space_set.all %} <a class="list-group-item" data-toggle="modal" data-target="#spaceModal" id="modalButton"> {{ space.name }} </a> {% endfor %} </div> I want to be able to populate a modal with all detailed information about whichever space is clicked on (hence why I'm using the anchor tag instead of a div, though I guess it might not matter as much). The modal would look something like this, though the goal is to populate it using appropriate IDs, etc using the response from the AJAX call instead of the template variables currently used as placeholders: <div class="modal fade" id="spaceModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <div class="wrapper"> <div class="box"> <h2>{{ space.name }}</h2> <div class="float-left">{{ space.location }}</div> <div class="float-right">{{ space.defense_points }}</div> <br /> <div class="float-right">{{ space.attack_points }}</div> </div> </div> </div> </div> </div> </div> What I want to be able to do is use an AJAX call to populate the … -
How do I send inputted email to built-in "reset password" view from custom template?
I have a template with a custom "forgot password, please reset" form. <form name="forgotPWForm" method="post"> <input type="email" ng-model="forgotPW.email"> <div class="input-group-append"> <button type="submit">Submit</button> </div> </form> That form is part of a template called login.html, which also has a login form. I want the user to type their email into the input, hit "Submit," and for the form to send the email to Django's reset_password view. But as I understand it, that view is limited to a certain template. How do I set up my "forgot pass" form to do what I described?