Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Nested for loop do not work properly
We have two tables that have many to one relationships. in models.py : class Author(models.Model): name = models.CharField(max_length=100, null=False) username = models.CharField(max_length=35, null=False) def __str__(self): return self.name class Article(models.Model): CATEGOTY = ( ('programming', 'programming'), ('other', 'other') ) title = models.CharField(max_length=100, null=False) content = models.TextField(null=False) category = models.CharField(max_length=100, choices=CATEGOTY, null=False) creation = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title and in views.py: def articles(request): authors = Author.objects.all() articles = Article.objects.all() totalArticles = articles.count() authorAticles = Author.objects.annotate(numberOfArticles=Count('article')) return render(request, 'articles/article.html', { 'articles' : articles, 'authors' : authors, 'totalArticles': totalArticles, 'authorAticles': authorAticles }) and html code: <div class="container mb-3 p-3" id="author-aricle"> <div class="row"> <div class="col-sm"> totle articles: {{totalArticles}} </div> {% for author in authors %} <div class="col-sm"> {{author}}: {% for authorAticle in authorAticles %} {{authorAticle.numberOfArticles}} {% endfor %} articles </div> {% endfor %} </div> </div> I want the html output to display the number of articles by each author next to its name This means how many articles does each author have? I want the html output to be like this: author1: 2 articles author2: 3 articles author3: 3 articles etc but this does not happen and the output is: author1: 3 3 2 articles author2: 3 3 2 articles author3: … -
403 Forbidden making Ajax GET request to Django endpoint
Not really familiar with Ajax requests and am trying to learn about them. The following code is returning: GET http://127.0.0.1:8000/data/ 403 (Forbidden) jquery.min.js:2 views.py: def load_posts_data_view(request): qs = Post.objects.all() data = [] for obj in qs: item ={ 'id' : obj.id, 'title' : obj.title, 'body' : obj.body, 'author' : obj.author.user.username } data.append(item) return JsonResponse({'data':data}) urls.py: urlpatterns = [ path('data/', views.load_posts_data_view, name = 'posts-data'), ] main.js: $.ajax({ type: 'GET`', url: '/data/', success: function(response){ consoe.log(response); }, error: function(error){ console.log('error'); } }); On questions related to making POST requests, I see you have to provide a CSRF_TOKEN but I don't think I should have to do this when making a GET request? Can anyone help with this? -
Hiding html element clicked after ajax success
I'm new to Web Development and making a mock twitter application. I want the tweet box to be removed after I click on the delete button (only if it is actually deleted in the backend) I'm using django templating to loop through each tweet: {% for tweet in data%} <div class="container border border-primary rounded"> <p> tweet: {{tweet.content}}</p> <div class="row"> {{tweet.id}} <p class = "likes" style="margin: 0px 10px;"> likes: {{tweet.likes}} </p> <button class="btn btn-dark like" style="margin: 0px 10px;">like</button> <p class = "retweets" style="margin: 0px 10px;" > retweets: {{tweet.retweets}}</p> <button class = "btn btn-dark retweet" style="margin: 0px 10px;">retweet</button> <button class="btn btn-dark float-right delete_tweet" onclick="delete_tweet('{{tweet.id}}')">delete</button> </div> </div> {% endfor %} Here's the delete_tweet function: function delete_tweet(id){ $(document).ready(function(){ $.ajax({ url: "{% url 'deleteTweet'%}", data: {'id':id}, dataType: 'json', success: function(data){ console.log(data); $(this).parent().parent().remove(); } }); }); } This deletes the tweet in the backend fine, but the remove method doesn't work - I'm pretty sure that I'm this is not referring to the right scope, what should I be doing instead? -
403 Error when using Axios to post to Django
I am using a Django server connected to a React Native front end. The server works fine in my browser, but I get an error when trying to post in my app from Axios. I get the following error: [26/Aug/2021 13:26:53] "POST /api/ticket/ HTTP/1.1" 403 58 Forbidden: /api/ticket/ Here is my axios function: const getTicket = async function () { try { let res = await axios.post("http://127.0.0.1:8000/api/ticket/", { userID: 5, eventID: 1, }); return res; } catch (err) { console.error(err); return err; } }; Here is my models.py for the Ticket class: class Ticket(models.Model): ticketID = models.AutoField(primary_key=True) userID = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) eventID = models.ForeignKey( Event, related_name='tickets', on_delete=models.CASCADE) bookedAt = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.ticketID) Here is my TicketSerializer in serializers.py: class TicketSerializer(serializers.ModelSerializer): class Meta: model = Ticket fields = "__all__" My views.py class TicketViewSet(viewsets.ModelViewSet): queryset = Ticket.objects.all() serializer_class = TicketSerializer filter_backends = [DjangoFilterBackend] class MyTicketViewSet(viewsets.ModelViewSet): queryset = Ticket.objects.all() serializer_class = TicketSerializer def get_queryset(self): user = self.request.user return Ticket.objects.filter(userID=user) My urls.py router = DefaultRouter() router.register('ticket', TicketViewSet) router.register('myticket', MyTicketViewSet) urlpatterns = [ path('', include(router.urls)), ] What is confusing me is that more complex axios calls are working, such as this one below which correctly identifies the userid from the axios call … -
how to use django message framework for login required to show message
I am using @login required decorator in my most of views so what I want is to use message in my login page telling user if you want to open that page you have to login first so how I can achieve that I know I cannot achieve that on my views so anyone does that and know how to do please tell me how to achieve that if a user redirected to login because of @login required I want to show message please login to continue -
Created Model is not showing in Django Atomic Trasaction Block
Following code not working, it should increase count within the block itself: I am using django with mysql database. >>> len(ModelObject.objects.all()) 89 >>> with transaction.atomic(): ... ModelObject.objects.create(modelId="123") ... print(len(ModelObject.objects.all())) ... <ModelObject: ModelObject object (16125)> 89 >>> len(ModelObject.objects.all()) 90 -
Django handle files uploaded through React without letting users waiting
Apologies if the title is confusing. So, I'm trying to build a webapp where users upload some files through a React site, then once Django receives those files, it starts processing those files by calling some functions. However, the workload is quite heavy, it might take 3-5 mins for backend to finish the processing operation. I'd like to have the backend do its thing without letting the frontend user to wait. So, while the backend is processing those files, users can continue use the site however they want, and when the processing operation is done, there can be a snackbar or something to notify the front end user that the operation is done. Backend settings.py # Configure path to uploaded files DATA_ROOT = os.path.join(BASE_DIR, 'myapp/main/data') DATA_URL = 'data' Model: myproject/myapp/models.py class Document(models.Model): docfile = models.FileField(upload_to='') View: myproject/myapp/views.py I was thinking about using Python's async to do this, but wouldn't the return immediately kill the process? The upload function is just some slight modification of Django's documentation on how to handle uploaded files. # import a bunch of stuff... async def handle_uploaded_files(files): await process(files) def upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): files = request.FILES.getlist('ix_files') for file … -
DRF: Wrong content type recognition for CSV files when sending request by curl
I have a simple DRF view: @api_view(['post']) def test(request): file = request.FILES['file'] content_type = file.content_type return Response('ok') I'm making requests with curl. The problem is that when I send CSV file in request content type is not defined correctly. For example: curl --location -X POST \ -F 'file=@"file.csv"' \ 'http://localhost:8000/tasks/test' shows content type == 'application/octet-stream'. I would expect text/csv. But when I send png file content type is 'image/png'. How to force recognize content type when sending csv files correctly? -
Django Using attribute of queryset object
I create comments/messages area for my page. and I create like buttons for them too. When user enter the page I want show he default like button(Like or Unlike). If user is in the like list I want show he Unlike but I want to show the Like button if it is not in the list, that is, if it is not liked yet. Views: def detail_post(request,_detail): postDetail = UserPosts.objects.get(pk = _detail) #This is post messages = UserMessages.objects.all().filter(post_id =postDetail.id) #This is comment of post # I tried this but iit is not works for x in messages: total = x.like_message.all() print(total) context= { "detail":postDetail, "messages":messages, } Template: {% for message in messages %} {% if message.username_id == request.user.id %} <button class="btn btn-primary btn-sm" title="You can't like your message" disabled >Like</button> {% else %} <button class="btn btn-primary btn-sm text-white btn-like {{ message.id }} " type="submit" name="usermessages_id" value="{{ message.id }}" id="{{ message.id }}"> Like </button> {% endif %} {% endfor %} Here is the output of the for loop I wrote in the Views file: <QuerySet [<User: vahandag>]> <QuerySet [<User: vahandag>, <User: GladyaTH0R>, <User: user2>, <User: user3>, <User: vahandag1905>]> <QuerySet []> <QuerySet []> <QuerySet [<User: vahandag1905>]> <QuerySet [<User: vahandag1905>]> <QuerySet [<User: vahandag>]> … -
Direct graphql queries to DB READ Replicas
Want to direct graphql query requests to DB read replicas. We use a master slave architecture for DB(i.e. use master DB for write operations and several DB READ replicas for just reading data from DB). Since we use AWS RDS, the DB router puts a check on the type of request (POST vs GET) to forward the request to respective replica. GET requests are forwarded to DB READ REPLICAS while POST requests are forwarded to master DB. Now Graphql Queries use a POST request to read data from DB, reason being if graphql queries become large and complex they cannot be put in the GET request queryparams so a POST request is used to fetch data from DB. We would like to forward our graphql queries to READ replicas instead of master DB so that READ replica can be fully utilized and master DB is not overloaded. We plan to set some header in the request to do that. Will header setting work for our use case? If yes how do we do that in Django specifically for graphql queries. Any other ways to achieve this? -
geting more than one user in django
i created an app with referral system the challenge is that i want the referrer to see other models of his referred user say for example. investment platform i want the referrer to see the persons the refereed main account(a model) and investment status(a model). models class TheMain(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) main_balance = models.IntegerField(default=0) earning_balance = models.IntegerField(default=0) def __str__(self): return str(self.user) the referral returns more than one user class Referral(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) referral_balance = models.IntegerField(default=0) code = models.CharField(max_length=12, blank=True) referred_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="ref_by") updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user.username}- {self.code}' def get_reffered(self): qs = Referral.objects.all() my_refs = [] for reffered in qs: if reffered.referred_by == self.user: my_refs.append(reffered) return my_refs theviews referral = Referral.objects.get(user=request.user) my_ref = referral.get_reffered() refer_main = [] refer_invest =[] for my in my_ref: main = TheMain.objects.filter(user = my.user) for ma in main: refer_main.append(ma) print(f'this is the mama {ma} and amount funded{ma.main_balance}') the print statement returns all the referred name and amount paid Quit the server with CTRL-BREAK. this is the mama user1 and amount funded1100 this is the mama user2 and amount funded800 this is the mama user and amount funded400. the problem is loooping all these users … -
django, upload tif image
I am trying to upload a tif image (greyscale), using django ImageField. I have installed Pillow==8.3.1 and using Python 3.9. The app works only with PNG/JPEG images. Here is the model I am using: class Upload(models.Model): image = models.ImageField(upload_to='images') title = models.CharField(max_length=200) action = models.CharField(max_length=50,choices=ACTION_CHOICES) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title #breakpoint() # def __str__(self): # pixels = tfi.imread(self.image) # return np.shape(np.array(pixels)) def save(self,*args,**kwargs): #open image #breakpoint() if self.action=='tif': pixels = tfi.imread(self.image) else: pixels = Image.open(self.image) #pixels = tfi.imread(self.image) pixels = np.array(pixels) pixels=pixels[:,:,0] #pixels = pixels[0,:,:] #use the normalisation method img = get_image(pixels) im_pil=Image.fromarray(img) #save buffer = BytesIO() im_pil.save(buffer,format='png') image_png = buffer.getvalue() self.image.save(str(self.image), ContentFile(image_png),save=False) super().save(*args,**kwargs) #return self.image_png -
Get nginx error after 30 seconds work of script
In my Django project i have a script that can work more than 1 minute (i'm loading data through api, and each time service give me response to my request for about 2-3 seconds), each time after 30 seconds nginx give me error page with An error occurred. Sorry, the page you are looking for is currently unavailable. Please try again later. If you are the system administrator of this resource then you should check the error log for details. Faithfully yours, nginx. I have tried change my nginx config to set more time for connection My nginx.config: ... http { ... proxy_connect_timeout 90; proxy_send_timeout 120; proxy_read_timeout 120; ... } My /etc/nginx/conf.d/default.conf: upstream gunicorn { server unix:/run/gunicorn.sock; } ... location /api/ { proxy_read_timeout 300; proxy_connect_timeout 75; ... } ... Also my error.log of nginx: [error] *1 upstream prematurely closed connection while reading response header from upstream, client: ip_addres, server: _, request: .... Can someone tell pls what i'm doing wrong, i have tried everything i found from same questions, nothing helped Maybe gunicorn close connection? Thanks -
Django Forms: How to populate the choices of a choice field with data that required two other models that are related
here is the flow of the website: user creates an account. then registers some addresses. then when he/she wants to place an order, he/she has to choose one of the previously registered addresses here is the models: class User(models.Model): customer_id = models.AutoField(primary_key=True) class Address(models.Model): address_id = models.BigAutoField(primary_key=True,) address = models.CharField(max_length=500, blank=False,null=False,) customer = models.ForeignKey(User, on_delete= models.CASCADE) class Order(models.Model): order_id = models.BigAutoField(primary_key=True) customer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True) the cause of my problem is i have to use formtools (FormWizard) to split the ordering form into several pages. here is Forms: class NewOrderForm1(forms.Form): ... class NewOrderForm2(forms.Form): address = forms.ChoiceField(required=True,choices=??) name = forms.CharField() class NewOrderForm3(forms.Form): ... class NewOrderForm4(forms.Form): ... i have 4 forms as u see and the address field is in the second form. in views.py i have this: class NewOrder(SessionWizardView, LoginRequiredMixin): form_list = [NewOrderForm1, NewOrderForm2, NewOrderForm3, NewOrderForm4] def get_template_names(self): return [TEMPLATES[self.steps.current]] # templates for each form def done(self, form_list,*context ,**kwargs): type_form, deliver_info_form, time_form, final_form = form_list # "deliver_info_form" is the second form(NewOrderForm2) in forms.py address = deliver_info_form.address name = deliver_info_form.name customer = self.request.user order = Order.objets.create( address=address, name=name, customer_id=customer.customer_id, ) order.save() return render(self.request, template_name="thanks.html",) every thing till the second form/template works fine. but i can not … -
Docker-compose for microservice application
I have a web appliication, which consists of main server and 5 microservices (Django everywhere). I also have 2 databases (PostgreSQL) and redis working in one of microservices. I also use nginx for main server. I set up all on remote server and now services run through tmux just by commands like that: gunicorn --bind 127.0.0.1:5050 --workers 5 --threads 5 some_service.wsgi Now I think that the whole application must me containerized and I am an absolute beginner in Docker. As I understand, I need to build docker-compose.yml file and set every entity there. I made Dockerfile for every microservice. They look like: FROM python:3.8 RUN mkdir -p /usr/src/main_server WORKDIR /usr/src/main_server ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY . /usr/src/main_server RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt EXPOSE 5001 RUN chmod a+x ./run.sh ENTRYPOINT ["./run.sh"] and run.sh looks like: #!/bin/bash python manage.py collectstatic --settings=main_server.settings.development --noinput exec gunicorn --bind 127.0.0.1:5001 --workers 5 --threads 5 --timeout 15 main_server.wsgi so for now i made such docker-compose file: version: "3.8" services: user_db: "????" app_db: "????" redis: "????" main_server: build: context: . dockerfile: main_server/main_server/Dockerfile user_service: build: context: . dockerfile: user_service/user_service/Dockerfile session_service: build: context: . dockerfile: session_service/session_service/Dockerfile apartment_service: build: context: . dockerfile: apartment_service/apartment_service/Dockerfile … -
Relation does not Exist/ Programming Error in django
My this django WebApp works fine in Local development but when I tried it in production it says relation does not exist, I am probably sure it would be the problem with data base connection in production, it is sqlite3 on local but in production on heroku it is postgresql and I am unable to make it functional properly even I modified database connectivity in settings.py from sqlite3 to postgresql by applying new provided database credentials enter image description here ScreenShot -
Django Save multiple files uploaded from html to directory and process on them
here is my views .py ''' def savefile(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['filename'] fs = FileSystemStorage() name = fs.save(uploaded_file.name.replace(' ', '_'), uploaded_file) context['url'] = fs.url(name) if context['url']: print(context['url']) obj = Resume_extractor() global texting texting= obj.extract_text_from_pdf(context['url']) ''' here is html code ''' <form enctype = "multipart/form-data" method = "post"> {% csrf_token %} <input type = "file" name = "filename" multiple/> <input type = "submit" value = "Upload" /> </form> ''' How to iterate over multiple files to save them in a folder and used them 1 by 1 for processing over them -
Using rowspan inside a nested forloop in django on converting html to pdf?
I have the data set like below, comp={ {('Programming','gtu1','gects1','dtu1','5') : [['Javacode','Java','5','8','0'], ['Pythoncode','Python','6','9','1'],['Rubycode','Ruby','7','10','0']], ('Technical','gtu2','gects2','dtu2','8') : [['Djangocode','Django','8','NA','2'], ['Springcode','Spring','9','11','1'],['Flask','Flask','10','12','0']], ('Cultural','gtu3','gects3','dtu3','5') : [['cricketcode','Cricket','11','13','0'], ['Footballcode','Football','12','14','1']]}, } **i want to convert to html table using the rowspan like below image I have acheived till now like below but i am unable to add rowspan.. if i add it raises the error like below IndexError at /downloadcurriculumtranscripts/156/ list index out of range spanning problem in <PmlTable@0x18D91A309E8 9 rows x 10 cols(tallest row 35)> with cell(0,0) containing '<PmlKeepInFrame at 0x18d900e3748> size= maxWidth=63.87992x maxHeight=792.6969' hmax=9 lim=9 avail=538.5826771653543 x 648.6909950944882 H0=[None, None, None, None, None, None, None, None, None] H=[35.249999, 12.75, 12.75, 12.75, 12.75, 12.75, 12.75, 12.75, 12.75] spanCons={(1, 3): 12.749999, (2, 4): 12.749999, (3, 5): 12.749999, (4, 6): 12.749999, (5, 7): 12.749999, (6, 8): 12.749999, (7, 8): 12.749999, (8, 9): 12.749999} -
Django models FileField large file upload
I need to upload large files while using FileField field in Django model. This gives the error DATA_UPLOAD_MAX_MEMORY_SIZE. I think I need to use chunked-upload while saving in the model. How can I do that? Or is there any other solution? -
how to make a project for several companies - django
i made a project for an hotel , but now i want to make it dynamic to reuse by other hotels , i bought a good hosting plan , i want to make something like odoo application , one code base use by several companies ,now i've registered two hotels hotelA and hotelB , when i enter hotelA , i want to change the entire menu to hotelA and all rooms and booking , etc related to hotelA when i went to hotelB the same as well , i dont want to make new apps for hotelB i created hotel categories for defining new hotels class Hotels(models.Model): hotel_name = models.CharField(max_length=40,unique=True) def __str__(self): return self.hotel_name class Rooms(models.Model): hotel= models.ForeignKey(Hotels,on_delete=models.PROTECT) room_number = models.IntegerField() beds = models.IntegerField(default=2) class Meta: constraints = [ models.UniqueConstraint(fields=['hotel','room_number'],name='full_information') ] and also we have booking and visitors apps but they also have foreign key connection with Hotelsapp , i made home page which shows name of hotels when i want to access to hotelA it shows everything relates to hotelA and when i want to access to hotelB it shows all info relates to hotelB def hotels(request): hotel_lists= Restaurants.objects.all() return render(request,'hotel/lists.html',{'lists':hotel_lists}) #urls path('',hotels,name='hotels'), path('rooms/<str:hotel>',rooms,name='rooms'), <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 … -
best practice with models
i was wondering what is the best best way between: class User(AbstractUser): """Default user model""" email = EmailField(unique=True) is_photographer = BooleanField(default=False) and class Photographer(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) In both cases I can filter on user beiing photographer or filter on Photographer table but I do not know what is the best way to design my data. -
How to handle bulk create with multiple related models?
Here I have a form that have multiple input values with same name. I want to bulk create objects based on the following template design. I think the current approach with zipping the list wouldn't work properly if one of the list are unequal. What will be the better approach ? The front part should be like this as I posted you can check code snippet <script> $(document).on("click", ".q-name", function () { $(this).closest(".untitled").hide(); $(this).siblings('.q-title').prop('hidden', false); }); </script> <script> $(document).on("click", ".addOption", function () { option = `<div class="item"> <div> <input class="form-control" type="text" name="title" placeholder="Enter title" /> </div> <div> <select name="type" class="form-control"> Select <option disabled>Select</option> <option value="1">Option1</option> <option value="2">Option2</option> </select> </div>`; $(this).closest(".options").prepend(option); }); $(document).on("click", ".newOptionGroup", function () { group = `<input type="text" name="q_title" placeholder="model A field" class="form-control q-title"/></div> <p>Options of that model (Another model fields)</p> <div class="options"> <div class="item"> <div> <input class="form-control" type="text" name="title" placeholder="Enter title"/> </div> <div> <select name="type" class="form-control"> Select <option disabled>Select</option> <option value="1">Option1</option> <option value="2">Option2</option> </select> </div> </div> <div class="last"> <button type="button" class="btn btn-icon-only addOption"> Add more </button> <div> <div class="custom-control custom-switch"> <input name="is_document" type="checkbox" class="custom-control-input" id="customSwitche" value="1" /> <label class="custom-control-label" for="customSwitche" >Is File</label > </div> </div> <div></div> </div> </div> </div> <div class="option-group-new newOptionGroup"> <button> Add New group</button> </div> … -
Tabulator and Django Rest Framwork - error onremote pagination
I had some issues with figuring out how to use Tabulator 4.9 and DRF 3.1.2 for working with each other using pagination. Everything works fine until I use the page size setting of Tabulator which I used a simple DRF GenericViewSet with ListModelMixin and RetrieveModelMixin: class ProductViewSet(RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = ProductSerializer lookup_field = "number" def get_queryset(self): try: return Product.objects.all() except: return None def retrieve(self, request, serial = None): try: query = Product.objects.filter(serial = serial) results = ProductSerializer(data = query, many = True) results.is_valid() return Response(data = results.data, status = status.HTTP_200_OK) except Exception as E: return Response(data = f"""{E}""", status = status.HTTP_400_BAD_REQUEST) I also defined a paginaton.py in the main project folder: from rest_framework import pagination class PageNumberPaginationWithCount(pagination.PageNumberPagination): def get_paginated_response(self, data): response = super(PageNumberPaginationWithCount, self).get_paginated_response(data) response.data['last_page'] = self.page.paginator.num_pages return response and added it in settings.py: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PAGINATION_CLASS': 'sstester3.pagination.PageNumberPaginationWithCount', 'PAGE_SIZE': 25 } In the js for the table I used the pagination for the remote setting: let cols = [{title: "number", field: "number"}, {title: "name", field: "name"}] var table = new Tabulator("#producttable", { layout: "fitColumns", pagination: "remote", paginationSize: 25, paginationSizeSelector: [50, 100], ajaxURL: "api/products", paginationDataReceived: {"data": "results"}, columns: cols }); … -
Merging two excel files into one files using python
I have tried using openpyxl, but I don't know which function could help me to append three worksheet into one. I found error with write this file into one import pandas as pd excel_names = ["/tmp/xlsx1.xlsx", "/tmp/xlsx2.xlsx"] pd.read_excel(excel_names, engine='openpyxl') excels = [pandas.ExcelFile(name) for name in excel_names] frames = [x.parse(x.sheet_names[0], header=None,index_col=None) for x in excels] frames[1:] = [df[1:] for df in frames[1:]] combined = pandas.concat(frames) combined.to_excel("c.xlsx", header=False, index=False) excl_merged.to_excel('total_food_sales.xlsx', index=False) -
How to write batch of data to Django's sqlite db from a custom written file?
For a pet project I am working on I need to import list of people to sqlite db. I have 'Staff' model, as well as a users.csv file with list of users. Here is how I am doing it: import csv from staff.models import Staff with open('users.csv') as csv_file: csv_reader = csv.DictReader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: firstname = row['firstname'] lastname = row['lastname'] email = row['email'] staff = Staff(firstname=firstname, lastname=lastname, email=email) staff.save() csv_file.close() However, I am getting below error message: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Is what I am doing correct? If yes what I am missing here?