Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i use variables as index in a list of list in django templates?
I'm working on a school project for a room manager. I have to show the reservations on a specific day, using a table. Actually the data is stored in a list of list called "slots" placed in views.py. I'm trying to iterate it in different ways but i can't totally find a solution. Actually, this is the template: {% extends 'base.html' %} {% load staticfiles %} {% load filters %} {% block content %} <form> <center><p><h2>Reservations in: {{ dt }}</h2></p></center> <table style="width:90%"> <thead><tr> <th>Rooms</th> <th>8</th> <th>9</th> <th>10</th> <th>11</th> <th>12</th> <th>13</th> <th>14</th> <th>15</th> <th>16</th> <th>17</th> <th>18</th> <th>19</th> <th>20</th> </tr></thead> <tbody> {% for i in rooms %} <tr> <td>{{ i.name }}</td> {% for j in count %} <td> {{ slots }} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> <center> <p>{{ form.date }}</p> <p><input type="submit" value="Done" /></p> {% csrf_token %} </center> </form> {% endblock %} This is the view: def index(request): dtflag = True rooms = Room.objects.all().order_by('name') resv = Reservation.objects.filter(date=datetime.date.today()) hr = [0, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] count = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] slots = [] if request.method == 'GET': form = β¦ -
How can I verify if TLS end-to-end encryption is configured properly?
I just tried to set up TLS on a django app hosted by Heroku PaaS. How can I verify if TLS was configured properly and that the communication is encrypted? I tried: curl -vI https://www.example.com but I cannot tell if it is properly configured. I tried: heroku certs:info --app Appname and it says appname has no SSL certificates If not set up properly but if I go to the url using chrome, I get the padlock symbol followed by 'secure'. What is going on? xD -
Django : Can't find module error
I am fairly new to django and I'm trying to play around with it. I have imported a python file into my views to get some details I need from it. But when I try to run my server, I get an error saying the module is not found. Help, please. Thanks in advance server error files I have got -
Django Test Runner can't find tests
I am running into issues with the Django (1.10.6) Test Runner being unable to find my tests. I am using Python 3.6. The following works: python manage.py test apps.foo but this does not: python manage.py test My project structure looks as follows: apps/ foo/ migrations/ __init__.py admin.py apps.py models.py tests.py urls.py views.py manage.py And tests.py looks like this: from django.test import TestCase class ConfirmationTests(TestCase): def setUp(self): pass def test_email_confirm(self): pass Is there any reason why the Test Runner would fail to pick up my tests? -
Read Only Field First Time Creation
I am a little confused here. I have a model form and I would like a field to be read only with a default value. I have the following code: class CreateTeamForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreateTeamForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['team_creator'].widget.attrs['readonly'] = True In my views.py: return render(request, 'teams/team_form.html', {'form': CreateTeamForm(initial={'team_creator':request.user.username})}) As you can see, I want the team_creator to have a default value that is read only. When I first create this object, the field is not read only. However, when I edit/update this form instance, it works! So I am confused in the sense that why it won't be read-only when I first create the object? -
missing something with autentication in django?
PYTHON: from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.contrib.auth import authenticate class Firstapp(View): def get(self, request): return render(request, 'index.html') def post(self, request): username = request.POST['your_name'] user = authenticate(username=username) return HttpResponse(user) HTML: <form method="POST"> {% csrf_token %} <input type="text" name ='your_name' placeholder="username"/> <button type="submit">Button</button> I have created many users: admin, user_one, user_two etc. Checked via /admin page and usernames are there as they should be. Followed by documentantion in Django I wrote the code, however I don't understand why submiting a username which is in database returns none in Fistapp.post? like authnetication(username='user_one') returns None. Would appreciate your help. -
When adding an image in my text editor, it just renders the image url. How do I make it so it renders the actual image instead?
I'm currently using django-pagedown as my text editor for users submitting Posts: https://github.com/timmyomahony/django-pagedown When you click add image on the toolbar, it just renders the image url in the editor body, e.g. someimage.png How do I implement a feature where it renders the actual image instantaneously instead? I've had a look at the documentation but i'm not too sure how to go about it. I'm fairly sure the code would be changed/written in the Markdown.Editor.js folder (https://github.com/timmyomahony/pagedown/blob/77f33b47bc670b50a3b19947a7a434f7138feabd/Markdown.Editor.js), but i'm not 100%. If someone could have a quick look at the documentation and assist me on what to do that would be great. -
Deleting a table from MySQL database in Django manually
During my experimentation with my blog app (blogapp) in Django, I created two models (Category and Language), connected them to another model (Post) using following connections: category = models.ManyToManyField(Category) language = models.ForeignKey(Language) Then it gave an error like THIS due to the lack of default value. Tried to roll that back by using an amalgam of THIS and THIS. Then I tried to add a default value using THIS. I've got an error "django.db.utils.OperationalError 1050, Table XXX already exists", then I tried THIS. Tried to revert back migrations by deleting the created migrations from the migrations folder manually. At some point I got django (1054, "Unknown column in 'field list") error. Finally I decided to revert back to my original starting place. When I connect to my MySQL database using python manage.py dbshell, I realized that my MySQL server still have two tables that should have been deleted, blogapp_category and blogapp_language. Server is working properly but I keep getting "Table XXX already exists" error when I try to add those models. Dropping tables from MySQL seems to be the only option at the moment. When I run mysql> SHOW COLUMNS FROM blogapp_post; I did not see any reference to language β¦ -
How to configure SSL for Heroku+Django with the new Heroku SSL (ACM)
I have updated the settings in django to include: SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') And I have upgraded to paid dynos (Hobby) on heroku. What more needs to be done to enable end-to-end encryption on Heroku? I do not have any other domains (just https://appname.herokuapp.com/) and I am using this URL from an iOS app that I am building. -
Only display an inline "add object" field if no objects exist
In my Django application, I have a model, X. It has a related/helper model Y, which contains some extra info about it. Instances of Y are bound to their Xs with a ForeignKey (that is, Y contains a models.ForeignKey(X)). I also have this code in my admin.py: class YInline(admin.TabularInline): model = Y extra = 1 This works fine, but the inline field for adding a new Y is always displayed: when adding a new X, and when editing an existing X which already has some Ys bound to it. I would like to show the field only if X has no Ys bound to it yet (either because it's being created or because no Ys were assigned to it previously). If we're editing an X which already contains some Ys, the inline should not be displayed; the user will use the "Add another Y" button if they wish to add one. How can I achieve this? I'm using the latest stable version of Django, 1.10 at the time of writing. -
Django inline model formset: can't pass the foreignkeyword value in
As the title says I am having a problem with django formset. I have this forms.py file: class ScoreForm(forms.ModelForm): class Meta: model = models.Score fields = ( 'fixture', 'period', 'home_team_score', 'away_team_score', ) ScoreFormSet = forms.inlineformset_factory( models.Fixture, models.Score, form=ScoreForm ) This is my the ralted part of my views.py file: @method_decorator(login_required, name='dispatch') class InsertScoreView(CreateView): template_name = 'gamestream/insert_score.html' model = Score form_class = forms.ScoreForm success_url = "/score_list/" def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of the form and its inline formsets. """ self.object = None fixture = Fixture.objects.get(id=self.kwargs['fixture_id']) form_class = self.get_form_class() form = self.get_form(form_class) score_form = forms.ScoreFormSet(initial=[ {'period':1}, {'period':2}, {'period':3}, {'period':4}, {'period':5}]) return self.render_to_response( self.get_context_data( form=form, score_form=score_form, fixture=fixture)) def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a form instance and its inline formsets with the passed POST variables and then checking them for validity. """ self.object = None form_class = self.get_form_class() form = self.get_form(form_class) fixture = Fixture.objects.get(id=self.kwargs['fixture_id']) score_form = forms.ScoreFormSet(instance=fixture) if form.is_valid() and score_form.is_valid(): return self.form_valid(form, score_form, fixture) else: return self.form_invalid(form, score_form) def form_valid(self, form, score_form, fixture): """ Called if all forms are valid. Creates a Recipe instance along with associated Ingredients and Instructions and then redirects to a success page. """ self.object = β¦ -
Django TemplateDoesNotExist in production server when it works in development
I get the following error. It's ONLY IN PRODUCTION where I deploy Django application using apache + mod_wsgi. IT WORKS PERFECTLY IN DEVELOPMENT server(my computer): TemplateDoesNotExist at / base.html postmortem. as you can see only one of my two folders from settings are being searched: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: Using loader django.template.loaders.app_directories.Loader: /home/bot_frontend/horses/templates/base.html (File does not exist) /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/base.html (File does not exist) /usr/local/lib/python2.7/dist-packages/django/contrib/auth/templates/base.html (File does not exist) /home/virtualenvs/bot_frontend/lib/python2.7/site-packages/django_extensions/templates/base.html (File does not exist) Here are my settings. The base.html template is in "templates" folder.: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, "templates"), os.path.join(BASE_DIR, "horses/templates") ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Here I confirm that this template actually exists: >>> from django.template.loader import get_template >>> get_template("base.html") <django.template.backends.django.Template object at 0x7f6af68d38d0> As you can see only one folder out of two in my template dirs are being searched while in development server it works just fine. Any ideas why this could be ? Is it possible it's some kind of permissions issue. -
Incomplete form request
I have a form, when i pressing accept button of this form, timeout occuring, i have no any idea, what happend and how can i resolve this? HTTP/1.1 200 OK Date: Wed, 22 Feb 2017 15:20:32 GMT Server: Apache/2.4.18 (Ubuntu) Vary: Cookie,Accept-Encoding X-Frame-Options: SAMEORIGIN Content-Encoding: gzip Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: application/javascript GET /favicon.ico HTTP/1.1 User-Agent: Mozilla/5.0 (Android 6.0.1; Mobile; rv:51.0.3) Gecko/51.0.3 Firefox/51.0.3 Host: ut3taavoni.ir Accept-Encoding: gzip If-Modified-Since: Wed, 22 Feb 2017 15:19:39 GMT Cache-Control: max-age=60 Connection: keep-alive HTTP/1.1 200 OK Date: Wed, 22 Feb 2017 15:20:34 GMT Server: Apache/2.4.18 (Ubuntu) Content-Length: 0 Keep-Alive: timeout=5, max=99 Connection: Keep-Alive Content-Type: image/vnd.microsoft.icon Host: ut3taavoni.ir User-Agent: Mozilla/5.0 (Android 6.0.1; Mobile; rv:51.0) Gecko/51.0 Firefox/51.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Referer: http://ut3taavoni.ir/m3s/m3s-panel/members/user/501/ Cookie: csrftoken=3yVd9UL6g69U6Chhy5MQqIcPAy9VyGUM; sessionid=d8xvyszgs05occnnac57lz0vd8zuvqy5 Upgrade-Insecure-Requests: 1 Content-Type: multipart/form-data; boundary=---------------------------6169424391163634213177052432 Content-Length: 19033 Cache-Control: max-age=0 Connection: keep-alive Content-Disposition: form-data; name="csrfmiddlewaretoken" Content-Disposition: form-data; name="username" Content-Disposition: form-data; name="first_name" Content-Disposition: form-data; name="last_name" Content-Disposition: form-data; name="email" Content-Disposition: form-data; name="birth_date_0" Content-Disposition: form-data; name="birth_date_1" Content-Disposition: form-data; name="birth_date_2" Content-Disposition: form-data; name="academic_degree" Content-Disposition: form-data; name="picture"; filename="" Content-Type: application/octet-stream Content-Disposition: form-data; name="international_card_scaned_file"; filename="" Content-Type: application/octet-stream Content-Disposition: form-data; name="certificate_scaned_file_page1"; filename="" Content-Type: application/octet-stream Content-Disposition: form-data; name="certificate_scaned_file_page2"; filename="" Content-Type: application/octet-stream Content-Disposition: form-data; name="academic_degr <<<<<<<< incomplete Line :0 Date: Wed, 22 Feb 2017 15:16:32 β¦ -
Django: Design decision django-polimorphic & django-filter combination
I'm building a second hand products website based on Django. I've been learning Python, Flask and Django for some time now and have finshed several tutorials and books. I'm still a novice, but willing to learn. The problem i am facing is the following: Second hand products can be anything, with a plenthora of attributes i'd like to be filterable/searchable. Setting this up with a base model, this would look like this: class BaseProduct(PolymorphicModel): PRICE_CHOICES = ( ('VRPR', 'Asking Price'), ('VPBI', 'Asking Price + bids'), ('VRIJ', 'Free bids'), ) STATE_CHOICES = ( ('NIEU', 'New'), ('ZGAN', 'As good as new'), ('GEBR', 'Used'), ) title = models.CharField(max_length=50) description = models.TextField(max_length=400) price = models.FloatField(null=True, blank=True) viewed = models.IntegerField(default=0, editable=False) state = models.CharField(max_length=4, choices=STATE_CHOICES) created_date = models.DateTimeField(default=timezone.now(), editable=False) modified_date = models.DateTimeField(auto_now=True) price_type = models.CharField(max_length=4, choices=PRICE_CHOICES) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, editable=False) product_website = models.URLField(null=True, blank=True) category = models.ForeignKey('Category') Followed by a specific product as: class MotorCycleProduct(BaseProduct): BRAND_CHOICES = ( ('KAWA', 'Kawasaki'), ('HOND', 'Honda'), ('YAMA', 'Yamaha'), ('MOTG', 'Moto Guzzi'), ) TYPE_CHOICES = ( ('CHOP', 'Chopper'), ('ENDU', 'Enduro'), ('NAKE', 'Naked bike'), ) POWER_CHOICES = ( ('11', '11'), ('25', '25'), ('35', '35'), ) CAPACITY_CHOICES = ( ('TO250', '< 250 cc'), ('TO500', '500 tot 750 cc'), ('T1000', '750 tot β¦ -
How to pass data from child template to parent template then to included template in Django?
Basically what i want to accomplish is be able to access some variable or content from a template after performing extend then include. No better way to explain what i want to do better than a sample code so, home.html {% with page="homepage" %} {% extends "base.html" %} {% endwith %} base.html {% include "sidebar.html" with origin=page %} sidebar.html <h1>This is {{ origin }}'s sidebar</h1> In the above example i want to end up with a header stating "This is homepage's sidebar" Is there any built-in way to do so in Django? if not is there any non built-in solution? -
Django custom error pages
I have django project. My dir structure is like below. βββ contributors.txt βββ db.json βββ db.sqlite3 βββ manage.py βββ requirement.txt βββ site_media β βββ back.jpeg βββ static β βββ css β β βββ *.css β βββ favicon.ico β βββ js β β βββ *.js β βββ *.jpg βββ djpj β βββ __init__.py β βββ __init__.pyc β βββ settings.py β βββ settings.pyc β βββ urls.py β βββ urls.pyc β βββ wsgi.py β βββ wsgi.pyc βββ app βββ accountview.py βββ accountview.pyc βββ admin.py βββ admin.pyc βββ forms.py βββ forms.pyc βββ __init__.py βββ __init__.pyc βββ models.py βββ models.pyc βββ promo_rest.py βββ promo_rest.pyc βββ serializers.py βββ serializers.pyc βββ somerequireddatainit.py βββ tasks.py βββ tasks.pyc βββ templates β βββ app β β βββ 404.html β β βββ *.html βββ tests.py βββ testview.py βββ testview.pyc βββ urls.py βββ urls.pyc βββ views.py βββ views.pyc βββ zflib.py βββ zflib.pyc I am confused from the tutorials where to put the 404 url patterns and overides in main urls.py or app urls.py. I am using Djabgo 1.10. If there is any tutorials for error page it would be helpful if I were to be pointed in that direction. -
Django Channels doesn't run basic test case
I'm trying to test my consumers with the testing framework from django channels, but even a basic test doesn't seem to work This is what my test case looks like: from channels import Channel from channels.test import ChannelTestCase, HttpClient, apply_routes from rci.consumers import Demultiplexer from rosbridge.consumers import OtherWebSocketConsumer class ChannelTestCase(ChannelTestCase): def test_channel(self): client = HttpClient() client.send_and_consume('websocket.connect', '/new/') # <--- here's the error self.assertIsNone(client.receive()) This is my routing: http_routing = [ route("http.request", admin.site.urls, path=r"^/admin/", method=r"^$"), #...and so on ] channel_routing = [Demultiplexer.as_route(path=r"^/sock/")] This is my consumer: class Demultiplexer(WebsocketDemultiplexer): channel_session_user = True consumers = { "rosbridge": ROSWebSocketConsumer, "setting": SettingsConsumer, } This gives me the following error: ERROR: test_ros_channel (robot_configuration_interface.tests.unit.test_channels.ROSChannelTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/cjds/development/robot_configuration_interface/robot_configuration_interface/tests/unit/test_channels.py", line 36, in test_ros_channel client.send_and_consume('websocket.connect', '/new/') File "/usr/local/lib/python2.7/dist-packages/channels/test/http.py", line 94, in send_and_consume self.send(channel, content, text, path) File "/usr/local/lib/python2.7/dist-packages/channels/test/http.py", line 79, in send content.setdefault('reply_channel', self.reply_channel) AttributeError: 'str' object has no attribute 'setdefault' I'm trying to follow this tutorial here: http://channels.readthedocs.io/en/stable/testing.html#clients -
Large project files in Heroku on Django
I have some large files that I need to store in my project. Their sum total size is 157 MB. When my application starts, I have an AppConfig which runs. It reads the files into memory and they stay there for the lifetime of the application. By the way, these files aren't static/media assets like images; they're numpy arrays for some server-side logic. So I want a solution which accomplishes the following: Keeps my files out of source control / the Heroku slug Does not require me to read from some cloud service S3/Google frequently Has my files readily available during the stage where AppConfigs are initialized. Here is one solution that I thought of: Store the files in S3/Google, and download them from the server when AppConfig is initialized. The downside of this is that it would make restarting my server really slow because downloading 157 MB is pretty time-consuming, and it might cost a bit too. Is there a better way? -
Is an alamofire request to a HTTPS domain any different from that to HTTP?
I just added SSL to my backend framework (Django REST API) and I want my iOS application to talk to it. Do I have to do anything differently on the iOS side of my project? How do I tell Alamofire to encrypt the data its sending? Or Does it happen automatically? -
Adapt a template tags method
I am trying to use a template tags in a template. from django import template from datetime import datetime from django.template.defaultfilters import date as datefilter from django.utils import translation register = template.Library() DATE_FORMATS = { "en": "l, F j, Y", "fr": "l, j F Y" } DEFAULT_LANG = 'fr' @register.simple_tag(name="localdate") def localdate(lang=DEFAULT_LANG): fmt = DATE_FORMATS.get(lang, DATE_FORMATS[DEFAULT_LANG]) now = datetime.now() with translation.override(lang): return datefilter(now, fmt) I tried to use {{ localdate : 'en'}}, but everything went wrong. Is there an easy way to adapt tags so that it works? In fact, the file is called date_tags.py. So in the template I load the file with {%load date_tags %}. -
Django ckeditor save and load options?
Is there anyway to implement a Save and Load option for django ck-editor? What I mean is, clicking "Save" should save the current text in the editor to the database. Clicking "Load" should present to the user a list of text files that were previously saved. On selecting one, the ckeditor must be populated with the content of that text file. Out of these, I believe it is possible to save the text editor content using JS and Ajax calls, but I'm not sure if I can load something up. Does Django ckEditor come with such options? If not, how would I solve this? -
Python/Pip ModuleNotFoundError: No module named 'setuptools' even after "pip install setuptools"
beginner here and need some help with doing this command in powershell: pip install virtualenvwrapper-win the error that appears is: PS C:\Windows\system32> pip install virtualenvwrapper-win Collecting virtualenvwrapper-win Using cached virtualenvwrapper-win-1.2.1.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'setuptools' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in I've tried doing: "pip install setuptools" also tried uninstalling and reinstalling and update but the error persists. pip and python executables have been added to environment variables. Help me understand what I'm doing wrong as well. Thanks! :) -
OS X Django/Apache app not serving media files, works using python shell
I have a simple Django app that displays a bunch of thumbnails to videos. The first thing the app does is finds all of the thumbnail files in the MEDIA_ROOT. Everything else trickles down from that. I've got apache serving my site correctly, however it can't find the files in my media_root. views.py: def index(request): def walk_dir_tree(path, file_type): return[os.path.basename(x) for x in glob.glob(path + file_type, recursive=True)] # Gets all .jpgs in media_root all_thumb_files = sorted(walk_dir_tree( settings.MEDIA_ROOT + 'thumbnails/**/*', '.jpg'), reverse=True) ... return HttpResponse(template.render(context, request)) relevant info from settings.py: # URLs STATIC_URL = '/static/' MEDIA_URL = '/media/' # Root Dirs: STATIC_ROOT = os.path.join(BASE_DIR, "static/") # Dev MEDIA_ROOT = '/Users/user/Documents/temp/secureDash/' http-vhosts.conf: <VirtualHost *:80> LogLevel debug ServerName securedash ServerAdmin tylerkasselin@securedash.com Alias /static /Users/user/icloud/projects/secureDash/static <Directory /Users/user/icloud/projects/secureDash/static> Require all granted </Directory> Alias /media /Users/user/Documents/temp/secureDash <Directory /Users/user/Documents/temp/secureDash> Require all granted </Directory> <Directory /Users/user/icloud/projects/secureDash/secureDash> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess securedash python-path=/Users/user/icloud/projects/secureDash/secureDash python-home=/Users/user/Documents/VirtualEnvs/securedash WSGIProcessGroup securedash WSGIScriptAlias / /Users/user/icloud/projects/secureDash/secureDash/wsgi.py </VirtualHost> As a test to ensure that the path to my media was correct, I wrote a quick script and ran it in the python3 shell: MEDIA_ROOT = '/Users/user/Documents/temp/secureDash/' def walk_dir_tree(path, file_type): return[os.path.basename(x) for x in glob.glob(path + file_type, recursive=True)] all_thumb_files = sorted(walk_dir_tree( MEDIA_ROOT + 'thumbnails/**/*', '.jpg'), β¦ -
Doing a calculation while querying the database in Django
I want to obtain the objects of my Project model for whose ratio of the values in the two fields raised_amount and total_amount is less than 0.2. I have been trying this project_list = Project.objects.filter((raised_amount)/(total_amount)<0.2) I know this is the wrong way. Please help me do it the right way -
Calling a function in Django after saving a model
Context: I'm making a blog. This blog stores information on articles in a database via a Django model. I have a FileField in said model that takes an archive of all the assets that go with this file. I add articles through the admin site. I want to call a function that unpacks this file immediately after the the object is saved to the model. Where would I write this function?