Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have a model with M2M rel's to Attr and Corr. How do I pull in Attr and Corr values in a django?
I have a model (Person) with two M2M relationships to two other models; Attr and Corr. I have a graph that needs values from each of the Attr's and Corr's associated with each Person. A Person will usually have two Attr's and one Corr. I know can ref the attr values with ... {{ attr.value_i_need }} ... but I don't know how to specifically address them. I need them to be assigned to variables in javascript -- attr1 and attr2 (and so on through attr(i), attr(i+1)). I'm thinking some sort of construct that loops through the attr.values and for each value assigns a value of attr[i]. Would it be better to use js/django to loop through the values of person.attr.value or is there a way to directly reference the values given a pk? As I'm typing this, I'm thinking js/django mix is the way to go. -
Datetime error querying sqlserver database via django-mssql
I am using django-mssql to query a sqlserver database: querying a datetime value, I get 'Conversion failed when converting date and/or time from character string.' results = Sales.objects.using('eql').filter(saledate__year=2017) len(results) where 'saledate' is a datetime value - has anyone else experienced this? (and have a workaround?) -
How can I completely uninstall wagtail from my system?
I ran this command: pip uninstall wagtail Uninstalling wagtail: Proceed (y/n)? y Successfully uninstalled wagtail However when I then ran pip install wagtail i received the following message: root@daap:/usr/lib/python2.7# pip install wagtail Requirement already satisfied (use --upgrade to upgrade): wagtail in /usr/local/lib/python2.7/dist-packages Requirement already satisfied (use --upgrade to upgrade): Django<1.11,>=1.8.1 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): django-modelcluster<4.0,>=3.0 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): django-taggit<1.0,>=0.20 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): django-treebeard<5.0,>=3.0 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): djangorestframework>=3.1.3 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): Pillow>=2.6.1 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): beautifulsoup4>=4.5.1 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): html5lib<1,>=0.999 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): Unidecode>=0.04.14 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): Willow<0.5,>=0.4 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): requests<3.0,>=2.11.1 in /usr/local/lib/python2.7/dist-packages (from wagtail) Requirement already satisfied (use --upgrade to upgrade): pytz>=2015.2 in /usr/local/lib/python2.7/dist-packages (from django-modelcluster<4.0,>=3.0->wagtail) Requirement already satisfied (use --upgrade to upgrade): six in /usr/local/lib/python2.7/dist-packages (from html5lib<1,>=0.999->wagtail) Cleaning up... … -
using django-filer, "Must be a 'image' instance"
Im working with filer on a project, i have a big sized docuemnts with data in and a file with images that relate to the data. Now i needed to get all this on my system and some how connet them together. I am using import-export to uplaod the data. So i am thinking of using the filer import script to mass uplaod the images into a folder. But then how do i relate the record to the image without using the filer GUI in the admin system, if i did use that is would mean me going through every record and adding a image one by one. When i do try and uplaod anything into the image column i get the error shown below in the image. How can i get round this issue? -
Django select field without defining choices
How do I create a form select field in Django without defining the choices in it? I'm using {{ myform.field }}. Usual form select fields are defined in models as follows: CHOICE_1 = "choice1" CHOICE_2 = "choice2" MY_CHOICES = ( (CHOICE_1 = "1"), (CHOICE_2 = "2"), ) field = models.CharField(max_length=20, choices=MY_CHOICES, defaults="1") But I don't want to define my choices here, I want to add them in jQuery because the value list depends on the contents of another field. And I want this to change dynamically. 1) How do I get my template tag {{ myform.field }} to render as a select without choices? 2) If you define your choice list, will django allow you to save other values that aren't in the list or will this raise a validation error? This way I can use a 'default' choice list that I change later. -
Django: Query which excludes all children if the parent is included in the query
class Person(TimeStampedModel): name = models.CharField(max_length=32) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') is_child = models.BooleanField(default=False,) I am trying to form a query which excludes all children if their parent is present. Children, represent a 30% of the model's entries -for the time being- in my PostgreSQL. My approach would be to use a nested query. However, I am not sure that it would be the most efficient solution. I would appreciate your help. -
python double foreign key
First question posted on stackoverflow :) I'm a beginner on Django and a bit more advanced on Python. I'm completely amazed by Django and I've been playing with it for something like a week now. I looked into a lot of tutorials and stackoverflow questions/answers and discovered a lot. However, I'm still a little bit lost when it comes to OneToMany / Foreign Key relationships and the way to access it. I had a look at the "Library/Book" example of the official documentation but still trying to figure out how to solve the below problem. [Explanations] I have Users (already created) To the Django-built Users, I added a Profile (OneToOneField) The Profile contains only one item for each User: a title (Foreign Key) The Title in turn comes from a existing list of available Titles Finally, I have Opportunities (a class) which has one User linked (Foreign Key) in models.py class ProfileStatus(models.Model): """ table of available titles for users """ status = models.CharField(max_length=100) def __str__(self): return self.status class Profile(models.Model): """ add a title to an existing user """ user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.ForeignKey(ProfileStatus, on_delete=models.CASCADE) class OpportunityStatus(models.Model): """ status for an opportunity """ status = models.CharField(max_length=100) def __str__(self): return … -
Updating JSONField default in Django value for all records
While using JSONField with Django and Postgres, Im setting a default value as such { "custom_value_a": "foo", "custom_value_b": "bar" } Consider that after a period of time I want to change the default value of the field by adding another key into it "custom_value_c": "oof" One way of doing this would be to run a script which iterates through all the records and updates the JSONField to include the key:value in all of the records in the DB. Is there any other method to update the it via the Django ORM. -
Python is there a way to read custom headers and send a response back
Ok so I am new to python as a whole. That said I don't know what I'm really looking for to ask this question properly. I know this has to be possible though. I want to ask this before really digging in and finding out I did something wrong and have to do it all over. All in all what I want to know is, from the front end of my stack I want to pass down custom HTTP headers (which I can do with my Ajax calls, currently). The question is how do I actually read said headers? Similarly how can I pass back up from the server custom headers via python. -
Failed to load resource: the server responded with a status of 504 (Gateway Timeout)
I am developing a project using django - python, javascript. When I call a long running process (time-consuming) approx more than 20 minutes from views the process starts successfully. I used loader in ajax to notify user that process is running. After the process completes the loader will stop and change to completed state. But the issue is every time after 14.59 minutes from process started, the loader stops and status change to completed. But the process running in background is not yet completed. The page crash after that time. After the process complete I bind the result under a tag in web page. In that tag the error 504 (Gateway Timeout) arise. I web console log Failed to load resource: the server responded with a status of 504 (Gateway Timeout), the above error prints. If anyone knows please help me to fix this. Is the django is closing the connection after that time ? If so is there possible to mention timeout in django settings (settings.py). I tried giving timeout in ajax call but the same issue returns. My doubt is on django development server. Is there timeout in django development server. But when I search for this issue … -
How can I change the python path my django app is using to run with when I launch it with uWSGI
I have recently installed modules inside my virtualenv for my django project. When I run PIP freeze inside or outside of the virtualenv the modules show as being installed. If I run python, I can import the modules fine. However when I launch uWSGI to run my app, using the following command: uwsgi --chdir=/opt/django/src --module=core.wsgi:application --env DJANGO_SETTINGS_MODULE=core.settings --master --pidfile=/tmp/daap.pid --socket=/opt/django/core.sock --processes=5 --uid=www-data --gid=www-data --harakiri=20 --max-requests=5000 --vacuum --home=/opt/django/env --daemonize=/var/log/uwsgi/daap.log I receive the following error: ** Operational MODE: preforking *** Traceback (most recent call last): File "./core/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/django/env/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup() File "/opt/django/env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/django/env/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/opt/django/env/lib/python2.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named wagtail unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode *** Which states that ImportError: No module named wagtail The problem appears to be that python is being called from here /usr/lib/python2.7/ at some point in the execution of the program. I don't want … -
Trouble deploying Django application on Ubuntu server
So I've managed to setup my django project on my server by following this tutorial. I am able to run it on port 8000 by doing python manage.py runserver But I now want to deploy it to the server's domain name or IP address without specifying a port. After configuring 000-default.conf as instructed on the tutorial I get a 500 Internal Server Error error.log: [Tue Mar 28 12:34:29.006570 2017] [wsgi:error] [pid 12773:tid 140065216325376] [remote 31.49.113.30:62072] mod_wsgi (pid=12773): Target WSGI script '/home/ubuntu/myproject/myproject/wsgi.py' cannot be loaded as Python module. [Tue Mar 28 12:34:29.006623 2017] [wsgi:error] [pid 12773:tid 140065216325376] [remote 31.49.113.30:62072] mod_wsgi (pid=12773): Exception occurred processing WSGI script '/home/ubuntu/myproject/myproject/wsgi.py'. [Tue Mar 28 12:34:29.006695 2017] [wsgi:error] [pid 12773:tid 140065216325376] [remote 31.49.113.30:62072] Traceback (most recent call last): [Tue Mar 28 12:34:29.006714 2017] [wsgi:error] [pid 12773:tid 140065216325376] [remote 31.49.113.30:62072] File "/home/ubuntu/myproject/myproject/wsgi.py", line 12, in <module> [Tue Mar 28 12:34:29.006718 2017] [wsgi:error] [pid 12773:tid 140065216325376] [remote 31.49.113.30:62072] from django.core.wsgi import get_wsgi_application [Tue Mar 28 12:34:29.006733 2017] [wsgi:error] [pid 12773:tid 140065216325376] [remote 31.49.113.30:62072] ImportError: No module named 'django' I'm new to Django and Ubuntu so I don't really understand the error, any help would be much appreciated, thanks -
ImportError: No module named django_baker
I have installed django-baker from pip by sudo pip install django-baker. on macOS .The module can be found in /Library/Python/2.7/site-packages,but I am not able to import this package.I have tried sudo chmod -R go+rX /Library/Python/2.7/site-packages,but with no effect.Is there something wrong with path or the installation? -
Implement mercadopago in Django 1.10
I'm working on a shopping cart with Django 1.10 and I need to receive payments from Mercadopago. I was looking for help in their developer section but I'm too new even in Django and I can't figure it out how to use it. Do someone used this before and can help me with this? If you found some guide explained with more details about it? Sorry if I'm asking too much but I look for this topic in Google in so many ways and found nothing . Thanks in advance. -
Django inheritance: specify foreign key name
I'm new to the Django world, and am using Django REST Framework, but I don't think this is relevant to my problem. I designed my database by hand and prefer not to use Django migrations to generate it. I have as a convention to use the name tablename_id as a foreign key. My problem is that when I want to use inheritance, Django tries to use the name parenttablename_ptr_id instead of parenttablename_id. Is there a way to specify this ? Here is some fake code showing wanted result: class A(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) class B(A): # some other stuff # a_id as a foreign key to A, instead of a_ptr_id I hope this was clear, I couldn't find an answer elsewhere. Thank you in advance for your response ! -
Accessing remote repository using AJAX
I would like to access a remote repository's JSON data using AJAX. But the call must match the payload given here. Payload match Would that be possible, if so, what would be the most efficient way to carry this out? -
How to create virtual env with python3
I am using python 2.7 + virtualenv version 1.10.1 for running myproject projects. Due to some other projects requirement I have to work with other version of python(Python 3.5) and Django 1.9. For this I have installed python in my user directory. Also I have dowloaded and installed virtualenv( version - 15.1.0) into my user directory. But whenever I am trying to create virtual env I am getting the below error python virtualenv/virtualenv.py myproject Using base prefix '/home/myuser/python3' New python executable in /home/mount/myuser/project_python3/myproject/bin/python ERROR: The executable /home/mount/myuser/project_python3/myproject/bin/python is not functioning ERROR: It thinks sys.prefix is '/home/myuser/python3' (should be '/home/mount/myuser/project_python3/myproject') ERROR: virtualenv is not compatible with this system or executable Can anybody tell what I am doing wrong with this -
post contact for specific rent in rest framework
I am developing a rental application to get practice into rest framework. There is a feature where buyer can contact rent owner by clicking contact button on the rent where he has to then fill his/her email_id etc. I know if i want to contact specific rent then i have to do something like this rent = Rental.objects.get(id=token) contact.objects.create(rent=rent, email_id=email_id, buyer=request.user) I am confuse in rest framework create function of serializer and post function of APIView. Can anyone enlighten me with my example? class Rental(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=300, blank=False, null=False) phone_number = models.PositiveIntegerField(null=False, blank=False) class Contact(models.Model): buyer = models.ForeignKey(User) rental = models.ForeignKey(Rental, related_name="rent") email_id = models.EmailField(blank=False, null=False) class RentalSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') galleries = GallerySerializer(many=True) class Meta: model = Rental fields = ('__all__') class ContactSerializer(serializers.ModelSerializer): # buyer = UserSerializer(many=True) # rent = RentalSerializer(many=True) class Meta: model = Contact fields = '__all__' class ContactedRent(APIView): serializer_class = ContactSerializer def get(self, request, token=None, format=None): """ Returns a list of contactedRent """ reply = {} try: contacted_rent = Contact.objects.filter(buyer_id=request.user.id) if token: specific_contacted_rent = contacted_rent.get(rental__id=token) reply['data'] = self.serializer_class(specific_contacted_rent).data else: print ('no token') reply['data'] = self.serializer_class(contacted_rent, many=True).data except Contact.DoesNotExist: return error.RequestedResourceNotFound().as_response() except: return error.UnknownError().as_response() else: return Response(reply, status.HTTP_200_OK) def post(self, request, token=None, format=None): … -
AttributeError: 'tuple' object has no attribute 'rsplit in django [on hold]
File "prototypes.py", line 39, in <module> execute_from_command_line(sys.argv) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/leo/Desktop/prototypes/sitebuilder/management/commands/build.py", line 41, in handle call_command('collectstatic',interactive=False,clear=True,verbosity=0) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 130, in call_command return command.execute(*args, **defaults) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle collected = self.collect() File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 106, in collect self.clear_dir('') File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 227, in clear_dir if not self.storage.exists(path): File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/utils/functional.py", line 234, in inner self._setup() File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 406, in _setup self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/files/storage.py", line 469, in get_storage_class return import_string(import_path or settings.DEFAULT_FILE_STORAGE) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/utils/module_loading.py", line 15, in import_string module_path, class_name = dotted_path.rsplit('.', 1) AttributeError: 'tuple' object has no attribute 'rsplit' when i run python prototypes.py build i got this question . import os import sys from django.conf import settings BASE_DIR = os.path.dirname(__file__) settings.configure( DEBUG=True, SECRET_KEY='plasq@qb+&t-@=x56@=ss=+y-4kp*hj1wy5p!+$cinzhnd+erb', ROOT_URLCONF='sitebuilder.urls', MIDDLEWARE_CLASSES=(), INSTALLED_APPS=( 'django.contrib.staticfiles', 'sitebuilder', 'compressor', ), TEMPLATES=( { 'BACKEND':'django.template.backends.django.DjangoTemplates', 'DIRS':[], 'APP_DIRS':True, }, ), STATIC_URL='/static/', SITE_PAGES_DIRECTORY=os.path.join( BASE_DIR,'pages'), SITE_OUTPUT_DIRECTORY=os.path.join( BASE_DIR,'_build'), STATIC_ROOT=os.path.join( BASE_DIR,'_build','static'), STATICFILES_STORAGE=( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) ) if __name__=="__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) and this is my setting. I don't … -
How to logout in django?
html code {% if request.user %} <a href="{% url 'main:logout' %}"> Выход </a> {% else %} <a href="{% url 'main:registration' %}"> Регистрация </a> {% endif%} settings.py LOGIN_REDIRECT_URL = 'main/index' views.py def logout(request): logout(request) urls.py from django.conf.urls import url from . import views from django.conf import settings urlpatterns = [ url(r'^logout/$', views.logout, {'next_page': settings.LOGOUT_REDIRECT_URL}, name='logout') ] what's wrong? -
NoCredentialsError : Unable to locate credentials - django module boto3
I am running django in a python virtual environment(virtualenv). The django website is served by apache2 from an amazon ec2 instance(ubuntu 16.04). I use boto3 module to write to amazon s3. I installed awscli and ran aws configure and set up my aws access keys correctly. ( I know I configured it correctly, because $ aws s3 ls returns the correct lists of my s3 buckets.) However, when I try to write some objects to s3 from django application, it fails producing the error as described in the title. I recently moved to a new instance and started using python virtual environments. Before that, it used to work fine. I have read the questions on SO and the docs from aws. Below is the stack trace. Environment: Request Method: POST Request URL: http://*******/product/4 Django Version: 1.10.6 Python Version: 3.5.2 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'abc.apps.abcdirectConfig') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback: File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/.virtualenv/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, … -
Django's 'NoneType' object has no attribute 'has_header' [on hold]
I'm facing this problem from yesterday, and it is slapping me so hard I just don't understand why. And also been searching, but with the only good response being that response is None (obvious). The problem is this: I go to a model admin's add view, fullfill the data, and save it. The object is saved onto the DB. The HttpResponseRedirect fails to be generated for some reason I don't get to understand, so as Django cannot wrap the response to automatically add non-cache header (add_never_cache_headers, I cannot find right now the part of the docs that talked about it) an exception is raised. This happens every time I want to insert a new record, no matter which is it. I've manually looked the functions that are called, setting some raises here 'n there, but I just get no clue about why Django isn't generating a response. I also do not have code in any place that could be modifying this behaviour. Anyone had this issue before? Traceback: File "/home/.virtualenvs/my_project/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/.virtualenvs/my_project/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/.virtualenvs/my_project/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper 541. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/.virtualenvs/my_project/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. … -
how to give filtered annotate value to html table in python django
This is my actual code view.py: def report_static_occupation(request): all_user = Tenant.objects.values('t_religion').annotate(count=Count('t_religion')) return render(request, 'users/report_static_occupation.html', {'all_user': all_user, }) report_static_occupation.html: <td>{{ all_user }}</td> My output is, [{'count': 1, 't_religion': u'Muslim'}, {'count': 2, 't_religion': u'hindhu'}] But,i need like this,in table format **Religion** **count** hindhu 2 Muslim 1 -
Post data in djangon api and unable to get variable value
I have created a api which i am sending request by post but didn't get vairable in a view def login_list(request): if request.method == 'POST': data = json.dumps(request.POST) print(data) serializer = LoginSerializer(data=request.data) #print(serializer) return JsonResponse({"message":'fdsafdsa'}) when i print data print(data) then out put is coming like this {"{\"login\":122122,\"abvc\":\"544545\"}": ""} and i calling this api like this in postman Post http://localhost:8000/login/login/ {"login":122122,"abvc":"544545"} I am not geting value with this print(request.POST['login']); how can i get value -
IndexError at /delta/ - list index out of range - Django
On my list page I have several aircraft that the user can choose to compare. The user selects them with a checkbox and the ID's of those aircrafts are sent via JS. The problem I have is that the comparison sometimes works and other times and other times if throws up the error below. It's complaining about first_value = getattr(aircraft_to_compare[0], key). Those ID's are taken in and sent to another page where the comparison between the two objects will be made. What exactly is the issue here? Function: def aircraft_delta(request): ids = [id for id in request.GET.get('ids') if id != ','] aircraft_to_compare = Aircraft.objects.filter(id__in=ids) property_keys = ['name','manufacturer', 'aircraft_type', 'body', 'engines', 'image', 'cost','maximum_range','passengers','maximum_altitude','cruising_speed', 'fuel_capacity','description','wing_span','length'] column_descriptions = { 'image': '', 'name': 'Aircraft', 'maximum_range': 'Range (NM)', 'passengers': 'Passengers', 'cruising_speed': 'Max Speed (kts)', 'fuel_capacity': 'Fuel Capacity', 'manufacturer': 'Manufacturer', 'aircraft_type': 'Type', 'body':'Body', 'engines':'Engines', 'cost':'Cost', 'maximum_altitude':'Maximum Altitude', 'description':'Description', 'manufacturer':'Manufacturer', 'wing_span':'Wing Span (FT)', 'length':'Total Length (FT)' } data = [] for key in property_keys: row = [column_descriptions[key]] first_value = getattr(aircraft_to_compare[0], key) <-----HERE! second_value = getattr(aircraft_to_compare[1], key) if key not in ['image', 'name']: delta = abs(first_value - second_value) else: delta = '' row.append(first_value) row.append(delta) row.append(second_value) data.append(row) return render(request, 'aircraft/aircraft_delta.html', { 'data': data })