Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing live search using JavaScript and Django
I am trying to make a livesearch feature similar to when you conduct a google search. The search queries cafes in my database by name. I have gotten the functionality to the point where if the whole search value matches a cafe's name in the database it shows up for the user but would like to make it so the search value is checked letter by letter (assuming this is the best way to do a live search). Here is what I have: $("#search-box").keyup(function() { search() }); function search(){ let searchTerm = document.getElementById("search-box").value; $.ajax({ type: 'GET', url: '/electra/search/', data: { 'search_term':searchTerm }, success: function (data) { console.log(searchTerm); //refer to below function for the running of this loop $("#search-results").text(data); } }); }; views.py: def search(request): template_name = 'testingland/write_image.html' search_term = request.GET.get('search_term', None) print(search_term) qs = mapCafes.objects.filter(cafe_name = search_term) return JsonResponse([ [cafe.cafe_name, cafe.cafe_address] for cafe in qs ], safe=False) I have been playing around with the qs filter but can't figure out the best way to approach this. -
Crop/Mask WMS geoTIFF using Polygon
I am building a geospatial webapp with Django. If I have a polygon of class django.contrib.gis.geos.polygon.Polygon, how can I crop/mask a rectangular geoTIFF (gathered via a WMS request; dataset) to the shape of polygon? I've gone down the route of using rasterio to load the TIFF into memory (based on answers to this question), but being new to GIS within Python, I'm not sure this is the best approach to take for my crop/mask requirement. I'm happy to consider any and all solutions to this question. My call to the Corine landcover service, which returns a rectangular tiff: from owslib.wms import WebMapService from rasterio import MemoryFile wms = WebMapService('https://copernicus.discomap.eea.europa.eu/arcgis/services/Corine/CLC2018_WM/MapServer/WMSServer?request=GetCapabilities&service=WMS',version='1.1.1') bbox = (0.823974609375, 52.1081920974632, 1.1700439453125, 52.3202320760973) img = wms.getmap(layers=['12'], srs='EPSG:4326', size=(600, 500), bbox=bbox, format='image/geotiff') with MemoryFile(img) as memfile: with memfile.open() as dataset: print(dataset.profile) And a polygon used to crop/mask dataset: polygon = "SRID=4326;POLYGON ((0.9063720703125029 52.32023207609735, 0.8239746093749998 52.10819209746323, 1.170043945312496 52.14191683166823, 1.170043945312496 52.31351619974807, 0.9063720703125029 52.32023207609735)" Interestingly--and I'm not sure if this will cause cropping issues--when I call dataset.profile I see that there is no CRS information, despite defining srs in getmap and returning a geoTIFF: {'driver': 'PNG', 'dtype': 'uint8', 'nodata': None, 'width': 600, 'height': 500, 'count': 3, 'crs': None, 'transform': Affine(1.0, 0.0, 0.0, … -
On off toggle switch in django BooleanField
I am building a BlogApp and I am stuck on a Problem. What i am trying to do I am trying to change BooleanField into On and Off Toggle Switch. But Failed many times. models.py class Using(models.Model): user = models.ManyToManyField(User,default='') choice = models.BooleanField(default=True,blank=True) template.html <style> .switch { width: 50px; height: 17px; position: relative; display: inline-block; } .switch input { display: none; } .switch .slider { position: absolute; top: 0; bottom: 0; right: 0; left: 0; cursor: pointer; background-color: #e7ecf1; border-radius: 30px !important; border: 0; padding: 0; display: block; margin: 12px 10px; min-height: 11px; } .switch .slider:before { position: absolute; background-color: #aaa; height: 15px; width: 15px; content: ""; left: 0px; bottom: -2px; border-radius: 50%; transition: ease-in-out .5s; } .switch .slider:after { content: ""; color: white; display: block; position: absolute; transform: translate(-50%,-50%); top: 50%; left: 70%; transition: all .5s; font-size: 10px; font-family: Verdana,sans-serif; } .switch input:checked + .slider:after { transition: all .5s; left: 30%; content: ""; } .switch input:checked + .slider { background-color: #d3d6d9; } .switch input:checked + .slider:before { transform: translateX(15px); background-color: #26a2ac; } </style> <label class="switch"> <input type="checkbox" name="choice" id="id_choice" /> <div class="slider"></div> </label> What have i tried :- I tried many CSS and HTML methods BUT nothing worked for … -
One search module to search all models or seach from diiferent apps using Django REST Framework search filter.How to build it?
How to create a custom search filter module for different classes or serializers? I have the 1st Restuatant app with serializer and models and have another app called Books. Now I want a third app called search app to search all the fields from both the apps. Using Django Search filter - https://www.django-rest-framework.org/api-guide/filtering/ -
How to redirect to page where request came from in Django
I currently work on a project an i want to redirect to page where request is came form, when request method is GET. this is my views.py file Views.py def delete_patient(request): if request.method == 'POST': patient_id = request.POST['patient_id'] rem = Patient.objects.get(pk=patient_id) rem2 = CustomUser.objects.get(aid=patient_id, role=4) rem.delete() rem2.delete() return JsonResponse({'delete': 1}) else: // // so please tell me what I want to write in else part of view. -
Django M2M relationship retrieve dynamically using Search
I have implemented a form with M2M relationship and I was following this link. But the issue is that it loads all M2M relationship when the form renders (the M2M records are 150+). Can I have a search input, through which I can load only that M2M record which matches the search input. I am using Django 2.2. Any help would be much appreciated. -
How to find tags inside a class with Beautiful soup
I tried finding all the p tags inside the class content-inner and I don't want all the the p tags that talks about copyright(the last p tags outside the container class) to appears when filtering the p tags and my images shows an empty list or nothing comes out at all and therefore no image is been saved. main = requests.get('https://url_on_html.com/') beautify = BeautifulSoup(main.content,'html5lib') news = beautify.find_all('div', {'class','jeg_block_container'}) arti = [] for each in news: title = each.find('h3', {'class','jeg_post_title'}).text lnk = each.a.get('href') r = requests.get(lnk) soup = BeautifulSoup(r.text,'html5lib') content = [i.text.strip() for i in soup.find_all('p')] content = ' '.join(content) images = [i['src'] for i in soup.find_all('img')] arti.append({ 'Headline': title, 'Link': lnk, 'image': images, 'content': content }) this website have an html page like this <html><head><title>The simple's story</title></head> <body> <div class="content-inner "><div class="addtoany_share_save_cont"><p>He added: “The President king administration has embarked on railway construction</p> <p>Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p> <script></script> <p> we will not once in Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p> <p>the emergency of our matter is Once … -
DJANGO DEBUG=FALSE CUSTOM ERROR PAGE (ConnectionAbortedError)
Am trying to create a custom error handling page for production, when am working with local project I noticed am getting error 500 for most of the pages, except few page. ERROR I get is Exception occurred during processing of request from ('127.0.0.1', 52141) Traceback (most recent call last): File "E:\Dev\Python\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "E:\Dev\Python\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "E:\Dev\Python\lib\socketserver.py", line 720, in __init__ self.handle() File "e:\Dev\REPOS\2021 PROJECTS\cognizance_cms\.env\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "e:\Dev\REPOS\2021 PROJECTS\cognizance_cms\.env\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "E:\Dev\Python\lib\socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine I have followed all the steps properly and my custom 500 page loads, but the pages such as login which used to work gets error 500. If more input his needed let me know I'll add them. I have referred most of the issues raised, nothing seems to be conclusive. I tried: # settings.py DEBUG = False ALLOWED_HOSTS = ['*'] as a hotfix. I know it should not be done, still it didn't work -
I want a list of responses from the Chatterbot?
I am making a contextually based chatbot using ChatterBot library of Python and I have trained the chatbot using a ListTrainer where I passed the question and answer in the Trainer. The response is working fine, but now I need a response list of only questions which was can shown next to the user based on previous question asked by the user. I am using a JSON file which contains all the questions and the Answers. I am using Django as a backend for this project. I need to know do I need to create a logic adapter that can give me a list of questions based on the previous question or is there any other way. Like creating a second chatbot for the same. import json from django.views.generic.base import TemplateView from django.views.generic import View from django.shortcuts import render,redirect from django.http import JsonResponse from chatterbot import ChatBot from chatterbot.ext.django_chatterbot import settings from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer import requests class ChatterBotAppView(TemplateView): template_name = 'chatbot/chatbot.html' class ChatterBotApiView(View): """ Provide an API endpoint to interact with ChatterBot. """ """ Training Only Once """ chatterbot = ChatBot(**settings.CHATTERBOT) # # train(chatterbot) # trainer = ChatterBotCorpusTrainer(chatterbot) # trainer.train("chatterbot.corpus.english") # trainer.train("chatterbot.corpus.english.greetings") # trainer … -
NoReverseMatch Error trying to render from html to pdf
I am a newbie on Django and I am currently working on this result management project, I actually downloaded the whole project from a website but while trying to explore its functionalities especially while trying to render the result to show me a pdf file. I encountered an error reading NoReverseMatch at /dashboard/find-result/4/result/ Reverse for 'pdf' not found. 'pdf' is not a valid view function or pattern name. I actually intended to later tweak the models to conform with my own specifications to build the Result Management System but as seen I can not proceed. I need some help. Below are the codes. Views.py from django.http.response import Http404 from xhtml2pdf import pisa from django.template.loader import get_template from django.http import HttpResponse, HttpResponseServerError from io import BytesIO from django.shortcuts import redirect, render, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.views import PasswordChangeView from django.contrib.auth import update_session_auth_hash from django.contrib.auth import authenticate, login from django.views.generic import TemplateView, View from django.contrib.auth.models import User from results.models import DeclareResult from django.http import JsonResponse from django.urls import reverse_lazy from django.core import serializers import json from student_classes.models import StudentClass from results.models import DeclareResult from subjects.models import Subject from students.models import Student def index(request): if request.method == … -
Django send email reminder based on date how to?
I'm using a Windows OS and have a model where users selects a date. Based on the date I want to send an email to the user at an interval of 10, 25, 35, 50 days. I checked celery but now celery isn't supported on windows....can someone please help me with it..how to setup this functionality? -
Migrations files not created in dockerized Django
I've made changes to a model in a Django app and need to apply migrations to the database. I'm new to Docker, so this is giving me problems. I've been able to makemigrations and migrate, but migration files aren't being created, so I can't push my code to production because of the missing migration files. I think this is because I'm running makemigrations while connected to the Docker container. If I try to makemigrations without being connected to a running container, I get the following error: Traceback (most recent call last): File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 228, in ensure_connection self.connect() File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 205, in connect self.connection = self.get_new_connection(conn_params) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 172, in get_new_connection connection = Database.connect(**conn_params) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "postgres" to address: Temporary failure in name resolution The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 393, in execute_from_command_line utility.execute() File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 387, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/core/management/base.py", line 336, in run_from_argv self.execute(*args, **cmd_options) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/core/management/base.py", line 377, in execute output = self.handle(*args, **options) File "/home/andrew/Desktop/app/venv/lib/python3.6/site-packages/django/core/management/base.py", line 87, … -
DJANGO: TYPE ERROR: an integer is required
Please help! I am new to DJANGO and have little experience coding. I am working through a tutorial that involves building a shopping cart. When the user navigates to localhost/cart/cart the code should create a cart. I had a previous error which I fixed but the fix appears to have unmasked a different problem. ALthough the cart loads, no cart is created in admin portal. When attempting to create the cart from the DJANGO admin UI manually on clicking add the following error appears: Traceback error Internal Server Error: /admin/cart/cart/add/ Traceback (most recent call last): File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\contrib\admin\options.py", … -
Logo doesn't display using Django admin_interface
I have django-admin-interface installed in my django app. The problem is that when i try to upload a logo it says that all is okay but logo doesn't show. Logo uploaded correctly but not showing I want to change de default Django logo. Is there any way to accomplish this? -
Which is the best way to get user browsers to re-cache static files when using Django Tenants?
I am using Django Tenants and I am following the Django Tenant's file handling guide. According to this guide, I must use the following setting for managing static files in a multi-tenant environment: STATICFILES_STORAGE = "django_tenants.staticfiles.storage.TenantStaticFilesStorage" This works fine for me. However, I have the challenge of client browsers not re-caching my static files. I came across the Django's ManifestStaticFilesStorage class, which seems like a very good solution to manage changes to static files. However, very sadly, to use it, I must use this setting: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' This seems to be incompatible with the setting I need for handling static files in my multi tenant project. I believe an option would be to have nginx/gunicorn "tell" browsers to reload static files every time they load my site but I am worried that will make my site too slow... Would anyone know a way I can manage changes to my static files without having to manually change the name of my static files nor to avoid browser caching? Any ideas will be much appreciated. -
Django Inline Formset : render parent foreign key value in template
I have looked through many suggestions but can't get this to work. models.py class TestOrder(models.Model): test_item = models.ForeignKey(TestItem, on_delete=models.CASCADE, limit_choices_to={'is_active': True}) value = models.CharField(max_length=100,null=True, blank=True) report_id = models.ForeignKey('reports.Report', on_delete=models.CASCADE) class TestItem(models.Model): name = models.CharField(max_length=64) group = models.ForeignKey(Group, related_name="test_item_group", on_delete=models.CASCADE,limit_choices_to={'is_active': True}) category = models.ForeignKey(Category, related_name="test_item_category", on_delete=models.CASCADE,limit_choices_to={'is_active': True}) views.py def create_test_result(request, pk): context={} report = Report.objects.get(pk=pk) TestOrderInlineFormSet = inlineformset_factory(Report, TestOrder, fields=('test_item','value', ), extra=0) if request.method == "POST": .... context['formset']= TestOrderInlineFormSet(instance=report) return render(request, "tests-result/test_result.html", context) test_result.html {{ formset.management_form }} {% csrf_token %} {% for form in formset %} {{form.id}} <div class="form-row"> <div class="col-md-5"> <h6>{{form.test_item}}</h6> <small>{{form.test_item.group}}{{form.test_item.category}}</small> </div> <div class="col-md-2"> {{form.value}} </div> </div> {% endfor %} form.test_item gives me select option which is basically i want to be text but i think i can figure it out with widget attribute related to readonly. but I can't find out how i would display form.test_item.group, category or other values. -
Django - get all users permissions?
Hi could anybody help me to get all the permissions for every user in my system , not just for the current logged in, that's the most frequent answer I saw My objetive is that an administrator from the template can assign to each user their permission I don't upload my code because I'm using the basic user model, I think this is generic Please could anyone help me -
Update a Status Graphic in a Web UI
I am considering writing a web ui using python and django. Part of the ui would show status of network equipment, such as turning a power led graphic red when the device turns on, or a network port the color green when it's operational. The graphic representing the network device is a single vector graphic. How do I change the colors of these parts of the graphic? Do I define some areas of the vector graphic as geometric shapes that represent the smaller area of the overall vector image that needs to be updated? This is essentially the same way network device GUIs work for devices like a Netgear switch for example. When you're logged in and using the web ui, there is a small graphic of the switch at the top of the page replicating device status for LEDs and ports and such. Are these graphics made up of multiple smaller graphics somehow so that the program can directly target those elements to change their color/status? -
convert datetime format to 'a time ago' in django
I want to change datetime format to 'a time ago'. I know there are several ways to do that. My first question is what is the best way? (using script in html template, do that in views.py or etc) I write the code in views.py, but datetime doesn't show in template. This is the code for convert datetime: date = float(models.Catalogue.objects.get()) d_str = datetime.datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f') d_datetime = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S.%f') now = datetime.datetime.now() time_ago = timeago.format(d_datetime, now, 'fa_IR') views.py: class crawler(generic.ListView): paginate_by = 12 model = models.Catalogue template_name = 'index.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) for cat in models.Catalogue.objects.all(): if models.Catalogue.source == 'kilid': date = float(models.Catalogue.objects.get()) d_str = datetime.datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f') d_datetime = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S.%f') now = datetime.datetime.now() time_ago = timeago.format(d_datetime, now, 'fa_IR') context['time_ago'] = time_ago return context index.html: <div class="card-footer" dir="rtl" style="text-align:right"> <small id="datetime">{{ time_ago }}</small> </div> And then, if I want to write it in a script, how can I do that? -
Whats the reason for decorator returns None in Django?
I am doing a customer relation project in Django and it returns this 'ValueError at /login/' error. I can log into the admin panel and when I logout this error occurs. *ValueError at /login/ The view accounts.decorators.wrapper_func didn't return an HttpResponse object. It returned None instead.* decorators.py from django.http import HttpResponse from django.shortcuts import redirect,render def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') views.py from django.shortcuts import render,redirect from django.http import HttpResponse from django.forms import inlineformset_factory from accounts.models import * from .forms import orderForm,createUserForm from .filters import orderFilter from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from .decorators import unauthenticated_user,allowed_users,admin_only # Create your views here. @unauthenticated_user def registerPage(request): form = createUserForm() if request.method == 'POST': form = createUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='customer') user.groups.add(group) messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'form':form} return render(request, … -
Django : 'str' object has no attribute 'objects' in create_user
This is my registration code def registration_with_js_form(request): if request.method=='POST': first_name=request.POST.get('first_name') last_name=request.POST.get('last_name') mobile_number=request.POST.get('mobile_number') email=request.POST.get('email') password=request.POST.get('password') confirm_password=request.POST.get('confirm_password') checkbox=request.POST.get('checkbox') if checkbox==False: """Redirect with error message""" return redirect('home') if(password!=confirm_password): """Redirect with error message""" return redirect('home') code =''.join(random.choices(string.ascii_uppercase , k=3)) random_str=str(random.randint(10,99))+str(code) username_=first_name+"@"+random_str print(username_) curr_user=Account.objects.create_user(email=email,username=username_, password=password) curr_user.phone_number=mobile_number curr_user.first_name=first_name curr_user.last_name=last_name curr_user.save() """Redirect with success message""" return redirect('home') return render(request,'main/index.html') And this is my Abstract user model ANd IT shows error like this And all of the fields are field with the appropriate data that I filled in that form if I print all of these print([first_name,last_name,mobile_number,email,password,confirm_password,checkbox]) OutPut ['Samir', 'Patil', '1234567890', 'm@gmail.com', '123', '123', 'on'] Please Help.! -
Django: How can I dynamically reload assets into my web pages WITHOUT reloading the whole page?
I'm looking for a solution similar to the one described in the answers to How to force a script reload and re-execute?, but I'd preferably like to have a button on my page that does this when clicked. In other words, I'd like to have a button that when clicked, grabs the newest version of some_script.js that I just saved in VS Code, and injects it into the page. The process would also need to run $.off against all event handlers currently attached to the DOM from the old version of some_script.js, and attach the new ones dynamically. Even better would be a way that I can have the browser do this automatically when I save some_script.js in VS Code. All without having to request the entire page. Is this possible, and if so, do any VS Code extensions already exist for this? MTIA :-) -
How will I implement try or except method in this case?
I want to bring try or except method in this program, where when an invalid user is searched it should return a message "Invalid user". from django.contrib.gis.geos import Point from django.contrib.gis.measure import D from Admin_Section.models import Distance class ServiceProviderList(generics.ListAPIView): serializer_class=ProfilecompletioneSerializer filterset_class=SnippetFilter filter_backends = [DjangoFilterBackend,SearchFilter,OrderingFilter] filterset_fields = ['fullname', 'category','departments','services'] search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name'] def get_queryset(self,*args, **kwargs): pk=self.kwargs.get('pk') customer = CustomerProfile.objects.get(user=pk) Dist=Distance.objects.get(id=1) rad=float(Dist.distance) radius=rad/111 query = ProfileCompletion.objects.filter(location__distance_lte=(customer.location,radius)) return query -
Why am I seeing message for Unapplied Migration(s) after Upgrading Django from 2.0 to 2.2
I upgraded Django from version 2.0 to 2.2. The upgrade completed without any issue. However trying to start the server issues the following message: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth. Run 'python manage.py migrate' to apply them. March 27, 2021 - 08:37:07 Django version 2.2.19, using settings 'lead.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. My application so far is working fine as before (i.e. prior to upgrade). I have checked the database in migrations table but fine no entry for the reference date. There are also no migration file/s in the app's "migrations" folder. My question is: What are these migrations the system is pointing to? Will it be prudent to go ahead and apply the migrations? Additionally, I am not sure I have come across the following entry at the beginning before the upgrade: Watching for file changes with StatReloader Has it something to with the upgrade? -
how to filter out data using filter if its a foreign key?
I have two models: Profile model class Profile(models.Model): idno=models.AutoField(primary_key=True) name=models.CharField(max_length=30) email=models.CharField(max_length=40) username=models.CharField(max_length=30) def __str__(self): return self.username Connection Request model class ConnectRequest(models.Model): idno = models.AutoField(primary_key=True) sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(Profile,on_delete=models.CASCADE, related_name="receiver") def __str__(self): return f"{self.sender} to {self.receiver} " when I am trying to filter out all the data where sender is suppose "XYZ" then its giving me an error on the shell obj=ConnectRequest.objects.filter(sender="XYZ") "idno expected a number but got "xyz" i have tried all these things but it still didn't work and gave errors obj=ConnectRequest.objects.filter(sender.name="XYZ") obj=ConnectRequest.objects.filter(Profile.name="XYZ")