Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
index.html not found in django
I'm very new to django and I'm working on resetting password. I use the link to set the new password but when I submit the form I'm getting the following error. Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/accounts/profile/reset-password/confirm/Ng/set-password/index.html urls.py from django.urls import path, reverse_lazy, reverse from . import views from django.contrib.auth.views import ( LoginView,LogoutView,PasswordResetView,PasswordResetDoneView,PasswordResetConfirmView,PasswordResetCompleteView ) app_name='accounts' urlpatterns=[ path('',views.home,name='accounts_home_page'), path('login/',LoginView.as_view(template_name='accounts/login.html'),name='login_page'), path('logout/',LogoutView.as_view(template_name='accounts/logout.html'),name='logout_page'), path('register/',views.registration,name='register_page'), path('profile/',views.profile,name='profile'), path('profile/edit_profile/',views.edit_profile,name='edit-profile'), path('profile/change-password/',views.change_password,name='edit-profile'), path('profile/reset-password/',PasswordResetView.as_view(template_name='accounts/reset_password.html',success_url = reverse_lazy('accounts:password_reset_done'),email_template_name='accounts/reset_password_email.html'),name='password_reset'), path('profile/reset-password/done/',PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'),name='password_reset_done'), path('profile/reset-password/confirm/<uidb64>/<token>/',PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html',success_url = reverse_lazy('accounts:password_reset_complete')),name='password_reset_confirm'), path('profile/reset-password/complete/',PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'),name='password_reset_complete'), ] Hoping for a solution. -
Is Python Selenium the best solution for me?
I'm currently setting up a new Django app with a user member area. One of the features I require is for the users to be able to log into their GetResponse autoresponder accounts (from within my Django app) in order to change and/or update stuff. Looking at the GetResponse API it only does half of what I require. So my questions are... Would Selenium be the best option to use where I could write scripts to log them in and update all the necessary fields and carry out the required tasks in their GetResponse accounts at the click of a button? I know that API's are the best way but is this sort of practice (automation) common where an API wouldn't do? I appreciate that doing this could raise flags with IP addresses being the same for multiple users and whatever else but the script would only have to run once per user. I am a beginner when it comes to Django and Python so I understand if my questions might come across as naive! -
Django database communication -- get special key and add to it characters
I'm creating Django kind of a blog. I need the blog posts will be connected in tree logic. let's say if I create the first blog post it will have a special key-value '1001'. when I will make the second post related to the first one the special key will be 10014522 (extra 4 numbers will be randomly generated), if I making a third connected post the key will be 100145235847, notice 10014522 --> 10014523. if another user will create a connected post the key will be 100145221254. All of this logic is not the problem. The problem is to pass the key to form a creating page and to pass a new key to the database. I think it is possible to do it if you create a form using def but I'm using class: in my models directory: I thing it is possible to do it if you create form using def but i'm using class: in my models directory: class Post(models.Model): # The fields in the database title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() chapter_date = models.DateField(auto_now_add=True) special_key = .....? in my views directory: # This code will create form in … -
Nested routers POST method in Django Rest Framework
I've got 2 models: class Person(models.Model): name = models.CharField(max_length=50) class Language(models.Model): person = models.ForeignKey( Person, related_name='prs', on_delete=models.CASCADE) name = models.CharField(max_length=50) I used drf-nested-routers so that I can access them like that person/{person_id}/language and that works when i try to get data - it only shows languages related to a person but when I try to add another language in person/{person_id}/language I have to pass a person. Can i somehow change it so that I won't have to manually include person in a POST request? Second question is how can I prevent person/{non-existent_id}/language returning empty list? It works fine with person/{non-existent_id}/language/{non-existent_id} -
How to add class to options within a CheckboxSelectMultiple displayed with crispy forms
I'm wanting to add bootstrap classes to the options of a CheckboxSelectMultiple displayed with crispy forms. I know how to add a class to the whole CheckboxSelectMultiple div, but not to each of the elements within it (I'm wanting to give each a class of col-3 so they align next to each other in a neat grid). I'm displaying the form (the form also has many other fields) with: {% crispy form form.helper %} and this is the form.py TOPICS = ( ('ANI', 'Animals'), ('ART', 'Art'), ('COM', 'Communication'), ('CRI', 'Crime'), ('CUL', 'Culture/Society'), ) topics = forms.MultipleChoiceField(choices=TOPICS, required=False, widget=forms.CheckboxSelectMultiple()) Thank you. -
How do i hack viewsets.ModelViewSet in Django REST FW?
So my model is simple as class Face(models.Model): uid = models.CharField(max_length=510, primary_key=True) photo = models.ImageField(upload_to='face_photos') serializer class FaceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Face fields = ['uid', 'photo'] extra_kwargs = {'uid': {'required': True}, 'photo': {'required': True}} and view should be something like class FaceViewSet(viewsets.ModelViewSet): queryset = Face.objects.all() serializer_class = FaceSerializer permission_classes = [permissions.AllowAny] And it works. However: I don't want list, update, delete options. Only POST and GET. I want to add my logic on post, so if uid exists then update, else create... as well other processing. I want custom response after the POST. How do I achieve this all not loosing all the goodies that viewsets.ModelViewSet provides, like validations, auto generated HTML fields in Rest API web view, etc? -
Prevent the user with session from entering the URL in browser and access the data in Python Django Application
I have a Python Django web application. In Get method how to prevent the user from entering url and access the Data. How do i know weather the url accessed by Code or Browser. I tried with sessionid in Cookie, But if session exist's it allow to access the data. Thanks. -
TemplateDoesNotExist at / index.html error when django+react app deployed to Heroku
I created a simple django & react app (which just loads react default page for now) and I am trying to deploy to Heroku. When I run python manage.py runserver on localhost it runs fine (with default react page showing), but when I deploy it to Heroku, I get the following error: TemplateDoesNotExist at / index.html This is the site : https://temp-app-test.herokuapp.com/ I'm pretty sure I included index.html in templates using os.path.join(BASE_DIR, 'build') in settings.py, but it doesn't work. I also included "postinstall": "npm run build" in scripts in package.json file. requirements.txt asgiref==3.2.7 Django==3.0.6 pytz==2020.1 sqlparse==0.3.1 whitenoise==5.0.1 gunicorn==20.0.4 runtime.txt python-3.7.4 Procfile release: python manage.py migrate web: gunicorn test_test_test.wsgi --log-file - settings.py """ Django settings for test_test_test project. Generated by 'django-admin startproject' using Django 2.2.10. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = … -
ImportError: cannot import name 'views' from '__main__' (C:\Users\Kalyan Mohanty\Documents\GitHub\Django\rek\calc\urls.py)
I am learning Django but in the way of building my first I am facing this issue. ImportError: cannot import name 'views' from '__main__' (C:\Users\Kalyan Mohanty\Documents\GitHub\Django\rek\calc\urls.py) Under my app 'calc' folder urls.py from django.urls import path from . import views urlspatterns = [ path('', views.home, name = 'home') ] views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib import admin def home(request): return HttpResponse('Hello world') rek folder urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ] structure -calc (folder) `-__pycache__ (folder)` `-migrations (folder)` `-__init__` `-admin.py` `-apps.py` `-models.py` `-test.py` `-urls.py` `-views.py` -rek (folder) `-__pycache__` `-__init__` `-settings.py` `-urls.py` `-wsgi.py` db.sqlite3 manage.py -
NoReverseMatch at / - Reverse for 'new_entry' with arguments '('',)' not found
I have tried searching high and low for a solution to this, as well spending many frustrating hours staring at the code trying to figure out how to fix it. I'm pretty new to Python and I'm working through Python Crash Course, creating the Web Application using Django, specifically Chapter 19-1 where I have to recreate the steps to make a blog. I had thought I'd adapted the code to suit this project, but it doesn't look that way as I keep getting this NoReverseMatch error. Now I understand it's to do with it effectively not being able to find the page - either through the template or because of an error in the code. The problem is I can't seem to see what is wrong. The error is: Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_post/(?P<post_id>[0-9]+)/$'] Error during template rendering In template C:\Users\mcgar\Documents\blog\blog\templates\blog\base.html, error at line 0 Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_post/(?P<post_id>[0-9]+)/$'] 1 <p> 2 <a href="{% url 'blog:index' %}">Blog</a> 3 </p> 4 5 {% block content %}{% endblock content %} Here are my files: views.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse … -
Django: Excel file generated by django cannot open because the file format or file extension is not valid?
Say there's a dataframe from pandas like : mediabuy cpa mediabuy cpc cost 2020-02 0.00 371929.95 15956581.16 16328511.11 2020-04 1311.92 224747.07 26710431.81 26936490.80 total 1311.92 596677.02 42667012.97 43265001.91 And I want to return a excel file by using django, and I'tried with codes as below: # return excel view df = pd.DataFrame(data, index=index, columns=column) # saved as excel excel_writer = pd.ExcelWriter(path='temp.xlsx', engine='openpyxl') df.to_excel(excel_writer) wb = excel_writer.book response = HttpResponse(save_virtual_workbook(wb)) response["Content-Type"] = 'application/vnd.ms-excel' response['Content-Disposition'] = 'attachment; filename={}.xlsx'.format("data")) return response I'm working with python3.6.8, django2.2.4, pandas1.0.3, openpyxl3.0.3 But I always get a excel file cannot opened because the file format or file extension is not valid Why the excel file is not correct? How can I make it work ? Thanks. -
Checking if one field is less than the other - forms, Django
I try to check if the start time is less than the end time. If I did not want to raise a error. My code looks like this: class TimeOpeningHoursForm(forms.ModelForm): class Meta: model = BusinessOpeningHours fields = ('mon_st', 'mon_end', ...) widgets = { 'mon_st': Select(attrs={'class': 'form-control'}), 'mon_end': Select(attrs={'class': 'form-control'}), ... } def compare_mon(self): cleaned_data = self.cleaned_data st = cleaned_data['mon_st'] end = cleaned_data['mon_end'] if st > end : raise forms.ValidationError("The start time must be less than the end time.") else: return cleaned_data My validation code works as if it wasn't there at all. Does not raise errors or verify correctness. In the view, of course, I check form via the is_valid method. -
How to fix unbound local error on django?
I have written this code. Every time I assign a variable I am getting "local variable 'obj' referenced before assignment". I don't know where I did wrong. This is my view.py file: def blog_detail(request, slug): queryset = Blog.objects.filter(slug=slug) if queryset.count() == 1: obj = queryset.first() templates = "temp_app.html" context = {"object": obj} return render(request, templates, context) Here is my models.py file class Blog(models.Model): title = models.TextField() slug = models.SlugField() content = models.TextField(null=True, blank=True) every time I run the server I am getting UnboundLocalError. bt if I use "queryset" without assigning it into "obj" I don't get the error. I am getting the error after assigning the "queryset" in "obj". Where am I doing wrong? -
How to setup all ForeignKey & OneToOneField fields into raw_id_fields
For example I have this 3 fields as set_soal, soal and folder. I need to assign all of this fields into raw_id_fields into their admin.ModelAdmin without add manually per-single fields. class DaftarSoal(TimeStampedModel): .... set_soal = ForeignKey(SetSoal, ...) soal = ForeignKey(Soal, ...) folder = ForeignKey(Folder, ...) the basic way to enable raw fields inside the admin.ModelAdmin look like this; @admin.register(DaftarSoal, site=admin_site) class DaftarSoalAdmin(admin.ModelAdmin): raw_id_fields = ('set_soal', 'soal', 'folder') # manually But, can I setup all that OneToOneField and ForeignKey fields automatically into raw_id_fields without add it manually? such as applying the class mixin, for example: class CustomAdminMixin: raw_id_fields = () def __init__(self): self.setup_raw_id_fields() def setup_raw_id_fields(self): # search all OneToOneField and ForeignKey fields. # and assign into variable `raw_id_fields` above. and to implement it; @admin.register(DaftarSoal, site=admin_site) class DaftarSoalAdmin(CustomAdminMixin, admin.ModelAdmin): pass @admin.register(AnotherModel, site=admin_site) class AnotherModelAdmin(CustomAdminMixin, admin.ModelAdmin): pass -
How to capture radio box values in Django?
I am working on a Django project. I am not able to capture radio button values. What I want is this - if out of three answers(three radio buttons with values a, b, c respectively, the user selects say b, then in the answers table, out of the three answers columns, the second column should capture 'b' and nothing (meaning blank) should be stored in the other two columns. Quite obviously the "nm" I have written in request.POST as of now is wrong. Thanks in advance for any help. The form code is as below <input type="radio" id = "ans1" name = "nm" value = "a" class = "form-control">{{question.ans1}} <input type="radio" id = "ans2" name = "nm" value = "b" class ="form-control">{{question.ans2}} <input type="radio" id = "ans3" name = "nm" value = "c" class ="form-control">{{question.ans3}} <input type="submit" value="Submit"> In the views file the function is as below def updateans(request): if request.method == 'POST': user_id = request.POST['user_id'] questionid = request.POST['questionid'] ans1 = request.POST['nm'] ans2 = request.POST['nm'] ans3 = request.POST['nm'] myans = Answers(questionid_id = questionid, userid_id = user_id, ans1 = ans1, ans2=ans2, ans3=ans3) myans.save() -
Django - How to use greater than in template
i am having an issue when implementing greater than in my template. I have a post in homepage which users liked, and i have my friends profile image displayed beside like count if my friends liked a post. Now if 10 friends liked my post, i want only five of my friends profile image to display on template, and there will be a "+" at the end of displayed images. The "+" signifies that there are more friends who liked my post. I tried this but not working; def home(request): #all post in homepage posts = Post.objects.filter(poster_profile=request.user) #Show friend who liked Post friends_like_img = request.user.profile.friends.all().order_by('-id') context = {'posts':posts,'friends_img':friends_img} return render..... {% for post in posts %} {% for img in friends_like_img %} {% if img in post.likes.all > 20 %} <img src="{{ img.profile_pic.url }}" height="25" width="25" alt="profile_pic"> {% else %} <img src="{{ img.profile_pic.url }}" height="25" width="25" alt="profile_pic"> + {% endif %} {% endfor %} {% endfor %} -
Django 2.2 Deleting any user in the admin interface raises this error
Here is the error in question: IntegrityError at /admin/accounts/user/ FOREIGN KEY constraint failed I looked elsewhere and couldn't find any simple fix. This error I believe is because I've used a custom User model where I inherit from AbstractBaseUser because I want my website to not have usernames but instead users are identified primarily by their emails. I am at a beginner level for using Django as well as anything related to relational databases. #src/accounts.models.py from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) from django.core.mail import send_mail from django.template.loader import get_template class UserManager(BaseUserManager): def create_user(self, email, full_name=None, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user_obj = self.model( email = self.normalize_email(email), full_name=full_name ) user_obj.set_password(password) # change user password user_obj.staff = is_staff user_obj.admin = is_admin user_obj.is_active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email,full_name=None, password=None): user = self.create_user( email, full_name=full_name, password=password, is_staff=True ) return user def create_superuser(self, email, full_name=None, password=None): user = self.create_user( email, full_name=full_name, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) is_active = … -
Django ModuleNotFoundError: No module named 'product'
I am absolute new to django and I have followed the example of Django documentation https://docs.djangoproject.com/en/3.0/intro/tutorial01/ but getting a problem in main project's urls.py file which is Module not found error pls help -
How do i shorten this django view request
def test(request): x1 = MenuItem.objects.filter(item_category__icontains='PANCAKE') x2 = MenuItem.objects.filter(item_category__icontains='EGG') x3 = MenuItem.objects.filter(item_category__icontains='PANNIS') x4 = MenuItem.objects.filter(item_category__icontains='SUBS') x5 = MenuItem.objects.filter(item_category__icontains='WRAPS') x6 = MenuItem.objects.filter(item_category__icontains='TEA') x7 = MenuItem.objects.filter(item_category__icontains='FRAPPE') x8 = MenuItem.objects.filter(item_category__icontains='SMOOTHIE') x9 = MenuItem.objects.filter(item_category__icontains='GLUTENF') x10 =MenuItem.objects.filter(item_category__icontains='WAFFLES') x11 =MenuItem.objects.filter(item_category__icontains='TOAST') x12 =MenuItem.objects.filter(item_category__icontains='HOTPASTA') x13 =MenuItem.objects.filter(item_category__icontains='BAGELS') x14 =MenuItem.objects.filter(item_category__icontains='FRIES') x15 =MenuItem.objects.filter(item_category__icontains='SALADS') x16 =MenuItem.objects.filter(item_category__icontains='DESSERTS') context={ 'p':x1, 'e':x2, 'pn':x3, 's':x4, 'w':x5, 't':x6, 'f':x7, 'sm':x8, 'gf':x9, 'wa':x10, 'to':x11, 'hp':x12, 'b':x13, 'fr':x14, 'sa':x15, 'd':x16, } return render(request, 'posts/test.html',context) I know there are many different ways to shorten this but i was considering taking suggestions on how would someone who's proficient in python frameworks would handle this -
Django Custom model method with additional parameters
I want a price method on model which accepts a parameter from the frontend form and calculates the price and displays in a Listview. MODELS.PY class VehicleCategory: @property def price(self, duration): for item in VehiclePrice.objects.all(): If item.vehicle_category.title == self.title and (duration >= item.slab.start and duration <= item.slab.end): return item.net_price VIEWS.PY class HomeView(ListView): template_name = 'app/home.html' def get(self, request): if request.method == "GET": start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') duration = end_date - start_date return (duration.days + 1) context = { 'vehiclecategory':VehicleCategory.objects.all()} here I get the duration, how can I pass this in the model method price parameter and get the above Queryset to work????""" -
Container exited with code 0 when run from docker-compose
I am trying to run a container from docker file. **docker-compose.yml** services: djangoapp: build: . volumes: - .:/opt/services/djangoapp/src ports: - 8000:8000 **Dockerfile** this is entry in Docker file ENTRYPOINT bash start.sh **start.sh** #!/bin/bash ## run gunicorn in background...... gunicorn --chdir hello --bind :8000 hello_django.wsgi:application & when i build image from same Dockerfile, its working fine. when i launch from docker-compose up, it shows exited with code 0. I wanted to know the reason why my docker exited (Exited (0) 18 seconds ago) ?? -
Django ManytoMany not showing in admin
Respected Sir/Mam, As my models are in MANYTOMANY relationship so connection should be in both ways.But is it not. Example in admin For BusinessProfile section i am able to see name and image field of Services model as they are in MANYTOMANY relationship, But this not the case for viceversa.Like i am not able to see BusinessProfile models field in Services model in admin. Is my model structure correct. I have also attached images. models.py class Service(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to='image', blank = True) #business_profile = models.ManyToManyField("BusinessProfile", blank=True, related_name="business_of_services") def __str__(self): return "Service - {}".format(self.name) class BusinessProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) business_name = models.CharField(max_length=100, unique =True) register_date = models.DateTimeField(default=timezone.now) pan_number = models.IntegerField(unique=True) pan_name = models.CharField(max_length=100) address = models.TextField(max_length=200) pincode = models.IntegerField() city = models.CharField(max_length=50) state = models.CharField(max_length=50) service = models.ManyToManyField("Service", blank=True, related_name="services_of_business") image = models.ManyToManyField("Service", related_name="image_of_business") def __str__(self): return "Business - {}".format(self.business_name) -
Create a custom user tacking method on the wagtail?
I have been followed [accordbox][1] to create some models. For user activity analysis, I would like to save the user_id, restaurant_id, and time on visited RestaurantPage. The logic is when get_context function in the Restaurant Model, it will use tracking function to save record in TrackUserRestaurant model. The print function is used to check the request.user.id and restaurant.id. But I can't get any new record on the TrackUserRestaurant model. Did I misunderstand something? I am new to Django and wagtail. class RestaurantPage(Page) .... #other fields view_count = models.PositiveIntegerField(default=0, editable=False) @property def restaurant_page(self): return self.get_parent().specific def get_context(self, request, *args, **kwargs): context = super(RestaurantPage, self).get_context(request, *args, **kwargs) context['restaurant_page'] = self.restaurant_page context['restaurant'] = self self.tracking(request) return context def tracking(self, request): current_user = request.user track = TrackUserRest track.user = 0 track.rest = self.pk track.date = timezone.now() if request.user.id != None: print('user id:' + str(current_user.id)) track.user = request.user.pk print('rest id:' + str(self.pk)) return track.save(self) class TrackUserRestaurant(models.Model): user_id = models.PositiveIntegerField(null=True) restaurant_id = models.PositiveIntegerField(blank=False, null=False) time = models.DateTimeField(auto_now=True, auto_now_add=False) class Meta: ordering = ('time', ) def __str__(self): return 'Restaurant Tracking system: user.id({}) viewed rest.id({}) at timezone.({})'.format(self.user_id, self.restaurant_id, self.time) -
using djongo and while making miratioin its showing AppRegistryNotReady
I am using Djongo in django for using mongodb. I tried to migrate the models all the models get migrated but when i need arrayfield. and when i am trying to migrate it. Its rasing error. I tried all things what i was able to find on internet.I tried Django.setup in manage.py field i tried all things please help me. code for my setting Django settings for questions project. Generated by 'django-admin startproject' using Django 2.2.12. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'w6(hj1%1d=kc%z^$@0z4&r(02&00jz#-t%ql2l7g&#3+!(csjr' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multi_questions', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'questions.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], … -
Python, enumerate list assignment index out of range error
I have the following code: iva_versamenti_totale={'Liquidazione IVA': [sum(t) for t in zip(*iva_versamenti.values())],} utilizzato=dict() riporto=dict() utilizzato['Key_1']=list(0 for m in range(13)) riporto['Key_2']=list(0 for m in range(13)) for index, xi in enumerate(iva_saldo_totale['Saldo IVA'], 0): if xi > 0 : riporto['Key_2'][index] = riporto['Key_2'][index] + xi else: riporto['Key_2'][index] = riporto['Key_2'][index-1]-utilizzato['Key_1'][index] for index, xi in enumerate(iva_saldo_totale['Saldo IVA'], 1): if xi > 0 : utilizzato['Key_1'][index] == 0 elif riporto['Key_2'][index-1] >= xi: utilizzato['Key_1'][index] = - xi else: utilizzato['Key_1'][index]=riporto['Key_2'][index-1] But Python give me the following error: IndexError: list assignment index out of range I want that the for loop start from the second element of each variable (riporto, utilizzato and iva_versamenti_totale) in such a way that I can set manually these values.