Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to send a message and wait for a reply in python, twilio in whatsapp
i want to take the details of a person on whatsapp and store it but it seems its not working as i want it. its not waiting for the user to input the first data before the second one coming. this is my #models.py class student_Account(models.Model): name = models.CharField(max_length = 30) place_of_stay = models.CharField(max_length = 30) def __str__(self): return self.name and this is my views.py @csrf_exempt def sms(request): incoming_msg = request.POST.get('Body', '').lower() resp = MessagingResponse() msg = resp.message() msg1 = resp.message() if 'hi' in incoming_msg: reply = ("Hello and welcome to kkk banking system WhatsApp bot!\n\n" "What would you like to do\n" "1. Create an accout?\n" "2. Check your account balance\n") msg.body(reply) if incoming_msg == '1': reply = ("Enter your name") a = incoming_msg student.name = a reply = ("Enter your place of stay") b = incoming_msg student.place_of_stay = b msg.body(reply) student.save() reply = ("Your details has been saved!!.") msg.body(reply) -
What would I miss, if I don't use any authentication in django and login the user using django query filter with a manually hashed password
I have seen the default user authentication and custom user uathentication in django, I would like to know what would I be missing if I just login a user by using a normal query like, ____.objects.get(password = ______, email = ______) and just hash the password stored in the model column.And store the login details in session and clear them on logout. Would it ruin the security altogether or is it something else I wouldn't get which is found in the normal django authentication? -
Why TabularInline looks different on differen sites. How to control its apperence
I have 2 different registers on my admin panel and on one TabularInline allows multiple choice: and on another not: They are created absolutely the same way: class GenreInlineAdmin(admin.TabularInline): model = FilmWork.genre.through class PersonInlineAdmin(admin.TabularInline): model = Person.movie.through Where does the difference come from? How can I control it? -
Booking system for fitness / gym company - Where to store booking data, what django-models should I use?
I have to make (high school project) booking/reservation system for fitness / gymnastics service company. Users (clients) can have: tickets - for 1 hour (on 1 day) - "single ticket" subscription - 1 hour a day for one, two or three months. Overall, I have some idea how to make this application, but only need help with choosing best / optimal Django model for storing booking / reservation information. Assuming that there can be maximum N ( N ~ 15) persons in fitness club at the same time, I can sell limited number of tickets and subscriptions for particular day/hour. Where (what Django model suits best) should I store booking / reservation informations, For example: User No. 0001 is taking fitness at Monday, 25 January, 2021, 5 pm to 6 pm (single ticket) User No. 0002 is taking fitness at Friday, 30 January, 2021, 11 am to 12 am (single ticket) ..... User No. 0055 is taking fitness every weekday from 3 pm to 4 pm for whole January and February (subscription) ..... etc. What Django model do You recommend in my case? -
Django and Heroku - Migration is applied before its dependency
I'm having trouble getting my Django web app from a local server to Heroku. To try and troubleshoot I created a new app from scratch and managed to push that through to Heroku with no problems. The issue comes when I add class User(AbstractUser): pass to models.py, then run makemigrations and migrate. The error is: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency mainapp.0001_initial on database 'default'. One thing that might be causing it is that I'm using sqlite3 on localhost then Postgres on the Heroku server (although I'm not advanced enough to know if that is actually the problem!) Also my gitignore file contains: /venv __pycache__ db.sqlite3 mainapp/static/ Should it also include the migrations folder? Any help or ideas would be appreciated! Full traceback is: remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 85, in wrapped remote: res = … -
Jinja .css template logic
I am wiring my framework to wagtail. It is a custom module css framework called reely.io that is made for Hubspot. It has jinja variables for breakpoints, colors, etc. one of the variables is a multiplier for padding and margin settings. I have the css file set up and coming through to the template. the issue is with any logic in the css file: {{ spacing_multiplier * 1 + 'px' }} {{ break_sm + 30 + 'px' }} Yes, this works in Hubspot's HubL, which I always considered a derivative of Jinja, but the syntax is a bit different. am I doing it wrong? views.py from django.views.generic import TemplateView class Themes(TemplateView): template_name = "css/reely.css" content_type = "text/css" def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) ''' Responsive Breaks ''' context["break_xl"] = 1773 context["break_lg"] = 1292 context["break_md"] = 768 context["break_sm"] = 576 context["break_xs"] = 396 ''' Spacing Multiplier ''' context["spacing_multiplier"] = 10 ''' Font ''' context['google_font_link'] = "https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;600;700&display=swap" context['font_family_1'] = "'IBM Plex Sans', sans-serif;" ''' Color Set 1 ''' context["primary_color"] = '#333333' '''rgb(51,51,51)''' context["secondary_color"] = '#555555' '''rgb(85,85,85)''' context["tertiary_color"] = '#FFFFFF' '''rgb(255,255,255)''' ''' Color Set 2 ''' context["primary_font_color"] = '#333333' '''rgb(51,51,51)''' context["secondary_font_color"] = '#555555' '''rgb(85,85,85)''' context["tertiary_font_color"] = '#FFFFFF' '''rgb(255,255,255)''' ''' Color Set … -
Django website is in constant loading and it doesn't show anything
I don't know what's happening but the website doesn't load correctly. This is the following traceback of the error. I've put everything correctly, the static tags, the img static tags for them to work on Django and it still doesn't load. Any help I would really appreciate it! Thank you: Django version 3.1.3, using settings 'ecommerce.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: /custom/js/mresto.js Not Found: /custom/js/select2.js [23/Jan/2021 13:07:15] "GET /custom/js/select2.js HTTP/1.1" 404 2163 [23/Jan/2021 13:07:15] "GET /custom/js/mresto.js HTTP/1.1" 404 2160 Not Found: /vendor/select2/select2.min.js [23/Jan/2021 13:07:15] "GET /vendor/select2/select2.min.js HTTP/1.1" 404 2190 Not Found: /custom/js/js.js Not Found: /vendor/vue/vue.js [23/Jan/2021 13:07:15] "GET /custom/js/js.js?id=1.9.7 HTTP/1.1" 404 2157 Not Found: /vendor/axios/axios.min.js [23/Jan/2021 13:07:15] "GET /vendor/vue/vue.js HTTP/1.1" 404 2154 [23/Jan/2021 13:07:15] "GET /vendor/axios/axios.min.js HTTP/1.1" 404 2178 Not Found: /vendor/flatpickr/flatpickr.js Not Found: /custom/js/notify.min.js Not Found: /custom/js/rmap.js [23/Jan/2021 13:07:15] "GET /vendor/flatpickr/flatpickr.js HTTP/1.1" 404 2190 [23/Jan/2021 13:07:15] "GET /custom/js/notify.min.js HTTP/1.1" 404 2172 [23/Jan/2021 13:07:15] "GET /custom/js/rmap.js HTTP/1.1" 404 2154 Not Found: /default/logo_qrzebra.png [23/Jan/2021 13:07:15] "GET /default/logo_qrzebra.png HTTP/1.1" 404 2175 Not Found: /manifest.json [23/Jan/2021 13:07:16] "GET /manifest.json HTTP/1.1" 404 2142 Not Found: /serviceworker.js [23/Jan/2021 13:07:18] "GET /serviceworker.js HTTP/1.1" 404 2151 [23/Jan/2021 13:07:24] "GET / HTTP/1.1" 200 37802 Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\wsgiref\handlers.py", … -
How to load form content into a table, and then save this content in a database
Hello guys. I have a template in Django that has a form. When I hit the Submit button, I need to load this data into a table, without loading it into a database at the moment. Then, in the table I have another button that has to validate that information from the table and if it is correct then it has to save it in a database. Do you have any idea how to do it? Thank you all. -
DigitalOcean django application with Gunicorn and Nginx issue
I am having an issue getting my gunicorn service to boot. I am working in digitalocean droplet. gunicorn.service: [Unit] Description=Gunicorn daemon for Django Project Before=nginx.service After=network.target [Service] WorkingDirectory=/home/django/papayas/ ExecStart=/home/django/papayas/env/bin/gunicorn --bind unix:/home/django/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py config.wsgi:application User=django Group=django [Install] WantedBy=multi-user.target error: ● gunicorn.service - Gunicorn daemon for Django Project Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sat 2021-01-23 11:50:27 UTC; 2s ago Process: 16563 ExecStart=/home/django/papayas/env/bin/gunicorn --bind unix:/home/django/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py config.wsgi:application (code=exited, status=1/FAILURE) Main PID: 16563 (code=exited, status=1/FAILURE) DigitalOcean gives you a project that is working and that gunicorn.service is: [Unit] Description=Gunicorn daemon for Django Project Before=nginx.service After=network.target [Service] WorkingDirectory=/home/django/django_project ExecStart=/usr/bin/gunicorn3 --name=django_project --pythonpath=/home/django/django_project --bind unix:/home/django/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py django_project.wsgi:application Restart=always SyslogIdentifier=gunicorn User=django Group=django [Install] WantedBy=multi-user.target I have been trying to fix this for days now. I don't know what to do anymore. please help. -
Does the Django ORM support SQL "AS" operator?
I want to be able to write a query like... SELECT month(date) AS m, name FROM users; What is the django ORM equivalent? -
Nginx returns 403 when serving a file from S3 via x-accel-redirect
I have the following nginx config: upstream upstream_server { server localhost:8000; } server { client_max_body_size 50M; error_log /dev/stderr; listen 80; location ~ ^/document_store/(.*?)/(.*?)/(.*) { internal; resolver 8.8.8.8 ipv6=off; set $download_protocol $1; set $download_host $2; set $download_path $3; set $download_url $download_protocol://$download_host/$download_path; proxy_set_header Host $download_host; proxy_set_header Authorization ''; proxy_set_header Cookie ''; proxy_hide_header Content-Disposition; proxy_hide_header Access-Control-Allow-Origin; add_header Content-Disposition $upstream_http_content_disposition; add_header Access-Control-Allow-Origin *; proxy_max_temp_file_size 0; proxy_pass $download_url$is_args$args; } location / { proxy_pass http://upstream_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Context: All requests hit the / block and are proxied to the django app running on gunicorn behind this server. For some requests, the django app will return a 200, with an x-accel-redirect header of the form: /document_store/<PROTOCOL>/<PRE-SIGNED S3 URL>. Expected behaviour: Nginx intercepts the response with the x-accel-redirect header, and instead serves the file from the pre-signed s3 url. Actual behaviour: Django successfully returns a 200, with the header set as expected. Nginx intercepts this request, and returns a 403. I have logged out the contents of the x-accel-redirect header, and passed <PROTOCOL>://<PRE-SIGNED S3 URL> to curl, which results in the file being downloaded successfully, so I am confident that: The header is being constructed properly The pre-signed header gives … -
'NoneType' object has no attribute 'display_name' in django
I have an django project where there are some apps , and models.py for each app with some ForiegnKey Fields. like below. for example this is Master_data app and inside models : class MaintenanceType(models.Model): name = models.CharField(max_length=10) display_name = models.CharField(max_length=100, null = True, blank = True) def __str__(self): return self.display_name or self.name calculator app model: class FamilyGroup(models.Model): name = models.CharField(max_length=10, choices=name_choices) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_type = models.ForeignKey(FamilySituation, on_delete=models.PROTECT, null=True, blank=True) maintenance_type = models.ForeignKey( MaintenanceType, on_delete=models.PROTECT, limit_choices_to={'name__in': ['Single', 'Couple']}, null=True, blank=True) so i have a property function in the FamilyGroup model : @property def maintenance_type_rate(self): b = self.maintenance_type.display_name r = MaintenanceTypeRate.objects.filter( Q(rate__gte=0) & Q(maintenance_type__display_name=b)) for d in r: return float(d.rate or 0) im getting an error 'NoneType' object has no attribute 'display_name' the error occurs at the property function traceback: File "/home/abdallaoss/cra-calculator/calculator/models.py", line 301, in maintenance_type_rate b = self.maintenance_type.display_name or Exception Type: AttributeError at /calculator/transaction/ Exception Value: 'NoneType' object has no attribute 'display_name' -
How to use django exceptionreporter's get_traceback_text() function?
I want to collect info about the exception that happened on the server by saving the exception's text (e.g traceback) in the database. How to do this without using any third-party apps like Sentry? How to create a view, that handles http500 errors on site and saves their traceback in database? -
Django Group By Permutations of ManyToManyField
I'd like to perform a group_by on a ManyToManyField habit_type = models.ManyToManyField(HabitType, blank=True), but not on every single existing element but on the existing permutations. E.g. currently there are 7 existing elements which are referenced to and with the query below it is grouped by each element. I'd like to group by the existing permutations like (1,2), (1,3,5), (1,4,6,7) But I do not want all possible combinations which would be a little bit too much... result = obj.registration_set.values(habit_type=F('participantpersonal__habit_type'))\ .annotate(number_personal=Coalesce(Count('participantpersonal__habit_type'), 0)) return result As example I have 6 entries with the habit (1,2) the current output is: { "habitTypeGroup": 1, "numberGroup": 6 }, { "habitTypeGroup": 2, "numberGroup": 6 } And my wished output is: { "habitTypeGroup": [1,2], "numberGroup": 6 }, Thanks for your help in advance -
Receiving a hidden input trough a submit button that has also other functionalities
I am building a django app in which the user has to write a sentence in a text box. After that the user has to click on continue and the sentence gets sent to the server and received by it. then it returns the next html page and with the sentence as context data for the render function. Now on this second html page the user has to record an audio of a word he sais. The word is then turned into a string and after that sent to the server trough a submit button. Since I passed the sentence to the second html page I can put a hidden input that has the sentence as value on the second html page. But now I would like that this sentence(the hidden input value) gets sent to the server with the word as a string. And this is what I tried but it does not work and I do not understand why. This is the impotant part of the second html page: <div id='result' class='voc'> Your text will appear here </div> <br> <div id= 'record'> <button onclick="startConverting()" class='btn btn-info btn-sm' id="re">record</button> <form action="/audio_data" method="POST"> <button class='btn btn-info btn-sm ml-3' value="Send" id="send" … -
cant add mysql database in django
i have problem with mysql database. i creat new django project. and i add in settings.py mysql database connection information after that i migrate to mysql database and everything is fine. data tables was created and information of admin was added to user_auth. when i created superuser with python manage.py createsuperuser user was added to user_auth table in phpmyadmin "mysql" database. but when i want to enter on admin panel i'm getting this error. screenshot of admin login "picture" user is created in database "picture" my settings.py code import pymysql pymysql.install_as_MySQLdb() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'century_21_db', 'USER': 'century21', 'PASSWORD': '!nxSb543js!6bX60', 'HOST': 'localhost', 'PORT': '3306', } } -
Filter Djangos Admin list_display and inline
I have a table with films which is connected through intermediate table to to the table Person, which has name and role (writer, actor, director) a person. I am now searching a way to display writers, actors and director separately in list_display. What I have made: list_display = ('title', 'ratings', 'created_on', 'actors', 'writers', 'director') def actors(self, obj): actors = FilmWork.objects.filter(person__role__iexact='actor').values_list('person__name', flat=True) return ", ".join([a for a in actors]) (Same for writers and director). But it shows all actors to each film, but not only belonging to this film. The same in inline edit form, I want to edit them separately, but see the whole list of the names: class ActorInlineAdmin2(admin.TabularInline): model = FilmWork.people.through def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(person__role__iexact='actor') How can I fix it? Is there actually also a way to add new name to the inline, if there is no such name in the drop down? My models: class FilmWorkPerson(models.Model): movie = models.OneToOneField('FilmWork', models.DO_NOTHING, primary_key=True) person = models.ForeignKey('Person', models.DO_NOTHING) created_on = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'film_work_person' unique_together = (('movie', 'person'),) class FilmWork(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) people = models.ManyToManyField('Person', through=FilmWorkPerson) class Person(models.Model): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=100) role = models.CharField(max_length=100) created_on … -
Is there any way to perform QueryStrings through selenium. If my selenium project is to automate recharges
I want to create a link to my selenium mobile recharge file. Thus whenever I hit no. and amount in the link (maybe using query string) it should automate my ** pay.find_element_by_id('mobileNumberTextInputId').send_keys('1234567890')** to something like "automatically" adding no. to 'send.keys' does class= "pagination" can solve my issue? if yes then how? do I have to first create a template to run selenium? or POSTMAN is one of the options? -
Django: TypeError: 'Dossier' object is not iterable while implementing Ajax and Json
I am trying to implement CRUD using Ajax and Json following this tutorial. My URL: from django.urls import path from . import views urlpatterns = [ path('dossier_create/', views.dossier_create, name="dossier_create"), ] My Views: def dossier_create(request): if request.method == 'POST': dossier_form = DossierForm(request.POST) activity_form = ActivityForm(request.POST) else: dossier_form = DossierForm() activity_form = ActivityForm() return save_dossier_form(request, dossier_form, activity_form, 'sbprofile/dossier/partial_dossier_create.html') def save_dossier_form(request, dossier_form, activity_form, template_name): data = dict() if request.method == 'POST': if dossier_form.is_valid() and activity_form.is_valid(): dossier_form = dossier_form.save(commit=False) dossier_form.added_by = request.user dossier_form.added_date = timezone.now() dossier_form.save() dossier = get_object_or_404(Dossier, id=dossier_form.id) activity_form = activity_form.save(commit=False) activity_form.dossier = dossier activity_form.added_by = request.user activity_form.added_date = timezone.now() activity_form.save() data['form_is_valid'] = True dossiers = Dossier.objects.all() data['html_dossier_list'] = render_to_string('sbprofile/dossier/partial_dossier_list.html', { 'dossiers': dossiers }) else: data['form_is_valid'] = False context = {'dossier_form': dossier_form, 'activity_form': activity_form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) My JS: // Create dossier $(".js-dossier-create").click(loadForm); $("#modal-dossier").on("submit", ".js-dossier-create-form", saveForm); var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-dossier").modal("show"); }, success: function (data) { $("#modal-dossier .modal-content").html(data.html_form); } }); }; var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#dossier-table").html(data.html_dossier_list); $("#modal-dossier").modal("hide"); } else … -
Django Foreign key automatic assignment on form submission
Hey Fellow Django coders I have a Booking(Parent) and tblProcessBooking(Child) tables so I created a model form of the tblProcessBooking that has a foreign key called Approval_Status, so I want the Approval_Status to match the correct booking please check my HTML file and image to see what I mean. I tried setting using a dyanamic url valvue by saving it into a cache then accessing it in the Admin_home function as to set the approriate foreighn key value for the corresponding booking. MODELS.PY FILE class Booking(models.Model): purposes = (('Per', 'Personal use'), ('SV', 'Site Visit'),) pick_up_locations = (('JHB', 'Johannesburg Office'), ('DBN', 'Durban Office'), ('PE', 'Port Elizabeth Office'), ('MP', 'Mpumalanga Office'), ('PLK', 'Polokwane Office'), ('BLOE', 'Bloemfontein Office'), ('CPT', 'Cape Town Office'), ('MFK', 'Mafikeng Office'),) purpose = models.CharField(max_length=255, choices=purposes) description = models.CharField(max_length=1080, default='') client_name = models.CharField(max_length=255) pickUp_date = models.DateTimeField() dropOff_date = models.DateTimeField() booking_date = models.DateTimeField(default=datetime.now()) pickUp_location = models.CharField(max_length=255, choices=pick_up_locations) dropOff_location = models.CharField(max_length=255, choices=pick_up_locations) destination = models.CharField(max_length=255, ) vehicle_type = models.ForeignKey(VehicleType, default=10, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.SET_NULL, null=True, blank=True) unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) def __str__(self): id_ = str(self.pk) return id_ class tblProcessBooking(models.Model): statuss = (('A', 'Approved'), ('D', 'Declined')) status = models.CharField(default="Pending", max_length=1080, choices=statuss) description = models.CharField(max_length=1080, default='Booking requirements met') date_processed = models.DateTimeField(default=datetime.now, … -
How to access the csrf_token inside django view
I'm trying to access the csrf_token inside the django view function. I have tried importing the csrf: from django.template.context_processors import csrf and using it like this landingPageHtml = landingPageHtml.replace('csrf_token', csrf(request)['csrf_token']) But I'm getting an error. second argument must be a str not lazy object. How can I access the csrf token in a view? @login_required def viewLandingPage(request, slug): lp = getLandingPage(request, slug) landingPageHtml = getLandingPageFile(request, lp['file']) landingPageHtml = landingPageHtml.replace( '{{ lp.seo_title }}', lp['seo_title']) landingPageHtml = landingPageHtml.replace( '{{ lp.seo_description }}', lp['seo_description']) landingPageHtml = landingPageHtml.replace('csrf_token', 'csrf_token') return HttpResponse(landingPageHtml) -
Django: invalid certificate after installing SSLSERVER
I am trying to run my server with https, so I installed django-sslserver, and running as below. py manage.py runsslserver --certificate F:/certs/server.crt --key F:/certs/server.key 127.0.0.1:8000 The output after execution is: Watching for file changes with StatReloader Validating models... System check identified no issues (0 silenced). January 22, 2021 - 23:20:11 Django version 3.1.2, using settings 'ecommerce.settings' Starting development server at https://127.0.0.1:8000/ Using SSL certificate: F:/certs/server.crt Using SSL key: F:/certs/server.key Quit the server with CTRL-BREAK. The website is running well but I still get What is wrong? -
saving generated otp into database
i am creating a booking system in which i send the user a code via sms when they submit their booking form, the code is for them to bring to the company when they are attending their appointment but i am failing to save the code to the database, the code is generated and passed on in the message, here is the views.py file code = generateOTP() def booking(request): if request.method == 'POST': print(request.POST) book = BookingForm(request.POST, ) if book.is_valid(): phone = book.cleaned_data['phone'] book = book.save(commit=False) book.user = request.user book.otp_code = request.GET.get[code] book.save() messages.success(request, 'Form submission successful') sendSms(message, phone) msg_body = f''' Hello {request.user.username}! Your Verification Code is : {code} Make sure you give this code when attending booking Thank you for booking with us :) ''' Models.py class Booking(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) otp_code = models.CharField(max_length=6, null=True) -
Django - How to take first word of a string in html template?
I have this list where I want to only get the first word (I would like to remove the "engineering" in all of them) and I am displaying this in my html template like this: {% for course in courses %} <li>{{ course }}</li> {% endfor %} I tried to do this: {% for course in courses %} <li>{{ course|first }}</li> {% endfor %} but it only gives me the first letter of each string. I know that i can do the truncate but not all of them have the same number of letters. I also tried to do this but to no avail. What solutions can I try? Thanks in advance! -
Does DRF Model serializer preserve the order in the list when creating multiple objects?
I want to use ModelSerializer to create multiple objects. If I have a list of the data for the objects as, data = [{object_1_data},{object_2_data},...] and when I use model serializer to create the objects as, serializer = serializer(data=data, many=true) if serializer.is_valid(): objects = serializer.save() Does the return objects list contain the objects in the same order as earlier? objects = [object_1, object_2, ...]