Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django data is not rendering as saved in model
I'm uploading data to one of the models using CSV file. There is no issue in saving the data. It is getting saved as needed. But just after uploading the data all the foregin key value rendering same. In the above image all data is same. But on restarting the server using python manager.py runserver. The value are rendering as expected. Function used in rendering the data. There is no effect of refreshing it. It starts rendering the correct data on performing python manage.py runserver -
how to model formset in modal form - django
i'm trying to implement two formset in one view , one of the formsets should be pop up modal form : here is the models class MobileCollection(models.Model): mobile = models.ForeignKey(ModelCategory,on_delete=models.PROTECT,related_name='model_category') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) serial_no = models.CharField(max_length=7,unique=True,blank=True,null=True) status = models.BooleanField(default=True) def __str__(self): return f'{self.mobile}-{self.imei}' if quantity = 10 then we have 10 unique imei , for each mobile item we have multiple imei , the im ei should be inserted in a pop up modal @login_required def create_collection(request): item_formset = mcollection(queryset=MobileCollection.objects.none()) imei_formset = imei_modelformset(queryset=Imei.objects.none()) if request.POST: item_formset = mcollection(request.POST) imei_formset = imei_modelformset(request.POST) if imei_formset.is_valid() and item_formset.is_valid() and request.user.is_superuser: for item in item_formset: item_obj = child.save(commit=False) item_obj.save() for imei in imei_formset: imei_obj = imei.save(commit=False) imei_obj.mobile = item_obj imei_obj.save() return JsonResponse({'success':True}) else: return JsonResponse({ 'success':False,'error_child_msg':item_formset.errors,'error_imei_msg':imei_formset.errors}) context = { 'item_formset':item_formset, 'imei_formset':imei_formset } return render(request,'storage/collection.html',context) but it only saves the last item entry and doesnt save imei , only its instance(from the item) will be saved and here is my formsets mcollection = modelformset_factory( MobileCollection,form=MobileCollectionForm,fields= ['mobile','qnt','price'],can_delete=True,extra=1) imei_modelformset = modelformset_factory(Imei,form=ImeiForm,fields= ['imei'],extra=1,can_delete=True) and here is my html and jquery const addNewRow = document.getElementById('add-more') const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') addNewRow.addEventListener('click',add_new_row); function add_new_row(e){ if(e){ e.preventDefault(); } const currentFormClass = … -
Django Rest Framework Handle a lot of Request & Responses with put method for text editor
I Have a Text Editor in FrontEnd And I want to save text changes as soon as I stop typing but requests and responses are a lot I want to handle this problem with best way Do you know a solotion or package for handling this? thank you -
Trying to get data from data base in django
Trying to get data from database table, i want to show data by when user click on the employee name and it should show data from OverTime table , i have attempted many way to get it dome but none of them worked, please mentor and guide me. models.py class Employee(models.Model): user = models.ForeignKey(User, null = True, on_delete = models.CASCADE) emp_name = models.CharField(max_length = 250, default = '') emp_l_name = models.CharField(max_length = 250, default = '') emp_email = models.EmailField(max_length = 250, default = '') emp_number = models.IntegerField() def __str__(self): return self.emp_name class OverTime(models.Model): emp_user = models.ForeignKey(Employee, null = True, on_delete = models.CASCADE) overTime = models.FloatField( blank = True, null=True) reaion = models.CharField(max_length = 250, blank = True, null=True) date_ot = models.DateTimeField(null = True, blank = True) def __str__(self): return str(self.emp_user) urls.py path('add_Ot/', views.add_Ot, name = 'add_Ot'), path('add_ex/<int:pk>', views.add_Ot, name = 'add_ex'), views.py def add_Ot(request, pk = None): emp = Employee.objects.filter(user=request.user) forms = OverTimeAdd(request.GET) detail_id = Employee.objects.filter(pk = pk) if request.method == "GET": if forms.is_valid(): forms.save() messages.success(request, 'Successfully Over Time added !') contex = { 'emp': emp, 'forms': forms, 'detail_id' : detail_id } return render(request, 'working/html/add_Ot.html', contex) html <tbody> {% for emp in emp %} <tr> <td class="detail"><a href="">{{ emp.id }}</a></td> … -
how to get iterable collection (queryset) from a more than one ManyToManyField field in Django?
I want to get a list of doctors from clinics based on a particular city. I have developed a workaround but it seems expensive operation as I am using a loop to do so. Clinic Model: class Clinic(models.Model): clinic_name = models.CharField(max_length=255) address = models.CharField(max_length=255, null=True, blank=True) doctor = models.ManyToManyField(Doctor, blank=True) city = models.ForeignKey(City, on_delete=models.CASCADE) latitude = models.CharField(max_length=255, null=True, blank=True) longtitude = models.CharField(max_length=255, null=True, blank=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.clinic_name City Model: class City(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name Doctor Model: class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name="doctor") speciality = models.ManyToManyField(Speciality, blank=True) service = models.ManyToManyField(Service, blank=True) condition = models.ManyToManyField(Condition, blank=True) def __str__(self): return f"{self.title} {self.user.full_name}" My workaround is: >>> my_city = City.objects.get(name='Kabul') >>> clinics = Clinic.objects.filter(city=city) >>> doctor_list = [] >>> for clinic in clinics: doctor_list.extend(clinic.doctor.all()) >>> doctor_list [<Doctor: Dr. Doctor Khan One>, <Doctor: Prof. Doctor Khan Two>, <Doctor: Dr. Doctor Khan One>, <Doctor: Dr. Doctor Khan One>] >>> the_result = set(doctor_list) >>> new_doctor_list = list(the_result) >>> new_doctor_list [<Doctor: Dr. Doctor Khan One>, <Doctor: Prof. Doctor Khan Two>] -
I am having issue with django web application deployement on ubuntu VPS. The issue is that the server do not give any respnse even on 0.0.0.0:8000
While deploying the Django website everything goes right but when I run the command python manage.py runserver 0.0.0.0:8000 then the server starts successfully but then if I try the IP:8000 on the browser, it shows the site can't be reached and even no computation executes on the server terminal of Django. I have executed sudo ufw allow 8000 but still, the error is the same. I have tried apache and nginx but got the same output for both. I am following this guide https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 also tried: https://www.codewithharry.com/blogpost/django-deploy-nginx-gunicorn I am using VPS having 1 core, 0.5 GB RAM, Data transfer rate:400 Mbps, I am wondering if Django's requirements for running the application are not met. Kindly Help me solve this problem. It is my 4th day struggling with this error. -
Can I migrate some models dynamically in Django?
I have a few apps, so in each app I have multiple models. Assuming in app X I have models A, B and C, but I want model A to be dynamically migrated. In other words, in a development environment I can migrate or not, depending on some environment variable. I configured managed to get the value from the environment variable, but that only works to generate the migration. I want it to work anytime I'm going to apply the migration. How can I do this? -
Django: NoReverseMatch at
So when I go to the url: http://127.0.0.1:8000/post/2/. instead of showing me the post detail view, it gives me an error. I am so confused about it. However I can see it in list view and in profile page. posts views.py class PostDetailView(LoginRequiredMixin, DetailView): model = Posts template_name = 'posts/detail.html' models.py class Posts(models.Model): caption = models.CharField(max_length=2200) date_posted = models.DateTimeField(default=timezone.now()) image = models.ImageField( upload_to='PostsImages') user = ForeignKey(User, on_delete=models.CASCADE ,related_name='userposts') def __str__(self): return f"Post {self.id} ({self.user.username})'s" def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) img.save(self.image.path) the main urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('posts.urls')), path('user/', include('users.urls')), path('comments/', include('comments.urls')) ] posts urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import PostsListView, PostCreatView, PostDeleteView, PostDetailView urlpatterns = [ path('', PostsListView.as_view(), name='homepage'), path('delete/<int:pk>/', PostDeleteView.as_view(), name='delete-post'), path('creat-post', PostCreatView.as_view(), name='create-post'), path('post/<int:pk>/', PostDetailView.as_view(), name='detail-post') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) users urls.py from django.urls import path from django.contrib.auth import views as auth_views from .views import ProfileDetailView from .views import SignUp, LogOut urlpatterns = [ path('signup/', SignUp, name='signup'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), #template_name'xx' tells it where to find the log in url path('logout/', LogOut, name='logout'), path('<int:pk>/profile', ProfileDetailView.as_view(), name='profile') ] -
serving media files in Django for Production
I want to serve all types of media files in my Django Project I used Whitenoise to server static files and static files are working well but I'm having issues with serving images that are uploaded by users (I'm using Linux shared hosting Cpanel) Directory structure Project_name App_1 App_2 Staticfiles (that are collected via collectstatic cmd) manage.py passenger_wsgi.py and here is the project's settings.py STATIC_ROOT = BASE_DIR / 'staticfiles' STATIC_URL = '/static/' MEDIA_URL = '' STATICFILES_DIRS =[ BASE_DIR/ 'static' ] MEDIA_ROOT = BASE_DIR / 'staticfiles/images' and file urls.py urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Uncaught SyntaxError: Unexpected identifier pls help me
I tried to display the message but it won't display This is views def allmessage(request, room): room_details = Room.objects.get(name=room) messages = Message.objects.filter(room=room_details.id) return JsonResponse({"messages":list(messages.values())}) This is display method This link doesn't work /getMessages/{{room}}/ in my terminal $(document).ready(function(){ setInterval(function(){ $.ajax({ type: "GET" url: "/getMessages/{{room}}/", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.messages) { var temp="<div class='chat-box'><b>"+response.messages[key].user+"</b><p>"+response.messages[key].value+"</p><span class='time-left'>"+response.messages[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('There is an error') } }); },1000); }) </script> and also have this problem pls help thank you -
Error when trying to access an item in a for loop
Greetings all I'm trying to get a value if it is equal to a string in looping through items. But I'm getting error "Dictionary entries must contain key/value pairs" and I don't know how to fix that. I'm new to python programming and I'm struggling to find information of how it should be done. I'm using python3.x My code looks like this for index, debtor in enumerate(case.get_debtors): if debtor.type==1: context = { "recipientName": f"{debtor.first_name} {debtor.middle_name} {debtor.last_name}".replace('None', ''), "debtorRole": "Длъжник", "debtorAddress": debtorAddress, "publicExecutorDefaultBankAccount": "ygvyvb", "courtStaff": f"{case_details.systav}".replace('None', ''), "courtName": f"{case_details.courtName}".replace('None', ''), "archNumber": case.id, "debtorName": f"{debtor.first_name} {debtor.middle_name} {debtor.last_name}".replace('None', ''), "creditorName": f"{creditor.first_name} {creditor.middle_name} {creditor.last_name}".replace('None', ''), #creditor.type==2 "creditorAddress": creditorAddress, "executionListDate": executionListDate, "exListIdentifier": exListIdentifier, "amount": amount, "amountDate": amountDate, "agreementInterest": agreementInterest, "penaltyInterest": penaltyInterest, "expences": expences, "taxPublicExecutor": taxPublicExecutor, "brokerage": brokerage, "measuresSum": measuresSum, if debtor(index).postcode1=="1000": "recipientNameNAP": "ТД НА НАП – СОФИЯ", "recipientAddressNAP": "Адрес: ул.„Аксаков” № 21 1000 София", "BASE_DIR": f"{settings.BASE_DIR}".replace("""\\""", "/"), } Please help me. I know it is something simple, but I can't find a solution -
Trouble with Django Channels AllowedHostsOriginValidator
Everytime I use the AllowedHostsoriginValidator I'm unable to get a websocket connection. it immediately handshakes, rejects and disconnects : (where 'my ip' is my ip) WebSocket HANDSHAKING /ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/ [my ip:62745] WebSocket REJECT /ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/ [my ip:62745] WebSocket DISCONNECT /ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/ [my ip:62745] application = ProtocolTypeRouter({ # (http->django views is added by default) "http": get_asgi_application(), 'websocket': AllowedHostsOriginValidator( URLRouter( uppicdoapp.routing.websocket_urlpatterns ) ) , }) my settings.py file i have: ALLOWED_HOSTS = ['127.0.0.1', '10.0.2.2', 'my ip'] now when I remove that allowedhostsoriginvalidator, I am able to connect! Is there something I'm missing for the ALLOWED_HOSTS setting? -
I want find a point in between given points rectangle using python if possible in django
Here in my given points i was tried to match from django query, please help me to best way. y=800.2816162109375 1200, 750 block_list = Block.objects.filter( Q(block_coordinates__topRight__y__gte=y)&Q(block_coordinates__botRight__y__gte=y)& Q(block_coordinates__topLeft__x__gte=x)&Q(block_coordinates__topRight__x__lte=x)& Q(block_coordinates__topLeft__y__lte=y) | Q(block_coordinates__botLeft__y__gte=y) ).values('block_id','block_coordinates') ``` -
Program 'pip.exe' failed to run: The file or directory is corrupted and unreadable
While I was trying to download Django, I got this error that can be found in here. These are some clues for you: Before I downloaded django, I activated the virtual environment but maybe something went wrong with it because I couldn't see anything changed after activating. And one more thing is I'm trying to download Django in my external USB. -
django get id for traverse a list
i want to convert my list into dict to have my id so i try this in my views def img2(request): posts = Post.objects.all() i=[] for p in posts: print(p.id) i.append(p.id) #post={'id':str(p.id)} #print(i) '''def Convert(lst): res_dct = {str(lst[i]): lst[i] for i in range(0, len(lst), 1)} return res_dct # Driver code d=Convert(i)''' d = {str(i[k]): i[k] for k in range(0, len(i), 1)} print(d) for j in d: print(j) return render(request, 'imgg.html', d) then i want to display every id in html and this is my html file: test {% for n in d %} {{n}} {% endfor %} so.. nothing happened and i don't know what's the problem some help plz and thx a lot in general i have a model form post and another one for images with foreignkey and i want to display every post with first image uploded so i have my db with post and images but i never get the first image to display at home page then i try to make a dict with all post_id with for i will try to display every single image_post for her post if u have another method i will be thankfull ^^ -
Getting error when attempting to add items into the database
So, I am actively trying to create categories with subcategories. My current app is listings, and the idea is to create a ManyToManyField inside my Listing models. Here is my code inside models.py. from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=150, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] class Blist(models.Model): name = models.CharField('Business Name', max_length=250) address = models.CharField('Address', max_length=300) city = models.CharField('City', max_length=100) zip_code = models.CharField('Zip Code', max_length=10) phone_number = models.CharField('Phone Number', max_length=20) web = models.URLField('Website') def __str__(self): return self.name But when I go into the shell to add items into the category, I'm getting errors: django.db.utils.ProgrammingError: column listings_category.name does not exist LINE 1: SELECT "listings_category"."id", "listings_category"."name",... What am I doing wrong here? -
Adding dictonary values while using HttpResponseRedirect
I want to redirect to the existing page and display a queryset which would be determined based on the values submitted via the form. The dictionary values I get from function get_context_data display correctly. The dictionary values I try and add in the post function do not display correctly. def post(self, request, *args, **kwargs): RoomBookingsForm = BookRoomsForm(request.POST or None) self.object = self.get_object() # assign the object to the view context = self.get_context_data( *args, **kwargs) context.update({'room_type_queryset': RoomType.objects.all().filter()}) print("all context values") print(context) if request.method == 'POST': return HttpResponseRedirect(self.request.path_info, context ) As well as context.update I also tried context['room_type_queryset'] = RoomType.objects.all().filter() Based on the two print statements above I got all context values {'object': <AmericanHotel: Caesars Palace>, 'americanhotel': <AmericanHotel: Caesars Palace>, 'slug': 'caesars-palace', 'view': <hotel.views.HotelDetailSlugView object at 0x00000210575117F0>, 'cart': <Cart: 5>, 'hotel_extra_photos': <QuerySet [<AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>]>, 'room_type': <QuerySet [<RoomType: Caesars Palace, Triple>, <RoomType: Caesars Palace, Double>]>, 'room_type_queryset': <QuerySet [<RoomType: Caesars Palace, Double>, <RoomType: Caesars Palace, Triple>]>} The results from room_type are correctly displayed in red. {% for instance in room_type %} <H1 style="color:red">{{instance}}</H1> {% endfor %} The results from … -
Django - How to store emojis in postgres DB properly?
I'm running the latest version of Django on postgres. I'm trying to store emojis in my postgres DB in a way that a React Native app can properly render it. Below I have the initial emojis variables setup that'll go into the talbe. I've copy and pasted the emojis from here. As you can see I'm getting an error from PyCharm regarding it being a "BAD_CHARACTER". How do I store emojis in my postgres DB so that a React Native app can render it properly? -
postgres performance is very slow with django
I made a very small web-app in django with sqllite3 and then I just connected the same app to postgres db in which I reccreated the tables using makemigrations and then now when I am using even the admin page, with just one superuser - admin - its very very slow. I tried postgresql.conf file to set the parameters - seq_page_cost = 1.0 and random_page_cost = 1.0 and restarted postgres.sql from services, but to no avail. is there anything I need to do apart from this ?? please let me know. -
Django/Foundation CSS Accordion Not Displaying Contents
When using the sample code here in my Django template, the information in the accordion-content div will not display on the screen, but inspecting the HTML shows that it exists. In my provided code I have both my dynamic version of the accordion and the sample code copy pasted to show both do not work, but that the information is seemingly loaded into the webpage. I can provide more information but I am unsure what would be relevant so I only included my HTML and a screenshot of the webpage. Is it possible Django is interfering with the Foundation CSS/JS? Base.html {% load static %} <!DOCTYPE html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/foundation.css' %}"> <link rel="stylesheet" href="{% static 'css/select2.css' %}"> {% block css %}{% endblock %} </head> <body> <!--Need to fix top bar--> <div class="top bar"> <div class="top-bar-left large-offset-1 medium-offset-1"> </div> <div class="top-bar-right"> <ul class="dropdown menu" data-dropdown-menu> <li class="menu-text">Reading List Website</li> {% if user.is_authenticated %} <li><a href="/logout/">Logout</a></li> {% else %} <li><a href="/login/">Login</a></li> {% endif %} </ul> <ul class="menu"> {% if user.is_authenticated %} {{ user.username }} {% else %} Guest {% endif … -
"created" value of TimeStampedModel is showed diffrently
I am creating the review part in my Django project. When the new review is created, the page will show the new review without redirect(with javascript), and after the page is redirected it will show the same review from DB. but the there is some difference between the created time of new review from javascript and the other one from DB. On the template, the review from DB is showed exactly my local time. But the new review created from javascript that takes the value of "created" from the backend, is different from the same review form DB after redirect. for example, 27-November-2021-00:11 (after the new review is rendered with JS without redirect) 27-Novembre-2021-09:47 (after redirecting, the new review from DB) It seems to me maybe the first one is not applicated UTC time. but printing the value of "created", the console shows 2021-11-27 00:49:57.878138+00:00 the hours are the same as the first one but the minutes are the same as the last one... I can't understand. because these two values are from the same thing, "created" of the TimeStamped Model. How could I make this value the same? models.py class TimeStampedModel(models.Model): """TimeStampledModel Definition""" created = models.DateTimeField( auto_now_add=True ) updated … -
API connection and getting the returned result
I'm sorry for my bad english Hello, I am using a brokerage firm for payment instrument. The API connection is successful and I get the result. But I can't use the returned result information. payment_card = { 'cardHolderName': kartisim, 'cardNumber': kartno, 'expireMonth': kartskt_ay, 'expireYear': '2030', 'cvc': karcvc, 'registerCard': '0' } buyer = { 'id': adres.id, 'name': adres.adres_uye.username, 'surname': 'Doe', 'gsmNumber': '+905350000000', 'email': adres.adres_uye.email, 'identityNumber': '74300864791', 'lastLoginDate': '2015-10-05 12:43:35', 'registrationDate': '2013-04-21 15:12:09', 'registrationAddress': adres.adres_detay, 'ip': '85.34.78.112', 'city': 'Istanbul', 'country': 'Turkey', 'zipCode': '34732' } address = { 'contactName': 'Jane Doe', 'city': 'Istanbul', 'country': 'Turkey', 'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'zipCode': '34732' } basket_items = [] for bas in uye: basa = { 'id': str(bas.id), 'name': str(bas.sepet_urun.urun_baslik), 'category1': str(bas.sepet_urun.urun_anakategori.anakategori_baslik), 'category2': str(bas.sepet_urun.urun_altkategori.altkategori_baslik), 'itemType': 'VIRTUAL', 'price': str(bas.sepet_fiyat) } basket_items.append(basa) print(basket_items) request_payload = { 'locale': 'tr', 'conversationId': '123456789', 'price': str(sepetf), 'paidPrice': str(sepetf), 'currency': 'TRY', 'installment': '1', 'basketId': str(sepetid), 'paymentChannel': 'WEB', 'paymentGroup': 'PRODUCT', 'paymentCard': payment_card, 'buyer': buyer, 'shippingAddress': address, 'billingAddress': address, 'basketItems': basket_items } payment = iyzipay.Payment().create(request_payload, options) print(payment.read().decode('utf-8')) return HttpResponse(payment["status"]) I cannot use the returned result information. The returned result is as follows The error I get is as follows: 'HTTPResponse' object is not subscriptable -
React django permissions
I am still new in react when I tried to delete an element from API(django rest framework) in my case it's not working Error message : Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/events/delete/3' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.enter image description here -
How to save timeslot details when creating a booking instance django
I have a django app in which I am implementing a booking system. I have created a TimeSlot model that has a start_time, end_time, and time_slot_owner. I want to implement a booking system in which the timeslot details, such as the start_time, end_time, and time_slot_owner are added to the Booking Model once it has been created. My TimeSlot model: class TimeSlot(models.Model): time_slot_owner = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() My Booking Model: class Booking(models.Model): bookings_owner = models.ForeignKey(User, on_delete=models.CASCADE) # time_slot = models.ForeignKey(TimeSlot, on_delete) meals_booked = models.IntegerField(default=0, validators=[MinValueValidator(0)]) start_time = models.TimeField() end_time = models.TimeField() restaurant = models.ForeignKey(User, on_delete=models.CASCADE, related_name="restaurant") What I have in my create_booking function so far in views.py def create_booking(request): instance = Booking() data = request.POST.copy() data["bookings_owner"] = request.user form = BookingForm(data or None, instance=instance) if request.method == "POST" and form.is_valid(): start_time = request.POST.get("start_time") print(start_time) form.save() return HttpResponseRedirect(reverse("food_avail:view_bookings")) return render(request, "food_avail/create_booking.html", {"booking": form}) When I click on Book: It leads me to this page where I can enter number of meals I want to book: Once I enter the number of meals I want the final page to show the following details for each booking: Booking.booking_owner.username | TimeSlot.time_slot_owner.username | TimeSlot.start_time | TimeSlot.end_time | Booking.meals_booked -
Reportlab pdf prints only one page
I am able to create table with reportlab as shown below, but it prints only on one page, how I can print data to multiple pages def pdf_view(request): enc = pdfencrypt.StandardEncryption("pass", canPrint=0) buf = io.BytesIO() c = canvas.Canvas(buf, encrypt=enc) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) lines = [] users = User.objects.filter(is_staff=False) for user in users: lines.append(user.username) lines.append(user.email) lines.append(user.first_name) table = Table(lines, colWidths=10 * mm) table.setStyle([("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)]) table.wrapOn(c, width, height) table.drawOn(c, 0 * mm, 5 * mm) styles = getSampleStyleSheet() ptext = "This is an example." p = Paragraph(ptext, style=styles["Normal"]) p.wrapOn(c, 50 * mm, 50 * mm) # size of 'textbox' for linebreaks etc. p.drawOn(c, 0 * mm, 0 * mm) # position of text / where to draw c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='users.pdf')