Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I use inline formset/model formset to create new records in the database?
I have an inventory and booking application for a science laboratory for which I need to create allow the user to store equipments(and their quantities) under the name of an experiment. For example: Practical Name: Chemical Test Equipment Needed: Test tubes - 5; Burners - 2; Stands - 1 etc... To do so I have a many to many relationship between inventory equipment and practical because many practicals can use many equipments. This is the models.py file: class Inventory_Equipment(models.Model): #id = models.IntegerField(primary_key=True, null=False, blank=True) name = models.CharField( max_length=255, #maximum length of input blank=True, #the field can be blank null=True, #the field can be null default="Name this Equipment") # the defualt value if it is left blank total_quantity = models.IntegerField( null=True, blank=True) location = models.CharField( max_length=20, default='Physics Office', blank=True) img_reference = models.ImageField( null=True, blank=True, upload_to='images_uploaded/', #the location of where to store uploaded images #currently the location is local device default='images_uploaded/default.jpg') #the default image stored if no image is uploaded by user class Meta: db_table="inventory" #name of the table in the database to which this model links to def __str__(self): return self.name #when queryed, the 'name' is returned #add validation functions - validation is a step i will do after barebones of … -
Why the projecet cant be deployed on heroku
Im deploying my first project using Django on heroku. I have stuck in a error: remote: -----> Installing python-3.8.5 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting appdirs==1.4.3 remote: Downloading appdirs-1.4.3-py2.py3-none-any.whl (12 kB) remote: ERROR: Could not find a version that satisfies the requirement apt-xapian-index==0.49 (from -r /tmp/build_4d208449/requirements.txt (line 2)) (from versions: none) remote: ERROR: No matching distribution found for apt-xapian-index==0.49 (from -r /tmp/build_4d208449/requirements.txt (line 2)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: b6448ab5f99718f2452407bed32ed667b2e2c8d6 remote: ! remote: ! We have detected that you have triggered a build from source code with version b6448ab5f99718f2452407bed32ed667b2e2c8d6 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push … -
Why value gets changed after return json response in django
When I request for order that contains multiple order items and after filter data from the database at the time of return response my order item id gets changed it contains id that even didn't exits in the database. def list_order_by_entrepreneur_view(request): order = Order.objects.distinct().filter(orderitem__entrepreneur_id=request.data['entrepreneur_id'], orderitem__status=request.data['status']) serializer = ListOrderSerializer(order, many=True) for order in serializer.data: for order_item in order['order_items']: print(order_item['order_item_id']) return Response(serializer.data) In the above printing statement it will return the correct order item ids like this 41750862938521900 48770276682006700 64456048092798900 94735086015354602 94735086015354601 14875991458541102 14875991458541101 84042205998714300 But when I return the response to client side then the id '94735086015354601' will convert to '94735086015354610' and same for id '94735086015354602'. I don't know why. -
Celery 5.x how to lock a task using celery-singleton or redis?
I just want to have a single instance of a celery task running at a time, so I started to use celery-singleton, also see: https://github.com/steinitzu/celery-singleton. Call Task: something = allocate_something.apply_async(kwargs={"user": user.pk}) Task itself: @app.task(name="Allocate something", base=Singleton, ignore_result=False) def allocate_something(user): user = User.objects.get(pk=user) print(user) But I always get back the following error: TypeError: Object of type UUID is not JSON serializable removing base=Singleton solves this behaviour but not the actual problem. Im also fine with direct locking onto redis, but never done that before. Can somebody help? -
Why Django signals doesn't work for me? (updated INSTALLED_APPS as it should be.)
I want to have a profile created after a user is registered to the app. So I put the Django signals in my app as it is told in Corey Schafer's tutorial part 8. But It seems I have some weird and hidden problems in the project. Because it literally doesn't work, doesn't create a profile based on a newly registered user. To solve this, I added a line to my init.py file and updated the INSTALLED_APPS section in settings.py as explained in other questions at StackOverflow. But none of them has made a change. So, what is my missing point? How can I solve this issue? Thank you in advance, for your time and effort! auctions/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.timezone import now from PIL import Image class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) img = models.ImageField(default='profile_pics/profile_default.jpg', upload_to = 'profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.img.path) if img.height > 300 or img.width > 300: size = (300,300) img.thumbnail(size) img.save(self.img.path) auctions/signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: … -
Accessing "temporary_file_path()" on a file smaller than 2.5 megabytes in Django
I am successfully able to access the temporary_file_path() on files larger than 2.5 megabytes. In the Django docs it says that files smaller than 2.5 megabytes are not stored temporarily so you cannot use this method. I was wondering how to change the default behavior of Django so that it temporarily stores all files regardless of size. -
Django multiple images upload
I am trying to implement an image multi upload feature in blog post like app. I created a post model and images model which contains image and foreignkey fields. I am plannig to receive multiple images from user through 'multiple' html attribute in the image field in form. Then i'm going to iterate through request.FILES.getlist('images') to get every image. But i just can't figure out how to tie everything together and receive data from form and populate my 2 models with this data. I tried doing it in some strange way but not only it did not work but it also gave an integrity error saying that "Column 'author_id' cannot be null" in post model. -
How can I send file to django app from flutter?
I am trying to send a pptx file to a django server at this link from flutter this is the html form which is in the original django app: <form method="post" enctype="multipart/form-data" action="find_file_type"> {% csrf_token %} <div> <label class = "custom-file-upload" > Choose file <input name = "filePath" type="file" accept = ".pdf , application/vnd.ms-powerpoint , application/vnd.openxmlformats-officedocument.presentationml.presentation" id="file"> </label> <input type="submit" value="Make it dark" id= "submit"> </div> </form> I am unable to send file to this server and have no idea what's wrong. Here is what I'v tried using the dio package: void sendRequest() async{ FormData formData = new FormData.fromMap({ "file": await MultipartFile.fromFile(file.path,filename: filename)}); response = await dio.post("https://nitemode.herokuapp.com/find_file_type", data: formData); print(response); if (response.statusCode == 200 || response.statusCode == 201) { print('Uploaded!'); } print("Process complete"); } } Here is the output I'm getting: [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: DioError [DioErrorType.RESPONSE]: Http status error [403] E/flutter (19891): #0 DioMixin._dispatchRequest (package:dio/src/dio.dart:966:7) E/flutter (19891): <asynchronous suspension> E/flutter (19891): #1 DioMixin._request._interceptorWrapper.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:di o/src/dio.dart:849:37) E/flutter (19891): #2 DioMixin.checkIfNeedEnqueue (package:dio/src/dio.dart:1121:22) E/flutter (19891): #3 DioMixin._request._interceptorWrapper.<anonymous closure>.<anonymous closure> (package:dio/src/dio.dart:846:2 2) E/flutter (19891): #4 new Future.<anonymous closure> (dart:async/future.dart:174:37) E/flutter (19891): #5 _rootRun (dart:async/zone.dart:1182:47) E/flutter (19891): #6 _CustomZone.run (dart:async/zone.dart:1093:19) E/flutter (19891): #7 _CustomZone.runGuarded (dart:async/zone.dart:997:7) E/flutter (19891): #8 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23) E/flutter … -
Django selectfilter like group field in User form?
Looking suggestion how to create field with select-filter like group field in User form. -
Supposed simple Django slug categories, but I get a 404 and I can't figure out why
thanks for taking a moment to try and help me out. Haven't done much coding in many years, switched careers for some reason.. Decided to play with Django, everything was going fine, and I can't figure out this URL/slug problem. I've got some links, first. It's explained on their GitHub rep but I can't figure it out. I've also used this handy site and am still in the dark. I Know its relatively simple, just having a hard time finding up to date code and books, and I've been frustrating myself on it for too long to quit. It's got to be an error with my URL's, I just don't know what though. So, have a laugh at my expense (seriously, you should have heard Linode support when I logged into the wrong account and deleted the wrong server.. they have excellent support!) and help me amuse myself a bit through this pandemic, because I'm mostly playing with stufff as part of a bigger project I started a while before I quit computer science and went into welding.. Basically, add a page to a category. Better looking URL's with slugs, no problem, until I try to access outside of /admin … -
DRF one-to-one relation serializer with a pre-populated model
I have a couple models, one of which is already populated with data (book name/ chapter number/ paragraph number data), and I am implementing the feature for each user to be able to add a note per each unique book name/ chapter number/ paragraph number, which I could, but I have been stack for a couple of days trying to retrieve books with the related_name note of the current user if they have any. Here are my models: Book model that is already populated with data. from django.db import models class Book(models.Model): day = models.CharField(max_length=128) book = models.CharField(max_length=128) chapter = models.CharField(max_length=256) paragraph = models.CharField(max_length=256) text = models.TextField() link = models.CharField(max_length=256) def __str__(self): return f'{self.book}_{self.chapter}.{self.paragraph} ' class Meta: ordering = ['-id'] verbose_name = "Paragraph" verbose_name_plural = "Paragraph" Here is the Note model that should store the current user's note regarding a specific unique book name / chapter number / paragraph number: from django.db import models from django.conf import settings from rest_framework.reverse import reverse from paragraphs.models import Book class Note(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='author', on_delete=models.CASCADE) paragraph = models.ForeignKey(Book, related_name='note', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) text = models.TextField(default=None) def __str__(self): return f'Note on {self.paragraph}' class Meta: ordering = ['created'] def save(self, *args, **kwargs): """ … -
how can I solve Django TemplateSyntaxError?
I suspect it might be due to the version of Django installed automatically by python anywhere, but if you think it's something else, please let me know if I'm missing anything. Here's the error message populating my page, with the accompanying code issue: django.template.exceptions.TemplateSyntaxError: Unclosed tag on line 9: 'block'. Looking for one of: endblock. "GET /employee/ HTTP/1.1" 500 143845 Code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Employee</title> </head> <body> {% extends 'base.html' %} {% block content %} <div class="row"> {% for employeess in employees %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ employeess.EmployeeName }}</h5> <p class="card-text">{{ employeess.EmployeeAddress }}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% endfor %} </div> </body> </html> And views.py from django.shortcuts import render from django.http import HttpResponse from .models import Employee def index(request): employees = Employee.objects.all() return render(request, 'index.html', {'employees': employees}) -
Django search pagination error, page not found error each time I try to move to page 2
I'm popping up with an error on my comic book ecommerce application. It's a Django app. Basically, the search function isn't paginating properly, giving me a page not found error each time I try to move to page 2 and onwards. It works fine in my general products listing area though, where there is no q-based search. It works fine when I paginate just the products section, adding in... paginate_by = 6 ...into the class ListView section... ...and adding this section into the view.html section... <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> ...But, once I try to paginate the search function in the same way, it appears to paginate, but page 2 and onwards just gives me a page not found error... http://127.0.0.1:8000/search/?page=2 Request Method: GET Request URL: http://127.0.0.1:8000/search/?page=2 Raised by: search.views.SearchProductView ....I think it has something to do with q, and the view.html section, but I'm not sure. Any help would be much-appreciated. -
How do I get a Django serializer/view to import only one data field?
thank you for helping me out. I have a Django project I'm working on. The goal is to import data from one Docker container/database into another. The data fields I'm working with are: unique_record_identifier provider_name date_inserted metadata_key metadata_hash metadata record_status date_deleted metadata_validation_date metadata_validation_status I've been tasked to rewrite the POST function so that only one data field, the unique_record_identifier, is imported (for testing purposes). Here is my views.py: class MetadataLedgerView(APIView): def post(self, request, format=None): serializer = MetadataLedgerSerializer(data=request.data, many=True) if serializer.is_valid(): logger.info(json.dumps(request.data)) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: logger.info(json.dumps(request.data)) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How do I rewrite the IF statement to ignore all the other data fields when importing, and to import only the unique_record_identifer? -
Bootstrap hamburger menu not expanding
I'm getting back into web development using Django after quite some time and I've got the seemingly common issue of my bootstrap hamburger menu not expanding in my nav bar. It's driving me absolutely nuts. It was working fine, then I did some refactoring and it's no longer working. I can't seem to find the issue, I've tried switching out the bootstrap links with ones found here, confirming the ID matches etc but no avail. Any help is greatly appreciated. Scripts from Bootstrap: <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <title>Title</title> ... <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> HTML: <nav id="bootstrap-override-customnav" class="navbar navbar-expand-lg navbar-light"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home'%}"> <img src="{% static 'images/logo.png'%}" alt="" width="40" height="40"> </a> <button class="navbar-toggler navbar-dark" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link" href="{% url 'home'%}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'interactivequery'%}">Interactive Query Tool</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'education'%}">Education</a> … -
IntegrityError: NOT NULL constraint failed, not identifying foreignkey
These are my models. class Category(models.Model): name = models.CharField(max_length=255, primary_key=True) description = models.TextField(null=True) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=255, primary_key=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) description = models.TextField(null=True) def __str__(self): return self.name def product_display_image_path(instance, filename): return f"products/{instance.pid}/{filename}/" def product_image_path(instance, filename): return f"products/{instance.product.pid}/{filename}/" class Product(models.Model): pid = models.UUIDField(default=uuid.uuid4, primary_key=True) name = models.TextField() description = models.TextField() display_image = models.ImageField( upload_to=product_display_image_path, default='products/image_unavailable.png' ) artist = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.PROTECT) subcategory = models.ForeignKey(SubCategory, on_delete=models.PROTECT) stock_left = models.IntegerField(default=0) price = models.CharField(max_length=255) click_count = models.BigIntegerField(default=0) purchase_count = models.BigIntegerField(default=0) def __str__(self): return self.name class Meta: ordering = ['-click_count'] This is my view. class ProductCreateView(CreateAPIView): queryset = Product.objects.all() permission_classes = [IsAuthenticated, IsArtist] serializer_class = ProductSerializer parser_classes = [FormParser, MultiPartParser, JSONParser] def create(self, request, *args, **kwargs): request.data['artist'] = request.user.id serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) This is the request I'm making: This is the error: I'm constantly getting this error IntegrityError at /store/create/product/ NOT NULL constraint failed: products_product.category_id (the name of my app is products). I have flushed the whole database and tried again. Nothing seems to work. PS. I already have a category names 'accessories' and a subcategory named 'bands' created. I dont know why the new product … -
Django - OpenCV Integrate pop up camera window into static page
OpenCv code to open and save image from webcam: camera = cv2.VideoCapture(0) while True: return_value,image = camera.read() cv2.imshow('image',image) if cv2.waitKey(1) & 0xFF == ord('s'): cv2.imwrite('./media/test.jpg',image) break camera.release() cv2.destroyAllWindows() return render(request,'page.html') When I run this function, the webcam window opens on a popup python window. Does anyone know if and how could I integrate that window to open into the same or different Html page? Meaning, when I press the button instead of opening outside the webpage, I need to open the can in the Html page itself. Thanks for any help in advance. -
Django remove foreign relationship from model
I have two models. I want to remove the recommendation foreign field from the Document model and change it to many-to-many. class Recommendation(models.Model): name = models.TextField() question = models.ForeignKey(Question, on_delete=models.CASCADE) class Document(models.Model): name = models.TextField() recommendation = models.ForeignKey(Recommendation, on_delete=models.CASCADE) Inteded result: class Recommendation(models.Model): name = models.TextField() question = models.ForeignKey(Question, on_delete=models.CASCADE) documents = models.ManyToManyField('Document') class Document(models.Model): name = models.TextField() But there is an error when I run ./manage.py makemigrations <class 'questions.admin.DocumentInline'>: (admin.E202) 'questions.Document' has no ForeignKey to 'questions.Recommendation'. -
How do I pass the form to the get_context_data function?
How can I get the form variable here? def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = kwargs['form'] return context Comment model code: class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) View class: class CommentCreate(LoginRequiredMixin, CreateView): model = Comment fields = ('text', ) template_name = 'post/details.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = kwargs['form'] return context DetailView: class PostDetailView(DetailView): model = Post context_object_name = 'post' template_name = 'post/details.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context -
'User' object has no attribute 'user'
I have a User model class User(AbstractBaseUser): username = None first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=200, null=True, blank=True) phone_regex = RegexValidator(regex=r'^09(\d{9})$', message="Phone number must be entered in the format: '09111111111'") phone = models.CharField(validators=[phone_regex], max_length=11, unique=True) email = models.EmailField(max_length=255, null=True, blank=True) # cart_number = models.PositiveBigIntegerField(null=True, blank=True) # shomare cart banki birth_day = models.DateField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] def __str__(self): return self.phone def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin in view I want to have a class to get a User and update it class UserRetrieveUpdateView(generics.RetrieveUpdateAPIView): queryset = User.objects.filter(is_active=True) serializer_class = UserSerializer permission_classes = (IsOwner,) when I want to test it with post man I give this error: AttributeError at /account/1/ 'User' object has no attribute 'user' this is my url: path('<int:pk>/', views.UserRetrieveUpdateView.as_view(), name='dashboard'), -
How I can display the video after uploaded from fileInput in the website using ajax
I working on uploading video with progress bar using ajax and I need to display the video after upload it in the video element, instead of image. I using the Django backend, How I can display the video file which I will choose in the website from fileInput to display it in specific video html element The Html (Template) <video src="<!--here I need to display the video-->" autoplay> </video> <!-- Form --> {% if request.user.is_authenticated %} <div id="alert-box"></div> <div id="image-box"> </div> <br> <form id="upload-form" action="." method="post" enctype="multipart/form-data"> {% csrf_token %} {{V_form.as_p}} <button class="btn btn-primary btn-block mt-5" name="submit_v_form"> <i class="icon-upload icon-white " name="submit_v_form"></i> Upload </button> </form> {% endif %} <br> <br> <div id="progress-box" class="d-none">progress</div> <div id="cancel-box" class="d-none"> <button id="cancel-btn" class="btn btn-danger">Cancel</button> </div> </div> <hr> </div> </div> The javaScript file success: function(response) { console.log(response) // imageBox.innerHTML = `<img src="${url}" width="300px">` imageBox.innerHTML = `<video src="${url}" width="300px">` alertBox.innerHTML = `<div class="alert alert-success" role="alert">Successfully uploaded the image below!</div>` }, -
Problem with Django project. AttributeError at / 'Product' object has no attribute 'Category'
Hello I was wondering could anyone help me with an issue I've ran into while working on a Django project. I've tried a few different things but cant seem to get it working a screenshot of the error is attached. -
When this code in views.py is run, there is a duplicate row in the Excel spreadsheet for each record in the table
The following code exports to an Excel file, but when this code in views.py is run, there is a duplicate row in the Excel spreadsheet for each record in the table def export(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="persons.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Person Data') # this will make a sheet named Person Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['first_name', 'last_name', 'middle_name', 'email', 'country', 'phone_country_code', 'area_code', 'phone_number', 'time_zone', 'select_languages', 'team', 'experience', 'ref_name', 'ref_email', 'contemplative_inq', 'start_date', 'hours_month', 'hear_about', 'linked_in_url', 'web_site_url', 'employment', 'resume_sent', 'resume', 'picture', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Person.objects.all().values_list('first_name', 'last_name', 'middle_name', 'email', 'country', 'phone_country_code', 'area_code', 'phone_number', 'time_zone', 'select_languages', 'team', 'experience', 'ref_name', 'ref_email', 'contemplative_inq', 'start_date', 'hours_month', 'hear_about', 'linked_in_url', 'web_site_url', 'employment', 'resume_sent', 'resume', 'picture') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response -
Django pass data from HTML table to database model
I am creating a student attendance system using django. I am fetching all students name from student database into a HTML table and updating information about student to django model. This is my view.py to get data def attendanceFill (request, subject): context = '' ad_standard = request.session.get('standardO') subjects = CustomStudent.objects.filter(className__name__contains = ad_standard, subjectName__subjects__contains = subject) # attendanceForm = Attendance(request.POST or None, instance=subjects) print(ad_standard) print(subject) print(subjects) context = {'subjects' : subjects} if request.method == 'POST': student = request.POST print(student) return render(request, 'teacher/attendance_fill.html', context) This is my HTML template for data handling. <div class="container"> <div class= "row mt-4"> <form action="" method="POST"> {% csrf_token %} <table> {% for student in subjects %} <tr> <td name= 'student'><p class="student-name" id="student-name">{{ student.sname }}</p></td> <td> <input type="checkbox" name="attendance" id="attendance"> </td> </tr> {% endfor %} <tr> <td> <button type="button" name="checked" id = "checked" class="btn btn-outline-dark mb-4 shadow" style="border-radius:25px;">Submit</button> </td> <td></td> </tr> </table> </form> </div> </div> This is jquery function I am using to capture data. var formData = new FormData() $(document).ready(function(){ $("#checked").click('click', function(){ $students = document.getElementsByClassName('student-name').textContent; $attendance = $('#attendance').val() console.log($students) console.log($attendance) }) }) I have tried $('student-name').val() to get value for all students but it returns blank. Nothing is captured with this method. I wish capture all data … -
How to detect if user is still online with django session
I use Django 2.2 and trying to detect if user is still connected when the user close his browser without logging out I tried to use some Django packages like qsessions but it need to replace 'django.contrib.sessions.middleware.SessionMiddleware', with qsession middleware but it makes another error django.contrib.sessions.middleware.SessionMiddleware not found I need your help to get every user session separately.