Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Selectively apply CSS Styles to Radio Buttons in Quiz in Django
I have users take a quiz. After each question, I want to show them whether their answer was correct or incorrect. The correct answer should be highlighted in Green, and their answer (if incorrect) should be highlighted in red (using Twitter Bootstrap styles). I am currently rendering the quiz results page in Django and HTML like so: {{ player.question }} <div class="myradio"> <label for="choice_1"><input id="id_1" type="radio" value="q1" disabled/> {{q1}}</label> </div> <div class="myradio"> <label for="choice_2"><input id="id_2" type="radio" value="q2" disabled /> {{q2}}</label> </div> <div class="myradio"> <label for="choice_3"><input id="id_3" type="radio" value="q3" disabled /> {{q3}}</label> </div> <div class="myradio"> <label for="choice_4"><input id="id_4" type="radio" value="q4" disabled /> {{q4}}</label> </div> <b><p>Correct Answer: {{solution}}</p><b> Total Score: {{total_score}} I am storing the solution to the question in {{solution}}. I have been trying to figure out how to selectively apply CSS filters if, for example, {{q1}} == {{solution}} that should be highlighted green. I can grab the participant's answer with {{player.submitted_answer}}, and so want to highlight a div element red if {{player.submitted_answer}} != {{solution}}. I have tried messing around with if statement blocks, but can't seem to get it right. Any ideas? -
How do i include bootstrap class in django forms without widget-tweaks?
I want to make a site using django which include forms, but i am not able to find a way to include form-control classes in fields. Is there any way to do so? When i try to install Django-widget-tweaks Could not find a version that satisfies the requirement django-widjet-tweaks (from versions: ) No matching distribution found for django-widjet-tweaks -
How do I access the the following model tables
So I am working on a Django project and I am a beginner. I have a page which displays the list of incubators (from the database). When I click on them, I want to show the their details for which I have made a separate model class. models.py: class Incubators(models.Model): # These are our database files for the Incubator Portal incubator_name = models.CharField(max_length=30) owner = models.CharField(max_length=30) city_location = models.CharField(max_length=30) description = models.TextField(max_length=100) logo = models.FileField() verify = models.BooleanField(default = False) def get_absolute_url(self): return reverse('main:details', kwargs={'pk': self.pk}) def __str__(self): # Displays the following stuff when a query is made return self.incubator_name + '-' + self.owner class Details(models.Model): incubator = models.ForeignKey(Incubators, on_delete = models.CASCADE) inc_name = models.CharField(max_length = 30) inc_img = models.FileField() inc_details = models.TextField(max_length= 2500) inc_address = models.TextField(max_length = 600, default = "Address") inc_doc = models.FileField() inc_policy = models.FileField() def __str__(self): return self.inc_name And this is my views for details: def details(request, incubator_id): inc = get_object_or_404(Incubators, pk = incubator_id) details = Details.objects.all() return render(request, 'main/details.html', {'inc': inc, 'details': details}) And this is my urls.py urlpatterns = [ url(r'^home/', views.home, name='home'), # Home page url(r'incubators/$', views.incubators, name='incubators'), # Incubator list page url(r'about/', views.about, name='about'), # Websie about page url(r'results', views.result, name = … -
Check if an object exists in django content type framework
I want to be able to check if the object exists using get_object_for_this_type content_type = get_object_or_404(ContentType, pk = id1) if content_type.get_object_for_this_type(pk= id2).exists():` This is obviously not working because it's not a query. Is there a way around it without calling the actual mode. I'm trying to avoid try and except as proposed in the following answer: Django - Proper exception for ContentType.get_object_for_this_type() -
Geodjango intepreting MultiPolygon as LinearRing
I'm importing some OSM data from Trimble into a PostGIS database to process it as part of a Django app. This works fine for points and lines but I'm struggling with the polygons. The import appears to work fine: shp2pgsql -d -I aeroway_polygon_polygon.shp aeroway_polygon | psql -d osm Django InspectDB interprets the data in a sensible manner: ./manage.py inspectdb > models.py models.py contents: class AerowayPolygon(models.Model): gid = models.AutoField(primary_key=True) id = models.FloatField(blank=True, null=True) osm_id = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True) z_order = models.FloatField(blank=True, null=True) aeroway = models.CharField(max_length=80, blank=True, null=True) name = models.CharField(max_length=80, blank=True, null=True) name_en = models.CharField(db_column='name:en', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters. operator = models.CharField(max_length=80, blank=True, null=True) ref = models.CharField(max_length=80, blank=True, null=True) faa = models.CharField(max_length=80, blank=True, null=True) iata = models.CharField(max_length=80, blank=True, null=True) icao = models.CharField(max_length=80, blank=True, null=True) website = models.CharField(max_length=80, blank=True, null=True) contact_we = models.CharField(db_column='contact:we', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters. phone = models.CharField(max_length=80, blank=True, null=True) contact_ph = models.CharField(db_column='contact:ph', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters. ele = models.CharField(max_length=80, blank=True, null=True) tower_type = models.CharField(db_column='tower:type', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters. geom = models.MultiPolygonField(srid=0, dim=4, blank=True, null=True) class Meta: managed = False db_table = 'aeroway_polygon' Any attempt … -
dynamically show django model objects attributes with javascript
I am trying to dynamically change text on a webpage on hover that is grabbed from the related. I have a html area tag on a map. <map name="Map"> <area shape="rect" title="Govan" coords="60,510,160,550" alt="Govan" onmouseover="mouseOver(alt)" onmouseout="mouseOut()" href='govan'> <area shape="rect" title="Ibrox" coords="200,620,280,660" alt="Ibrox" onmouseover="mouseOver(alt)" onmouseout="mouseOut()" href='ibrox'> and a java script function that takes the alt as it's input, which is the same as the object name for the stations. class Station(models.Model): name = models.CharField(max_length=128, unique=True) stringName = models.CharField(max_length=128,default='') firstTrainMonSat = models.TimeField(blank=True,null=True) lastTrainMonSat = models.TimeField(blank=True,null=True) firstTrainSun = models.TimeField(blank=True,null=True) lastTrainSun = models.TimeField(blank=True,null=True) latitude = models.DecimalField(max_digits=8, decimal_places=6, blank=True, null=True) longitude = models.DecimalField(max_digits=8, decimal_places=6, blank=True, null=True) slug = models.SlugField(unique=True,default='') def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Station, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'stations' def __str__(self): return self.name I basically want to display the attributes of specific objects (stations) when i get that object name in as text from in the javascript function. Which currently just displays the alt tag that I get in: function mouseOver(x) { document.getElementById('station').innerHTML = x; } -
How we can perform different actions in single HTML form for changing url dynamically in django?
HTML Template <form action="" method="post"> ... ... <input type="submit" name="Next" value="Next"/> <input type="submit" name="Cancel" value="Cancel"/> </form> I want to navigate on different pages by click this buttons. Specifically in django environment. -
Worker failed to boot
I'm trying to deploy my Django project on Heroku, but something is going wrong, and I'm not able to found out what is happening, and what to do in order to solve this. I read in other posts that the problem may be something related with Gunicorn, but I can't solve it. (env) ignacio@ignacio:~/atletico$ heroku logs 2018-03-15T18:04:33.770218+00:00 app[web.1]: [2018-03-15 18:04:33 +0000] [4] [INFO] Reason: Worker failed to boot. 2018-03-15T18:04:47.082000+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi --log-file -` 2018-03-15T18:04:49.411412+00:00 heroku[web.1]: Process exited with status 3 2018-03-15T18:04:49.139027+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [4] [INFO] Starting gunicorn 19.7.1 2018-03-15T18:04:49.139593+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [4] [INFO] Listening at: http://0.0.0.0:25381 (4) 2018-03-15T18:04:49.139786+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [4] [INFO] Using worker: sync 2018-03-15T18:04:49.149373+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [8] [ERROR] Exception in worker process 2018-03-15T18:04:49.149376+00:00 app[web.1]: Traceback (most recent call last): 2018-03-15T18:04:49.149391+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 2018-03-15T18:04:49.149394+00:00 app[web.1]: worker.init_process() 2018-03-15T18:04:49.143828+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [8] [INFO] Booting worker with pid: 8 2018-03-15T18:04:49.149396+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process 2018-03-15T18:04:49.149398+00:00 app[web.1]: self.load_wsgi() 2018-03-15T18:04:49.149400+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 2018-03-15T18:04:49.149401+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-03-15T18:04:49.149408+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2018-03-15T18:04:49.149411+00:00 app[web.1]: self.callable = self.load() 2018-03-15T18:04:49.149413+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, … -
How can I mock the created field of a model that inherits from TimeStampedModel using model_mommy?
I am trying to test a date filter but have been unable to set the created date using mommy.make(). When I make the objects with model mommy the created field is set to the time the objects were created rather than what I passed in with mommy.make() def test_mommy(self): today = arrow.now() yesterday = today.replace(days=-1) mommy.make('Model', created=today.naive) mommy.make('Model', created=yesterday.naive) model_1_created = Model.objects.all()[0].created model_2_created = Model.objects.all()[1].created self.assertNotEqual(model_1_created.strftime('%Y-%m-%d'), model_2_created.strftime('%Y-%m-%d')) This test fails with the Assertion Error: AssertionError: '2018-03-15' == '2018-03-15' I may have a misunderstanding of how model_mommy creates these objects. But I would think this should create it and set the created dates properly. Though it looks like the default TimeStampedObject behavior is taking over. -
How to get the foreignKey related primary key (pk) in the same model in django?
I need to get the id (pk) of a related model.foreignKey object in order to set the "upload_to" attr of a model.FileField of the same model. Something like this: class myClass(models.Model): related_model = models.ForeignKey(RelatedModel,on_delete=models.CASCADE) file = models.FileField(upload_to=str(related_model.id)+"/") So for example, if the related_model has the primary_key 10 the upload_to attr has to be "10/" It is possible or I have to set that value in the view.py file when the object is created? -
Updating SQLite values periodically
Say I have the following four records (assume there are more): record 1 record 2 record 3 record 4 area California Texas California California food Lobster Lamb Rabbit Bagels popular Bagels Elk Rabbit Rabbit Right now I am adding new records into the database by manually choosing an area and a food. The popular field is then automatically populated by finding the most common food for that specific area at the time of entry. For example, if the above four records were the ONLY records in the entire database, then if I were to add another record with area: California and food: Bagels then popular (for the record I just added) would automatically be assigned the value Bagels because there would be two Bagels in the food field, for the area California. The above is already working, which I achieve the above with the following code: popular = list(ModelData.objects.filter(area=area).values_list('food', flat=True)) Counter(popular).most_common() The problem is, the above still leaves existing records in the database with the incorrect popular value; because popular is only calculated at the time of entry, and never 're-calculated' when more entries are added. Using the above example (adding a new record with area: California and food: Bagels), …