Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create multiple image upload widget like this
hey i am trying to implement this type of image upload feature in my project but cant find any good resources can someone tell me how to make this type of multiple image upload: I am using Django for the backend and plain HTML,CSS and JS for the frontend. this widget also has a drag and drop feature and it shows the uploaded image as you can see but i dont know how to do that in django. -
How to convert a array of dictionaries into an array javascript?
I have imported an array from python, the array is in form of string for example - "["{"key1":"value1","key2":"value2"}","{"key1":"value1","key2":"value2"}"]" I want to parse this into an actual array in javascript, so basically I want it like - [{"key1":"value1","key2":"value2"}, {"key1":"value1","key2":"value2"}] Is there any possible way to do this? Any help is appreciated -
Subprocess cannot access pipenv
I'm trying to write a Django starter so I wouldn't have to keep typing separate long commands. I could not access my path using /home/stevek/.local/share/virtualenvs/startdjango-iuzIP2Ap . I tried sudo /home/stevek/.local/share/virtualenvs/startdjango-iuzIP2Ap and it would not work. I found this path by using `pipenv --venv. I want to use subprocess to run my startprojects and startapp since they'll only work while inside pipenv because it has the installed django packages. I couldn't access pipenv shell so I couldn't do any django stuff. Anyone know how to fix this? #!/usr/bin/env python3 import subprocess import time import sys import os ################################################################ # arg0 is main.py # arg1 is pipenv django version # arg2 is project name # arg3 is app name # arg4 is for debug ################################################################ venv_python = '/home/stevek/.local/share/virtualenvs/startdjango-iuzIP2Ap' project_arg = [venv_python, 'django-admin', 'startproject', sys.argv[2]] app_arg = [venv_python, 'python3', 'manage.py', 'startapp', sys.argv[3]] """ Create in main environment """ subprocess.run(["pipenv", "install", f"django~={sys.argv[1]}"]) subprocess.run(["pipenv", "shell"]) """ Needs pipenv compatible""" subprocess.run(project_arg) subprocess.run(debug_arg) subprocess.run(app_arg) if sys.argv[4].startswith("debug"): debug_arg = [venv_python, 'debug', sys.argv[4]] subprocess.run(debug_arg) seconds = debug_arg[2][-2:] # Waits for the amount of seconds before nuke time.sleep(seconds) # deletes virtual environment subprocess.run([venv_python, "pipenv --rm"]) subprocess.run([venv_python, "rm Pipfile*"]) # leave virtual environment subprocess.run([venv_python, "exit"]) # delete pipenv files and the … -
1 unapplied migration even though I have performed migration operation
I was creating AbstractUser model in django. I have performed migrations but while running the server there occurs the error that 1 unappllied migrationenter image description here this was the model I created. from django.db import models from django.contrib.auth.models import AbstractUser Create your models here. class LoginTable(AbstractUser): phone = models.BigIntegerField(default=0,null=True) user_type = models.CharField(max_length=30,default='admin',null=True) -
Getting Error => ModuleNotFoundError: No module named 'django' When I attempt to deploy my django app to heroku
When I attempt to deploy my django app to heroku, the deployment will fail with the following error message Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Here is my requirements.txt asgiref==3.3.4 dj-database-url==0.5.0 Django==3.2.3 django-cors-headers==3.7.0 django-on-heroku==1.1.2 djangorestframework==3.12.4 gunicorn==20.1.0 psycopg2-binary==2.8.6 python-dotenv==0.17.1 pytz==2021.1 sqlparse==0.4.1 whitenoise==5.2.0 My Procfile release: python3 manage.py migrate web: gunicorn app_name.wsgi --log-file - And the buildpacks (using nodejs for the frontend) 1. heroku/nodejs 2. heroku/python I have tried to deploy the app from both the CLI and a github repository. Both result in the same error. I am happy to provide any additional information from the project if needed. How can I fix this error so my app will deploy successfully? -
django-oscar 3.0 with paypal payment
I am fairly new with Django as well as Djnago-oscar, so far I have django-oscar store setup and I am trying to integrate with paypal but because I am running django.oscar 3.x 'django-oscar-paypal' doesn't work for me and there is not enough documentation on how to implement payments. My checkout process: Adding items to cart User enter details including shipping etc Select payment method, review redirect to Paypal to complement payment Redirect back to website and confirm the order On paymentMethodeView I have created a form to get the payment method, and on paymentDetailsView I have handle_payment def handle_payment(self, order_number, order_total, **kwargs): method = self.checkout_session.payment_method() if method == 'pt': #payment terms admin manually invoice return self.handle_pt_payment(order_number, order_total, **kwargs) elif method == 'paypal_payment': return self.handle_paypal_payment(order_number, order_total, **kwargs) else: raise PaymentError(_('Bad payment method in handle_payment!')) And at handle_paypal_payment function I am not sure how to proceed. Any help would be much appreciated -
How to show paginated items in their respective pages
I tried paginating models items but all of the items are showing on the same page... What could it be that I'm not doing well??? def view_books(request): books = Books.objects.filter(school = request.user.school) page = request.GET.get('page', 1) paginator = Paginator(books, 10) try: userd = paginator.page(page) except PageNotAnInteger: userd = paginator.page(1) except EmptyPage: userd = paginator.page(paginator.num_pages) return render(request, 'libman/view_book.html',{'userd':userd}) The rendering template {% if userd.has_other_pages %} <ul class="pagination container text-center"> {% if userd.has_previous %} <li><a href="?page={{ userd.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in userd.paginator.page_range %} {% if userd.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if userd.has_next %} <li><a href="?page={{ userd.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} -
name field is not defined
On the existing API in django I am trying to add a text area field. I have tried adding a create with serializer but experience following error; NameError at /api/v1/notes/images/ name 'dateImg' is not defined My model has: class ImageAttachment(models.Model): note = models.ForeignKey(Note, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_file_path, storage=NoteS3Boto3Storage(bucket=settings.AWS_STORAGE_BUCKET_NAME)) dateImg=models.TextField() My serializer has: class ImageListSerializer(serializers.Serializer): note = PrimaryKeyRelatedField(queryset=Note.objects.all()) image = serializers.ListField( child=serializers.ImageField(max_length=None, allow_empty_file=False)) dateImg=serializers.CharField(style={'base_template': 'textarea.html'}) def create(self, validated_data): note = validated_data.pop('note') images = validated_data.pop('image') dateImg=validated_data.pop('dateImg') self.dateImg = dateImg image_obj = [] for image in images: image_obj.append(ImageAttachment.objects.create(note=note, image=image,dateImg=dateImg)) return image_obj -
How to link input in html form to its form actions in django?
Is it possible to get value from HTML form input and use it in form action? <form action="/wiki/ /" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> Here,I want the form action to be "/wiki/input_in_q/".How do you do that? -
Hello, I need help to update a field when the other is filled on Django
Here is the fields in my model : PAID = 'PG' UNPAID = 'UN' OVERDUE = 'OV' status_CHOICE = [ (PAID, 'Pago'), (UNPAID, 'Aberto'), (OVERDUE, 'Vencido') ] status = models.CharField(max_length=10, blank=True, null=True, choices=status_CHOICE) subtotal = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) I need the 'status' field filled with status_CHOICE when change the subtotal field is equal to zero, and equal to date OVERDUE -
Migration error(django.db.utils.OperationalError)
I'm trying to migrate my custom user model and I run makemigrations command to make migrations for new models. But when I run migrate command it throws this error : conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError Trace back: (venv_ruling) C:\Users\enosh\venv_ruling\ruling>python manage.py migrate Traceback (most recent call last): File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\enosh\venv_ruling\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\enosh\venv_ruling\ruling\manage.py", line 22, in <module> main() File "C:\Users\enosh\venv_ruling\ruling\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) … -
How to let Django drf backend UpdateAPIView only update required fields rather than all?
In my Django Rest Framework backend, those are my code: serializers.py: class DomainUpdateSerializer(serializers.ModelSerializer): class Meta: model = Domain fields = "__all__" my model: class Domain(models.Model): domain_name = models.CharField(max_length=512, help_text='domain. eg.example.com') cname = models.ForeignKey( to=CNAMEModel, on_delete=models.DO_NOTHING, related_name="domains") ssl_key = models.TextField(max_length=40960, help_text="SSL. key") ssl_cert = models.TextField(max_length=40960, help_text="SSL. cert ") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.domain_name def __unicode__(self): return self.domain_name class Meta: verbose_name = "domain" verbose_name_plural = "domain" ordering = ['ctime'] In my frontend when I use the API to update domain. I must fill up all fields, but in my thinking, if I want to update domain_name there should just use id and domain_name, the ssl_key and ssl_cert should be optional. Is is possible to implements my thinking in backend? -
Django Nested Serializer Issue: Field name is not valid for model
I'm trying to setup the following output: { season: 1, player_profile: { name: John Doe, } } The models are setup as such: class PlayerProfile(models.Model): name = models.CharField(max_length=120, null=True) class TeamAffinityReward(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, #db_constraint=False null=True) season = models.IntegerField(null=True, blank=True) The serializers are setup like this: class PlayerProfileForNestingSerializer(serializers.ModelSerializer): class Meta: model = PlayerProfile fields = ( 'name', ) class TeamAffinityRewardSerializer(serializers.ModelSerializer): class Meta: model = TeamAffinityReward playerprofile = PlayerProfileForNestingSerializer() fields = ( 'playerprofile', 'season', ) However, I get the following error: Field name `playerprofile` is not valid for model `TeamAffinityReward`. If I change playerprofile to player_profile, the error goes away but it displays the player_profile_ID instead of the PlayerProfileForNestingSerializer. -
Input value based on previous one
I have a Post method for an Rest API of django rest framework, it's all working so far but I would like to know if it's possible to have an input value automatically filled based on a previous one. Longitude='3.0' Latitude ='3.0' And now I would like for example to have Intensity ='low' because of the latitude value, all of this is in json. -
how to makemigrations in django without a recursion error?
I'm getting the following error when I try the command in windows: python manage.py makemigrations It's an error in some sort of recursion function and I understand that python stops after 999 recursion calls. This is a snippet of the repeating error that finally ends with a RecursionError... File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 414, in check messages.extend(self._check_custom_error_handlers()) File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 431, in _check_custom_error_handlers signature = inspect.signature(handler) File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 3130, in signature return Signature.from_callable(obj, follow_wrapped=follow_wrapped) File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2879, in from_callable return _signature_from_callable(obj, sigcls=cls, File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2330, in _signature_from_callable return _signature_from_function(sigcls, obj, File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2194, in _signature_from_function parameters.append(Parameter(name, annotation=annotation, File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2517, in __init__ self._kind = _ParameterKind(kind) File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\enum.py", line 360, in __call__ return cls.__new__(cls, value) RecursionError: maximum recursion depth exceeded while calling a Python object I have created a models.py: from django.db import models # Create your models here. class fligjt(models.Model): origin = models.CharField(max_length=64) destination = models.CharField(max_length = 64) duration = models.IntegerField() I'm quite new to Django and I'm not sure how to understand this error. -
Different serializers for different objects in a single queryset
For a ForeignKey relationship, how can I change the serializer used based off some criteria? # models.py class Relationship(models.Model): ... class Item(models.Model): relationships = ForeignKey(Relationship) class OddPKSerializer(serializers.Serializer): ... class EvenPKSerializer(serializers.Serializer): ... class ItemSerializer(serializer.Serializer): # relationships = OddPKSerializer and/or EvenPKSerializer(many=True) # depending on some criteria class Meta: model = Item fields = ["relationships"] # Where for example, OddPKSerializer is used if # the specific relationship object has an odd pk # and EvenPKSerializer is used for even pks In my actual use case, I'm looking to serialize differently based on the ForeignKey object's class. (I'm using proxy models so a single ForeignKey field can point to different classes.) I've tried using SerializerMethodField but that only seems to act on the "Item" object and not the "Relationship" objects that I'm looking to serialize. -
Foreignkey Searchbox and Django Crispy Forms
I am using the Django Crispy forms and a Foreignkey field. When creating a new form, is there a way to add a search box in the forms in order to search for the right foreignkey value? Many thanks -
Django social share links to show as buttons
I have installed change social share package and would like to have buttons instead of links. {% post_to_facebook <object_or_url> <link_text> <link_class> %} {% post_to_gplus <object_or_url> <link_text> <link_class> %} {% post_to_twitter <text_to_post> <object_or_url> <link_text> <link_class> %} {% post_to_linkedin <object_or_url> <link_class> %} {% send_email <subject> <text_to_post> <object_or_url> <link_text> <link_class> %} {% post_to_reddit <text_to_post> <object_or_url> <link_text> <link_class> %} {% post_to_telegram <text_to_post> <object_or_url> <link_text> <link_class> %} {% post_to_whatsapp <object_or_url> <link_text> <link_class> %} {% save_to_pinterest <object_or_url> <link_class> %} {% add_pinterest_script %} How can I do it? -
Django "No 'Access-Control-Allow-Origin' header is present on the requested" just to patch request
I am running a backend server made with django and I am trying to send requests to it from my React app. The "No 'Access-Control-Allow-Origin' header is present on the requested" error happened to me earlier when I was trying to send a get request, but I solved it doing what is shown here https://dzone.com/articles/how-to-fix-django-cors-error. What I can't understand is why this problem is happening again when I try to send patch requests if it worked just fine with post and get requests. Here you can see the error in my browser the first get request returned what it should, but then the patch request gets this error. Parts of my settings.py that I made changes: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL=True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', My patch django view: class UpdateUser(generics.ListAPIView): serializer_class = UserSerializer queryset = '' def patch(self, request, format=None): try: data = request.data user = User.objects.get(username=data['username']) user.level = data['level'] user.xp = data['xp'] user.completed_challenges = data['completed_challenges'] user.save(update_fields=['level', 'xp', 'completed_challenges']) return Response(model_to_dict(user), status=status.HTTP_200_OK) except: return Response({'Error': 'Invalid data'}, status=status.HTTP_400_BAD_REQUEST) My patch request made in my React frontend: fetch(`https://pedro-moveit-backend.herokuapp.com/update-user`, { method: 'patch', headers: … -
“unresolved import” error in Visual Studio Code pylint
I am using the following, Windows , Python 3.9.5 , Visual Studio Code 1.56 , Pylint 2.8.2 , Django 3.2.3 , If I use Every import has states "unresolved import". Even on default Django imports (i.e. from django.db import models). How can I fix this ? -
POST an image to django backend via Postman
I m not able to upload an image to the backend using via post request i m using django this is my model : class Upload(models.Model): image_file = models.ImageField(upload_to='images',null=True) created=models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) this is my view : @csrf_exempt def image_list(request): if request.method=='GET': images=Upload.objects.all() serializers=ImageSerializer(images,many=True) return JsonResponse(serializers.data,safe=False) elif request.method=='POST': data=JSONParser().parse(request) serializer=ImageSerializer(data=data, required=False) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=201) return JsonResponse(serializer.errors,status=400) and this is my serializer, i think the problem is in the isValid but i m really new and i can't seem to figure it out please help me. from rest_framework import serializers from .models import Upload class ImageSerializer(serializers.ModelSerializer): class Meta: model=Upload fields=['id','image_file'] -
When I delete a folder or a file in Django manually and try to run the project I'm getting error on the same module which I have deleted?
I have deleted a folder named accounts from my django project and tried to run the file but getting this error "ModuleNotFoundError: No module named 'accounts'" Eventhough I have deleted manually it's asking me to delete the paths as well. How to get over from this error. Help me out please. Thanks in advance -
To Do List item update in database not working with Django
I want to finish my To-Do app. However, I still can't edit an item properly. My idea was to update the database by picking the particular item and overwrite its information with .save(). Could someone figure out the correct update() function to make it work? Here is my code: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:aufgabenzettel_id>", views.details, name="details"), path("add/", views.add, name="add"), path("delete/<int:aufgabenzettel_id>", views.delete, name="delete"), path("edit/<int:aufgabenzettel_id>", views.edit, name="edit"), path("update/<int:aufgabenzettel_id>", views.update, name="update") ] models.py from django.db import models # Create your models here. class Aufgabenzettel(models.Model): Aufgabeselbst = models.CharField(max_length=64) def __str__(self): return f"{self.Aufgabeselbst}" views.py from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .models import Aufgabenzettel # Create your views here. def index(request): return render(request, "aufgabenzettel/index.html", { "Aufgabenliste":Aufgabenzettel.objects.all() }) def details(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) return render(request, "aufgabenzettel/details.html", { "details":aufgabenzettel }) def add(request): if request.method == "POST": Aufgabe = request.POST["Hinzufügen"] Aufgabenzettel.objects.create(Aufgabeselbst=Aufgabe) return HttpResponseRedirect(reverse("index")) return render(request, "aufgabenzettel/add.html") def delete(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) aufgabenzettel.delete() return HttpResponseRedirect(reverse("index")) def edit(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) return render(request, "aufgabenzettel/edit.html", { "details":aufgabenzettel }) def update(request, aufgabenzettel_id): if request.method == "POST": Aufgabe = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) Aufgabejetzt = request.POST["Bearbeiten"] Aufgabejetzt.save() return HttpResponseRedirect(reverse("index")) else: Aufgabe = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) return render(request, "aufgabenzettel/edit.html", … -
mqtt over socket in django-channels
I am trying to start a mqtt broker over websocket in django-channels to publish data over specific topics to authorized users. I have defined a url to filter mqtt request in a specific consumer where I am accepting the socket request. This all part is working fine but when I am establishing a mqtt connection the socket is restarting again and again, and I don't have any idea why this is happening!? and also it's a bit confusing how will i send the message from my views. Code snippets: routing.py from django.urls import re_path from . import consumer websocket_urlpatterns = [ re_path(r'ws/data/(?P<room_name>\w+)/(?P<auth_data>\S+)/$',consumer.ChatConsumer.as_asgi()), re_path(r'mqtt', consumer.ChatTwoConsumer.as_asgi()) ] consumer.py class ChatTwoConsumer(WebsocketConsumer): def connect(self): print('here') self.accept() -
Why does form.is_valid return false. Please advice
I have a project where one books a room online then is directed to the checkout page where you input a phone which is required in the backend. Code is as below: forms.py from django import forms class AvailabilityForm(forms.Form): check_in = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M'], required=True) check_out = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M'], required=True) class PhoneNoForm(forms.Form): phone_no = forms.IntegerField(required=True) views.py class RoomDetailView(View): def get(self, request, *args, **kwargs): category = self.kwargs.get('category', None) got_category = get_room_category(category) print(category) print(got_category) form = AvailabilityForm() if got_category is not None: context = { 'category':got_category, 'form':form } return render(request, 'detail.html', context) else: return HttpResponse("Category Nyet!") def post(self, request, *args, **kwargs): category = self.kwargs.get('category', None) form = AvailabilityForm(request.POST) if form.is_valid(): data = form.cleaned_data available_rooms = get_available_rooms(category, data['check_in'], data['check_out'] ) if available_rooms is not None: room = available_rooms[0] context = { 'room':room } return render(request, 'booking/checkout.html', context) else: return HttpResponse("We're out of those rooms" ) else: return HttpResponse('Form invlid') class CheckoutView(TemplateView): template_name = 'booking/checkout.html' def get_phone(request): if request.POST: phone_no = request.POST.get('PhoneNo', None) print(phone_no) context = { 'phone_no' : phone_no } return render(request, 'booking/checkout.html', context) else: return redirect('booking:RoomDetailView') checkout.html <div> <form action="" method="POST"> {% csrf_token %} <label for="Input No.">Input Phone No. :</label> <input type="number" name="id_PhoneNo" id="PhoneNo"> <input type="submit" value="Proceed"> </form> </div> detail.html <form id="booking-form" action="" method="POST"> {% …