Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django selenium (StaticLiverServerTestCase): tests run together fail but pass if run individually
I write tests with StaticLiverServerTestCase for my Django application. My issue: tests runs together fail while pass when run individually. I have read much about this behavior on SO but none of answer/comments help. It seems that issue may come from shared files/fields/data. I have tried using setUpClass/tearDownClass class methods as well as setUp/tearDown methods. Using fixture did not resolve anymore. I also tryed to make individual class for each test instead of one class with many test ethods but doesn't work anymore. My tests involve Ajax calls and I think this is related. For example, in the 2 tests below: L_new_patient_is_created_from_index_page_TestCase run first (I don't know why) and pass. L_search_form_exist_refresh_TestCase fail L_search_form_exist_refresh_TestCase will call an ajax view to display a table and change the url with JQuery ($(location).prop('href', redirect_url);). So if the user refresh the page (F5), it will be redirected to another page that hit the changed url and display the same table. What happen when the 2 tests are run together is that url is not changed so refresh do not redirect to the right page. How can I make my tests trully independant? class L_search_form_exist_refresh_TestCase(StaticLiveServerTestCase): fixtures = ['dumpdata.json'] port = 8000 # host = "0.0.0.0" # … -
Get empty OrderedDict through Serializer when retrieving
I have built two models: class Homepage(models.Model): org_name = models.CharField(max_length=20, blank=True) org_code = models.CharField(max_length=20, blank=True) class Meta: ordering = ('org_name',) def __str__(self): return self.org_name class MainDiag(models.Model): release = models.TextField(max_length=256, blank=True) code = models.CharField(max_length=20, blank=True) condition = models.CharField(max_length=20, blank=True) homepage = models.ForeignKey(Homepage, related_name='main_diag', on_delete=models.CASCADE) Serializers: class MainDiagSerializer(serializers.ModelSerializer): class Meta: model = MainDiag fields = ( 'release', 'code', 'condition', ) class HomepageSerializer(serializers.ModelSerializer): main_diag = MainDiagSerializer(many=False) class Meta: model = Homepage fields = ( "org_name", "org_code", "main_diag", ) def create(self, validated_data): main_diag_data = validated_data.pop('main_diag') homepage = Homepage.objects.create(**validated_data) MainDiag.objects.create(homepage=homepage, **main_diag_data) return homepage I can add MainDiags into MySQL successfully, however, when I get Homepages through serializer = HomepageSerializer, the main_page in serializer.data is always an empty OrderedDict(). Is there any issue with my code? How can I get the main_page through serializer.data? Thank you very much! -
How do I access User Model field in the Serializer of extended User Model in Django Rest Framework?
I am creating a simple registration/login app in Django Rest Framework using Rest APIs with Django Rest Knox's authentication, in which, upon registration, user will also upload a CSV File (which is an optional field). I have a Person Model which is an extended (derived or OneToOne) Model of User Model and has FileField for the file to be uploaded. I have two ModelSerializers, one is based on User Model named MainRegisterSerializer and serializes username, email and password fields, and the other is based on Person Model named RegisterSerializer, which serializes FileField and register field (that is initialized with MainRegisterSerializer class's constructor. Now, in views.py, I am accessing the RegisterSerializer, to get the data from front that which includes username, email and password fields from User Model, and FileField from Person Model. But, when I enter data in front-end and upload the file, and click on POST button, I get the following error: KeyError at /api/v1/register 'username' on the code line user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password'], validated_data['file']) in serializers.py file. My views.py is: from rest_framework.response import Response from knox.models import AuthToken from .serializers import RegisterSerializer class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user … -
uploading multiple files in django form and function in views
I am trying to upload multiple files in Django form. I followed multiple methods. I am successful via models to views but I want via models to forms to views. I followed Use view/form in Django to upload a multiple files this question but my form is not submitting. Here I am sharing my codes. I hope to get the mistake I am doing by any expert. #models.py class Question(models.Model): description = models.TextField(blank=True, null=True) created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) def __str__(self): return self.description class QuestionFile(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name='files', null=True, blank=True) file = models.FileField( 'files', upload_to=path_and_rename, max_length=500, null=True, blank=True) def __str__(self): return str(self.question) #forms.py from django import forms from .models import * class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ['description'] class QuestionFileForm(QuestionForm): # extending Questionform file = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta(QuestionForm.Meta): fields = QuestionForm.Meta.fields + ['file', ] def clean(self): cleaned_data = super().clean() description = cleaned_data.get("description") file = cleaned_data.get("file") if not description and not file: self.add_error( 'description', 'Kindly describe the question details or upload any file') #views.py def questionView(request): if request.method == 'POST': form = QuestionFileForm(request.POST or None, request.FILES or None) files = request.FILES.getlist('file') if form.is_valid(): question = form.save(commit=False) question.created_by = request.user # add everything needed … -
How to style an Image Field button in Django App
I want to style my Image Field Button (Choose File) with CSS. Currently, its displaying in the default theme. I am using Bootstrap V5.0.1, Django V3.2.12, Python 3.7.6. First, I tried to identify or add a class or id which I can add and style the button regularly but was unable to add as the button was added by Django Image Field. The Code in my forms.py is given below: from django import forms class ImageUploadForm(forms.Form): image = forms.ImageField(label='') Then I used the Hover functionality of the Chrome Developer Tools to identify any leads and found that the button and its area had 2 id's #file-upload-button and #id_image. I tried to add CSS to the above-mentioned id's but did not get the result i desired. I want to style the Choose File Button Below also if possible can i add any bootstrap to the button, any help would be appreciated! Thanks. HTML-Django Code <div class="form-group text-center"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <br> <button type="submit" id="btnUpload" class="btn btn-primary" style="margin-top:20px;">Upload</button> </form> </div> -
ImportError: cannot import name 'profile' from 'user.models'
from django.contrib import admin from django.urls import path,include from user import views as user_view from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import staticyour text -
Check data exist in any foreign key table of pk table in MySQL database using django python
I am trying to check if there has any data in all referenced table of a primary key table. Is it possible in mysql using django, not any raw query, need to do it in django, python. Find 02 queries in mysql, but need more details in django. SELECT \* FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE SELECT DISTINCT KEY_COLUMN_USAGE.CONSTRAINT_NAME, KEY_COLUMN_USAGE.TABLE_NAME, KEY_COLUMN_USAGE.COLUMN_NAME, KEY_COLUMN_USAGE.REFERENCED_TABLE_NAME, KEY_COLUMN_USAGE.REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ON TABLE_CONSTRAINTS.CONSTRAINT_NAME=KEY_COLUMN_USAGE.CONSTRAINT_NAME WHERE TABLE_CONSTRAINTS.CONSTRAINT_TYPE="FOREIGN KEY" AND TABLE_CONSTRAINTS.CONSTRAINT*SCHEMA=\<DATABASE*NAME\>; Thanks in advance! I tried to get all referenced foreign key table of a primary key table. Then check if any data exists in those foreign key tables. But I am not getting any source in django. Is ist possible? -
Django left join or analog
I can’t figure out how to use Django ORM for left joins, please see case below. So, my models are (please, don’t mind native language): class Production(models.Model): '''Выработка.''' project = models.ForeignKey( Project, on_delete=models.PROTECT, verbose_name='проект') timeperiod = models.ForeignKey( Timeperiod, on_delete=models.PROTECT, verbose_name='период') time = models.DurationField('трудочасы') ammount = models.DecimalField('выработка', max_digits=10, decimal_places=2) note = models.TextField('заметка', blank=True, null=True) is_auto = models.BooleanField( 'признак автоматического расчета', default=False) class Timeperiod(models.Model): '''Периоды.''' start_date = models.DateField('дата начала') end_date = models.DateField('дата окончания') target_duration = models.DurationField('длительность') is_open = models.BooleanField('открыт', default=True) I would like to make following selection: Get all the Timeperiod with filters on start_date and end_date Get related Production with filter on project (if any exists for this particular period) Pass it to template_processor and render it as a table (in for loop) I know how to filter queryset, and know how to get related queryset, but I don’t understand how to filter my RELATED queryset -
Django authentication with .NET httpWebRequest and HttpWebResponse
I have an issue with the login with the "POST", following this link here: Django Authentication from .NET using HttpWebRequest and HttpWebResponse via HTTP POST Without "POST", I don't seem to get logged on because the received ResponseStream is still on the login page. Adding the request method "POST" caused me to be caught in "The remote server returned an error: (403) Forbidden." Also tried .Credentials rather than "Dim postData As String = "username=" & m_username & "&password=" & m_password" but nothing helps. Trying AllowAutoRedirect True/False, PreAuthenticate True/False doesn't help at all. myRequest.AllowAutoRedirect = True myRequest.Method = "POST" myRequest.PreAuthenticate = True myRequest.Credentials = New NetworkCredential(username, password) I am sure I can access the site with the password I am using. Any advice? -
Monitoring of loggings using Django
I have a pipeline of steps that I want to monitor and also alert the user in the front end about the process. Now, the logging messages can come from many parts of the code, is it a good approach to create a Django task that monitors the logging file (until the pipeline finishes) and via a channel sends the information to the front-end? Is there a better approach to that problem ? -
I want to choose IOT based project in my final year semester?
Basically, I know python and its worth in the future and I m currently working as a Backend developer on Django and Django rest framework but don't know how I choose IOT related projects. In our country, there is a little bit of working on IoT and I also want to work on IoT can anyone help me with this or suggest to me or guide me. -
Django Rest Framework method in action decorator needs be specified in class http_method_names
DRF version is 3.11.2 I was working on some existing code to add an extra "delete" action to a viewset, but I got 405 Method not allowed, consider the following made up example class UserViewSet(ViewSet): .... queryset = User.objects.all() http_method_names = ['get', 'post'] @action(detail=True, method=['delete']) def delete_profile(self, request, pk=None) Profile.objects.get(user=pk).delete() .... Like I said, when I make a delete method call to /user/123/delete_profile, I get 405 Method not allowed, however, if I add delete to http_method_names as below, it works fine. class UserViewSet(ViewSet): .... queryset = User.objects.all() http_method_names = ['get', 'post', 'delete'] @action(detail=True, method=['delete']) def delete_profile(self, request, pk=None) Profile.objects.get(user=pk).delete() .... But this is not ideal as I don't want to allow "delete" operation on the User, whilst I can overwrite the delete method on the viewset to avoid user being deleted, this is not very elegant. So the question is, is this a bug or by design? -
Page redirection with populated data
I have a django site which has the name records as model in which it stores the data of particular items i have other model task in which we give the information of records(dropdown shows the records related to that particular user) to create the task, so inside the record we are adding a create task button upon clicking it redirects to the task creation page and it should populate the record details in the record dropdown on page how can i achieve this. -
UNIQUE constraint failed: auth_user.username while creating the user using a custom designed form
I am new to django and I am working on student login for examination portal. I am basically passing two forms in my view. One form is for getting the user details and second is for storing details of student. I have used django widget tweak package to load the fields of my forms. My user gets created but at the same time I still get the error- UNIQUE constraint failed: auth_user.username. Here's my model.py class StudentInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.IntegerField(max_length=20, blank=True) branch = models.CharField(max_length=50, blank=True) forms.py class StudentForm(forms.ModelForm) class Meta(): model = User fields = ['username', 'email', 'password'] widgets = { 'password': forms.PasswordInput() } class StudentInfoForm(forms.ModelForm): class Meta(): model = StudentInfo fields = ['mobile','branch'] views.py def register(request): userForm= forms.StudentForm() studentForm=forms.StudentInfoForm() mydict={'userForm':userForm,'studentForm':studentForm} if request.method=='POST': userForm=forms.StudentForm(request.POST) studentForm=forms.StudentForm(request.POST) if userForm.is_valid() and studentForm.is_valid(): user=userForm.save() user.is_active = True user.set_password(user.password) messages.success(request,"Student User created Succesfully.") student=studentForm.save(commit=False) student.user=user student.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) return redirect('login') return render(request,'student_signup.html',context=mydict) html file {% load widget_tweaks %} <!doctype html> <html lang="en"> <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.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Student Signup</title> </head> <body> <h1 style="text-align: center; margin-top: 5px;">Student Signup</h1> <div class="container mt-5" style="width: 50%;"> <form … -
django not functioning over HTTPS with apache and mod_wsgi
My requirement is to take my django app over HTTPS. I generated ssl certs with the help of command: openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout ssl_cert.key -out ssl_cert.crt Installed mod_wsgi and mod_ssl and configured them into httpd.conf as: SSLCertificateChainFile "location/to/certs/ssl_cert.cert" WSGIScriptAlias / /location/to/django/app/wsgi.py WSGIPythonHome /root/python3.9 #WSGIPythonPath "/root/python3.9/lib;/root/python3.9/lib/python3.9/site-packages" WSGIPythonPath /location/to/django/app <Directory /location/to/django/app> <Files wsgi.py> Require all granted </Files> </Directory> And restarted apache service. I made changes in settings.py as: SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Now on starting Django App with command: HTTPS=on python3 manage.py runserver 8000 It says: Django version 2.2, using settings 'djangoApp.settings' Starting development server at http://localhost:8000/ And its still accessible over http only and if trying to access over HTTPS, it gives error as: This site can’t provide a secure connection from debug.log: You're accessing the development server over HTTPS, but it only supports HTTP. Can somebody please help what I'm missing to configure and how to solve this issue? -
44 connect() failed (111: Connection refused) while connecting to upstream on AWS Elastic Bean
I want to upload my django project to AWS ElasticBean but I have been getting 502 error. I have gone through few videos on youtube but it doesn't seems to work. Here is my project directory ├───.ebextensions ├───.elasticbeanstalk ├───ebdjango ├───.gitattributes ├───.gitignore ├───db.sqlite3 ├───manage.py ├───Pipfile ├───Pipfile.lock └───requirements.txt Here is my django.config setting The tutorials i have been seeing does not explain most of their settings in details and I don't want to just copy and paste code without knowing it's application. option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "awsdjango.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application I dont't have a Procfile, Gunicorn package nor their config in my project. Please let me know in details where i'm not getting it right whether in my settings file or anywhere, just point it out for me. -
Accessing Parent Model from child element of ManyToManyField (Django)
I am having a models.py as follows class Comment(models.Model): auther_name = models.CharField(max_length=20, null=False, blank=False) comment_body = models.TextField(max_length=200, null=False, blank=False) class Post(models.Model): comments = models.ManyToManyField(Comment) So let's say i have a comment Object Instance which's id is 2 and raw content How to get parent post_id which contains this comment?? -
Django object’s attributes becomes a strings if accessed through get first object attribute in queryset
I have a problem that if I access objects attributes in queryset like queryset.0.attr1 it looses it’s type and become a string (Django template processor processes it like a string) Simlple example: I got queryset, that have related set, but when I access this related set first object’s attibute by index.attribute_name it becomes string. If I do the same thing in a loop - this attribute maintain it’s type {% for p in periods %} BECOMES STRINGS accessed via .0.attr {{ p.productions.0.time }} str {{ p.productions.0.ammount }} str MANTAIN TYPES accessed in a loop {% for pp in p.productions %} {{ pp.ammount }} timedelta {{ pp.time }} decimal {% endfor %}{% endfor %} I want somehow to access attributes of first object in queryset with it’s original type -
How to send an email to email@somedomain.com in react frontend when update db column value (django+react+Mysql)
export class Employee extends Component{ constructor(props){ super(props); this.state={ employees:[], modalTitle:"", EmployeeId:0, EmployeeName:"", EmployeeEmail:"", Department:"", DateOfJoining:"", } } refreshList(){ fetch(variables.API_URL+'employee') .then(response=>response.json()) .then(data=>{ this.setState({employees:data}); }); } componentDidMount(){ this.refreshList(); } changeEmployeeName =(e)=>{ this.setState({EmployeeName:e.target.value}); } changeDepartment =(e)=>{ this.setState({Department:e.target.value}); } changeDateOfJoining =(e)=>{ this.setState({DateOfJoining:e.target.value}); } updateClick(){ fetch(variables.API_URL+'employee',{ method:'PUT', headers:{ 'Accept':'application/json', 'Content-Type':'application/json' }, body:JSON.stringify({ EmployeeId:this.state.EmployeeId, EmployeeName:this.state.EmployeeName, EmployeeEmail:this.state.EmployeeEmail, Department:this.state.Department, DateOfJoining:this.state.DateOfJoining, }) }) .then(res=>res.json()) .then((result)=>{ alert(result); this.refreshList(); },(error)=>{ alert('Failed'); }) } render(){ const { employees, modalTitle, EmployeeId, EmployeeName, EmployeeEmail, Department, DateOfJoining, }=this.state; return( {EmployeeId!=0? <button type="button" className="btn btn-primary float-start" onClick={()=>this.updateClick()} >Update</button> :null} ) } } I can update employee details in the above "updateClick()" I am updating "Department" in front end and it is updating. how to trigger an automatic email to "EmployeeEmail" with updated Department value inside "updateClick()" can someone help here please.. I am learning full stack development -
TAG INPUT BOX DJANGO [closed]
How to implement tag input box in Django in which the options or items would only come from the specific table in database? -
cannot convert null to strftime in django
I'm trying to convert the time in 12 hours format where I have few rows with time as NULL. I'm passing it as dictionary. How could I leave that NULL rows and convert others rows with have time Here, what I have tried views.py def GetUserInProgress(userid): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetUserInProgress] @UserId=%s', (userid,)) result_set = cursor.fetchall() data =[] for i in range(len(result_set)): data.append({ 'TaskId':result_set[i][0], 'CreatedOn':result_set[i][13], 'CreatedBy':result_set[i][14], 'StartedOn':result_set[i][15], 'ClosedOn':result_set[i][16], 'Requester':result_set[i][17], 'StartedOnPST':result_set[i][31], 'ClosedOnPST':result_set[i][32], 'ClosedonPST_Final':result_set[i][33].strftime('%d-%m-%Y %I:%M %p'), }) return Response(data) -
How to handle star topology in the Django Rest Framework
I have a Django model like this: class A(models.Model): slug = models.CharField(max_length=20, primary_key=True, unique=True) dataA = models.IntegerField(null=True, blank=True) class B(models.Model): slug= models.OneToOneField(A, to_field="slug", db_column="slug", on_delete=models.CASCADE, related_name='b') dataB = models.IntegerField(null=True, blank=True) class C(models.Model): ticker = models.OneToOneField(A, to_field="slug", db_column="slug", on_delete=models.CASCADE, related_name='c') dataC = models.IntegerField(null=True, blank=True) class D(models.Model): ticker = models.ForeignKey(A, to_field="slug", db_column="slug", on_delete=models.CASCADE, related_name='d') dataD = models.IntegerField(null=True, blank=True) It's like a star topology. B, C is making an OneToOne relation with A and D is making an OneToMany relation with A. So, I want a Django rest framework to get API in which when the user access the API with the slug field in A. It would retrieve the B, C, D data too in one call. I have written the code like this. class DSerializer(serializers.ModelSerializer): slug = serializers.PrimaryKeyRelatedField(queryset=D.objects.all()) class Meta: model = D fields = ['dataD', 'slug'] class ASerializers(serializers.ModelSerializer): d = DSerializer(many=True, read_only=True) class Meta: model = A fields = ['slug','dataA', 'd'] @api_view(['GET']) def api(request, slug): if request.method == 'GET': try: a= A.objects.prefetch_related('d').get(slug=slug) except A.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializers = ASerializers(a) return Response(serializers.data) My output returns like the below JSON format. { "slug": "term", "dataA": 1, "d": [{ "dataD": 2, "slug": "term" }, { "dataD": 3, "slug": "term" }, { "dataD": 4, … -
ManytoMany query and template rendering from one model to another
I'm new to Django. I had two different questions. I can't query between one of my model and another model (ManyToMany). I can do this with the shell, but I couldn't handle it in the template. I cannot assign a default value from one model to another model's field. For the first question; What I want to do is show values for multiple options. For this, I could make a query similar to this in the shell: room[0].room_type_id.all() But I can't do this in the template. On the other hand, when I want to show it with display, it returns empty. What I want to do here; returning the room types for each room or or accessing the room_cost of the RoomType class and displaying it in the template, repeated for each room type. {% for room in rooms %} <h3 class="card-title pricing-card-title"> {{room.room_type_id_display}} </h3> {% endfor %} My second question is; To set the value from the property of a different model as default in the other model field. That is, to assign the value returned from the total_price of the Booking model to the price field in the Payment model by default. I would appreciate it if anyone … -
PostgreSQL OLD not working in after update statement level trigger
It is working if I do select particular ID like this: BEGIN UPDATE course SET points = (SELECT COALESCE(SUM("lesson"."points"), 0) AS "sum_points" FROM "course" LEFT OUTER JOIN "lesson" ON ("course"."id" = "lesson"."course_id") WHERE "course"."id" = 7) WHERE "course"."id" = 7; RETURN NULL; END; But not working with OLD which is the updating instance. BEGIN UPDATE course SET points = (SELECT COALESCE(SUM("lesson"."points"), 0) AS "sum_points" FROM "course" LEFT OUTER JOIN "lesson" ON ("course"."id" = "lesson"."course_id") WHERE "course"."id" = OLD."course_id") WHERE "course"."id" = OLD."course_id"; RETURN NULL; END; I'm using django-pgtriggers -
According to doctors name (dropdown) and date selected ,change timeslot dropdown using AJAX in django
//This is my book_appoint.html <!DOCTYPE html> <html> <div class="wrapper"> <div class="register-page"> <div class="register-container"> <form id="appointment-form" role="form" method="post" enctype='multipart/form-data'> <!-- SECTION TITLE --> <div class="section-title wow fadeInUp" data-wow-delay="0.4s"> <h2>Book Appointment</h2> </div> {% csrf_token %} <input name="patient_name" value="{{request.user}}" hidden> <div class="wow fadeInUp" data-wow-delay="0.8s"> <div class="col-md-6 col-sm-6"> <label for="qualification">Doctor Name</label> {{ form.doctor_name }} </div> <div class="col-md-6 col-sm-6"> <label for="specialist"> Date</label> {{ form.date }} </div> <div class="col-md-6 col-sm-6"> <label for="location">Time slot </label> {{ form.time_slot }} // want to apply ajax to select available slot only </div> <div class="col-md-12 col-sm-12"> <label for="description"> Description</label> {{ form.description }} <br> <button type="submit" class="submitButton" id="cf-submit" name="submit">Submit Button</button> </div> </div> </form> </div> </div> </div> </html> //This is my view file: def book_appointment(request): if request.method == 'POST': form = BookAppointmentForm(request.POST or None, request.FILES or None) if form.is_valid(): patient_name = request.POST.get('patient_name') patient = form.save(commit=False) patient.patient_name = User.objects.get(username=patient_name) form.save() messages.success(request, 'appointment booked Successfully') return redirect(homepage) else: form = BookAppointmentForm() messages.error(request, 'Please Enter valid Request ') print(form) return render(request, 'book_appointment.html', {'form': form}) else: form = BookAppointmentForm() return render(request, 'book_appointment.html', {'form': form}) //Here is my models: class BookAppointment(models.Model): TIME_SLOT = ( (0, '09:00 - 10:00'), (1, '10:00 - 11:00'), (2, '11:00 - 12:00'), (3, '12:00 - 13:00'), (4, '13:00 - 14:00'), (5, '14:00 - 15:00'), …