Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass value from views to non-editable field django pyhton
i want to auto insert user to the follwing model: class Moduls(models.Model): module_name = models.CharField(max_length=255) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='created_by', blank=False, null=False , on_delete=models.CASCADE, editable = False) i have 2 cases : 1- in django admin and i solve this case by the following * add editable = False to created by field * in admin.py i used the follwoing: def save_model(self, request, obj, form, change): obj.created_by = request.user super().save_model(request, obj, form, change) but i face the problem when i try to use forms.py i can't pass user from user views.py and if i want to add created_by field to my form i have this error: 'created_by' cannot be specified for Moduls model form as it is a non-editable field -
JavaScript,Jquery, Django
is there anyway to update data in a JS file dynamically in django framework. i have a file where i want to update data in it or there is an alternative way of doing that without a js file. the data is in chart js. -
Django rest framework: added fields from one serializer do not get stored
I have two serializers IngredientSerializer and RecipeSerializer. I am trying to include the fields of the IngredientSerializer in the RecipeSerializers fields by just calling the required fields in RecipeSerializer: class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = ( 'ingredient', 'quantity', 'size', 'unit' ) class RecipeSerializer(serializers.ModelSerializer): ingredient = IngredientSerializer(many=True, read_only=True) quantity = IngredientSerializer(many=True, read_only=True) size = IngredientSerializer(read_only=True) unit = IngredientSerializer(read_only=True) class Meta: model = Recipe fields = ( 'cooking_time', 'degrees', 'description', 'difficulty', 'id', 'images', 'ingredient', 'mode', 'name', 'portions', 'preparation_time', 'quantity', 'size', 'total_time', 'type', 'unit' ) How ever I do not get any errors but the input values are not store in the DB. Any help is highly appreciated. -
How do you test a django webapplication's front end when it's heavy JS?
This is more of a guidance thing. Here's the general breakdown of my app: It has a backend with all the models It has an app for the API routing and the serializers/viewsets It has a frontend that takes care of the main routing (index, contact us, content, etc.) and serves the templates and the static components Part of the static components are mustache-js templates. When the user loads the page the client performs some ajax requests to the API and pulls in data, it then takes care of populating components. I currently have tests for Backend models API behavior and methods Frontend paths actually loading But how do I test the parts where it's mostly JS dependent? I've been using selenium to do this. Is this the right approach? It does seem awfully hacky. -
How to manipulate a CSV file without saving it using DJANGO
I want to add an option for uploading a CSV file and updating the database in my DJANGO project. Before updating the database I want to show the data of the file to the user. How can I do it precisely without saving the file? -
django.db.utils.OperationalError: (3780, "Referencing column '...' and referenced column '...' in foreign key constraint '...' are incompatible.")
I get this error message when I try to create a new table in my database which I in terms of values have already added to the database. The error message I get is this: Operations to perform: Apply all migrations: main Running migrations: Applying main.0113_user_accumulated_countries...Traceback (most recent call last): File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/MySQLdb/connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (3780, "Referencing column 'iso_code_id' and referenced column 'iso_code' in foreign key constraint 'main_user_accumulate_iso_code_id_65d73d54_fk_main_hs_c' are incompatible.") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in … -
Django: Invalid literal error when trying to use a basic ranking algorithm based on views
hey guys I am following a tutorial and they have this view for ranking images based on the number of views. I had followed it almost the same way, but I am getting an error like this. invalid literal for int() with base 10: b'nature' this is my code: def image_ranking(request): # get image ranking dictionary image_ranking = r.zrange('image_ranking', 0, -1, desc=True)[:10] image_ranking_ids = [int(id) for id in image_ranking] # get most viewed images most_viewed = list(Image.objects.filter(id__in=image_ranking_ids)) most_viewed.sort(key=lambda x: image_ranking_ids.index(x.id)) context = {'most_viewed':most_viewed} return render(request, 'images/trial.html', context) I have these 2 lines along with my detail view, where I use only the slug and not the id. # increment total image views by 1 image_views = r.incr(f'image:{image.slug}:views') r.zincrby('image_ranking', 1, image.slug) #to store views ranking How to resolve the error and have the ability to use id and slug depending on the application and not just the slug. -
Django form for writing blogs
As a beginner in Django I know how to create basic website for blogs, using a Django model of fields title and content... that's it. But now I want to create a real dynamic blog form, which can have multiple sub headings, code blocks, text blocks, and images. Or basically a blog form which can have random number of these kinds of blocks (field like code, text, image). And the user can add as many number of these blocks as required. Also these blocks (or fields) which would be the part of the blog post, should be saved in the dataset in the same order as the user created. How can I achieve this? Thanks for your time. -
Pictures are not getting updated in database even after submitting using DJANGO Model Forms
I intend to make a user profile model with profile picture in django. Everything works fine but I can't update the profile picture of the user. The form is being displayed on the website but on clicking submit, no changes are visible in the database and the image is also not getting uploaded. Below is my code for the form in HTML. <form method="POST" action="{% url 'profile' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <br><br> <div class="mb-3"><button class="btn btn-primary btn-sm" name="_picture" type="submit">Change Photo</button></div> </form> Below is the code models.py, for creating user profile model. class UserProfileInfo(models.Model): # Create relationship (don't inherit from User!) user = models.OneToOneField(User, on_delete=models.CASCADE) isInstructor = models.BooleanField(default=False) department = models.ForeignKey(Department,on_delete=models.CASCADE) role = models.ManyToManyField(Role) profile_picture = models.FileField(upload_to='static/profile_pic/'+str(time.time()),default='d.jpeg') address = models.TextField(max_length=256) city = models.TextF class UpdateProfilePic(ModelForm): class Meta: model = UserProfileInfo fields = ['profile_picture'] Below is the code for forms.py @login_required def profile(request): current_user_profile = UserProfileInfo.objects.get(user=request.user) current_user = request.user form = UpdateProfilePic(instance=current_user_profile) context = {'current_user':current_user,'current_user_profile':current_user_profile,'form':form} if request.method=='POST': if '_user' in request.POST: temp_user = request.user temp_user.username = request.POST.get('username') temp_user.e Help me with the code, please! -
Django list all projects [duplicate]
I have a directory with multiple projects. How can I list all the Django projects in a directory with a command possibly like django-admin? -
Append JWT as the "x-my-jwt" header to the upstream post request
Go a specific solution looking like this In Django as as you can see from my previous effort, got a specific endpoint #urls.py path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain'), #views.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer When I POST with an existing user like I get a response where it's possible to see an access token similar to this eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTE0MTk4LCJqdGkiOiJhZDZmNzZhZjFmOGU0ZWJlOGI2Y2Y5YjQ4MGQzZjY2MiIsInVzZXJfaWQiOjExLCJpYXQiOjE1OTA5MTc0OTgsInVzZXIiOiJ0aWFnbyIsImRhdGUiOiIyMDIwLTA1LTMxIn0.-5U9P-WWmhlOenzCvc6b7_71Tz17LyNxe_DOMwwqH4RqrNsilVukEcZWFRGupLHRZjIvPya2QJGpiju9ujzQuw How can I append the JWT as the "x-my-jwt" header to the upstream POST request? -
Deserializing array from ajax get()
I am trying to send two arrays with ajax: var pressIdList = []; var imprintArray = []; function getPressList(){ for (i = 0; i < pressList.length; i++) { pressIdList.push(parseInt(pressList[i].getAttribute("press"))); var pr = pressList[i] var prid = pr.getAttribute("press"); var prx = pr.getAttribute("x"); var pry = pr.getAttribute("y"); var imprint = { press_id : prid, x : prx, y : pry, }; imprintArray.push(imprint); }; }; $.ajax({ method: "GET", url: endpoint, data: { "pressIdList" : pressIdList, "imprintArray" : imprintArray, }, success: function(data){ console.log(data) } }); request.GET looks like this: <QueryDict: {'pressIdList[]': ['42', '43', '44', '129', '71'], 'imprintArray[0][press_id]': ['42'], 'imprintArray[0][x]': ['2.3069764e-07'], 'imprintArray[0][y]': ['-4.4408921e-16'], 'imprintArray[0][width]': ['13.229166'], 'imprintArray[0][height]': ['13.229166'], 'imprintArray[1][press_id]': ['43'], 'imprintArray[1][x]': ['18.52083'], 'imprintArray[1][y]': ['-7.1525574e-07'], 'imprintArray[1][width]': ['13.229167'], 'imprintArray[1][height]': ['13.229167']} So i can get first array out of it with request.GET.getlist('pressIdList[]'). But how do i get the second one out. And why isn't it wrapped inside imprintArray[]:[] if i declared it as array[]? -
psycopg2 not detected by postgres django
I am using PyCharm and using Python 3.8 - 64 bit and Django 2.2. pip install psycopg2 successfully installed psycopg2-2.8.5. My database settings are as follows: settings.py, DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'my-database', 'USER': 'my-user', 'PASSWORD': 'my-password', 'HOST': 'localhost', 'PORT': '', } } my-user is the user that I am using and my-password is my password. However, python manage.py makemigrations causes a few errors as follows: Traceback (most recent call last): File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 20, in <module> import psycopg2 as Database File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
Django channels load previous messages
I am in the process of building a simple chat application and have already managed to make a functioning chat that stores sent messages in a model. However, I am struggling to retrieve previous messages. consumers.py def old_messages(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] room = ChatRoom.objects.get(room_name=self.room_name) messages = ChatMessage.objects.filter(room=room) content = { 'command': 'old' } return content room.html chatSocket.onopen = function(e) { console.log("open",e) old_messages() }; function old_messages() { chatSocket.send(JSON.stringify({ 'command': 'old_messages' })); }; Whenever I call old_messages() I get the error message = text_data_json['message'] KeyError: 'message' which refers to this chunk of code def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] -
list indices must be integers or slices, not str Django
I m getting this error. I am new in django. I am trying so send mail with django. Tracke Back : response = self.process_exception_by_middleware(e, request) File "/home/bari/Desktop/email_send/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/bari/Desktop/email_send/Simple_Email_Send_Project/email_app/views.py", line 36, in send_mail message_body = form.changed_data["message_body"] TypeError: list indices must be integers or slices, not str [05/Jun/2020 17:55:22] "POST / HTTP/1.1" 500 69463 my views.py def send_mail(request): form = SendMailForm(request.POST) template = 'send_mail.html' if form.is_valid(): subject = form.cleaned_data["subject"] message_body = form.changed_data["message_body"] email_address = form.cleaned_data["email_address"] try: mail = EmailMessage(subject, message_body, settings.EMAIL_HOST_USER, [email_address]) mail.send() return render(request, template, {'email_form': form, 'error_message': 'Sent mail to {}'.format(email_address)}) except: return render(request, template, {'email_form': form, 'error_message': 'Email Send failed. Please try again later'}) How can I solve this ??? help will be highly appreciated... -
Multiple levels of lookups in a Django queryset
With these models: class Work(models.Model): creator = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name = 'creator') class dateEvent(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) class Event(models.Model): repertoire = models.ManyToManyField(Work, blank=True) how can I get the dateEvents in whose repertoire feature works by a specific creator? dateEvent.objects.filter(event__repertoire__creator=1) returns an empty queryset. What am I doing wrong? -
nested annotation with OuterRef not working
I want to annotate a field to an annotated field of a parent Model. My code : user_enrolments = UserEnrolment.objects.filter( enrolment__enrollable__id__in=course_ids_taught_by_teacher).annotate( not_graded_attempt=Exists( AssignmentModuleProgress.objects .annotate(user_enrolment=OuterRef('id')) .filter(user_enrolment__id=OuterRef('id'), module_progress__module=instance, score=None) )) This particular querycall is made in a serializer method field . Im annotating a field not_graded_Attempt as a boolean field. For this im checking Exists of AssignmentModulePRogress. I want to query this table with the current user_enrolment in annotation , so i want to annotate the id of the current user enrolment in the ASsignmentModuleProgress queryset since its not directly preset in the Model. For this im using OuterRef . Im getting error as : AttributeError: 'ResolvedOuterRef' object has no attribute 'get_lookup' -
Open image file, save it as a string and convert it to base64
I am doing a Django project that needs to receive an image and store it into the database as a TextField. To accomplish that I am doing something similar to this: In my models.py: class Template(models.Model): image = models.TextField(null=True, blank=True) The equivalent code is: with open('logo.png', 'wb') as file: image = str(file.read()) Template.objects.create(id=1, image=image) Later, when I need to get back the file and convert it to base64 to insert in an HTML file, I am doing the following: import base64 from django.template import Template as DjangoTemplate from django.template import Context from weasyprint import HTML from .models import Template template = Template.objects.get(id=1) data = {'logo': base64.b64encode(str.encode(template.image)).decode('utf-8')} html_template = DjangoTemplate(template.html_code) html_content = html_template.render(Context(data))) file = open('my_file.pdf', 'wb') file.write(HTML(string=html_content, encoding='utf8').write_pdf()) file.close() But the problem is that the image is not showing in the pdf file. I've also tried to copy the decoded data and open it with another site, but I got a broken file. How can I fix my code to convert the image properly? -
how to run Django web app locally in Heroku
I am following this instruction to run my django project locally https://devcenter.heroku.com/articles/getting-started-with-python#run-the-app-locally When I type heroku local web, it says "[FAIL] No Procfile and no package.json file found in Current Directory - See run-foreman.js --help". However, my project is a Django/python app and I don't have package.json. But my project does have requirements.txt and Procfile in the root directory of my web application. What should I do? Thanks -
Django: Static Image Not Loading
I'm having issues getting an image to load on my Django web application. I have used the online documentation and tried peoples suggestions that I found on Stackoverflow but I am still not having any luck getting it to load. Here is what I have: Settings.py: STATIC_DIR = os.path.join(BASE_DIR,'static') INSTALLED_APPS = [ ... 'django.contrib.staticfiles' ] STATIC_URL = '/static/' STATIC_ROOT = [STATIC_DIR,] Urls.py: from django.urls import path from dir_app import views from django.conf import settings from django.conf.urls.static import static app_name = 'dir_app' urlpatterns=[ path('', views.tradesmen, name='tradesmen'), path('register', views.register,name='register'), path('user_login', views.user_login,name='user_login') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Index.html: (Gist) <!DOCTYPE html> {% load static %} <html> <head> </head> <body> <img src="{% static 'dir_app/tools.png' %}"> </body> </html> Here is where the image is stored: -
unable to download video created using moviepy in django
I am trying to import a video, add a watermark and then download the processed video in django using moviepy. The problem is that I am able to save the processed video to my computer by specifying an absolute path to the computer drive. However, I have not been able to download this processed video. I have tried researching on the internet. However, no luck till now. below is my code: views.py from django.shortcuts import render import numpy as np from .forms import UploadFileForm import tempfile import os from django.core.files.storage import default_storage from django.http import HttpResponse from django.core.files.storage import FileSystemStorage import sys import moviepy.editor as mp from .utils import CFEVideoConf, image_resize # Create your views here. def watermark(request): if request.method=="GET": form = UploadFileForm() return render(request, 'video_et.html', {'form':form}) else: if request.method=="POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): fs = FileSystemStorage(location='/media') x = bytes() #arr=cv2.VideoWriter() image = request.FILES['Watermark_Image'] video = request.FILES['Video_File'] print("Name of the Watermark Image: ", image.temporary_file_path()) print("Name of the Video: ", video.name) file_name1 = default_storage.save(video.name, video) file1 = default_storage.open(file_name1) file_url1 = default_storage.url(file_name1) print("file url= ",file_url1) url_now1 = "http://127.0.0.1:8000/"+file_url1 #image = request.FILES['Watermark_Image'].read() file_name2 = default_storage.save(image.name, image) file2 = default_storage.open(file_name2) file_url2 = default_storage.url(file_name2) print("file url= ",file_url2) url_now2 = "http://127.0.0.1:8000/"+file_url2 video = mp.VideoFileClip(url_now1) … -
Cart Item Update(add or Remove) throwing Type Error
TypeError("'%s' instance expected, got %r" % ( TypeError: 'CartItem' instance expected, got I am getting this error when I tried to add or remove the product obj from cartItem. Help me to overcome this error. CartUpdate view def cart_update(request): product_id = request.POST.get('product_id') print(product_id) try: qty = request.POST.get('qty') update_qty = True except: qty = None update_qty = False if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect("cart:cart") cart_obj, new_obj = Cart.objects.new_or_get(request) cart_item, created = CartItem.objects.get_or_create(cart=cart_obj, product=product_obj) if created: print("created") if update_qty and qty: if int(qty) == 0: cart_item.delete() else: cart_item.quantity = qty cart_item.save() else: pass if product_obj in cart_obj.cartitem_set.all(): cart_obj.cartitem_set.remove(product_obj) added = False else: cart_obj.cartitem_set.add(product_obj) added = True new_total = 0.0 for x in cart_obj.cartitem_set.all(): line_item = float(x.product.price) * x.quantity new_total += line_item request.session['cart_items'] = cart_obj.cartitem_set.count() cart_obj.subtotal = new_total if cart_obj.subtotal > 0: cart_obj.total = Decimal(cart_obj.subtotal) * Decimal(1.08) else : cart_obj.total = 0.00 cart_obj.save() -
Django Retrieve Data From Two Tables By Join
Hi I have two tables which are Employee(eid,eName,contact_num,e-mail,adress,salary) and Nurse(nurse_id,e_id) and the "e_id" column of Nurse model has foreign key on 'eid' of Employee model.I know how to filter by specific id, however all of them as list so that, I want to return all nurses from Employee table.You can find my models below. I am new to Django that is why any help or hint is appreciated. Thanks in advance. class Employee(models.Model): eid = models.IntegerField(primary_key=True) ename = models.CharField(db_column='eName', max_length=25) # Field name made lowercase. contact_num = models.DecimalField(max_digits=12, decimal_places=0) e_mail = models.CharField(max_length=30) adress = models.CharField(max_length=250, blank=True, null=True) salary = models.IntegerField() class Nurse(models.Model): nurse_id = models.IntegerField(primary_key=True) e = models.ForeignKey(Employee, models.DO_NOTHING) -
Django - Signal receiver not being called
I am working on a project utilizing Django All Auth. Inside the package, there is an account.signals file that contains a signal. email_confirmed = Signal(providing_args=["request", "email_address"]). It is used inside of a model for EmailConfirmationHMAC. ef confirm(self, request): if not self.email_address.verified: email_address = self.email_address get_adapter(request).confirm_email(request, email_address) signals.email_confirmed.send(sender=self.__class__, request=request, email_address=email_address) return email_address Adding a stack trace in here, I can see it is getting to this part. Inside my project, I have a python file receivers.py from allauth.account.signals import email_confirmed from django.dispatch import receiver @receiver(email_confirmed) def custom_logic(sender, **kwargs): a = 0 import ipdb; ipdb.set_trace() if a: pass However, whenever I confirm an email verification my custom logic debugger is not being hit, the email is being confirmed and the page is being re-routed. How do I ensure that my custom_logic function can be ran, after the signal is sent? signals.email_confirmed.send(sender=self.__class__, request=request, email_address=email_address) Thanks! -
Cannot assign SimpleLazyObject for CustomUser Model in django
hey everyone i created a blogpost so whenever i want to add a new blogpost i get this error ValueError at /pages/blog/new/ Cannot assign ">": "Blog.doctor" must be a "Doctor" instance. here is my views.py class BlogCreateView(CreateView): model = Blog fields = ['title', 'categories', 'overview'] def form_valid(self, form): form.instance.doctor = self.request.user return super().form_valid(form)