Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save to two models in one django form?
I currently have a working form for job tickets using django 2.0. I want to add the ability for multiple file uploads as supporting docs and assets. I can easily add this into the admin side of things using inlines, but how would I accomplish something similar on the front end of the site? I'm not sure how to have a form submit to two models when a key/id has yet to be set. I'm using primary keys to associate the files with the entries... models.py: class Job(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) ... class File(models.model) file = models.FileField(upload_to='uploads/%Y/%m') job = models.ForeignKey(Job, models.set_NULL, blank=True, null=True) admin.py class FileInline(admin.TabularInline): model = File extra = 0 @admin.register(Job) class JobAdmin(admin.ModelAdmin): exclude = ['ticket_number'] inlines = [FileInline] This system is great in my admin and in my templates, but I just can't figure out how to get these two to live in one form together. Is there a better way to be doing this? -
django can't reverse project level view?
I'm trying to redirect to a view after a successful POST. Not sure why it isn't working if I try to add a kwargs on it. I tried to reverse it without the extra parameters and it worked. but then when I add the additional variable which I need for some conditional statment, it cause an error. I already checked the docs, some of the issues that was raised here and namespace is the solution but as far as I understand, it's for the app level. I created the view under the project. project urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.Index_With_Email_Subscription, name="index"), path('humongousdata/', admin.site.urls), path('termsofservices/', views.Terms_Of_Services, name="termsofservices"), path('me/', include('me.urls')), path('thankyou/', views.ThankYou, name="givethanks"), ] project views.py from django.shortcuts import render, redirect from django.urls import reverse def index(request): return redirect(reverse('givethanks', kwargs={'thanks_for':'registered'})) def ThankYou(request, **kwargs): print(thanks_for) error message error screenshot -
Ajax search form django
Trying to create a search form similar to the one facebook and twitter use. Currently using ajax autocomplete function for this purpose. <div class="ui-widget"> <label for="search">Search for friends: </label> <input id="search"> </div> $(function() { $("#search").autocomplete({ source: "/accounts/ajax/search/", minLength: 2, select: function( event, ui ) }); }); Below is my view that processes my ajax request. def get_ajax_search(request): query = request.GET.get('term', '') print(query) if request.is_ajax(): qs1 = BasicUser.objects.filter(Q(first_name__icontains=query) | Q(last_name__icontains=query)) qs2 = MediaUser.objects.filter(Q(media_name__icontains=query)) results = [] for user in qs1: basic_user_json = {} basic_user_json['id'] = user.pk basic_user_json['label'] = user.first_name+" "+ user.last_name basic_user_json['value'] = user.first_name+" "+ user.last_name results.append(basic_user_json) for user in qs2: media_user_json = {} media_user_json['pk'] = user.pk media_user_json['label'] = user.media_name media_user_json['value'] = user.media_name results.append(media_user_json) data = json.dumps(results) print(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) Appreciate your help with a couple of questions: How can I redirect to a different page when selecting results. How can I display a user profile picture next to every search result Most importantly is there a better way of retrieving data from the database and sending it to the ajax function, assuming it's going to be a high load website. Any ideas or insights would be appreciated. -
How to write test for django FileBrowser - python
I used FileBrowser in my django project in one of models. class Person(models.Model): name = models.CharField(max_length=50) avatar = FileBrowseField( max_length=200, directory='avatars/', extensions=['.jpg', '.jpeg', '.png', '.gif'], ) I'm going to write test for it. but I don't know how to write. in it's documentation, it just said python manage.py test filebrowser I give it file path (str) and it raised following error: AttributeError: 'str' object has no attribute 'path' How can I write test for it? -
In Django tests, why do I need to use <Model>.objects.get() instead of what was returned by <Model>.objects.create()?
Although this is perhaps not a minimal example, I'm building on How to test an API endpoint with Django-rest-framework using Django-oauth-toolkit for authentication. I have a model Session which I'd like to be able to update using the Django REST framework. To this end I wrote the following view: from rest_framework import generics from oauth2_provider.contrib.rest_framework import OAuth2Authentication from ..models import Session from ..serializers import SessionSerializer class SessionDetail(generics.UpdateAPIView): authentication_classes = [OAuth2Authentication] queryset = Session.objects.all() serializer_class = SessionSerializer where the default permission_classes are set in settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } I've written the following test case: import json from django.contrib.auth.models import User from datetime import timedelta from django.urls import reverse from django.test import TestCase, Client from django.utils import timezone from rest_framework import status from ..models import Family, Session, SessionType, SessionCategory from oauth2_provider.models import get_application_model, get_access_token_model Application = get_application_model() AccessToken = get_access_token_model() class OAuth2TestCase(TestCase): def setUp(self): self.username = "test_user" self.password = "123456" self.user = User.objects.create_user(username=self.username, password=self.password) self.application = Application( name="Test Application", redirect_uris="http://localhost", user=self.user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) self.application.save() self.TOKEN = '1234567890' self.token = AccessToken.objects.create( user=self.user, token=self.TOKEN, application=self.application, scope='read write', expires=timezone.now() + timedelta(days=1) ) self._create_session() def _create_session(self): self.session_category = SessionCategory.objects.create( name='Birth Prep') self.session_type = SessionType.objects.create( title='Initial Postpartum Lactation', category=self.session_category) self.family = … -
How do I display only the non empty or non null fields from a django a model?
I have a model called Address and it has about 7 different fields. The corresponding form for this model is completely optional and the user may fill in either all 7 fields or just 1 field or none of the fields. There are no required fields here. Now, if the user has filled only the city and country field, how would I in my class method fetch only those fields and then display it properly in the template? This is the closest I've come to achieving what I want: class Address(models.Model): address_name = models.CharField(...) line1 = models.CharField(...) line2 = models.CharField(...) line3 = models.CharField(...) city = models.CharField(...) state = models.CharField(...) zipcode = models.CharField(...) country = models.CharField(...) def get_fields(self): values = [] for field in Address._meta.fields: if field.name in ('line1', 'line2', 'line3', 'city', 'state', 'postcode', 'country'): if field.value_to_string(self): values.append(field.value_to_string(self)) return values In my template: {% for field in address.get_fields %} {{field}}{% if not forloop.last %}, {% else %}.{% endif %} {% endfor %} Now this achieves almost what I want, but in one of the test cases, if only one field has been filled out (for ex: only country was filled), it prints: , US. How do I make it say only … -
Generate url for Django Simple History historical object
Given an model called Stuff, I want the url to a HistoricalStuff object. In other words, how does one implement get_historical_url in the below code snippet? stuff = Stuff.objects.first() stuff.pk -> 100 historical_stuff = stuff.history.first() # we want to get url for this historical_stuff.pk -> 1 get_historical_url(historical_stuff) -> /path/to/admin/stuff/100/history/1 Obviously the dumb solution would be to use a format string but I'd rather use urlresolvers -
How to use serializer in Rest Frame work
I'm really new at django rest framework .It's a very noob question but i'm not able to understand how does serializer work ? How do we send data to serializer and how do we get data from it. I'm trying to serialize my queryset as it is a list of dictionaries here is my views.py def get(self,request): z= int(request.GET.get('q','')) queryset=[] queryset.append(models.Cart.objects.filter(UserId=z).values('id')) k=[] for values in queryset: k.append(models.ProductsDiscription.objects.filter(id=values).values()) abc = serializers.NewSerializer(k,many=True) return JsonResponse({'pcartlist':((abc))}) if i dont use a serializer i get an error "k:queryset is not json serializable. so i tried to create a serializer for this error and still im getting the same error.i dont have any idea how to work with serializer serializers.py class NewSerializer(serializers.Serializer): product_id= serializers.IntegerField() k is the list of dictionries and i also dont know which field to use for that. i have tried reading and understanding from evry possible place but im unable to.so,please help me understand how serializers work ,if possible by giving a very simple example.it will be very helpful.Thank you -
How do I link to Django static assets from my JavaScript files?
I'm trying to load a specific file but failing due to the way Django manages relative paths. Here's the structure of my app: mysite |-- manage.py |-- mysite |-- __init__.py |-- settings.py |-- urls.py |-- wsgi.py |-- app |-- __init__.py |-- models.py |-- tests.py |-- views.py |-- static |-- JS |-- myScript.js |-- data |-- myData.geojson |-- templates |-- app |-- index.html In other words, pretty standard. The two key parts are that I load myScript.js in to my index.html like so: <script type='text/javascript' src="{% static '/JS/myScript.js' %}"></script> The issue is that, within myScript.js, I want to load in myData.geojson. This doesn't work: ... 'url': '/static/data/myData.geojson' ... nor does 'url': '{% static /data/myData.geojson %}' #this throws an error I just want a project setup where I can use relative path to do this: 'url': '../data/myData.geojson' Is that possible? My current settings are this: STATIC_URL = '/static/' STATIC_ROOT = '/var/www/mysite/static' -
Turn off django 2.0 admin responsive behavior
This behaviour is not friendly for me and my team, we need a full view. Is there a way to disable this: <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"> <link rel="stylesheet" type="text/css" href="/static/admin/css/responsive.css" /> -
insert an element into a list of dictionaries
I have declared an empty list and I want to append dictionaries through a for loop by using the extend() method, but I end with a list with the same content in all its positions (the same dictionary) This is the code: def get_tasks(self, actor, task_state): tasks = Task.objects.filter(actor=actor.id, state=task_state) tasks_to_return = [] task_data = {} for task in tasks: task_data['name'] = getattr(task, 'name') task_data['description'] = getattr(task, 'description') task_data['start_date'] = getattr(task, 'start_date') task_data['finish_date'] = getattr(task, 'finish_date') task_data['situation'] = task.get_situation() tasks_to_return.extend(task_data) return tasks_to_return If I change extend() for append(), the result is even worst. -
How to use hset with django-redis-cache?
I am new in django/redis and i'm starting to familiarize with heroku redis addon. However, i can only use set and get. When i'm trying to use other methods like hset , i get this error : 'RedisCache' object has no attribute cache.hset('key', 'value') How can i manage this ? -
relation "cms_urlconfrevision" does not exist
ProgrammingError at / relation "cms_urlconfrevision" does not exist LINE 1: ...sion"."id", "cms_urlconfrevision"."revision" FROM "cms_urlco... ^ Request Method: GET Request URL: http://192.168.99.100:8000/ Django Version: 1.8.18 Exception Type: ProgrammingError Exception Value: relation "cms_urlconfrevision" does not exist LINE 1: ...sion"."id", "cms_urlconfrevision"."revision" FROM "cms_urlco... ^ Exception Location: /virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py in execute, line 64 Python Executable: /virtualenv/bin/python Python Version: 3.5.2 Python Path: ['/app', '/virtualenv/lib/python35.zip', '/virtualenv/lib/python3.5', '/virtualenv/lib/python3.5/plat-linux', '/virtualenv/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5', '/usr/local/lib/python3.5/plat-linux', '/virtualenv/lib/python3.5/site-packages'] Server time: Wed, 31 Jan 2018 14:38:53 -0600 I am using Divio when I click on open local site icon the browser shows the above error Thanks -
querying in django multiselectcheckbox
from django.db import models from multiselectfield import MultiSelectField from django.core.urlresolvers import reverse SEX_CHOICES = ( ('MALE', 'Male'), ('FEMALE', 'Female'), ) BRANCH_CHOICES = ( ('CSE', 'B.Tech CSE'), ('IT', 'B.Tech IT'), ('ECE', 'B.Tech ECE'), ('ME', 'B.Tech ME'), ('BBA', 'BBA'), ('BCA', 'BCA'), ('BCOM', 'B.Com'), ('MBA', 'MBA'), ) SEMESTER_CHOICES = ( ('SEM2', 'Sem 2nd'), ('SEM4', 'Sem 4th'), ('SEM6', 'Sem 6th'), ('SEM8', 'Sem 8th'), ) TRACK_EVENTS_CHOICES = ( ('100M', '100 Meter'), ('200M', '200 Meter'), ('400M', '400 Meter'), ('800M', '800 Meter'), ('1500M', '1500 Meter'), ('5000M', '5000 Meter'), ) FIELD_EVENTS_CHOICES = ( ('JAVELINE', 'Javeline Throw'), ('DISCUS', 'Discus Throw'), ('SHOTPUT', 'Shotput Throw'), ('HIGH', 'High Jump'), ('LONG', 'Long Jump'), ('TRIPLE', 'Triple Jump'), ) class Particiepents(models.Model): roll_no = models.IntegerField() Full_name = models.CharField(max_length=40) father_name = models.CharField(max_length=40) sex = models.CharField(max_length=10, choices=SEX_CHOICES) branch = models.CharField(max_length=20, choices=BRANCH_CHOICES) semester = models.CharField(max_length=10, choices=SEMESTER_CHOICES) track_events = MultiSelectField(max_length=30, null=True, blank=True, choices=TRACK_EVENTS_CHOICES, default="track_events") field_events = MultiSelectField(max_length=30, null=True, blank=True, choices=FIELD_EVENTS_CHOICES, default="track_events") def __str__(self): return self.Full_name This is my model.py, I want to retrieve individual lists of Full_name participating in different track_events(100m, 200m, 300m, 400m....). I am not able to set query in views.py. I want to create a query_set such that i can retrieve list of full_name participating in any event as query_set.Full_name -
map/import data from spreadsheet in django models for a particicular field
I have a django model in which i have my data- class School(): school = models.CharField(blank=True, null=True) contact = models.CharField(blank=True, null=True) roll_no = models.CharField(blank=True, null=True) parking_no = models.CharField(blank=True, null=True) The parking_no does not have any data, I have an excel (spreadsheet) document(.xlsx) from which i want to map my django models and wants to import the entry of parking_no only. (models already have other data) The excel document have the data like follow- SCHOOL ROLLNO PARKING_NO sch1 u101 p101 sch2 u102 p102 The roll_no is unique in my django models and excel document, based on the roll_no, How can I map / import to fill the parking_no alone in my models. Any help would be appriciated. -
Getting Null Value vilates integrity error when registering user or trying to migrate
Recently migrated database to RDS. Using django 2.0 Now when I try to register a user I get a: ProgrammingError at /accounts/register/ relation "auth_user" does not exist LINE 1: SELECT (1) AS "a" FROM "auth_user" WHERE "auth_user"."userna... ^ If I try to manage.py migrate I get the following response: (boxtrucks-Dleh71wm) bash-3.2$ python manage.py migrate Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, saferdb, sessions Running migrations: Applying accounts.0002_auto_20180131_0135...Traceback (most recent call last): File "/Users/Dev/.local/share/virtualenvs/boxtrucks-Dleh71wm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, accounts, 0002_auto_20180131_0135, 2018-01-31 20:01:35.801905+00). The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/Dev/.local/share/virtualenvs/boxtrucks-Dleh71wm/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() return self.cursor.execute(sql, params) File "/Users/Dev/.local/share/virtualenvs/boxtrucks-Dleh71wm/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/Dev/.local/share/virtualenvs/boxtrucks-Dleh71wm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, accounts, 0002_auto_20180131_0135, 2018-01-31 20:01:35.801905+00). -
Django: confused by manytomany relationship
I have been trying figure out the working of pre_fetch and manytomany relationship. It is confusing for me. I don't get it. I have these models: class Clinic(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=200) class Doctor(models.Model): name = models.CharField(max_length=100) clinics = models.ManyToManyField(Clinic, through='ClinicDoctor', related_name='doctors') patients = models.ManyToManyField('Patient', through='DoctorPatientAppointment', related_name='doctors_appointment') class ClinicDoctor(models.Model): doctor = models.ForeignKey(Doctor, related_name='doctorsF') clinic = models.ForeignKey(Clinic, related_name='clinicsF') class Patient(models.Model): name = models.CharField(max_length=100) mobile = models.CharField(max_length=20) class DoctorPatientAppointment(models.Model): patient = models.ForeignKey(Patient, related_name='patient_appointments') doctor = models.ForeignKey(Doctor, related_name='doctor_appointments') clinic = models.ForeignKey(Clinic, related_name='clinic_appointments') I went through the documentation and many SO quetions/answers. Also, searched Google. But I think I am not getting it how should I do this. Here is what I want to achieve. I want to find Patients that have a given mobile number and then I want to get which doctors and clinics they have appointments with. I tried many solutions found on SO. It is not working. Doc = Doctor.objects.all().prefetch_related('patients','clinics') for doc in Doc: docString = ..... for pat in doc.patients.filter(mobile=12345): patientString = ..... for cli in doc.clinics.all(): clinicString = ..... I feel this is not right. I tried few other ways as well. I don't even remember what I have tried all day from the internet. All … -
QuerySets after login using simple login form doesn't display
I have such a small problem. I created a model that displays posts. Everything is ok when I go to index.html Then I created a simple login form from the AuthUser module and the login runs without any problem directing me to the destination page. And here the stairs start because: - After logging in through the admin panel as admin, I can manage the content and display it in html correctly - If I login as an admin via the login form, he does not show me my posts anymore Where can the problem lie? Unfortunately, now I can not paste the code because I write on the mobile -
does debug level INFO also show error too? django
I have such LOGGING setup for my django, but I realized using DEBUG level, it shows TOO much especially the template variableDoesNotExist debug is quite annoying. I have this as my current setup LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple_time': { # simple_time, that just outputs the log level name (e.g., DEBUG) plus time and the log message. 'format': '%(levelname)s %(asctime)s %(message)s' }, }, 'handlers': { 'debug_file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR) + '/debug.log', 'formatter': 'simple_time' }, }, 'loggers': { 'django': { 'handlers': ['debug_file'], 'level': 'DEBUG', 'propagate': True, }, }, } I am wondering if I change the level to INFO will it just show INFO and not show ERROR level if any? Else, is it possible to split different levels into different files? I tried something like this, but not sure if it'll work properly 'handlers': { 'debug_file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR) + '/debug.log', 'formatter': 'simple_time' }, 'info_file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR) + '/info.log', 'formatter': 'simple_time' }, }, 'loggers': { 'django_debug': { 'handlers': ['debug_file'], 'level': 'DEBUG', 'propagate': True, }, 'django_info': { 'handlers': ['info_file'], 'level': 'INFO', 'propagate': True, }, }, Thanks in advance for any suggestions -
Plus Minus Buttons in Django app
I'm new to Django and my first assignment is to create a model which is Inventory based. So far I have created a login page, after logging I am redirected to home page which is a basic template printing the Name, Code and Stocks left. I need to create two working buttons(+ and -) which increment and decrement the stocks left on my home page which update the values of my Model too. I have made it through JS but I can't seem to find my way around with Django! My app's models.py: from django.db import models import uuid class Inventory(models.Model): """ Model representing a the inventory. """ id = models.UUIDField(primary_key=True, default=uuid.uuid4) inventory_name = models.CharField("INVENTORY NAME" ,max_length=200, help_text="This contains the Inventory name:") short_name = models.CharField(max_length=20, help_text="This contains an abbreviation:") inventory_code = models.IntegerField("INVENTORY CODE" ,default = '0', help_text="This contains the Inventory code:") price = models.IntegerField(default = '0') stocks_left = models.IntegerField("STOCKS LEFT",default = '0') def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return '{0} ({1}) ({2})'.format(self.inventory_name,self.inventory_code,self.stocks_left) My app's views.py : from django.shortcuts import render from django.contrib import auth from django.views import generic from myapp.models import Inventory def home(request): names = Inventory.objects.all() return render(request, 'myapp/home.html', { "names": … -
Django AJAX to keep single element static
I have a site with a ticker bar at the top that is fetching JSON from my server based on stations current status (running, off etc). This part of the site needs to be in my base.html file, and I need it to last everywhere in the site. Im using AJAX to fetch the JSON, however when I switch to another page it resets unless I use AJAX for literally all of my links and pages. I feel like I am going about this wrong and really would like some input on how to better manage this. This green tiles in the top of the image below is the ticker im talking about, they change every 10 seconds and the data is constantly changing. Is there a better way to keep this in my base.html and not have it reload when switching template views? Example Page -
Django dynamic model for existing table "doesn't exist"
I'm trying to take data from an existing MySQL table and place it into a model using the code from this solution: def getModel(table_name): class MyClassMetaclass(models.base.ModelBase): def __new__(cls, name, bases, attrs): name += table_name return models.base.ModelBase.__new__(cls, name, bases, attrs) class MyClass(models.Model): __metaclass__ = MyClassMetaclass time_stamp = models.DateTimeField(db_column='Time_stamp', blank=True, null=True) # Field name made lowercase. price = models.DecimalField(db_column='Price', max_digits=8, decimal_places=3, blank=True, null=True) # Field name made lowercase. class Meta: db_table = table_name managed = False return MyClass I then call the class as follows: MyModel = getModel('test_table') MyModel._meta.db_table = 'test_table' and pass it into a DataPool (to create a chart using Django's Chartit): pricedata = \ DataPool( series= [{'options': { 'source': MyModel.objects.all()}, 'terms': [ 'time_stamp', 'price']} ]) At this point it throws an error (1146, "Table 'meowdb.test_table' doesn't exist"). Note that meowdb is the database name. Should it be prepending this? I also don't actively pass the database into the model anywhere. According to this, it seems like once the model is created Django automatically links it based on the name? Lastly, how do I get around this error? The table most certainly exists and is populated with many rows. -
wagtail 2.0 beta 'wagtaildocuments.Document' has not been loaded yet
I have installed the beta version of wagtail 2. Below is a code snippet from my project. When I try to makemigrations I get an error saying: ValueError: Cannot create form field for 'link_document' yet, because its related model 'wagtaildocuments.Document' has not been loaded yet class LinkFields(models.Model): link_document = models.ForeignKey( 'wagtaildocuments.Document', null=True, blank=True, related_name='+', on_delete=models.SET_NULL, ) @property def link(self): return self.link_document.url panels = [ DocumentChooserPanel('link_document'), ] class Meta: abstract = True class CarouselItem(LinkFields): embed_url = models.URLField("Embed URL", blank=True) caption = models.CharField(max_length=255, blank=True) panels = [ FieldPanel('embed_url'), FieldPanel('caption'), MultiFieldPanel(LinkFields.panels, "Link"), ] class Meta: abstract = True I am using Django 2, Python 3.6, Wagtail 2.0b1 -
How do I make django secrets available inside docker containers
My Environment docker 17.12-ce python 3.6.3 django 1.10.8 I have a django application that I want to containerise. Trying to maintain best practice I have followed the advice to split the settings.py file into a base file and then a file per stage so my base.py file where it loads the secret settings looks like this # Settings imported from a json file with open(os.environ.get('SECRET_CONFIG')) as f: configs = json.loads(f.read()) def get_secret(setting, configs=configs): try: val = configs[setting] if val == 'True': val = True elif val == 'False': val = False return val except KeyError: error_msg = "ImproperlyConfigured: Set {0} environment variable".format(setting) raise ImproperlyConfigured(error_msg) And it gets the file path from the SECRET_CONFIG environment variable. This works well when running the application locally without docker. I have created a dockerfile that uses the python3 onbuild image. My Dockerfile looks like this # Dockerfile # FROM directive instructing base image to build upon FROM python:3.6.4-onbuild MAINTAINER Lance Haig RUN mkdir media static logs VOLUME ["$WORKDIR/logs/"] # COPY startup script into known file location in container COPY docker-entrypoint.sh /docker-entrypoint.sh # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 # CMD specifcies the command to execute to start the server running. … -
Making calculator in html with django and python
I have two text box on my HTML page and now for example i want to type 2 numbers in two different boxes and now i have a button calculate. For example i want to add those two numbers and redirect the result to the third page called "result.html". My question is how should i get those 2 numbers from HTML text box and make them add together and proced to the result.html page with the result.