Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
creating a delete button that deletes on the template but not in the django database
deleting an object from the template but not in the database.On clicking delete button the object will be removed from the template but updates the database with canceled. -
It is possible to get backend custom error message with d3.json?
I develop a django application where I have a d3js interactive tree. I use d3.json to get the tree data from the django view. I have create a decorator to check if user is logged to allowed the request or not. I have no problem when the user is logged but when the decorator return the jsonResponse with redirection url I have only the status error with the status description. I read d3js and promise documentation but I'm not found a answer to return a jsonresponse with my custom response. d3.json(d.data.url).then(function(data) { // process data no problem }, function(error){ console.log(error); }); def check_user_permission_js(view_function): @wraps(view_function) def wrapper(request, *args, **kwargs): if request.user.is_authenticated: return view_function(request, *args, **kwargs) messages.warning(request, "Your account doesn't have access to this page " + "or your session has expired. " + "To proceed, please login with an account that has access.") return JsonResponse({'not_authenticated': True, 'redirect_url': settings.LOGIN_URL,'data':[]}, status=500) return wrapper -
Using Django authenitcation with Angular frontend
I wish to use Django's inbuilt user authentication but my frontend is currently all Angular. The login/user status should be shown on the navbar with an option to login/logout. I can't find a guide on this anyway and what I have tried so far isn't giving me any results. I have tried rendering the nav bar in django by using 'app-nav-bar' to reference the angular component and I have also tried moving all the html from angular into django and using the verbatim tag to try and keep the angular functionality but these haven't worked. Navbar Component: <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a [routerLink]="['']" class="navbar-brand"> <img src="../static/ang/assets/images/logo.svg" alt="Logo" height="30px"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse"> <div class="navbar-nav"> <a [routerLink]="['/view']" class="nav-item nav-link">View Projects</a> <a [routerLink]="['/manage']" class="nav-item nav-link">Manage Projects</a> </div> </div> </nav> Django template: //app-nav-bar had been going in here to test <app-root> <div class="container-fluid"> <div class="row align-items-center"> <div class="col text-center"> <div class="spinner-border p-5 m-5" role="status"> <span class="sr-only">Loading . . .</span> </div> </div> </div> </div> </app-root> I am expecting the navbar to have the same functionality in django as it does in angular but the links arent working or the navbar isnt … -
i want to call external bootstrap modal file using ajax in my django project but it is cannot working please give me a suppot
Here is my code which is calling the file shipper_modal.html file <script> $('.modalLink1').click(function(){ $.ajax({url: "shipper_modal.html", cache:false:function(result){ $(".modal-content").html(result); }) }) I want to ajax URL tag or other methods to call the shipper_modal file thanks in advance -
'ValueError: Required parameter not set' Django app following AWS configuration and Heroku deployment
I have just deployed my Django app to Heroku, having configured the app to store media files in an AWS S3 bucket. Everything was working correctly in the development server, but when I try to access pages containing these images in the Heroku-hosted version, I receive a ValueError informing me that the required parameter 'name' hasn't been set. A look through the traceback suggests that the supposedly nameless objects are the images. s3boto3 is also referenced. My configuration for AWS is detailed below: # settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') S3_USE_SIGV4 = os.environ.get('S3_USE_SIGV4') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # env.py os.environ.setdefault("AWS_ACCESS_KEY_ID", "**********") os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "**********") os.environ.setdefault("AWS_STORAGE_BUCKET_NAME", "**********") os.environ.setdefault("AWS_S3_REGION_NAME", "eu-west-2") os.environ.setdefault('S3_USE_SIGV4', 'True') I've read suggestions that I may need to add an AWS_SESSION_TOKEN to the configuration, but I have no idea how to go about identifying mine. I've also read elsewhere that a session token isn't a necessary part of the configuration. I'm just looking for a steer so that I don't wind up wasting time attempting something which isn't going to fix the problem. -
Debugging while developing Django apps
I'm aware of pdb built-in Python library for debugging Python programs and scripts. However, you can't really use it for debugging Django apps (I get errors when I try to use it in views.py). Are there any tools that I can use when Django's traceback isn't helpful ? -
Dajngo https with a dev server
I'm trying to use SpeechRecognition/ webkitSpeechRecognition in my website, and thus need to run a dev server in django using https. I've taken the following steps: install and configure runserver_plus from django-extensions add the cert generated by this to my cas in ubuntu. # run server python3 manage.py runserver_plus --cert-file certs/localhost --reloader-interval 2 0.0.0.0:8000 then # to copy certificates: sudo mkdir /usr/share/ca-certificates/netia sudo cp certs/localhost.crt /usr/share/ca-certificates/netia/localhost.crt sudo chmod -R 755 /usr/share/ca-certificates/netia/ sudo chmod 644 /usr/share/ca-certificates/netia/localhost.crt sudo dpkg-reconfigure ca-certificates sudo update-ca-certificates I then restart everything to ensure changes have been accouted for, but the website is still not trusted on https://127.0.0.1:8000 and https://localhost:8000 What am I doing wrong? Note: awk -v cmd='openssl x509 -noout -subject' ' /BEGIN/{close(cmd)};{print | cmd}' < /etc/ssl/certs/ca-certificates.crt # gives: ... subject=CN = localhost subject=CN = *.localhost/CN=localhost, O = Dummy Certificate This is my chrome certificate invlaid screenshot: -
checkbox getlist return nothing - django
I am using checkbox in this way: <input type="checkbox"name="group1"value="0"> <input type="checkbox"name="group1"value="1"> <input type="checkbox"name="group1"value="2"> <input type="checkbox"name="group1"value="3"> in my view.py boxes = request.POST.getlist("group1") Which the boxes is an empty array. I have also tried: boxes = requset.POST.getlist("group1", []) boxes = request.POST.getlist("group1[]") boxes = request.POST("group1") <-- I have seen from other post said this would only return the value the value of last element but I am also okay as the box will only have one box clicked however, all of the above cannot successfully get the checkbox value. So I am not sure is this javascript affect the getlist: $('input[type="checkbox"]').on('change', function() { $('input[name="' + this.name + '"]').not(this).prop('checked', false); }); But I have also tried to disable the javascript, still not working -
Please help me to remove this Django APP ID type error
I'm new to Django and I'm trying to install requirements for a Django project of My teammates after cloning it. but it is not working and I can't also make migrations. whenever I try running migrations I'm getting this error (name, text, type(obj))) TypeError: app_id should be a string instead it is a <class 'NoneType'> Any help will be highly appreciated -
Django: How to Access Installed Third Party App's Model and Data
I have been using django-river(https://github.com/javrasya/django-river) application within my app (https://github.com/rupin/WorkflowEngine) I have used the Django rest framework in my application and would like to get the data from the django-river tables. The name of the table is State. My serializer is as follows from river.models import State from rest_framework import serializers class StateSerializer(serializers.Serializer): class Meta: model = State fields = ['id', 'label'] Also, my API view is as follows from rest_framework import generics from workflowengine.riverserializers.StateSerializer import StateSerializer from river.models import State class StateList(generics.ListAPIView): serializer_class = StateSerializer def get_queryset(self): return State.objects.all() Through the Admin console, I have added 11 states inside my state table, which I have checked with pgadmin. When i access the API through the browser, I get 11 empty sections in my API ( no error, just the data is missing). I cant seem to understand how the 11 data points presented in the API are empty. That it presented 11 elements, but no data, which is pretty weird. -
How to get and set the page number in django listview with pagination?
In our application, we have some Records and RecordSets and the RecordListView page shows Records of a RecordSet: class RecordListView(PaginationMixin, ListView): paginate_by = 10 def get_queryset(self): record_set_pk = self.kwargs.get('record_set') recordSet = RecordSet.objects.get(pk=record_set_pk) self.recordSet = recordSet self.queryset = recordSet.record_set.all().order_by('title') return self.queryset The problem is that 'Record' have an attribute named checked and I want to navigate to the page that the last checked record is in there! (or the first not checked record) I have found that self.kwargs.setdefault('page', desired_page_number) shows the desired page but it freezes the page and disables the navigation. So I tried to set a condition to check page argument value but self.kwargs.get('page') is always None. However I found that I can get page number from in str(self.request) but I think it's a little messy and there must be a better solution. Isn't there?! -
Rest_framework_swagger without authorization in Django
I have the following settings for REST_FRAMEWORK in my django project: REST_FRAMEWORK = { ... 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticatedOrReadOnly',), ... } I want to see all methods in rest_framework_swagger without authorization. I know that by default swagger doesn't show the methods you don't have access to. How can I override it? I have already tried to experiment with SWAGGER_SETTINGS in my settings.py file but it seems to me that is hasn't 'no authorization' option. -
I want to dynamically change the form of django according to user information
Although it is in the title, I want to change the form dynamically with django. But now I get an error. I can't deal with it. I was able to get user information, but if I filter it, it will be “cannot unpack non-iterable UPRM object”. #forms.py class RecordCreateForm(BaseModelForm): class Meta: model = URC fields = ('UPRC','URN','UET','URT',) def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(RecordCreateForm,self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' self.fields['URN'].choices = UPRM.objects.filter(user=user) #views.py class RecordCreate(CreateView): model = URC form_class = RecordCreateForm template_name = 'records/urcform.html' success_url = reverse_lazy('person:home') def get_form_kwargs(self): kwargs = super(RecordCreate, self).get_form_kwargs() # get users, note: you can access request using: self.request kwargs['user'] = self.request.user return kwargs #models class UPRM(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) URN = models.CharField( max_length=30,editable=True) def __str__(self): return self.URN class URC(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) UPRC = models.CharField(max_length=300) URN = models.ForeignKey(UPRM, on_delete=models.CASCADE) def __str__(self): return self.UPRC cannot unpack non-iterable UPRM object -
i can not work with zeep in python - missing element error
i want to make a payment gateway in django with zeep module i want to test this payment gateway in my local host i got help from the site that produce payment gateway and wrote this code views.py from django.shortcuts import render, redirect from django.http import HttpResponse from zeep import Client MERCHANT = '00' client = Client('https://www.zarinpal.com/pg/services/WebGate/wsdl') amount = 1000 description = 'تست درگاه پرداخت' CallbackURL = 'http://localhost:8000/' #whatever! i am just testing def send_request(request): result = client.service.PaymentRequest(MERCHANT, amount, description, CallbackURL) if result.Status == 100: return redirect('https://www.sandbox.zarinpal.com/pg/StartPay/' + str(result.Authority)) else: return HttpResponse('Error code: ' + str(result.Status)) def verify(request): if request.GET.get('Status') == 'OK': result = client.service.PaymentVerification(MERCHANT, request.GET['Authority'], amount) if result.Status == 100: return HttpResponse('Transaction success.\nRefID: ' + str(result.RefID)) elif result.Status == 101: return HttpResponse('Transaction submitted : ' + str(result.Status)) else: return HttpResponse('Transaction failed.\nStatus: ' + str(result.Status)) else: return HttpResponse('Transaction failed or canceled by user') then runserver but i get this error Exception Value: Missing element CallbackURL (PaymentRequest.CallbackURL) Exception Location:C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\zeep\xsd\elements\element.py in validate, line 280 -
OSMGeoAdmin: Imported OSM maps: points, lines and roads are ok, not multipolygons
Download an OSM map from geofabrik. Import it with osm2pgsql (basic commands, no fancy stuff) You will have your tables ready to use. Here's are my models (all the same fields for Line, Polygon, Point and Roads, just one is enough): class PlanetOsmLine(models.Model): class Meta: db_table = 'planet_osm_line' managed = False osm_id = models.BigIntegerField(primary_key=True) # ...tons of other field (unused)... way = GeometryField(default=None) Now, to display it in the admin interface, basic admin.ModelAdmin does the job and it work, like this for a road: Let's add the OSMGeoAdmin interface with this code: class PlanetOsmAdmin(OSMGeoAdmin): pass my_admin_site.register(PlanetOsmLine, PlanetOsmAdmin) my_admin_site.register(PlanetOsmPolygon, PlanetOsmAdmin) my_admin_site.register(PlanetOsmPoint, PlanetOsmAdmin) my_admin_site.register(PlanetOsmRoads, PlanetOsmAdmin) You'll get this, which is way nicer: OSM Admin works with everything except polygons. Here's the basic view: And when I do my_admin_site.register(PlanetOsmPolygon, PlanetOsmAdmin) then I get only this, always the same place: If the polygons are displayed properly without OSMGeoAdmin, and are not displayed properly with it. There's no error in the console log of Chrome. What am I missing? -
Django Performance | Recalculating a field value in all related models after updating a model in Django
I want to learn what is the best approach to recalculate a model field value(total_cost in my Product model class) in all related models after updating a model. I wrote a piece of code and it works but it takes long time. How can I speed up my code? Here is model classes #models.py class Product(..): total_cost = models.FloatField(...) materials = models.ManyToManyField(Material, through="MaterialProduct") def calculate_cost(self): return round(calc_material_price(self.materialproduct_set.all()),2) def calc_material_price(self, mylist): res = 0 for m in mylist: res += m.material.price * m.material_rate return res class Material(..): price = models.FloatField(...) class MaterialProduct(..): product = models.ForeignKey(Product, ..) material = models.ForeignKey(Material, ..) material_rate = models.FloatField() And my serializer sample class UpdateProductMaterialSerializer(..): #... def update(self, instance, validated_data): #in front-end total cost calculated and I assign it here directly instance.total_cost = self.initial_data.get("total_cost") instance.save() mylist_data = self.initial_data.get("mylist") material_list_for_update = [] for item in mylist_data: material = item.get("material") material_instance = Material.objects.get(pk=material["id"]) # I use this list for updating all Products material_list_for_update.append(material_instance) material_rate = item.get("material_rate") mp = MaterialProduct.objects.filter(product=instance, material=material_instance).first() mp.material_rate = material_rate mp.save()# here my one product is updated successfully # TO UPDATE ALL PRODUCTS I call below method # But this takes 15 seconds update_all_product_by_sent_materials(material_list_for_update) return instance def update_all_product_by_sent_materials(self, material_list): for material in material_list: for mp in … -
How could I send email from users who are logged in to admin?
I am working on a project to send the withdraw request from user who is logged in to admin. In this case I don't have to send mail to users instead I will have to send mail to admin official email address for notification. I used reply_to, but it showed me that it is unexpected argument views.py @login_required def withdraw(request): form_class = WithdrawBalance if request.method == 'POST': form = form_class(request.POST) obj = form.save(commit=False) obj.owner = request.user obj.save() messages.success(request, f'Your request has been submitted.') send_mail('New Withdrawal Request', 'Hello there, A new withdrawal request has been received.', request.user.email, ['bilalkhangood4@gmail.com'], fail_silently=False) return redirect('index') else: form = form_class() context = {'form': form} return render(request, 'nextone/withdraw.html', context) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_SSL = False -
How can I update associated models in a django DeleteView
I have a couple of models, Content and Hostname. Hostname has a content_id associating the models: class Content(models.Model): name = models.CharField(max_length=120) message = models.TextField() class Hostname(models.Model): """ Hostname model """ name = models.CharField(max_length=250) content = models.ForeignKey(Content, on_delete=models.DO_NOTHING, null=True) On the content delete form/view, I have a drop-down selector to specify what content should be assigned to hostnames that are associated with the content being deleted. Contents: Content1 Content2 Content3 Hostnames Hostname1 (content_id: Content1) Hostname2 (content_id: Content2) Action: Delete Content2, user selects Content3 in the drop-down when deleting Content2 Hostname2 should be updated to be associated with Content3 The template for the content_confirm_delete looks like this, when selecting the content_id: <select name="content_id"> {% for new_content in contents %} {% if new_content.id != content.id %} <option value="{{ new_content.id }}" {% if default_content == new_content.name %}selected{% endif %}>{{ new_content.name }}</option> {% endif %} {% endfor %} </select> The content delete is using a generic.DeleteView: class ContentsDeleteView(generic.DeleteView): model = Content success_url = reverse_lazy('content.list') -
Running of os system before actual file content is formed
I'm currently encountering one major problem: script executing the command before file being formed. I'm currently running the codes on the Unix server using Django framework. Please refer to the code below (these are the portions of my main code): views.py get_bags = request.POST.getlist('bags[]') get_bags_others = request.POST.get('bagsss') f2 = open(os.path.join(Path, "bags.txt"), "w+") if get_bags == None: f2.write('') else: string_bags = ''.join(get_bags) f2.write(string_bags) if get_bags_others != '': f2a = open(os.path.join(Path, "bags.txt"), "a+") f2a.write(get_bags_others) ... os.system("/home/USER/anaconda3/bin/python /home/USER/AutoML/ML_AutoML_GUI.py") html <form id='upload' method="post" enctype="multipart/form-data" onsubmit="uploadFile();"> {% csrf_token %} <h4 style="font-size: 0.95em"><u>BAGs</u></h4> <input id="21" type="checkbox" name="bags[]" value="10 " /> <label for="21">10</label> <br /> <input id="22" type="checkbox" name="bags[]" value="20 " /> <label for="22">20</label> <br /> <input id="23" type="checkbox" name="bags[]" value="30 " /> <label for="23">30</label> <br /> <input id="24" type="checkbox" name="bags[]" value="40 " /> <label for="24">40</label> <br /> </form> In the code above, the file that I've tried to form here is 'bags.txt'. However, it kept giving me the value of NULL, which shows that the command is executed before the file is formed (through checking the checkbox). Also, the code ... above did not change anything with regards to the content of 'bags.txt'. The code of time.sleep(30) before os.system("/home/USER/anaconda3/bin/python /home/USER/AutoML/ML_AutoML_GUI.py") but it does not show any … -
How to place a custom drop down in django model admin page? [duplicate]
This question already has an answer here: django admin - add custom form fields that are not part of the model 5 answers I was unable create a custom drop down in Django model admin page. I need to create a custom drop down which have some custom options. After selecting the option and saving the data i need to get that option in the save_model() method -
How to alter or customize django admin page. (removing some built-in help texts) [duplicate]
This question already has an answer here: How to override and extend basic Django admin templates? 11 answers I'm customizing my django admin page. And on my add user form in admin page there is this help text that i want to remove that says, "First, enter a username and password. Then, you'll be able to edit more user options." And I inherited BaseUserAdmin in my UserAdmin class at my admins.py. I don't know if it has something to do with it. I'm new to django. Any help would be really appreaciated. Thank you. -
After saving form1, sending some information to form2
i have 2 form page page1 and page2 page1 fields are: name,game,info,extra,t1 (foreignkey field), t2 (foreignkey field) page 2 fields are: name,extra,t1 (foreignkey field), t2 (foreignkey field) After saved the of page1, I use redirect to page2 if form.is_valid(): f= form.save(commit=False) ... f.save() return redirect(reverse('page2', kwargs={"k":v ,"k1":v1})) How do I send some information as a value to the form on page 2 after saving the data on page 1? -
Mysql gone away with peewee as second database in Django
I'm using peewee to access a remote MySql database to retrieve data that I need to display in a Django app. It means that peewee isn't really used to access the main db but just to like, define custom models: Example in databases.py : from django.conf import settings from playhouse.pool import PooledMySQLDatabase database = PooledMySQLDatabase( settings.DB_PEEWEE, **{ "use_unicode": True, "charset": "utf8", "max_connections": 32, "stale_timeout": 300, # 5 minutes. "password": settings.DB_PEEWEE_PSWRD, "user": settings.DB_PEEWEE_USER, "host": settings.DB_PEEWEE_HOST, "port": settings.DB_PEEWEE_PORT, } ) in models.py: from .databases import database class BaseModel(peewee.Model): class Meta: database = database class CountryGroups(BaseModel): africa = peewee.CharField(null=True) group_code = peewee.AutoField() group_name = peewee.CharField() latin_eur = peewee.CharField(null=True) type = peewee.CharField() class Meta: table_name = "country_groups" ... # other main django models So the model can be easily called from the views.py file as : CountryGroups_list = ( CountryGroups.select() .where(CountryGroups.group_name << ["ERROR", "INFO"]) .order_by(CountryGroups.group_name.desc()) .limit(1000) ) I can run the query fine. But I get an error after 24 hours where the connection is broken: (2006, "MySQL server has gone away (error(32, 'Broken pipe'))") The suggested method of solving this in Django is trough the usage of a middleware but this assume that in that case peewee related db is the main one, … -
Capturing values from url in post request in Django
I want to capture url values from a url into my views in a post request. My urls.py looks like below from django.urls import path from . import views as projects_views urlpatterns = [ path('<str:project_id>/comments', projects_views.ProjectCommentList.as_view(), name="project_comments"), ] and I want to capture the value project_id in my ListCreateAPIView. Get call works fine. My views.py looks like below class ProjectCommentList(generics.ListCreateAPIView): queryset = projects_models.Comment.objects.all() serializer_class = projects_serializers.CommentSerializer def get(self, request, project_id=None): queryset = self.filter_queryset(self.get_queryset()) queryset = queryset.filter(project__id=project_id) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) def perform_create(self, serializer): project_id = ### Need "project_id" here project = projects_models.Project.objects.get(id=data.get('project_id')) serializer.save(project=project) How can this be done? -
How to fix " 'Query' object has no attribute 'contains_column_references'"
As i'm tring to insert some data using POST request into mysql dataBase i'm getting an error informing me that AttributeError: 'Query' object has no attribute 'contains_column_references' Internal Server Error: /add_borrow/ Traceback (most recent call last): File "D:\pyvenv\pyvenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\pyvenv\pyvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\pyvenv\pyvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python_workspace\dms\app01\views.py", line 23, in inner return func(req, *args, **kwargs) File "D:\Python_workspace\dms\app01\views.py", line 286, in add_borrow end_time=end_time, number=number, contents=content ,device_id=device) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\base.py", line 779, in save_base force_update, using, update_fields, File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\base.py", line 908, in _do_insert using=using, raw=raw) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1334, in execute_sql for sql, params in self.as_sql(): File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1278, in as_sql for obj in self.query.objs File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1278, in <listcomp> for obj in self.query.objs File "D:\pyvenv\pyvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1277, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) …