Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
String indices must be integers - Django
I have a pretty big dictionary which looks like this: { 'startIndex': 1, 'username': 'myemail@gmail.com', 'items': [{ 'id': '67022006', 'name': 'Adopt-a-Hydrant', 'kind': 'analytics#accountSummary', 'webProperties': [{ 'id': 'UA-67522226-1', 'name': 'Adopt-a-Hydrant', 'websiteUrl': 'https://www.udemy.com/, 'internalWebPropertyId': '104343473', 'profiles': [{ 'id': '108333146', 'name': 'Adopt a Hydrant (Udemy)', 'type': 'WEB', 'kind': 'analytics#profileSummary' }, { 'id': '132099908', 'name': 'Unfiltered view', 'type': 'WEB', 'kind': 'analytics#profileSummary' }], 'level': 'STANDARD', 'kind': 'analytics#webPropertySummary' }] }, { 'id': '44222959', 'name': 'A223n', 'kind': 'analytics#accountSummary', And so on.... When I copy this dictionary on my Jupyter notebook and I run the exact same function I run on my django code it runs as expected, everything is literarily the same, in my django code I'm even printing the dictionary out then I copy it to the notebook and run it and I get what I'm expecting. Just for more info this is the function: google_profile = gp.google_profile # Get google_profile from DB print(google_profile) all_properties = [] for properties in google_profile['items']: all_properties.append(properties) site_selection=[] for single_property in all_properties: single_propery_name=single_property['name'] for single_view in single_property['webProperties'][0]['profiles']: single_view_id = single_view['id'] single_view_name = (single_view['name']) selections = single_propery_name + ' (View: '+single_view_name+' ID: '+single_view_id+')' site_selection.append(selections) print (site_selection) So my guess is that my notebook has some sort of json parser installed or something … -
Upload different files with identical filenames using boto3 and Django (and S3)
I am trying to create a Django server that stores media files on S3 where users can upload their own files that might all have the same filename but be different files. I have set up S3 and gotten it working via explicit python commands like import boto3 s3 = boto3.resource('s3') s3.Object('my-bucket','text.txt').put(Body=open('/text.txt', 'rb')) I am setting up my model like this: import boto3 s3 = boto3.resource('s3') class MyModel(models.Model): my_file = models.FileField() file_url = models.CharField(max_length=200, blank=True, null=True) In my views.py, my upload form is: import boto3 s3 = boto3.resource('s3') ... if form.is_valid(): # creates object from form but doesn't go into database mymodel = form.save(commit=False) uploaded_file = request.FILES['my_file'] s3.Object('my-bucket',uploaded_file.name).put(Body=request.FILES['uploaded_file']) mymodel.file_url = 'http://my-bucket.s3.amazonaws.com/' + uploaded_file.name; I would like users to be upload their own files that might all have the same filename but be different files. I can imagine generating an md5 string and then appending that to the file name, but then when people go to download their files they will have a random hash string appended to the end of the file. I assume there is a better, more elegant way to do this. Can anyone help? I have found guides like this but I don't understand them: http://boto3.readthedocs.io/en/latest/guide/s3.html#generating-presigned-urls -
Reverse for '###' with arguments '('',)' and keyword arguments '{}' not found
The error im having is relatively widely discussed. I went through all of the privious topics but no solution seems to apply. The error is: "Reverse for 'favorite' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'music/(?P[0-9]+)/favorite/$'] [15/Mar/2017 22:09:49] "GET /music/ HTTP/1.1" 500 119546" URL PATTERN app_name = 'music' urlpatterns = [ url(r'^(?P<album_id>[0-9]+)/favorite/$', views.favorite, name='favorite'), ] TEMPLATE: <form action="{% url 'music:favorite' album.id %}" method="POST"> VIEW: def favorite(request, album_id): As you can see, I created the namespace, but django is still unable to revers the url. Can it be related to be direcotory of the template? -
Wagtail ModelAdmin read only
Using Wagtails Modeladmin: Is there any way to disable edit & delete options leaving only the inspect view? A possible approach that I can think of, is extending the template, removing the edit & delete buttons and then somehow disable the edit and delete view. Is there any cleaner approach? -
Filter a "drop-down" django-form element based on a value selected before
Let's consider the following models models.py Class Brand(models.Model): company_name = models.CharField(max_length=100) class CarModel(models.Model): brand = models.ForeignKey(Brand) name = models.CharField(max_length=100) Class FleetCars(models.Model): model_car = models.Foreignkey(CarModel) What is the best way to solve this problem in django? Suppose a form (for insertions in FleetCars) consists of two select elements, like this: Image example Html here In this case, I want the options in the second depends on the value selected in the first, For example, if the user chose Brand1 for a Brand in the first select, the second select would be filtered with only cars whose Brand was Brand1, this is, only "Model1_B1". Obs. I saw many solutions with forms.ModelChoiceField, but only works with edit and since the user do not change the brand. -
In Django how to pass JSON data to use for Ajax / jQuery?
I'm trying to use JSON data in Django to provide user option to search and select. I can load and extend data to html but not sure how to use it in jQuery. My code works just fine if I link my jQuery to some website outside my server. I mean if I can link it like that: $.getJSON("http://meme.computer/stack/data.json", function(data) { My code is: views.py: from django.shortcuts import render from aceform.forms import RequestForm import json def index(request): form = RequestForm() data = open('data.json').read() jsonData = json.dumps(data) return render(request, 'aceform/base.html', {'form': form, 'jsonData': jsonData}) base.html: {% load staticfiles %} <!doctype html> <html> <head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $.getJSON("{{jsonData}}", function(data) { autoComplete = []; for (var i = 0, len = data.length; i < len; i++) { autoComplete.push(data[i].iata + ", " + data[i].name); } console.log(data); $( "#optionOne" ).autocomplete({ source: autoComplete, minLength: 3 }); $( "#optionTwo" ).autocomplete({ source: autoComplete, minLength: 3 }); }); }); </script> </head> <body> {% block content %} {{ form.as_p }} {% endblock content %} </body> </html> -
Django combine REMOTE_USER auth with LDAP checks
I recently got LDAP authentication working with the django-auth-ldap module. That got me thinking, since this is being run behind IIS in an Active Directory environment, that there should be a way to do single sign-on. It looks like using the RemoteUserMiddleware you can do single sign-on using the REMOTE_USER environment variable. But problem is I need to lock this down to a small handful of users in an AD group. I'm a Django n00b so I'm having trouble wraping my head around how I would glue the two system together in order to get the user from REMOTE_USER and then do an LDAP lookup to AD to check group membership. And Google is failing me. Has anyone done anything like this before? -
Error in charging a one-off payment in pinax-stripe module of django python
I am developing an application in python in django framework where I have to charge one-off payment from the customers. I am using pinax-stripe module for payments(https://github.com/pinax/pinax-stripe). When I charge the customer in my view like this: #views.py from pinax.stripe.models import * if customer.can_charge(): customer.charge(15.00) #charge It gives me the the following error: Exception Type: NameError Exception Value: name 'customer' is not defined I know there is something I need to import from pinax.stripe into my app's views.py. Does anyone know what is it? -
How make manage.py compress?
When I run the python command manage.py compress I get the following error An error occurred during rendering /dir/lis_person.html:compressor/js_file.html INSTALLED_APPS = ( "django_admin_bootstrapped", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "compressor", ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) COMPRESS_ENABLED = True COMPRESS_OFFLINE = True COMPRESS_PARSER = 'compressor.parser.BeautifulSoupParser' COMPRESS_CSS_FILTERS = ['compressor.filters.cssmin.CSSMinFilter'] COMPRESS_JS_FILTERS = ['compressor.filters.jsmin.JSMinFilter'] -
Django REST Framework pagination links do not use HTTPS
I'm setting up pagination for a certain DRF endpoint that works well- however when deployed on my server, which uses HTTPS, the links to the next & previous pages are formed with http:// instead of https://. This causes the requests for next/previous pages to be blocked by the browser. I've double checked that the initial request was issued, with HTTPS, and the 2nd answer to this question states that it should be using HTTPS in the formed URLs since the request came over HTTPS. The first answer to that same question didn't help either- I added the X-Forwarded-Proto line to my nginx config and reloaded, to no avail. The DRF docs mention that reverse() should behave as the base Django reverse, however it seems pretty clear that the initial request is HTTPS while the returned URL is HTTP. Here are a couple screenshots that show the initial request (https://<domain>.com/api/leaderboard/): With the response containing next: http://<domain>.com/api/leaderboard/?page=2): I figured this would be a simple setting, but haven't been able to find anything after searching both this site and the DRF site. This is my nginx configuration: location / { # proxy_pass http://127.0.0.1:9900; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; add_header … -
How to test wsgi.py django?
I'm a beginner on Python and I'm just starting to learn about Django and Coveralls. I have developed a web application with Django and submitted it to Coveralls. The problem is that Coveralls says that my wsgi.py is not being tested (0%), what is true. How can I test the wsgi.py? The content of my wsgi.py file: import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "resizeme.settings") application = get_wsgi_application() # Heroku - based on: https://djangogirls.gitbooks.io/django-girls-tutorial-extensions/heroku/ application = DjangoWhiteNoise(application) Thanks -
How can I get the Django admin to let me log in normally?
In Why is Django not filling out variable entries? , insight based on a comment helped me get past the main obstacle I was struggling with, of not being able to get to the admin login screen. However, after that was addressed, there was another other issue that was uncovered, issues that also related to the admin interface but don't seem to be immediately connected to the initially reported issue. Specifically: While I can submit the login form, I don't seem to really seem to be able to log in. Every time I've entered my credentials I've been redirected to a Django admin login page, with the URL varying somewhat. I know it's treacherously easy to mistype a long password, but when I was getting login failures I used copy-and-paste to assign the same password as I was trying to log into again. So while mistyping a password is an easy trap to get stuck in, I adapted by trying an approach where the reassigned user password is the same pasted password as in trying to log in. I tried manually entering the first and last character to eliminate the possibility of including unwanted whitespace, but it still doesn't work. … -
Static files not loading with Django. (Bootstrap not working)
I have read many posts about the topic and tried to follow all the suggestions (new to python here) but I am unable to get bootstrap to work in Django. I have a project "myoffice" and an app "proposals" in it. I have downloaded a css file and put it in following folder django\bin\myoffice\proposals\static\bootstrap\bootstrap.min.css I have made following changes to the settings.py STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATICFILES_DIRS = ( os.path.join( os.path.dirname(__file__), 'static', ) STATIC_URL = 'proposals/static/' and included static files in my template like this. <!DOCTYPE html> <html> <head> {% load staticfiles %} <link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet" media="screen"> </head> <body> But it is still showing view without any formatting. -
Is there built-in functionality in django to make inline editing (admin side) objects?
Editing objects of one model (not as shown in the example, inline that has relation to the other model)? I want the same as on the picture above but to edit the objects of one model, no related ones... Any suggestions, or I have to customise admin template? -
How to include related columns in Django without including all columns
Django's ORM has a method called select_related() for joining related tables. However, if the field included is a foreign key to another model, the default behavior seems to be to include all columns in the related model. For example, if I have the models: class A(models.Model): field1 = models.CharField(...) field2 = models.CharField(...) class B(models.Model): field1 = models.CharField(...) field2 = models.ForeignKey(A) print str(B.objects.all().select_related('field2').query)) outputs: SELECT myapp_b.id, myapp_b.field1, myapp_b.field2_id, myapp_a.id, myapp_a.field1, myapp_a.field2 FROM ... but I only want to include A.field1, not all fields from A, so I tried doing: print str(B.objects.all().select_related('b__field1').query)) but that outputs the exact same query. How do I stop Django from including all fields from a foreign-key field listed in select_related()? -
python - DRF Unable to post data passing a Primary Key
I'm starting to work with Django and I followed the tutorial available in the Django Rest Framework website and now I'm trying to adapt the tutorial to do something a little more complex. I'm trying to create a "Like" system for a Social Network. A User can create Posts (UserPosts) and Like other user's posts. I'm creating new UserPosts (using the command line) this way: http -a admin:Pass1234 POST http://127.0.0.1:8000/posts/ description="I'm just a random comment" And everything works just fine. The problem is when I try to create a Like instance. In this case I need to pass a UserPost id, so I'm doing the same as I did to create a new comment: http -a admin:Pass1234 POST http://127.0.0.1:8000/likes/ post="1" But when I do this I get the following error: "post": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got unicode." ] } The models are the following: class UserPost(models.Model): owner = models.ForeignKey('auth.User', related_name='posts', on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=100, blank=True, default='') def save(self, *args, **kwargs): options = self.description and {'description': self.description} or {} super(UserPost, self).save(*args, **kwargs) class Meta: ordering = ('timestamp',) class Like(models.Model): owner = models.ForeignKey('auth.User', related_name='likes', on_delete=models.CASCADE) post = models.ForeignKey(UserPost, related_name='likes', on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def … -
Facebook Share button with facebook javascript sdk in a django template for loop
I am having a little trouble getting this to work, I want to generate a facebook share button for each post on my website, but the way I have it set I only get a working share button for the first button instance and it only shares the very last post that is on the page, none of the other share buttons do anything. Relevant Code blog/post_list.html {% extends 'blog/base.html' %} {% load cloudinary %} {% block content %} <div id='posts'> {% for post in posts %} [...] <div id="shareBtn" class="btn btn-success clearfix">Share</div> <script> document.getElementById('shareBtn').onclick = function() { FB.ui({ method: 'share', display: 'popup', href: 'http://example.com:8000{{ post.get_absolute_url }}', }, function(response){}); } </script> {% endfor %} [...] {% endblock %} -
'OneToOneField' object has no attribute 'get' in function-based view
I am writing a two-part form where I want to pass the object saved in the first part as a OneToOneField for the object in the second part. In views.py: def object_entry(request): if request.method == 'POST': title_form = TitleEntry(request.POST) object_form = ObjectEntry(request.POST) if title_form.is_valid(): title = title_form.cleaned_data['title'] title_type = title_form.cleaned_data['title_type'] title_lang = title_form.cleaned_data['lang'] title_translation = title_form.cleaned_data['translation'] title_currency = title_form.cleaned_data['currency'] title_level = title_form.cleaned_data['level'] title_note = title_form.cleaned_data['note'] title_source = title_form.cleaned_data['source'] new_title = title_form.save() return new_title else: return render_to_response('objectinfo/objectregister_form.html', {'object_form': object_form, 'title_form': title_form}) if object_form.is_valid(): object_form.preferred_title = new_title snapshot = object_form.cleaned_data['snapshot'] work_type = object_form.cleaned_data['work_type'] source = object_form.cleaned_data['source'] brief_description = object_form.cleaned_data['brief_description'] description_source = object_form.cleaned_data['description_source'] comments = object_form.cleaned_data['comments'] distinguishing_features = object_form.cleaned_data['distinguishing_features'] new_object = object_form.save() reorg.AccessionNumber.generate(new_object.pk) return HttpResponseRedirect('/work/') # return HttpResponseRedirect(reverse(description_edit, args=(new_object.pk,))) else: return render_to_response('objectinfo/objectregister_form.html', {'object_form': object_form, 'title_form': title_form}) else: title_form = TitleEntry() object_form = ObjectEntry() return render(request, 'objectinfo/objectregister_form.html', {'object_form': object_form, 'title_form': title_form}) And in forms.py: class ObjectEntry(ModelForm): class Meta: model = ObjectRegister fields = ['snapshot', 'work_type', 'source', 'brief_description', 'description_source', 'comments', 'distinguishing_features', 'storage_unit', 'normal_unit'] class TitleEntry(ModelForm): class Meta: model = ObjectName fields = ['title', 'title_type', 'lang', 'translation', 'currency', 'level', 'note', 'source'] When submitting the form it returns the error 'ObjectName' object has no attribute 'get'. What would be the correct way to pass new_title as the … -
apply variable on views in the template
A part of my html code var marker; function initMap() { map = new google.maps.Map(document.getElementById("mymap"), myOptions); getMapMetadata([]); // setInterval(function(){ getMapMetadata([]); }, 3000); } function createMarker(latlng, label, html) { // alert("createMarker("+latlng+","+label+","+html+","+color+")"); var contentString = '<b>' + label + '</b><br>' + html; var image; image = 'static/img/30.png'; var marker = new google.maps.Marker({ position: latlng, map: map, icon: image, title: label, zIndex: Math.round(latlng.lat() * - 100000) << 5 }); marker.myname = label; google.maps.event.addListener(marker, 'click', function () { infowindow.setContent(contentString); infowindow.open(map, marker); }); return marker; } function getMapMetadata(ids) { $.get("{% url 'app01:cate' %}", {ids: []}, function (data, status) { console.log("Data: " + JSON.stringify(data) + "\nStatus: " + status); var metadata; var i; //for(var i=0; i<data.length; i++) metadata=JSON.parse(JSON.stringify(data)); for( i=0; i<metadata.length; i++) { console.log("item: " + metadata[i].x); marker=createMarker(new google.maps.LatL ng(metadata[i].x,metadata[i].y),metadata[i].id+"",JSON.stringify(metadata[i])); A part of views uavs = [Map.objects.get(pk=str(i)) for i in range(1, NUAVs+1)] A part of my html code var marker; function initMap() { map = new google.maps.Map(document.getElementById("mymap"), myOptions); getMapMetadata([]); // setInterval(function(){ getMapMetadata([]); }, 3000); } function createMarker(latlng, label, html) { // alert("createMarker("+latlng+","+label+","+html+","+color+")"); var contentString = '<b>' + label + '</b><br>' + html; var image; image = 'static/img/30.png'; var marker = new google.maps.Marker({ position: latlng, map: map, icon: image, title: label, zIndex: Math.round(latlng.lat() * - 100000) << … -
Save image from media_root to Django Rest Serializer
I am currently working on a project that allows mobile app user to upload images to a Django Server. Here is my view that serves the POST request from the user: class ImageDetailsViewSet(APIView): def post(self,request, *args, **kwargs): try: ######### Accept string from the user imgStr = request.data['image'] media_filename = os.path.join(settings.MEDIA_ROOT, 'img.jpg') ######## Create decoded string to a JPEG file and save it to media_root img = Image.open(StringIO(imgStr.decode('base64'))) img.save(media_filename, 'JPEG') ###### Update request data to include the newly created image to the request user = request.user.get_username() data1 = {'image': media_filename, 'category': 1, 'status': 'Y', 'user': user} serializer = ImageDetailsSerializer(data=data1) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) except: raise return Response(serializer.errors, status=status.HTTP_415_BAD_REQUEST) My ImageDetailsSerializer: class ImageDetailsSerializer(serializers.ModelSerializer): class Meta: model = ImageDetails fields= ('image','status','category', 'user') The code always returns an HTTP 400 error which means that the serializer is not valid. Here are the solutions I tried to apply but doesn't work in this case: Change the media_filename from data1 = {'image': media_filename, 'category': 1, 'status': 'Y', 'user': user} to img but it returns TypeError: <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2976x3968 at 0x841D2F0> is not JSON serializable error Replace media_filename to media_url/img.jpg, it returns the same error. Update image field in the serializer … -
Why am I getting "AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user' Request Method: GET"?
When I try to access the admin interface login page, I get: AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user' Request Method: GET I am running Django 1.10 and serving it up via Gunicorn. There were a bunch of search results, some of which related to changes between Django 1.8 and 1.9, or otherwise didn't change things. I have not yet successfully logged into the admin interface, and I have created a superuser and don't think I'm causing trouble by entering invalid credentials: the page errors out before I can even give my credentials. -
Getting error in mixins when I try to login as a user
I created an order page where customer can view all the orders that he have done in past but as I want the customer to login and view the orders So I created a loginrequiredmixin mixins.py from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from carts.models import Cart from .models import Order class LoginRequiredMixin(object): @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(LoginRequiredMixin, self).dispatch(request,*args, **kwargs) class CartOrderMixin(object): def get_order(self, *args, **kwargs): cart = self.get_cart() if cart is None: return None new_order_id = self.request.session.get("order_id") if new_order_id is None: new_order = Order.objects.create(cart=cart) self.request.session["order_id"] = new_order.id else: new_order = Order.objects.get(id=new_order_id) return new_order def get_cart(self, *args, **kwargs): cart_id = self.request.session.get("cart_id") if cart_id == None: return None cart = Cart.objects.get(id=cart_id) if cart.items.count() <= 0: return None return cart views.py from django.shortcuts import render from django.views.generic.edit import CreateView, FormView from django.views.generic.list import ListView # Create your views here. from .mixins import CartOrderMixin, LoginRequiredMixin from .models import UserCheckout, Order class OrderList(LoginRequiredMixin, ListView): queryset = Order.objects.all() def get_queryset(self): user_check_id = self.request.user.id user_checkout = UserCheckout.objects.get(id=user_check_id) return super(OrderList, self).get_queryset().filter(user=user_checkout) models.py from decimal import Decimal from django.conf import settings from django.db import models from django.db.models.signals import pre_save # Create your models here. from carts.models import Cart class UserCheckout(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, … -
Counting occurrences of a foreign key in a related queryset
I have a model Visit, which has a ForeignKey to a model Store. I have a filtered queryset of Visits, and I need to get the count of how many Stores occur at least twice in the given queryset of Visits. I know I can accomplish this with a loop, as so: store_at_least_twice = {} for visit in visit_queryset: # Set the value as False if this is the first time we've seen this store # True if we've seen it already store_at_least_twice[visit.store] = visit.store in store_at_least_twice.keys() # Return count of True values return sum(store_at_least_twice.values()) This gives me the result that I need, but it seems like there should be a way to do this without the overhead of iterating through every item in what could potentially be a long queryset. I have looked into using annotate or creating a Store queryset based on visit_queryset but haven't yet found a solution which works without a loop. -
Form is never valid
Im trying to create a website models.py from django.db import models from django.forms import ModelForm class Calculator(models.Model): parents = models.CharField(max_length=100, blank=False) jobs = models.CharField(max_length=100, blank=False) grants_bursaries_scholarships = models.CharField(max_length=100, blank=False) student_loan = models.CharField(max_length=100, blank=False) other_income = models.CharField(max_length=100, blank=False) rent = models.CharField(max_length=100, blank=False) travel = models.CharField(max_length=100, blank=False) bills = models.CharField(max_length=100, blank=False) other_outcome = models.CharField(max_length=100, blank=False) def total_income(parents, jobs, grants_bursaries_scholarships, student_loan, other_income): return self.parents + self.jobs + self.grants_bursaries_scholarships + self.student_loan + self.other_income def fixed_outcome(rent, travel, bills, other_outcome): return self.rent + self.travel + self.bills + self.other_outcome def variable_outcomes(total_income, fixed_outcome): return self.total_income - self.fixed_outcome def food(variable_outcomes): return (43.66 * variable_outcomes) / 100.0 def socialising(percent, whole): return (22.54 * variable_outcomes) / 100.0 forms.py from django import forms class MyCalculator(forms.Form): parents1 = forms.CharField(max_length=40, required=True) jobs1 = forms.CharField(max_length=50) grants_bursaries_scholarships1 = forms.CharField(max_length=40, required=True) student_loan1 = forms.CharField(max_length=40, required=True) other_income1 = forms.CharField(max_length=40, required=True) rent1 = forms.CharField(max_length=40, required=True) travel1 = forms.CharField(max_length=40, required=True) bills1 = forms.CharField(max_length=40, required=True) other_outcome1 = forms.CharField(max_length=40, required=True) views.py from django import forms from .forms import MyCalculator def formview(request): if request.method == 'POST': form = MyCalculator(request.POST) if form.is_valid(): myform = MyCalculator() myform.parents = form.cleaned_data.get(parents1) myform.jobs = form.cleaned_data.get(jobs1) myform.grants_bursaries_scholarships = form.cleaned_data.get(grants_bursaries_scholarships1) myform.student_loan = form.cleaned_data.get(student_loan1) myform.other_income = form.cleaned_data.get(other_income1) myform.rent = form.cleaned_data.get(rent1) myform.travel = form.cleaned_data.get(travel1) myform.bills = form.cleaned_data.get(bills1) myform.other_outcome = form.cleaned_data.get(other_outcome1) myform.total_income(myform.parents, myform.jobs, … -
Permission denied error in heroku django application
I got the error Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. while giving git push heroku master How can I solve this?