Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get_absolute_url (Return user to the same page after form submission)
Learing django. I have one question. I have done feedback form and i need to redirect user to the same page after feedback form confirmation. Code look below models.py class Feedback(models.Model): title = models.CharField(max_length=255) text = models.TextField(max_length=5000) user_name = models.CharField(max_length=255) user_lastname = models.CharField(max_length=255) email = models.EmailField(max_length=255) send_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) def get_absolute_url(self): return views.py class FeedbackSendForm(CreateView): model = Feedback fields = [ 'title', 'text', 'user_name', 'user_lastname', 'email', ] template_name = 'feedback.html' feedback.html <form method="post"> {% csrf_token %} {% for field in form %} <span class="text-danger">{{ field.errors }}</span> <div> <label class="control-label">{{ field.label }}</label> {{ field }} </div> {% endfor %} <button type="submit">Submit</button> </form> Any ideas? Please help. Thank you in advance -
upload file to S3 using DRF
I have an issue. I want to upload a file to my S3 bucket with DRF but I'm getting an error when I try with Postman models.py class Asset(models.Model): game = models.ForeignKey(Game, related_name='assets', on_delete=models.CASCADE) file_path = models.FileField(upload_to='test', default='') created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'Asset' serializers.py class AssetSerializer(serializers.ModelSerializer): class Meta: model = Asset fields = ('id', 'file_path', 'created_at', 'updated_at') views.py class AssetList(generics.ListCreateAPIView): queryset = Asset.objects.all() serializer_class = AssetSerializer permission_classes = (IsAuthenticated,) parser_classes = (MultiPartParser, ) def perform_create(self, serializer): serializer.save(game_id=self.kwargs['game_id']) I have this in my local_settings.py AWS_ACCESS_KEY_ID = "..." AWS_SECRET_ACCESS_KEY = "..." AWS_STORAGE_BUCKET_NAME = "my-bucket-name" And when I do: POST /games/1/assets/ and upload a file with POSTMAN, I'm getting this error: File ".env/lib/python2.7/site- packages/boto/s3/bucket.py", line 232, in _get_key_internal response.status, response.reason, '') S3ResponseError: S3ResponseError: 400 Bad Request Thank you for helping! -
AttributeError: 'Price' object has no attribute 'update'
I got an error,AttributeError: 'Price' object has no attribute 'update' .I wrote fourrows_transpose=list(map(list, zip(*fourrows))) val3 = sheet3.cell_value(rowx=0, colx=9) user3 = Companyransaction.objects.filter(corporation_id=val3).first() if user3: area = Area.objects.filter(name="America").first() pref = Prefecture.objects.create(name="Prefecture", area=area) city = City.objects.create(name="City", prefecture=pref) price= Price.objects.create(city=city) pref.name = fourrows_transpose[0][0] pref.save() for transpose in fourrows_transpose[2:]: if len(transpose) == 5: if "×" in transpose or "○" in transpose: city.name = "NY" city.save() price.update(upper1000="○",from500to1000="○",under500="○") In models.py I wrote class Area(models.Model): name = models.CharField(max_length=20, verbose_name='area', null=True) class User(models.Model): user_id = models.CharField(max_length=200,null=True) area = models.ForeignKey('Area',null=True, blank=True) class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='prefecture') area = models.ForeignKey('Area', null=True, blank=True) class City(models.Model): name = models.CharField(max_length=20, verbose_name='city') prefecture = models.ForeignKey('Prefecture', null=True, blank=True) class Price(models.Model): upper1000 = models.CharField(max_length=20, verbose_name='u1000', null=True) from500to1000 = models.CharField(max_length=20, verbose_name='500~1000', null=True) under500 = models.CharField(max_length=20, verbose_name='d500', null=True) city = models.ForeignKey('City', null=True, blank=True) I wanna put "○" to upper1000&from500to1000&under500 column of Price model, but it cannot be done because of the error.What is wrong in my code?How can I fix this? -
how to add links and images in text field of django admin
I am using django to create a blog. In my model I am using a text field for my blog content. But I am unable to insert any image or a clickable link.How to add links(clickable) and insert images? -
Difficulties while using send_mail()
I have few issues regarding sending emails using Django: Why am I unable to send emails (using Gmail SMTP server ) when I am under VPN? How to configure my SMTP server in Django? (I want to use my organization's SMTP server other than Gmail's) What is the difference between: "[WinError 10054] An existing connection was forcibly closed by the remote host" and "[WinError 10061] No connection could be made because the target machine actively refused it " errors? I am stuck on this issue since two weeks. Please help me to understand things better. Thanks in advance! -
Using extra_columns in django_tables2.tables.Table
Trying to use extra_colums and get no error but the table does not show up. I've use the documentation from here. I am trying to add a column which will have checkboxes into the table. I have already predefined the table and can exclude some fields but with using the documentation I cannot figure out how to add a new column. I must be missing something The implementation can be seen below. Would appreciate any assistance. Thanks IN TABLES.PY import django_tables2 as tables from project.models import Project class ProjectTable(tables.Table): project_name = tables.TemplateColumn(""" {%if record.department == "TRACER"%} <a href=" {% url 'project_detail' record.id %}"> {{ value }} </a> {%else%} {{value}} {%endif%} """, orderable=True, accessor='name', verbose_name="Project name") project_type = tables.TemplateColumn(""" {% if value == 'Yes' %}Special{% else %}Normal{% endif %} """, orderable=True, accessor='is_special', verbose_name="Project type") project_code = tables.Column(accessor='code', verbose_name="Project code") project_status = tables.Column(accessor='status', verbose_name="Project status") department = tables.Column(accessor='department', verbose_name="Department") class Meta: model = Project attrs = {'class': 'table table-striped table-hover'} sequence = ( 'project_name', 'project_type', 'project_code', 'project_status',) IN THE VIEW from project.tables import ProjectTable from django_tables2.columns import CheckBoxColumn class AllocationChangeView(PagedFilteredTableView): display_message = "You need to be logged in to view this page" table_class = ProjectTable queryset = Project.objects.all() template_name = 'matter_allocation/change_project.html' paginate_by … -
How to filter gte,lte date on datetime field?
I'm trying to figure out how to filter QuerySet using date extracted from datetime. I use Django-filter and I can't compose such lookup without iterating over QuerySet which is very uneffective. I tried datetime__date__gte which doesn't work. class MyReservationsFilter(FilterSet): datetime__lte = DateFilter(method='datetime_filter',name='lte') class Meta: model = Reservation fields = {'status': ['exact'], # 'datetime': ['lte', 'gte'], 'destination_from': ['exact'], 'destination_to': ['exact'],} def datetime_filter(self, queryset, name, value): lookup = 'datetime__'+name return queryset.filter(**{lookup:value}) Do you know what to do? -
Create disk snapshot using google cloud python api client
I'm trying to create a disk snapshot using python api client of google cloud platform, Heres what's I have tried: From views.py if request.method == 'POST': form = forms.SnapshotForm(request.POST) if form.is_valid(): obj = snapy() obj.project = form.cleaned_data['project'] obj.instance = form.cleaned_data['instance'] obj.zone = form.cleaned_data['zone'] obj.snapshot = form.cleaned_data['snap_name'] # Google Cloud stuff for Snapshot service = discovery.build('compute', 'v1', credentials=credentials) project_id = obj.project zone = obj.zone disk = obj.instance snapshot_body = {} request = service.disks().createSnapshot(project=project_id, zone=zone, disk=disk, body=snapshot_body) response = request.execute() pprint(response) obj.save() print(obj) return HttpResponse('Good', status=200) It returns no error but snapshot not created on gcp console. Is there something wrong I have configured? help me, please! Here's the response: [10/Sep/2017 08:09:46] "GET /snap/ HTTP/1.1" 200 2740 {'id': '8462873153659819689', 'insertTime': '2017-09-13T01:11:51.025-07:00', 'kind': 'compute#operation', 'name': 'operation-1505290310763-5590db641c1f8-9be2938e-9e1b974f', 'operationType': 'createSnapshot', 'progress': 0, 'selfLink': 'https://www.googleapis.com/compute/v1/projects/istiodep/zones/asia-northeast1-c/operations/operation-1505290310763-5590db641c1f8-9be2938e-9e1b974f', 'status': 'PENDING', 'targetId': '1514253394633906452', 'targetLink': 'https://www.googleapis.com/compute/v1/projects/istiodep/zones/asia-northeast1-c/disks/instance-1', 'user': 'saqib.rasool@seecs.edu.pk', 'zone': 'https://www.googleapis.com/compute/v1/projects/istiodep/zones/asia-northeast1-c' } Snapshot object -
redirect user after update in class based view in django
I'm using Django 1.11. I'm using Class based view for update profile page, to updated auth user profile info. myapp/accounts/views.py class UpdateProfile(UpdateView): model = User fields = ['first_name', 'last_name'] template_name = 'accounts/update.html' def __init__(self, **kwargs): super().__init__(**kwargs) self.request = None def get_object(self, queryset=None): return self.request.user This works fine for updating profile. But after update, it gives error No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. I followed some YouTube tutorials here which is using method based view and form.py to generate form, There I can check for request method and call form.save() and then redirect user to profile page (probably index). 1. How can I do I check if data updated and then redirect user to index class in my class? 2. Is this method suitable for editing data using pk? I also want to generate flash message after updation for which I can use messages.success(request, "Profile updated") 3. Since class is not have request object, how to use messages in class based view? -
$ manage.py runserver /system/bin/sh: manage.py: not found
I would be away from a computer (pc) for a while but I have a project on my neck so I got qpython. I installed Django successfully but after creating a project when I $ manage.py runserver /system/bin/sh: manage.py: not found Though Django-admin runserver doesn't work... It tells something about DJANGO_SETTINGS_MODULE Or settings.configure() -
Why are wrong value put into model?
I wanna put list data to upper700&from300to700&under300 of Price model. I wrote fourrows_transpose=list(map(list, zip(*fourrows))) val3 = sheet3.cell_value(rowx=0, colx=9) user3 = Companyransaction.objects.filter(corporation_id=val3).first() if user3: area = Area.objects.filter(name="America").first() pref = Prefecture.objects.create(name="Prefecture", area=area) city = City.objects.create(name="City", prefecture=pref) price_u700 = Price.objects.create(upper700=city.name) price_u700.upper700 = city.name price_u700.save() price_300_700 = Price.objects.create(from300to700=city.name) price_300_700.from300to700 = city.name price_300_700.save() price_u300 = Price.objects.create(under300=city.name) price_u300.under300 = city.name price_u300.save() pref.name = fourrows_transpose[0][0] pref.save() for transpose in fourrows_transpose[2:]: if len(transpose) == 5: if "×" in transpose or "○" in transpose: city.name = "A" city.save() price_u700.name = "○" price_u700.save() price_300_700.name = "○" price_300_700.save() price_u300.name = "○" price_u300.save() Now in upper700&from300to700&under300's column of Price model,Null or "City" is in there.I wanna put "○" to these model. I think why Null is in there is data is put price_u700&price_300_700&price_u300 each one. But I really cannot understand why "City" is in there.How can I fix this?What is wrong?models.py is class Area(models.Model): name = models.CharField(max_length=20, verbose_name='area', null=True) class User(models.Model): user_id = models.CharField(max_length=200,null=True) area = models.ForeignKey('Area',null=True, blank=True) class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='prefecture') area = models.ForeignKey('Area', null=True, blank=True) class City(models.Model): name = models.CharField(max_length=20, verbose_name='city') prefecture = models.ForeignKey('Prefecture', null=True, blank=True) class Price(models.Model): upper700 = models.CharField(max_length=20, verbose_name='u1000', null=True) from300to700 = models.CharField(max_length=20, verbose_name='500~1000', null=True) under300 = models.CharField(max_length=20, verbose_name='d500', null=True) city = models.ForeignKey('City', null=True, blank=True) -
How to get qery string value in client side after page upload using Django and Python
I need some help. I need to fetch the the query string value from URL in client side i.e-Javascript and that URL is passed from Django template. I am explaining my code below. base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> {% load static %} <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> </head> <body> <header> <h1>Nuclear Reactor</h1> {% if count > 0 %} <b>Hi, {{ user.username }}</b> <a href="{% url 'home' %}?file=//cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js">Home</a> <a href="{% url 'view_reactor' %}?file=//cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js">View Reactor status</a> <a href="{% url 'logout' %}">logout</a> {% else %} <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a> {% endif %} <hr> </header> <main> {% block content %} {% endblock %} </main> </body> </html> Here I am passing some query string value for home.html loading. home.html: {% extends 'base.html' %} {% block content %} <center><h1>Welcome</h1> <p>This App allow to control the life cycle of the Nuclear Reactor and Retrive the status report </p> <p><a href="{% url 'status' %}">Status report</a><a href="{% url 'control' %}">Control panel</a></p> </center> <script type="text/javascript"> window.onload=function(){ } </script> {% endblock %} Here I need after home page rendering that query string value should fetch using Javascript. Please help me. -
if request.method =='POST': is always failing
#Contact.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class='row'> <div class ='col-md-4 col-md-offset-4'> <h1> {{title}} </h1> {% if confirm_message %} <p>{{ confirm_message }}</p> {% endif %} {% if form %} <form method='POST' action=''> {% csrf_token %} {{ form.errors }} {{ form.non_field_errors }} {% crispy form %} <input type='submit' value='submit form' class='btn btn-default' /> </form> {% endif %} </div> </div> {% endblock %} # froms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Field from crispy_forms.bootstrap import (PrependedText, PrependedAppendedText, FormActions) class contactForm(forms.Form): name = forms.CharField(required = False , max_length =100, help_text="100 characters max ") email= forms.EmailField(required = True) comment = forms.CharField(required =True, widget=forms.Textarea) Server Logs System check identified no issues (0 silenced). September 13, 2017 - 07:38:19 Django version 1.11.5, using settings 'app3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. GET hello from not valid [13/Sep/2017 07:38:23] "GET /contact/ HTTP/1.1" 200 5413 [13/Sep/2017 07:42:20] "GET / HTTP/1.1" 200 4356 [13/Sep/2017 07:42:27] "GET /about/ HTTP/1.1" 200 3985 GET hello from not valid [13/Sep/2017 07:42:37] "GET /contact/ HTTP/1.1" 200 5413 The request never becomes post. When I hit submit on the form it never shows up as post request. … -
A FastCGI error 0x8007010b about django1.11 on IIS7
I deploy the web services,following this, www.kronoskoders.logdown.com,but there is an error about FastCGI in the end ,and I am sure that my webproject code has no error.Does anyone know how to solve this error? Thank you for your help!!! ps I use the windows service r2 2012+django 1.11+IIS7+pyhon3.6 enter image description here -
Latest version of Elasticsearch supported by Haystack 2.6.1
I want to know the latest version of Elasticsearch which is supported by Django Haystack 2.6.1, as I feel upgrading Elasticsearch may solve some of the problems I am facing. -
User Registeration Using Django Rest Framework
I am trying to create a api for user Registration using the django rest framework. I have the following models.py file from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE , primary_key = True) mobileNumber = models.IntegerField(default=0) avatar= models.ImageField(upload_to = 'User/' , default = '/static/User/defaultProfileImage.png') def create_user_profile(sender, **kwargs): if kwargs['created']: profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_user_profile, sender=User) This is my Serializers.py file from rest_framework import serializers from User.models import UserProfile from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): username = serializers.CharField() password1 = serializers.CharField( style={'input_type': 'password'}, write_only=True) password2 = serializers.CharField( style={'input_type': 'password'}, write_only=True) email = serializers.EmailField() class Meta: model = User fields = ( 'id', 'username', 'password1', 'password2', 'email', 'first_name', 'last_name', ) class UserProfileSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: model = UserProfile fields = ( 'user', 'mobileNumber', 'avatar') And following is my views.py file from User.models import UserProfile from .serializers import UserProfileSerializer from rest_framework.viewsets import ModelViewSet class UserProfileViewSet(ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer What is the best way to create a User Registeration using the api view that i have created. I tried many alternatives like overriding the create method in the UserProfile Serializer class and … -
The render do not render to the template
In the admin index page I bind a id to a button, and use jquery ajax to request a logout event: $("#logout").click(function(){ $.ajax({ url:'/logout/', type:'POST' }) }) And in the frontend/views.py: def logout(request): if request.method == 'POST': request.session['username'] = None request.session['is_login'] = False import app_admin.views as app_admin_views app_admin_views.conn = None # clean the connection print ('before logout') return render(request,'frontend/login.html') In the Terminal have printed the 'before logout', but the page do not render to the frontend/login.html, and I also tried use redirect, all failure. -
django use column value for filtering
I have a table of points with location data as stored in the following columns: coordinates: the geolocation data in longitude and latitude radius: the distance from coordinate that it is visible Now I take a random point and want to find the points that are visible to the random point using django geolocation such as: LocationInfo.objects.filter(coordinates__distance_lt=(random_point, D(km=1)) Currently I am retrieving the points within 1 km radius but I want to use the radius from the table. How can I use the radius from the table? -
How to select a random file from a folder that where uploaded with django-filer
I use django-cms for a project and in the frontend (template) I want to select a random image from a folder. The media is managed by django-filer. I know how to use the files when I assign them directly in my models, but I can't figure out if and how it is possible to select a random image. For a better understanding, I have a model where I can choose an image. If that is not set by the editor, I want to choose a random image as backup. -
Render template and I want to the url address change too
I from login page render to the admin index page, but the url address did not change, how to change it? Code is below: return render(request, 'app_admin/index.html') As a common sense , all we know use render the url address do not change, but I want it change. how can I do that? I do not want to use the redirect, because I will pass data in render. how can I do that? -
Django connected SQL queries with filters
Example: class Room(models.Model): assigned_floor = models.ForeignKey(Floor, null=True, on_delete=models.CASCADE) room_nr = models.CharField(db_index=True, max_length=4, unique=True, null=True) locked = models.BooleanField(db_index=True, default=False) last_cleaning = models.DateTimeField(db_index=True, auto_now_add=True, null=True) ... class Floor(models.Model): assigned_building = models.ForeignKey(Building, on_delete=models.CASCADE) wall_color = models.CharField(db_index=True, max_length=255, blank=True, null=True) ... class Building(models.Model): name = models.CharField(db_index=True, max_length=255, unique=True, null=True) number = models.PositiveIntegerField(db_index=True) color = models.CharField(db_index=True, max_length=255, null=True) ... I want to output all rooms in a table sorted by Building.number. Data which I want to print for each room: Building.number, Building.color, Building.name, Floor.wall_color, Room.last_cleaning Furthermore I want to allow optional filters: Room.locked, Room.last_cleaning, Floor.wall_color, Building.number, Building.color With one table it's no Problem for me, but I don't know how I archive this with three tables. kwargs = {'number': 123} kwargs['color'] = 'blue' all_buildings = Building.objects.filter(**kwargs).order_by('-number') Can you please help me? Do I need write raw SQL queries or can I archive this with the Django model query APIs? I'm using the latest Django version with PostgreSQL. -
Django: inserted text into a text field sometime doesn't go trough after post
I have this weird bug that i can't replicate all the time. I have a html and with Jquery i populate a text field (Summernote). If i just populate the text, do nothing with it and i submit the form, sometimes the form field is, some time it goes trough just fine. Its like 30/70 ratio. But if i edit something, or even click on the text field it goes trough all the time. Has anyone encountered such behavior. My form class Form(forms.ModelForm): class Meta: model = modelname fields = ['field'] widgets = { 'notes': SummernoteInplaceWidget(attrs={'height': '600px'},), } my html var string = (function() {/* {{ message }} */}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1]; $('#button').click(function () { $('#id_field').summernote('code', string ); }); -
Permission error when installing Django within virtual environment
I have Django 1.10 installed within a virtualenv on my machine. Now I am creating another virtualenv (for another project) and installing Django 1.11 on it using the following command: pip install Django but I get a permission denied error: Collecting Django Using cached Django-1.11.5-py2.py3-none-any.whl Requirement already satisfied: pytz in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (from Django) Installing collected packages: Django Exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/wheel.py", line 377, in move_wheel_files clobber(source, dest, False, fixer=fixer, filter=filter) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/wheel.py", line 323, in clobber shutil.copyfile(srcfile, destfile) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/shutil.py", line 115, in copyfile with open(dst, 'wb') as fdst: PermissionError: [Errno 13] Permission denied: '/Library/Frameworks/Python.framework/Versions/3.5/bin/__pycache__/django-admin.cpython-35.pyc' I have read multiple SO posts about this but their solutions dont seem to apply to me. Please note: 1) I have already activated the new virtualenv before running the command. 2) I did not create the new virtualenv using sudo. I just did the following to create it: virtualenv name-of-the-new-virtualenv What could I be missing? -
IndexError: list index out of range Why can't I acsess two-dimensional array?
I cannot acsess the two-dimensional array. I wrote book3 = xlrd.open_workbook('./data/excel1.xlsx') sheet3 = book3.sheet_by_index(0) for row_index in range(7, sheet3.nrows): row = sheet3.row_values(row_index) area_row = row[0] or area_row row[0] = area_row if len(fourrows) == 5: fourrows=[] fourrows.append(row) fourrows_transpose=list(map(list, zip(*fourrows))) val3 = sheet3.cell_value(rowx=0, colx=9) user3 = User.objects.filter(corporation_id=val3).first() if user3: area = Area.objects.filter(name="America").first() pref = Prefecture.objects.create(name="prefecture", area=user3.area) city = City.objects.create(name="city", prefecture=pref) price_u1000 = Price.upper1000.objects.get(city=city) price_500_1000 = Price.from500to1000.objects.get(city=city) price_u500 = Price.under500.objects.get(city=city) pref.name = "NY" pref.save() for i in range(2,len(fourrows_transpose)): city.name = fourrows_transpose[i][1] city.save() print(fourrows_transpose[i][1]) price_u1000.name = fourrows_transpose[i][2] price_u1000.save() print(fourrows_transpose[i][2]) price_500_1000.name = fourrows_transpose[i][3] price_500_1000.save() print(fourrows_transpose[i][3]) price_u500.name = fourrows_transpose[i][4] price_u500.save() print(fourrows_transpose[i][4]) In print(fourrows_transpose),it is shown [['America', 'America', 'America', 'America', 'America'], ['', '', 'u1000', '500~1000', 'd500'], ['NY', 'City A', '×', '×', '×'], ['NY', 'City B', '×', '×', '×'], ['NY', 'City C', '×', '×', '×'], ['NY', 'City D', '×', '×', '×'], ['NY', 'City E', '×', '×', '×']] Now error happens,IndexError: list index out of range.Traceback says city.name = fourrows_transpose[i][1] is wrong.but I think fourrows_transpose is two-dimensional arrays,so I really cannot understand why I cannot access fourrows_transpose[2][1].What is wrong?How should I fix this? -
Automated answer in django's makemigrations
I want to automate the python manage.py makemigrations as in if a user encounters Did you rename game.last to game.las (a CharField)? [y/N] then the input will always be y but if the user encounters You are trying to add a non-nullable field 'las' to game without a default then it will automatically and continuously enter 1. I tried yes | python manage.py makemigrations as researched however this will just throw an infinite loop of Please select a valid option if the default input is asked My desire is the automation between 1 and y value as mentioned on my first paragraph or just throw an error if I input a wrong option on the default input