Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Simple solutions to create an interface with a python script?
I coded a simple Python script to automate some accounting work at my internship and it has worked wonderfully. However, now that I am leaving I am a bit worried about the other accountants being able to use the same script from the command line or JupyterLab. It would be amazing if I could create a simple interface for them so they don't have to learn anything new (: the script is really simple: it imports an excel file from the user's computer, transforms into a data frame, replaces a few strings, does some calculations, deletes some columns, and outputs an excel file with the new formatting. The script can be viewed at my github here: https://github.com/brunnatorino/FEC/blob/master/ALL_app.py I even tried adding some user input functions so they wouldn't have to mess with the code, but that has also proven challenging for them to learn and remember. Is there any simple interface solutions where I can use my existing script? I would prefer to have the least amount of modifications to the code as I don't have a lot of time left in my internship. -
How to Dynamically Remove Form from Formset
I have a Django formset where a user can dynamically add forms through a jQuery script. How can I use jQuery to dynamically remove the last form in the formset when the user clicks the #remove_form button? template.html <div id="form_set"> {{ presales_formset.management_form }} <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="presalesForm" method="post" name="presalesForm"> <div class="field"> <label class="label is-large">High Level Task List</label> </div> {% csrf_token %} {% for presales_form in presales_formset.forms %} {{ presales_form.field_errors }} {{ presales_form.errors }} {% endfor %} </div> <div id="empty_form" style="display: none;"> {{ presales_formset.empty_form }} <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="emptyPresalesForm" method="post" name="presalesForm"> {% csrf_token %} <div class="field is-inline-flex"> <div class="control"> <button class="button is-success" id="add_more" name="add_more" type="button">+</button> </div> </div> <div class="field is-inline-flex"> <div class="control"> <button class="button is-danger" id="remove_form" type="button">-</button> </div> </div> <script> $(document).ready(function () { $('body').on('click', '#add_more', function () { var form_idx = $('#presalesForm-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#presalesForm-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); }); </script> -
Unable to create a project with django-admin, the process is using a wrong path because I installed a wrong Python beforehand
When typing "django-admin startproject DEMOPROJECT" in command prompt, I'm getting the following feedback: "Fatal error in launcher: Unable to create process using '"c:\program files (x86)\python37-32\python.exe" "C:\Program Files\Python37\Scripts\django-admin.exe" startproject DEMOPROJECT'" The "c:\program files (x86)\python37-32\python.exe" is a wrong path and I'm not sure why django-admin is looking at this path. I have changed the path to my new path in the environmental variables. -
could not create unique index "credits_credit_pkey"
Initially, I had a model of Credit. But after adding models of Hypothec and AutoCredit with similar functionality, I realized that I needed to make a base model and inherit from it. When I tried makemigrations, I received a question: You are trying to add a non-nullable field 'abstractbaseproduct_ptr' to `credit` without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py I entered 1; 1 It is not clear what the 'abstractbaseproduct_ptr' field is? Then i got You are trying to add a non-nullable field abstractbaseaction_ptr to creditaction without a default; we can't do that (the database needs something to populate existing rows). Again introduced 1; 1. When I try to migrate, I get django.db.utils.IntegrityError: could not create unique index "credits_credit_pkey" DETAIL: Key (abstractbaseproduct_ptr_id) = (1) is duplicated. Such questions arose only with the Credit model. Apparently, because there is already data in this table... How to be, tell me? class AbstractBaseProduct(models.Model): bank = models.ForeignKey('banks.Bank', verbose_name=_('bank')) #other fields class AbstractBaseAction(models.Model): name = models.CharField(_('name'), max_length=255) short_description = models.CharField(_('short description'), … -
When I enter the admin panel I get an error DoesNotExist at /admin/login/ Site matching query does not exist
When I enter the admin panel I get an error. I go through localhost:8000/admin If you want, I will throw off the code of how I did the registration and settinngs I logged into the admin panel recently, and after that I worked with registrations and after that I could not log in, but I deleted everything I did and returned everything to its original form when I still entered but still had an error Traceback: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sites\models.py" in _get_site_by_request 39. SITE_CACHE[host] = self.get(domain__iexact=host) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in get 408. self.model._meta.object_name During handling of the above exception (Site matching query does not exist.), another exception occurred: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\sites.py" in login 399. return LoginView.as_view(**defaults)(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, … -
How to mock test python requests
I want to know how to write mock python request tests. def request_headers(): payload = { 'client_id': settings.STAT_SERVER['CLIENT_ID'], 'client_secret': settings.STAT_SERVER['CLIENT_SECRET'], 'username': settings.STAT_SERVER['USERNAME'], 'password': settings.STAT_SERVER['PASSWORD'], 'grant_type': 'password', } How can I mock test all of this? token_url = settings.STAT_SERVER['URL'] + 'o/token/' r = requests.request( method="POST", url=token_url, data=payload, verify=False) if r.status_code != 200: msg = "Failed to authenticate. Error code {}: {}" msg = msg.format(r.status_code, r.text) LOGGER.error(msg) credentials = r.json() Here's the base_headers base_headers = { 'Content-Type': 'application/json', 'Accept': 'application/json, */*' } base_headers['Authorization'] = "{} {}".format( credentials['token_type'], credentials['access_token'] ) LOGGER.debug('Get token: credentials={}'.format(credentials)) return base_headers -
Documenting Django rest framework with rest_framework.documentation
I am documenting rest api using rest_framework.documentation not swagger, But I did not find any proper docs on how to use it. Can anyone tell me how it works, How it picks the apis and create document? beacause for my application, it is picking every url and there is not heading to seperate those apis. Also, how can I edit the the generated document for apis. -
How to Paginate within an action in Django Rest Framework
Good afternoon community, I have a question about the django rest framework page, in this case I manage to do it in the viewset, but in a class action I have not been able to achieve it. class PostPageNumberPagination(PageNumberPagination): page_size=10 class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interfaces.objects.all() serializer_class=InterfaceSerializer pagination_class=PostPageNumberPagination # La siguiente funcion es un decorador(funciones extra) de la clase RegistrosViewSet para poder manipular los datos que voy a presentar de acuerdo a la URL que se le asigne con el url_path # El siguiente action actua para poder presentar todos los datos de todos los objetos @action(methods=['get'],detail=False,url_path='registros-data-table',url_name='registros_data_table') def registros_data_table(self, request): paginator=PostPageNumberPagination return Response( { 'id_interface':interface.id_interface, 'id_EquipoOrigen':interface.id_EquipoOrigen_id, 'EquipoOrigen':interface.id_EquipoOrigen.nombre, 'LocalidadOrigen':interface.id_EquipoOrigen.localidad, 'CategoriaOrigen':interface.id_EquipoOrigen.categoria, 'id_PuertoOrigen':interface.id_PuertoOrigen_id, 'PuertoOrigen':interface.id_PuertoOrigen.nombre, 'estatus':interface.estatus, 'etiqueta_prtg':interface.etiqueta_prtg, 'grupo':interface.grupo, 'if_index':interface.if_index, 'bw':interface.bw, 'bw_al':interface.bw_al, 'id_prtg':interface.id_prtg, 'ospf':interface.ospf, 'description':interface.description, 'id_EquipoDestino':interface.id_EquipoDestino_id, 'EquipoDestino':interface.id_EquipoDestino.nombre, 'LocalidadDestino':interface.id_EquipoDestino.localidad, 'CategoriaDestino':interface.id_EquipoDestino.categoria, 'id_PuertoDestino':interface.id_PuertoDestino_id, 'PuertoDestino':interface.id_PuertoDestino.nombre, 'ultima_actualizacion':interface.ultima_actualizacion, } for interface in Interfaces.objects.all() ) -
Django filter is not using the index on Postgresql JSONField
I have a Django model that contains a PostgreSQL jsonb field: class SocialUser(models.Model): id = models.BigIntegerField(primary_key=True) data = JSONField(blank=True, null=True, db_index=True) The data field contains a username attribute. I have indexed this attribute by CREATE INDEX ON users_socialuser ((data->>'username')); When I query it via Django ORM with the id, SocialUser.objects.get(id=123) and via the pgAdmin SELECT * FROM users_socialuser WHERE id = 123 they are both fast. But when I query with the JSONField's attribute username, pgAdmin SQL query SELECT * FROM users_socialuser WHERE data->>'username' = 'abc' is still equally fast, while SocialUser.objects.get(data__username='abc') is terribly slow. It seems that the Django ORM is not using the index on the username attribute. Why is that so? Can I explicitly force an index in Django ORM? Is there a workaround for this? -
Filter subset of a queryset in Django
I have these models: class Committee(models.Model): title = models.CharField("Title",max_length=50,null=False) members = models.ManyToManyField(User) class Meeting(models.Model): title = models.CharField("Title",max_length=50,null=False) date = models.DateTimeField("Date",null=False) committee = models.ForeignKey(Committee, on_delete=models.CASCADE) And I want my view to return all committees in which the logged user is in, and only the meetings that has already happened. I'm trying this code: class MeetingsView(generic.ListView): template_name = 'meetings/index.html' context_object_name = 'committees_list' login_required = True def get_queryset(self): return Committee.objects.filter(members__id=self.request.user.id,meeting__date__lte=timezone.now()) This returns me a queryset excluding the committees which has no meeting before today. What I want is to get all the committees, and the meeting_set to be filtered by the date. Is there another way to do it? -
NoReverse match at
Cannot find out why my web app keeps throwing this error. I am clueless NoReverseMatch at /new-orders/order-list/ Reverse for 'order-sent' with arguments '('',)' not found. 1 pattern(s) tried: ['new\\-orders/order\\-list/(?P<order_id>[0-9]+)/sent/$'] Request Method: GET Request URL: http://localhost:8000/new-orders/order-list/ Django Version: 2.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'order-sent' with arguments '('',)' notfound. 1 pattern(s) tried: ['new\\-orders/order\\-list/(?P<order_id>[0-9]+)/sent/$'] Reverse for 'order-sent' with arguments '('',)' not found. 1 pattern(s) tried: ['new\\-orders/order\\-list/(?P<order_id>[0-9]+)/sent/$'] here is my views.py where I want to change the booleanField order_sent to True. def sent(request, order_id): order = get_object_or_404(Order, pk=order_id) try: selected_order = order.objects.get(pk=request.POST['order']) except (KeyError, Order.DoesNotExist): return render(request, 'new_orders/order-list.html', { 'order': order, 'error_message': "You did not select a valid Order",}) else: selected_order.order_sent = True selected_order.save() return render(request, 'new_orders/order-list.html', {'order': order}) here is my model.py: class Order(models.Model): order_user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='myuser') order_number = models.CharField(max_length=11, unique=True) order_sent = models.BooleanField(default=False) here is urls.py app_name = 'new_orders' urlpatterns = [ path("order-list/", views.index, name='order-list'), path("order-list/<int:order_id>/", views.detail, name='order-detail'), path("order-list/<int:order_id>/sent/", views.sent, name='order-sent'), ] and my order-list.html: <form action="{% url 'new_orders:order-sent' order.id %}" method="post"> {% csrf_token %} <ul> {% for order in all_orders %} <li><a href="{{ order.id }}"> User: <b>{{ order.order_user }}</b> | Order Type : <b>{{ order.order_type }}</b> | Device: <b>{{ order.order_device }}</b> | Count: <b>{{ order.order_count }}</b> … -
I tried to create an django hello world program then I got this error
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('love/', include('love.urls')), path('admin/', admin.site.urls), ] I tried this code by seeing n online documentation and I see the code as same as the one in the documentation but I see the error and I can not start practicing django. from django.contrib import admin from django.urls import include, path urlpatterns = [ path('love/', include('love.urls')), path('admin/', admin.site.urls), ] Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in ad.urls, Django tried these URL patterns, in this order: ^love/ ^admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. It is being shown on the web -
How to remove input and confirm password fields from the form to a separate page?
good day!I have a form for editing data, in this form there is a new password field and confirmation of a new password, how can I correctly put these fields on a separate page? lines in the form below password1 and password2. I will be very grateful for the tips! class PatientEditForm(CustomUserChangeForm): username = forms.CharField(label='Логин') last_name = forms.CharField(label='Фамилия') middle_name = forms.CharField(label='Отчество') first_name = forms.CharField(label='Имя') image = forms.ImageField(required=False, label='Изображение') email = forms.CharField(required=False) day_of_birthday = forms.DateField(label='День рождения', required=False, widget=forms.DateInput(attrs={'class': 'datepicker', 'type': 'date', 'placeholder': 'Выберите дату рождения'})) password1 = forms.CharField(widget=forms.PasswordInput(), label='Новый пароль') password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля') def __init__(self, *args, **kwargs): super(PatientEditForm, self).__init__(*args, **kwargs) self.fields.pop('password') def clean(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='Повтор нового пароля не совпадает', ) return self.cleaned_data def save(self, commit=True): user = super(PatientEditForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class Meta: model = User fields = ('username', 'last_name', 'middle_name', 'first_name', 'email', 'day_of_birthday') -
Cascading addition of linked models
There are several related models class Skillset(models.Model): """ Skill set """ name = models.CharField('skill_set', max_length=32, unique=True) class Technology(models.Model): """Technologies.""" tech_set = models.ForeignKey(Skillset, on_delete=models.CASCADE, related_name="skillset", blank=True, null=True) name = models.CharField('technology name', max_length=32, unique=True) class Skill(models.Model): """Information about an employee's skills.""" employee = models.ForeignKey( Employee, on_delete=models.CASCADE, related_name="employee_skills") technology = models.ForeignKey(Technology, on_delete=models.CASCADE) year = models.CharField('common year using amount ', max_length=4) last_year = models.CharField('Last year of technology using ', max_length=4) level = models.CharField("experience level", max_length=64, choices=LEVELS) I need to make sure that the button is pressed to create instances of the Skills model related with a specific user. I wrote a function that creates one instance at a time using the form. template.html <form action="{% url 'add_skill_set' %}" method="post"> {% csrf_token %} Backend<input type="checkbox" name="back" value="back"> Frontend<input type="checkbox" name="front" value='front'> <input type="hidden" name="id" value="{{ employee.pk }}"> <input type="submit" value="Search"> </form> <div class="container my-5" id="about"> views.py def add_skill_set(request): id = int(request.POST.get('id')) back = request.POST.get('back', None) if request.method == "POST": if back: Skill.objects.create(employee=Employee.objects.get(id=id), technology_id=3) --> ADD CASCADE HERE return redirect('profile', pk=id) if front: ..... If the user chooses a checkbox, then after submitting the form, an instance of Skills is created that is associated with this user, but only one certain instance. Here I manually specify … -
Django I am unable to load the view I want to with a different URL
I am trying to create a new view which I can link to with a button on the index page. Clicking the button is changing the URL in the browser but is not changing the view. I tried to send an httpresponse in the view instead of trying to render a new html file hoping that that was the problem. Main urls urlpatterns = [ url(r'^$', include('posts.urls')), url('admin/', admin.site.urls), url('posts/', include('posts.urls')), url('forms/',include('posts.urls')) ] App urls urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/(?P<id>\d+)/$', views.details, name='details'), url(r'^forms/$', views.theform, name = 'forms') ] Views def theform(request): manystuff = ManyStuff.objects.all()[:10] context = { 'manystuff': manystuff } return render(request,'posts/randomform.html',context) I expect to click the button on the index and load randomform.html on the /forms url. All it does is change the url to forms and keeps the same view. -
I can't save an auth token sent from Django rest framework in my angular client side
I prepared the backend api in Django and am able to login/out and send a token when login is successful, so my problem is i can't build an http interceptor that is able to read the token and save it in local storage I have already tried some methods i found in the internet but with no success this is what i catch in the console token: "fd3e2c1f51d45066e291ad8209bdd7e7cb3b5398" __proto__: Object -
multiple database connection in Django
Issue with multiple database connections in django and assigning to a model As I need to create modules( which will only read records from the database) from diffrent source(MSSQL, ORACLE, CMS)I am trying to configure Database details in setting.py. For the setting of my MSSQL database, the connection was not happening when I look at the connection string that was created by django base.py file it is Driver={ODBC Driver 11 for SQL Server}; Server=, ; Trusted_Connection=yes; Database=; Passoword= but acctually the connection string will work only when the Trusted_Connection=yes comes after the database details like below Driver={ODBC Driver 11 for SQL Server}; Server=, ; Database=; Passoword= is there any thing Iam doing wrong in my DATABASE details. below is my database detail. 'MDMDB': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DATABSENAME', 'USER': '', 'HOST': 'HOSTNAME:PORTNAME', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, 'Trusted_Connection':'yes', } -
How can I execute a heavy-processing, background python code after submitting a form in a Django website?
I have a conceptual question regarding background tasks in Django. I am running a Python/Django site through PythonAnywhere. I have a webapp called "databooks" which is comprised of a form that has the following entries: Databook Name Folder Location/Link (which is on my PythonAnywhere file system) This databooks app then looks at the folder location and compiles all the miscellaneous files within to create one large PDF. However, due to the nature of merging pages and adding footers, etc, it is considered a "heavy process" by PythonAnywhere, which they define as a web worker that exceeds 5 minutes and which they respectively kill. My solution in mind would be to execute a background-python script after the form is submitted, which inputs the entires from the databooks views.py file into a backgrounddatabookgenerator.py file which can run independent of what a user does in the browser window. After looking at PythonAnywhere's diagnosis of this, I have been researching some options, but have been unsuccessful so far in implementing a background tasks (i.e., django-background-tasks). Is anyone familiar with a Django workflow I could implement to call another python file as a background task after a submit button is clicked? In doing so, I … -
Django model operations with foreign key and double underscore
I'm new to Django and just being curious to know more. Assuming I have two models defined as follows: class ModelA(models.Model): Item1 = models.Charfield() description = models.Charfield() class ModelB(models.Model): ItemTypes = models.CharField(ModelA, on_delete=models.CASCADE) When trying to reference or use the model, you use them like this (still assuming): something = ModelB.objects.filter(ItemType__Item) My question is on the double underscore __. I'm just curious to know: What does the code at the back end look like. Is there a valid syntax with a triple underscore or a single underscore? -
How to display only date from datetime field in modelAdmin in Django admin panel?
I have a model which has a column created_at which is actually a datetime field of this format 16.07.2019 12:26:37. I want to display only date present in this created_at field in admin panel in Django. I can display the whole field's value which is datetime if I mention the 'created_at' in list_display while creating modelAdmin. How can I display only the date value in results page like this 16.07.2019? Are there any inbuilt filters to do that while registering the modelAdmin? Python: 3.7.3 Django: 2.1.5 -
How to validate django form field while it is typing?
How to validate django form field while it is typing? For example for username field I am want to check if this username already exist def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise ValidationError("Entered username already exists") return username -
Getting { "user": [ "This field is required."] } on Postman everttime I try to post
I am trying to create a sign up api using createAPIView on Django rest Framework. Everytime I post data on Postman it returns the above error although it gets response when I run it in browser. Also the image field is causing problem in raw data on postman. I have tried a lot of things but nothng has seemed to work. What am I supposed to do? serializers class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(min_length=8) class Meta: model = User fields = ('id', 'first_name','last_name', 'email', 'username','password') extra_kwargs = {'user': {'required': False}} class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() code = serializers.CharField(read_only=True) avatar = serializers.FileField(use_url=False) class Meta: model = UserProfile fields = '__all__' extra_kwargs = {'user': {'required': False}} def create(self, validated_data): user_data = validated_data.pop('user',None) image = validated_data.pop('avatar') upr=UserProfile.objects.create(user=user_data, image=image**validated_data) return upr views class UserCreate(generics.ListCreateAPIView): serializer_class = UserProfileSerializer user_serializer = UserSerializer queryset = UserProfile.objects.all() parser_classes = (FormParser,MultiPartParser,FileUploadParser) def post(self, request): serializer = UserProfileSerializer(data=request.data) print(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How can i use fontawesome icon from django admin to template?
I would like to insert and choice fontawesome icon from django admin, that will show in template. What will be the model, view and template tag? -
How can I check the correctness of email end?
I need to check if there's a point in email after "@". if not email.endswith('.com'): args['reg_error'] = "Email is incorrect!" I need to do something like this, but with any end which has point after "@". -
'dict' object has no attribute 'pk' when using Django bulk_create() function
I have a table counters with 2 fields: date and value. I have a big list of objects which need to be inserted into table counters. But using serializer.save() for every row in list, there will a lot of inserts and if i have a lot of data, it will take some time until it the data has finished inserting. To solve this i looked into Django's documentation and i found that there is a function name bulk_create which can help me to insert into table a list of Objects in just 1 query. Now, here's my code: models.py: class CounterFileData(models.Model): date = models.DateTimeField() value = models.FloatField() serializers.py: class CounterFileDataSerializer(serializers.ModelSerializer): class Meta: model = CounterFileData fields = ['date', 'value'] and the code where i use bulk_create: objs = (CounterFileData(date=row.date, value=row.value) for row in parsed_data) batch = list(parsed_data) CounterFileData.objects.bulk_create(batch) row has the following schema. For example: { "date": "2018-12-31T22:00:00" "value": 9.23129792740622e-05 } When i try to do that CounterFileData.objects.bulk_create(batch) i get the following error: AttributeError: 'dict' object has no attribute 'pk' Can somebody tell me why it returns no attribute 'pk' ? I'm struggling with this thing some good hours and i still can't find a fix. Thanks in advance.