Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django view in array
I have 2 tables (posts, upvoted) that I am working within and am looking to see if a post has been upvoted already and if it has, replace the upvote arrow with a filled arrow. In my view, I am already sending over the Upvote object to my template and am trying to check if the post.id exists within the upvoted table. I tried the code below but it didn't work. How would I do it? {% if post.id in upvote.post_id.all %} -
Upload multiple images to a post in Django View Error(Cannot resolve keyword 'post' into field.)
My Model : class Gallary (models.Model): ProgramTitle = models.CharField(max_length=200, blank = False) Thum = models.ImageField(upload_to='Gallary/Thumb/',default = "", blank = False, null=False) VideoLink = models.CharField(max_length=200, blank = True,default = "") updated_on = models.DateTimeField(auto_now = True) created_on = models.DateTimeField(auto_now_add =True) status = models.IntegerField(choices=STATUS, default = 1) total_views=models.IntegerField(default=0) class Meta: verbose_name = 'Add Gallary Content' verbose_name_plural = 'Add Gallary Content' #for compress images if Thum.blank == False : def save(self, *args, **kwargs): # call the compress function new_image = compress(self.Thum) # set self.image to new_image self.Thum = new_image # save super().save(*args, **kwargs) def __str__(self): return self.ProgramTitle class GallaryDetails (models.Model): Gallary = models.ForeignKey(Gallary, default = None, on_delete = models.CASCADE) G_Images = models.ImageField(upload_to='Gallary/Images/',default = "", blank = False, null=False) #for compress images if G_Images.blank == False : def save(self, *args, **kwargs): # call the compress function new_image = compress(self.G_Images) # set self.image to new_image self.G_Images = new_image # save super().save(*args, **kwargs) def __str__(self): return self.Gallary.ProgramTitle My View def gallery(request): gallary = Gallary.objects.all() context = { 'gallary': gallary.order_by('-created_on') } return render(request, 'gallery.html',context) def album_details(request, post_id): post = get_object_or_404(Gallary,pk=post_id) photos = GallaryDetails.objects.filter(post=post) context = { 'post':post, 'photos': photos } return render(request, 'album_details.html',context) Gallary View <div class="our_gallery pt-60 ptb-80"> <div class="container"> <div class="row"> {% for post in gallary … -
Jinja elif not working even though condition is true
The fourth elif statement is the one causing me the issue. I have swapped the third elif statement with the fourth and every time the fourth is in third place it works. {% block content%} {% load static %} <link rel="stylesheet" href="{% static 'css/home_page.css' %}"> <link rel="stylesheet" href="{% static 'css/home_w_d_cs.css' %}"> {% if first_hour_d == 'clear sky' and time_of_day == True %} <!-- day == True means day --> <div class="side-hour-icon"> <img src="{% static 'images/sunny-black.png' %}" alt="" width="55" height="50"> </div> {% elif first_hour_d == 'clear sky' and time_of_day == False %} <!-- day == False means night --> <div class="side-hour-icon"> <img src="{% static 'images/clear-night-black.png' %}" alt="" width="55" height="50"> </div> {% elif first_hour_d == 'overcast clouds' or 'broken clouds' %} <div class="side-hour-icon"> <img src="{% static 'images/cloudy2.png' %}" alt="" width="55" height="50"> </div> {% elif first_hour_d == 'few clouds' or 'scattered clouds' %} <div class="side-hour-icon"> <img src="{% static 'images/few-clouds-black.png' %}" alt="" width="55" height="50"> </div> {% endif %} {% endblock %} I want to have a few elif statements, maybe 10 or 12. Is this possible? -
Django update_or_create defaults with a query object
I'm using Django 3.2 and I'm trying to call update_or_create like in the snippet below: from django.db import models result = model.objects.update_or_create( field1="value1", field2="value2", defaults={ "field3": "value3", "field4": ~models.Q(field3="value3"), }, ) field4 is a boolean. The problem is the returning value in field4 after the method is called isn't a boolean, but a query object: result[0].field4 <Q: (NOT (AND: ('field3', 'value3')))> However if I refresh the object, the content is correct: result[0].refresh_from_db() result[0].field4 False I'm sure the field was updated because before I ran the snippet, there was an instance with the same values for field1 and field2 but with the opposite value in field4 (True). My question is: is there a way for update_or_create return a boolean value for field4 without querying the instance again from the DB? I checked StackOverflow before for similar questions, this was the closest one I found but it still doesn't answer my question. -
User Registration alsongside simple-JWT with DRF
I am creating a social media type app(twitter clone). I was using allauth for signup and signin which was working perfectly with endpoints /accounts/login and accounts/signup with their default view. But now I was implementing simple-JWT for authentication. I was following this blog post. The guy is using dj-rest-auth with JWT. Login and logout are mounted with endpoints /dj-rest-auth/login/ and dj-rest-auth/logout/ respectively. Now what about the registration? In the blog it is mentioned: Notice that this list includes allauth social accounts; this is actually so that the registration endpoint of dj-rest-auth can work. But I am unable to figure out the endpoint of the same. So I decided to create my own registration url with following codes: views.py class UserRegister(APIView): def post(self,request): serializer = UserSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response({"User":serializer.data}) return Response({"errors":serializer.errors}) serializers.py class UserSerializer(serializers.Serializer): email = serializers.EmailField(max_length=50, min_length=6) username = serializers.CharField(max_length=50, min_length=6) password = serializers.CharField(max_length=150, write_only=True) class Meta: model = User fields = ['fname','lname','email','username','password'] def validate(self, args): email = args.get('email', None) username = args.get('username', None) if User.objects.filter(email=email).exists(): raise serializers.ValidationError({"email":"email already exists"}) if User.objects.filter(username=username).exists(): raise serializers.ValidationError({"username":"username already exists"}) return super().validate(args) def create(self, validated_data): return User.objects.create_user(**validated_data) But on launching the respective endpoint I am getting a response: { "detail": … -
Deploying Django App Using Google Cloud Run - gcloud builds submit error
I've followed the tutorial for deploying Django on Cloud Run (https://codelabs.developers.google.com/codelabs/cloud-run-django), and I followed the exact instructions up to "Build your application image" on Step 7: "Configure, build and run migration steps". When running the command: gcloud builds submit --pack image=gcr.io/${PROJECT_ID}/myimage [builder] × python setup.py egg_info did not run successfully. [builder] │ exit code: 1 [builder] ╰─> [25 lines of output] [builder] /layers/google.python.runtime/python/lib/python3.11/site-packages/setuptools/config/setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. [builder] warnings.warn(msg, warning_class) [builder] running egg_info [builder] creating /tmp/pip-pip-egg-info-xoozdk2u/psycopg2_binary.egg-info [builder] writing /tmp/pip-pip-egg-info-xoozdk2u/psycopg2_binary.egg-info/PKG-INFO [builder] writing dependency_links to /tmp/pip-pip-egg-info-xoozdk2u/psycopg2_binary.egg-info/dependency_links.txt [builder] writing top-level names to /tmp/pip-pip-egg-info-xoozdk2u/psycopg2_binary.egg-info/top_level.txt [builder] writing manifest file '/tmp/pip-pip-egg-info-xoozdk2u/psycopg2_binary.egg-info/SOURCES.txt' [builder] [builder] Error: pg_config executable not found. [builder] [builder] pg_config is required to build psycopg2 from source. Please add the directory [builder] containing pg_config to the $PATH or specify the full executable path with the [builder] option: [builder] [builder] python setup.py build_ext --pg-config /path/to/pg_config build ... [builder] [builder] or with the pg_config option in 'setup.cfg'. [builder] [builder] If you prefer to avoid building psycopg2 from source, please install the PyPI [builder] 'psycopg2-binary' package instead. [builder] [builder] For further information please check the 'doc/src/install.rst' file (also at [builder] <https://www.psycopg.org/docs/install.html>). [builder] [builder] [end of output] [builder] [builder] note: This error originates from … -
test router in DRF
hello im trying to test a router and i cant seem to find the url this is inside test function def test_send(self): token1 = Token.objects.get(user=self.user1) response = self.client.post( reverse('send-create'), data=json.dumps({ "receiver": self.user2, "subject": "my first message", "msg": "hello this is my first" }), content_type='application/json', **{'HTTP_AUTHORIZATION': f'Bearer {token1}'} ) this is router router.register('send', views.SendMessagesView, basename='send_message') and this is the view class SendMessagesView(viewsets.ModelViewSet): serializer_class = SendMessageSerializer permission_classes = [permissions.IsAuthenticated] http_method_names = ['post'] def create(self, data): msg = Message.objects.create( sender=self.request.user, receiver=User.objects.get(id=data.data['receiver']), subject=data.data['subject'], msg=data.data['msg'], creation_date=datetime.date.today() ) msg.save() serializer = MessageSerializer(msg) return Response(serializer.data). the error i get is : django.urls.exceptions.NoReverseMatch: Reverse for 'send-create' not found. 'send-create' is not a valid view function or pattern name. please if anyone can help me undertand what am i doing wrong test router in django rest framework -
How do I prescroll an element in django
I have a scrollable element that I would like to be pre-scrolled by 320px on loading the page in my django calendar project. Can I achieve that without using javascript? -
Python backend and javascript front end
I am new to the full stack development and have a question on what frameworks I should use for my project. my project description: my projet recived a csv file from user and uses to make network using networkx and pyvis python libraries. Then we get the network data from pyvis and use vis.js javascript library to display the network to the user. there can be different views for the same dataset and if a user moves things in displayed graph the new layout is saved for them. My main problem is choosing a frame work that allows bidirectional data flow between python and js. can anyone give me some insights? I am thinking about django and flask but not sure how useful they are by themselves -
How Filter Specific Result
Here Is My Space Model Which Include Plantes Details enter image description here Here Is My Moon Model Class Which Include Moons Details and Forgein Key Of Space Model So I Can Set Moon According To Its Planet enter image description here 1st How Can I Filter Object In View So I can Get Moon According To Related Planet Example: Jupiter Is Moon Name Is Eurpo - Eart Moon 2nd- Every Planet Has Different Numbers Of Moon So I also Want To Every Moon Related to that planets enter image description here I Just Stuck In Filtertion How To Get Specific information From two Differnt Models -
How to filter multiple checkboxes in django to check greater value
views.py if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) check_box_status_new_records = request.POST.get("new_records", None) print(check_box_status_new_records) check_box_status_error_records = request.POST.get("error_records", None) print(check_box_status_error_records) drop_down_status = request.POST.get("field",None) print(drop_down_status) global get_records_by_date if (check_box_status_new_records is None) and (check_box_status_error_records is None): get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)) else: get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)).filter(new_records__gt=0,error_records__gt=0) print(get_records_by_date) home.html <form action="" method="post"> {% csrf_token %} <label for="from_date">From Date:</label> <input type="date" id="from_date" name="from_date"> <label for="to_date">To Date:</label> <input type="date" id="to_date" name="to_date"> <input type="submit">&nbsp <input type="checkbox" name="new_records" value="new_records" checked> <label for="new_records"> New Records</label> <input type="checkbox" name="error_records" value="error_records" checked> <label for="error_records"> Error Records</label><br><br> <label for="field">Choose your field:</label> <select name="field" id="field"> <option value="">--Please choose an option--</option> <option value="started">Started</option> <option value="completed">Completed</option> </select> </form> I need to filter both new_records and error_records greater than 0. But my filter function get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)).filter(new_records__gt=0,error_records__gt=0) is not working. Is there any solution to filter both check boxes -
How do I amend a form template in Django?
Im using a custom/extended ModelMultipleChoiceField and ModelChoiceIterator as per the answer to another question here https://stackoverflow.com/a/73660104/20600906 It works perfectly but Im trying to amend the template used to generate the groups to apply some custom styling - but after poking around everywhere I cant find anything to overwrite. I have gone through all the template files in '\venv\Lib\site-packages\django\forms\templates\django\forms' and cannot find anything relating to the behaviour Im seeing on screen. The 'groups' are wrapped in tags which is fine, but id like to find the file specifying this so I can overwrite with some bootstrap classes. I've traced back through the class inheritance and the first widget specifiying a template is this one: class Select(ChoiceWidget): input_type = "select" template_name = "django/forms/widgets/select.html" option_template_name = "django/forms/widgets/select_option.html" add_id_index = False checked_attribute = {"selected": True} option_inherits_attrs = False Checking these files doesn't help as they don't appear to be the ones in use. Not sure where i'm going wrong? -
Displaying user orders in user's profile Django
I'm new in Python and hope that someone can help me. I realise that this is probably not a unique question, but please be sympathetic. I'm working on web-application (it's a bookstore). I make a cart and the proccess of forming an order. Now I'm trying to make a usr profile but unfortunately, I don't know how to display all user orders and make it possible to cahnge orders (change quantity of books for exmpl.) and how to make changable user profile information. I realised the following logic: User creates the cart and then create the order. After order creation cart also is in database. To summarise the above, main questions are: How to add all information from user cart (that was formed into the order) to user's profile? How to make user's data and order's/cart's data possible to change in the user's profile? How to display several user's orders in separate rows in HTML table (cause in my template all orders are in one row)? Cart models: User = get_user_model() class Cart(models.Model): customer = models.ForeignKey( User, null=True, blank=True, related_name="Customer", verbose_name="Customer", on_delete=models.PROTECT ) @property def total_price_cart(self): goods = self.goods.all() total_price_cart = 0 for good in goods: total_price_cart += good.total_price return … -
create users before running tests DRF
i want to run django tests, but i want to create some users before i run the test and the users' username will be attribute of the class and can be shared in all tests somthing like this: class DoSomeTests(TestCase): def setup_createusers(self): self.usr1 = create_user1() self.usr2 = create_user1() self.usr3 = create_user1() def test_number_one(self): use self.user1/2/3 def test_number_two(self): use self.user1/2/3 def test_number_three(self): use self.user1/2/3 how can i do it becuase every time i tried the test dont recognize the self's attributes ive tried use setupclass and setUp but nothing happend cretae users before running tests -
Deal with multiple forms from the same Model in Django
I have a template page where I can create multiple jobs at the same time. They all use the same Form, and when I submit the form, I receive POST data on the view like this: <QueryDict: {'csrfmiddlewaretoken': ['(token)'], 'name': ['name1', 'name2', 'name3'], 'min': ['1', '2', '3'], 'max': ['10', '20', '30'], 'color': ['green', 'blue', 'red']}> In the view, when I do form = JobForm(request.POST), I get the following clean data {'name': 'name3', 'min': 3, 'max': 30, 'color': 'red'}. I have seen this solution, but I don't know how many Jobs will be created at the same time so I can't create different prefixes on the view, so I only send the form to the template like this form = JobForm(). How can I check if all the submitted data is valid and create all the objects in a single page submission? -
wget Python package downloads/saves XML without issue, but not text or html files
Have been using this basic code to download and store updated sitemaps from a hosting/crawling service, and it works fine for all the XML files. However, the text and HTML files appear to be in the wrong encoding, but when I force them all to a single encoding (UTF-8) there is no change and the files are still unreadable (screenshots attached). No matter which encoding is used, the TXT and HTML files are unreadable, but the XML files are fine. I'm using Python 3.10, Django 3.0.9, and the latest wget python package available (3.2) on Windows 11. I've also tried using urllib and other packages with the same results. The code: sitemaps = ["https://.../sitemap.xml", "https://.../sitemap_images.xml", "https://.../sitemap_video.xml", "https://.../sitemap_mobile.xml", "https://.../sitemap.html", "https://.../urllist.txt", "https://.../ror.xml"] def download_and_save(url): save_dir = settings.STATICFILES_DIRS[0] filename = url.split("/")[-1] full_path = os.path.join(save_dir, filename) if os.path.exists(full_path): os.remove(full_path) wget.download(url, full_path) for url in sitemaps: download_and_save(url) For all of the XML files, I get this (which is the correct result): For the urllist.txt and sitemap.html files, however, this is the result: I'm not sure why the XML files save fine, but the encoding is messed up for text (.txt) and html files only. -
Consume only one tasks from same queue at a time with concurrency>1
In other words concurrency with priority across multiple queues not with in same queue I created queue for every user but I want worker to prioiritize concurrency across so that every one get a chance. -
How to update the data on the page without reloading. Python - Django
I am a beginner Python developer. I need to update several values on the page regularly with a frequency of 1 second. I understand that I need to use Ajax, but I have no idea how to do it. Help write an AJAX script that calls a specific method in the view I have written view class MovingAverage(TemplateView): template_name = 'moving_average/average.html' def get(self, request, *args, **kwargs): return render(request, 'moving_average/average.html') def post(self, request, *args, **kwargs): self.symbol = request.POST.get('symbol') self.interval = request.POST.get('interval') self.periods = int(request.POST.get('periods')) if request.POST.get('periods') != '' else 0 self.quantity = float(request.POST.get('quantity')) if request.POST.get('quantity') != '' else 0 self.delta = float(request.POST.get('delta').strip('%')) / 100 self.button() return render(request, 'moving_average/average.html') -
Implementing FastApi-cache in a Django python project with docker
Currently trying to cache some expensive database queries in a Django project. This is the code as it currently exists, Im having trouble verifying whats going wrong. Currently getting an error that reads redis.exceptions.ConnectionError: Error -2 connecting to redis:6379. -2. So after some searching it appears im missing a 'redis-server', but after adding it to requirements.py am met with this error: ERROR: No matching distribution found for redis-server==5.0.7 Ive also tried the other version i see listed, 6.0rc2, with no success below is the full code im trying to run up: import logging from django.core.exceptions import ObjectDoesNotExist from fastapi import Depends, FastAPI from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBackend from fastapi_cache.decorator import cache from redis import asyncio as aioredis LOGGER = get_logger_with_context(logging.getLogger(__name__)) @app.on_event("startup") async def on_startup() -> None: redis = aioredis.from_url("redis://redis", encoding="utf8", decode_responses=True, db=1) FastAPICache.init(RedisBackend(redis), prefix="api-cache") LOGGER.info("API has started.") @app.on_event("shutdown") async def on_shutdown() -> None: LOGGER.info("API has shutdown.") @app.get("/health", include_in_schema=False) def healthcheck() -> dict: """Lightweight healthcheck.""" return {"status": "OK"} @router.get( "/companies/attributes", summary="Retrieve company attributes, including leadership attributes, perks and benefits, and industry", response_model=CompanyAttributesOut, status_code=200, ) @cache(expire=60, coder=JsonCoder) def get_company_attributes() -> CompanyAttributesOut: """Retrieve the company attributes.""" with async_safe(): return CompanyAttributesOut.from_database_model() -
django Selenium error SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0x96 in position 0: invalid start byte
I want to load an extension in seleniuum, but it keep on giving me the error message SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0x96 in position 0: invalid start byte I have tried to install the extension directly on the browser and it installed. What could be wrong. This is what I have done chromeExtension = os.path.join(settings.SELENIUM_LOCATION,'capture_image_extension') chromiumOptions = [ '--other-arguments=all_this_worked_before_extension', '–-load-extension='+chromeExtensionStr ] I could not event compile the program. it was giving me the error message please what should i do. i have put all the files in a directory, i have used a .zip file and also a .crx file -
Djnago how to split users and customres
In my project (small online shop) I need to split registration for users and customers. So the information what I found when somebody registered in django then his account stored in one table, in this table I can see admin user and staff and another registered accounts, and I can sse them all in admin on Users page. But I do not want ot put all accounts in one "basket". I need split them fro different tables. For example superuser can create in admin area a new user (content manager) and provide him access/permission to manage admin area (create product etc.) - this users and super user will be on default User page. On the page Customers will be displaying only users who registered for example via https://mysite/account/register page, after registration this customer account I can see in Customers page in the admin area but not in Users page. And this customer can login to his account for example via https://mysite/account/login Is this possible? -
How to write anonymous ID during track call in segment in django? [closed]
I am using django. I can see these calls for analytics.io but none of it works for django. I am putting the first argument as a string but receiving anonymousId:null in the segment. -
Trying to override template in change_list django admin
I am trying to override the temaplate for change_list for a specific model. This is my dir apps and a directory in project root: Project root apps/ ├── FreedomTools │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── static │ ├── templates │ │ ├── activate_badge.html │ │ └── identiv_access.html │ ├── tests.py │ ├── urls.py │ └── views.py templates/ ├── __init__.py ├── admin │ └── FreedomTools │ └── identivaccess │ └── change_list.html I have changed TEMPLATES in settings.py : 'DIRS': [(os.path.join(BASE_DIR, 'templates')), ], so the template above overrides the django admin default template. I have a function in views.py which returns render that overriden template, and a dictionary with some information gathered from other functions: def identiv_access(request): identiv_acccess_form = UserIdentivAccess() user_groups_not_in_freedom_group_list = [] user_groups_in_freedom_group_list = [] submitted = False if request.method == "POST": if "search" in request.POST: **# next is a form made from the model with only 1 field:** identiv_acccess_form = UserIdentivAccess(request.POST) if identiv_acccess_form.is_valid(): user_request = identiv_acccess_form.cleaned_data['user'] user_groups = return_user_access_groups(user_request, "Freedom") for group in return_freedom_groups(): if group in user_groups: user_groups_in_freedom_group_list.append(group) else: user_groups_not_in_freedom_group_list.append(group) if "save" in request.POST: identiv_acccess_form = UserIdentivAccess(request.POST) if identiv_acccess_form.is_valid(): user_request = identiv_acccess_form.cleaned_data['user'] groups_request = request.POST.getlist('checked') … -
Django HttpResponseRedirect isn't working correctly
I'm trying to redirect using the HttpResponseRedirect and, in a tutorial on YT, the teacher typed the url like: return HttpResponseRedirect("challenge/" + month_list[month-1]) so the url "http://localhost:8000/challenge/1" changed to "http://localhost:8000/challenge/january". When I try to do it my url change to "http://localhost:8000/challenge/challenge/january", repeating again the "challenge". views.py from django.shortcuts import render from django.http import HttpResponse,HttpResponseNotFound,HttpResponseRedirect from django.urls import reverse # Create your views here. months_challenges = { "january" : "desafio janeiro", "february" : "desafio february", "march" : "desafio march", "april" : "desafio april", "may" : "desafio may", "june" : "desafio june", "july" : "desafio july", "august" : "desafio august", "september" : "desafio september", "october" : "desafio october", "november" : "desafio november", "december" : "desafio december", } def month_challenge_num(request,month): month_list = list(months_challenges.keys()) if(month>len(month_list)): return HttpResponseNotFound("Não achamos") else: return HttpResponseRedirect("challenge/" + month_list[month-1]) def month_challenge(request,month): try: return HttpResponse(months_challenges[month]) except: return HttpResponseNotFound("Não achamos str") urls.py of the app from django.urls import path from . import views urlpatterns = [ path("<int:month>",views.month_challenge_num), path("<str:month>",views.month_challenge) ] urls.py of the project """monthly_challenges URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. … -
NoReverseMatch at /doctorAcc
django.urls.exceptions.NoReverseMatch: Reverse for 'doctorAcc' with arguments '({' '})' not found. 1 pattern(s) tried: ['doctorAcc\Z'] I get this error while redirect and render in django. I wanna redirect for stopping resubmit form. views.py def doctorAcc(request): if request.method == "POST": docname = request.POST.get("doctor_name") department = request.POST.get("department") location = request.POST.get("location") working_H = request.POST.get("working_H") brife = request.POST.get("brife") clinicloc = request.POST.get("clinicloc") nw_pat_fee = request.POST.get("nw_pat_fee") ret_pat_fee = request.POST.get("ret_pat_fee") repo_fee = request.POST.get("repo_fee") lag_spoken = request.POST.get("lag_spoken") sunday_mor = request.POST.get("sunday_mor") sunday_ev = request.POST.get("sunday_ev") monday_mor = request.POST.get("monday_mor") monday_ev = request.POST.get("monday_ev") tuesday_mor = request.POST.get("tuesday_mor") tuesday_ev = request.POST.get("tuesday_ev") wedday_mor = request.POST.get("wedday_mor") wedday_ev = request.POST.get("wedday_ev") thursday_mor = request.POST.get("thursday_mor") thursday_ev = request.POST.get("thursday_ev") frday_mor = request.POST.get("frday_mor") frday_ev = request.POST.get("frday_ev") satday_mor = request.POST.get("satday_mor") satday_ev = request.POST.get("satday_ev") image=request.POST.get("image") obj = NearBy_Doctor(doctor_name = docname, department = department, location=location,working_H = working_H,brife = brife,clinicloc = clinicloc,nw_pat_fee = nw_pat_fee ,ret_pat_fee = ret_pat_fee,repo_fee = repo_fee,lag_spoken = lag_spoken,sunday_mor = sunday_mor,sunday_ev = sunday_ev ,monday_mor = monday_mor,monday_ev = monday_ev,tuesday_mor = tuesday_mor,tuesday_ev = tuesday_ev,wedday_mor = wedday_mor ,wedday_ev = wedday_ev,thursday_mor = thursday_mor,thursday_ev = thursday_ev,frday_mor = frday_mor ,frday_ev = frday_ev,satday_mor = satday_mor,satday_ev = satday_ev,image = image) obj.save() return redirect ('doctorAcc', {'docname':docname,'department':department,'location':location,'working_H':working_H,'brife':brife,'clinicloc':clinicloc ,'nw_pat_fee':nw_pat_fee,'ret_pat_fee':ret_pat_fee,'repo_fee':repo_fee,'lag_spoken':lag_spoken,'sunday_mor':sunday_mor ,'monday_mor':monday_mor,'monday_mor':monday_mor,'monday_ev':monday_ev,'tuesday_mor':tuesday_mor,'tuesday_ev':tuesday_ev,'wedday_mor':wedday_mor ,'wedday_ev':wedday_ev,'thursday_mor':thursday_mor,'thursday_ev':thursday_ev,'frday_mor':frday_mor,'frday_ev':frday_ev,'satday_mor':satday_mor,'satday_ev':satday_ev,'image':image} ) if request.method =="GET": docname = NearBy_Doctor.doctor_name # docname = request.GET.get("doctor_name") department = request.GET.get("department") location = request.GET.get("location") working_H = request.GET.get("working_H") brife = request.GET.get("brife") clinicloc …