Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cross website login two different domain?
I have a doubt for the cross website login. one website made by php and anothe website is made by python django. how to connect these two websites? cross web site login these website are different domain . one website is done in php and codeigniter . then another website is done in python django website. if i login through php website . That php website navigation bar have one menu is login into the django website . Need to login same user in the django click. in the one click need to done for this. Please help me. whta kind of method in the cross login?. Please mention me and attach any links and any tutorials share with me -
Collectstatic deleting wagtail blog images
I have a wagtail site that I deploy using elasticbeanstalk. When I deploy collectstatic is ran: .platform/hooks/postdeploy #!/bin/sh source /var/app/venv/staging-LQM1lest/bin/activate python /var/app/current/manage.py migrate python /var/app/current/manage.py createsu python /var/app/current/manage.py collectstatic --noinput I have found that this has the effect of deleting any images that are in my blog posts. I assume this is because the blog posts have been made using the page editor (of the deployed site) and are not on my local machine like the rest of the static files How should I be setting things so that I do not delete the images everytime collectstatic is ran? -
Add extra HTML markup to features in Wagtail RichTextField editor?
How can I add extra HTML markup to individual features in Wagtail's RichTextField and have it be stored in the database? Specifically, I need to change the default appearance of a rendered <ul> list, so it would use custom font icons instead of bullet points. So instead of a <ul> list like this: <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> It would save the following in the database: <ul> <li><i class="bx bx-chevron-right">Item 1</li> <li><i class="bx bx-chevron-right">Item 2</li> <li><i class="bx bx-chevron-right">Item 3</li> <li><i class="bx bx-chevron-right">Item 4</li> </ul> Is that possible? -
How to upload random pictures from a list of array of pictures (which is a folder i have turned into an a list using **listdir** )folder to database
i want to upload random pictures from a static named folder to my database. These are my files. Please suggest a way. I am stuck here forever. views.py class VerifyOTPView(APIView): permission_classes = (AllowAny,) serializer_class = VerifyOTPSerializer def post(self, request): serializer = VerifyOTPSerializer(data=request.data) mobile = request.data['mobile'] otp_sent = request.data['otp'] #print('one_time_password', one_time) if mobile and otp_sent: old = Profile.objects.filter(mobile = mobile) if old is not None: old = old.first() otp = old.otp if str(otp) == str(otp_sent): serializer = self.serializer_class(data=request.data) mobile = request.data['mobile'] if serializer.is_valid(raise_exception=True): instance = serializer.save() content = {'mobile': instance.mobile, 'otp': instance.otp, 'name':instance.name, 'username':instance.username, 'logo':instance.logo, 'profile_id': instance.profile_id } return Response(content, status=status.HTTP_201_CREATED) else: return Response({ 'status' : False, 'detail' : 'OTP incorrect, please try again' }) serializers.py class VerifyOTPSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['mobile','otp'] def create(self,validated_data): instance = self.Meta.model(**validated_data) mywords = "123456789" res = "expert@" + str(''.join(random.choices(mywords,k = 6))) path = os.path.join(BASE_DIR, 'static') random_logo = random.choice([ x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x))]) instance = self.Meta.model.objects.update_or_create(**validated_data, defaults = dict( username = res, name = instance.mobile, logo = random_logo, profile_id = res))[0] instance.save() return instance models.py class Profile(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) logo = models.ImageField(upload_to ='profile/', blank=True,null = True) profile_id = … -
Inner join not working when serializing data
Similar questions has been asked before but I cannot use any of the answers to my case. Desired (SQL) query: SELECT project.name, invitation.* FROM invitation INNER JOIN project ON invitation.project_id_id=project.id; Models: class project(models.Model): project_code = models.CharField(max_length=250, null=False, blank=False) internal_code = models.CharField(max_length=250, null=True, blank=True, unique=True) name = models.CharField(max_length=250, null=False, blank=False) class invitation(models.Model): project_id = models.ForeignKey( project, on_delete=models.CASCADE ) country = models.CharField( max_length=250, null=False, blank=False, ) Desired result after the query: project.name invitation.project_id invitation.country Project_1 1 Madagascar Project_2 2 Laos View: def search(request): if request.method == 'GET': result = invitation.objects.select_related('project_id') data = serialize("json", result, cls=DatetimeJSONEncoder) return HttpResponse(data, content_type="application/json") return HttpResponse('') Here I used select_related as suggested in many other SO questions, however, if I print data (already serialized), there are no fields from the project model. The inner join is not working, I did something wrong. print(data): [{"model": "app_name.invitation", "pk": 19, "fields": {"project_id": 1, "country": "Madagascar"}}, {"model": "app_name.invitation", "pk": 20, "fields": {"project_id": 2, "country": "Laos"}}] print(str(result.query)) SELECT "app_name_invitation"."id", "app_name_invitation"."project_id_id", "app_name_invitation"."country", "app_name_project"."name" FROM "app_name_invitation" INNER JOIN "app_name_project" ON ("app_name_invitation"."project_id_id" = "app_name_project"."id") Why project.name is missing in the serialized data? -
How to check data of POST/PUT api method in Flask
data = request.get_json(force=True) print(data) emp = Employee.query.get(employee_id_to_update) print(emp.name) print(set(data.keys())) if 'dm' in data.keys() and logged_user.designation.lower() != "hr": return jsonify("You cannot perform this action") if data.get('name') : emp.name=data\['name'\] if data.get('email'): emp.name = data\['email'\] if data.get('gender'): emp.name = data\['gender'\] I have tried this but i dont want multiple if statements , is there any way to replace if else statements -
Django - using HTMX, what character is posted/inserted when I tab across cells in a table?
I have a table and within the table is a form. Each cell in the table has an input tag and displays an object. This object can be modified directly because I am using htmx to detect a keyup in each cell. My view takes the post data every time htmx is triggered and checks the data. If this data is not equal to one of the options for input, I don't save the object. Additionally, I change the cell border to the color red. This worked as expected. Next, I changed the code so that whitespace is removed from the post data. This also worked as expected. template <form action="" method="post" class="form-group"> {% for student in student_list %} <tr> {% for g in grade_list %} {% if g.student.id == student.id %} <td> <input type="text" hx-post="{% url 'gradebook:grade-change' g.pk %}" hx-swap="outerHTML" hx-trigger="keyup delay:1200ms" class="form-control score" title={{ g.score }} name="score" id="input-{{ forloop.counter0 }}" placeholder={{ g.score }} required> </td> {% endif %} {% endfor %} </tr> {% endfor %} </form> view def post(self, request, *args, **kwargs): grade = self.get_object() user = grade.user ns = request.POST.get('score') new_score = ns.upper() print(new_score) # remove whitespace and tabs new_score = re.sub(r"[\n\t\s]*", "", new_score) score_list = ["EXT", … -
Guidance Needed … [closed]
I have learned python well in the last 3 months and a little bit of Django with it. Currently I am confused a lot that weather I should proceed with learning frontend and Django well or should I start learning Data Structures and Algorithms. As want to go into development. Please help me out with it... I just want guidance and support as I am confused a lot. -
nginx svelte django(waitress) external ip no response
'nginx.conf' server { listen 8888; server_name xxx.xx.xxx.xx; // my PC's external ip root html; } and i running django server by waitress in xxx.xx.xxx.xx:8072 this is my svelte code fetching django server const res = await fetch(http://xxx.xx.xxx.xx:8072/myapp/); so build this svelte app and copy public folder's component to nginx/html and run nginx, 'http://xxx.xx.xxx.xx:8888/myapp' no respond in django server however, if the fetching code is 'localhost:8072' and django server with locahost:8072, nginx server_name -> 'localhost', this work properly why nginx has no response for external ip? Sorry for my poor English. -
Need help to getting setup google login using Django rest framework plus React Js
views class GoogleCreateAccount(APIView): permission_classes = [permissions.AllowAny] def post(self, request): reg_serializer = RegisterSerializer(data=request.data) if reg_serializer.is_valid(): new_user = reg_serializer.save() if new_user: # add these r = requests.post('http://127.0.0.1:8000/auth/token', data={ 'username': new_user.email, 'id_token': request.data['code'], #'password': request.data['password'], 'client_id': '304129974707-79jslq7l318va16eacni8cveokn237g8.apps.googleusercontent.com', 'client_secret': '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', 'grant_type': 'id_token' }) return Response(r.json(), status=status.HTTP_201_CREATED) return Response(reg_serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py urlpatterns = [ path('auth/', include('drf_social_oauth2.urls',namespace='drf')), path('googleregister/',GoogleCreateAccount.as_view()), ] I was setting up an google login with django and react app i was setting it up based on the https://abhik-b.medium.com/step-by-step-guide-to-email-social-logins-in-django-5e5436e20591 above link. It is working on the bcakend as expected. But for getting the access token the parameters I giving is { clientid: client secret: grant type: password username: password: } But in the react it couldnt able to get the password parameter so it is not getting connected to the rest api call. I dont know exactly how to get this issue sorted. Please suggest me a best link or docs for setting up google login for django rest framework as backend and react js as frontend. And is this possible to change the grant type to authorisation code and if so what needs to be changed? -
Why django timezone offset is different?
Djanfo 3.2.10, python 3.9 settings.py TIME_ZONE = 'Europe/Moscow' script.py from django.utils import timezone tzinfo = timezone.localtime().tzinfo # <class 'pytz.tzfile.Europe/Moscow'> tz = timezone.get_current_timezone() # <class 'pytz.tzfile.Europe/Moscow'> dtz = timezone.get_default_timezone() # <class 'pytz.tzfile.Europe/Moscow'> datetime_object = timezone.now() print(datetime_object) # 2022-03-29 03:34:42.244830+00:00 print(datetime_object.replace(tzinfo=tzinfo)) # 2022-03-29 03:34:42.244830+03:00 print(datetime_object.replace(tzinfo=tz)) # 2022-03-29 03:34:42.244830+02:30 print(datetime_object.replace(tzinfo=dtz)) # 2022-03-29 03:34:42.244830+02:30 +0230 is not +0300 What is it?) Correct offset for this timezone is +0300. -
how to input array in django html
I am new to django. I want to make a website to change tables in a database. It should be implemented change, deletion, addition of a note. The problem is that one of the parameters of the Array table and I don't know how to make it input. I tried to do it through text input but it didn't work for me Here my code forms.py from .models import dj_ksg_p from django.forms import ModelForm, TextInput class KSGForms(ModelForm): class Meta: model=dj_ksg_p fields=['id','name','c_prof','smj_prof','KSG'] widgets={ "id": TextInput(attrs={ 'class':'from-control', 'placeholder':'Id' }), "name": TextInput(attrs={ 'class': 'from-control', 'placeholder': 'Название МО' }), "c_prof": TextInput(attrs={ 'class': 'from-control', 'placeholder': 'Профиль' }), "smj_prof": TextInput(attrs={ 'class': 'from-control', 'placeholder': 'Смежный профиль' }), "KSG": TextInput(attrs={ 'class': 'from-control', 'placeholder': 'КСГ' }) } views.py from django.shortcuts import render,redirect from django.views.generic.list import ListView from django.views.generic import DetailView, UpdateView,DeleteView from django.http import HttpResponse from .models import dj_ksg_p from rest_framework import viewsets from .forms import KSGForms \#from .serializers import HeroSerializer class KSGView(ListView): model = dj_ksg_p template_name = 'ksg/kss.html' queryset = dj_ksg_p.objects.all() class NewDataView(DetailView): model = dj_ksg_p template_name = 'ksg/create.html' context_object_name = 'dj_ksg_p' class DeleteKSG(DeleteView): model = dj_ksg_p template_name = 'ksg/delete.html' success_url = '/ksg/' class NewUpdateView(UpdateView): model=dj_ksg_p template_name = 'ksg/detail_view.html' fields = \['id','name','c_prof','smj_prof','KSG'\] form_class=dj_ksg_p def create(request): error = '' … -
Password Reset Custom Email Validation Message Django with MongoDB
I can successfully send an email for a password reset. But when the email address is invalid, the password reset email request has been sent. I don't know how I can check whether the email address is valid or invalid. When the email address is valid, the email will be sent, and when the email address is invalid, an error message will be displayed in the password reset form. I have found similar problems on Stackoverflow. But it didn't work for me. Password Reset Custom Validation Message Inform user that email is invalid using Django's Password Reset Here is my code: In forms.py class EmailValidationOnForgotPassword(PasswordResetForm): def clean_email(self): email = self.cleaned_data['email'] if not User.objects.filter(email__iexact=email, is_active=True).exists(): raise forms.ValidationError("Invalid Email address.") return email In urls.py urlpatterns = [ path('password_reset/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset.html"), name="password_reset"), path('password_reset/', auth_views.PasswordResetView.as_view(form_class=EmailValidationOnForgotPassword), name='password_reset'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="registration/password_reset_done.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="registration/password_reset_confirm.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="registration/password_reset_complete.html"), name="password_reset_complete"), ] Environment version: Django==4.0.2 djongo==1.3.6 sqlparse==0.2.4 Can anyone please help me? I need this fix as soon as possible. -
ModuleNotFoundError: No module named 'djangoherokuapp'
When deploying my django application on heroku I am getting the error 2022-03-29T03:17:52.079107+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2022-03-29T03:17:52.079107+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2022-03-29T03:17:52.079108+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked 2022-03-29T03:17:52.079108+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2022-03-29T03:17:52.079108+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2022-03-29T03:17:52.079108+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2022-03-29T03:17:52.079109+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked 2022-03-29T03:17:52.079109+00:00 app[web.1]: ModuleNotFoundError: No module named 'djangoherokuapp' 2022-03-29T03:17:52.079153+00:00 app[web.1]: [2022-03-29 03:17:52 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-03-29T03:17:52.116083+00:00 app[web.1]: [2022-03-29 03:17:52 +0000] [4] [INFO] Shutting down: Master 2022-03-29T03:17:52.116122+00:00 app[web.1]: [2022-03-29 03:17:52 +0000] [4] [INFO] Reason: Worker failed to boot.``` -
I want to use a filter regardless of whitespace in djangorestframework
i have class KceeService: def getTbBookCrwalingByTitleAndWriter(title, writer): bookData = [] queryset = tb_book_crawling.objects.filter(title__icontains=title, writer__icontains=writer).order_by('-publish_date') for query in queryset: bookData.append(TbBookCrawlingSerializer(query).data) return bookData but title = 'new york 1' , real column data = 'new york1' so, bookData is [] how to use title & column data overcome the whitespace? I want your help. thank,you i removed the whitespace . but , many title is same problems. how to use filter() overcome the whitespace. -
Deploy django rest to apache on window
I follow this link for deploying django https://github.com/Johnnyboycurtis/webproject#apache-and-mod_wsgi i'm using apache on xampp and this is my text adding to httpd.conf Listen 8080 ServerName localhost:8080 #first i try to use port 80 but it not work so i change to 8080 it not work too #Django Project LoadFile "C:/Users/Anaconda3/envs/ar-django/python39.dll" LoadModule wsgi_module "C:/Users/Anaconda3/envs/ar-django/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "C:/Users/Anaconda3/envs/ar-django" WSGIScriptAlias / "C:/xampp/htdocs/tutorial/tutorial/wsgi.py" WSGIPythonPath "C:/xampp/htdocs/tutorial/" <Directory "C:/xampp/htdocs/tutorial/tutorial/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/xampp/htdocs/tutorial/static/" <Directory "C:/xampp/htdocs/tutorial/static/"> Require all granted </Directory> and when i run mod_wsgi-express module-config this is my output LoadFile "C:/Users/Anaconda3/envs/ar-django/python39.dll" LoadModule wsgi_module "C:/Users/Anaconda3/envs/ar-django/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "C:/Users/Anaconda3/envs/ar-django" when i run apache server. apache PID keep changing what wrong with setting in httpd.conf file and how to fix it Thanks for any kind of help -
Keep getting Django form error "this field is required" even though the field has been filled
I am creating a Django web app and I'm starting out on using Django forms. I keep getting this error even though this project name field is entered. <tr><th><label for="id_title">projectName:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="title" maxlength="100" required id="id_title"></td></tr> Below is my code. I'm not sure on what I'm missing. index.html: <form id="project_form" action="{% url 'createproject' %}" method="post"> {% csrf_token %} <div class="form-group row"> <label for="projectName" class="col-sm-2 col-form-label">Project Name:</label> &nbsp; <div class="col-sm-9"> <input type="text" class="form-control" placeholder="Enter Project Name" name="projectName" id="projectName"> </div> </div> <input type="submit" class="btn btn-primary" id="submit-project-btn"> </form> forms.py: class CreateEditProjectForm(forms.Form): title = forms.CharField(label="projectName", max_length=100, required=True) models.py: class TestProject(models.Model): creator = models.ForeignKey(User,on_delete=models.CASCADE,related_name="testcreatorId") projectName = models.CharField(max_length=200, default=None) created_dt = models.DateTimeField(auto_now_add=True, auto_now=False) last_modified_dt = models.DateTimeField(auto_now_add=False, auto_now=True) views.py: def create_project(request): print("in create_project") print(request.method) if (request.method == "POST"): form = forms.CreateEditProjectForm(request.POST) print(form) if form.is_valid(): projectName = form.cleaned_data["projectName"] print(projectName) if (len(projectName) > 0): creator = User.objects.get(id=request.session['_auth_user_id']) project = TestProject(projectName=projectName, creator=creator) print(project) project.save() return HttpResponseRedirect(reverse("index")) return render(request, "index.html", { "form": form }) return render(request, "index.html", { "form": form }) else: form = forms.CreateEditProjectForm() return render(request, "index.html", { "form": form }) -
AWS SES Setup with Django
I am trying to add AWS SES into my project. Where I get a different region listed MessageRejected at / An error occurred (MessageRejected) when calling the SendRawEmail operation: Email address is not verified. The following identities failed the check in region US-EAST-1: email@hotmail.com In the AWS verified identities it is listed: email@hotmail.com Email address Verified I have the permissions for the SES for my policy for that user. Attached from group AmazonSESFullAccess AWS managed policy from group AmazonSESFullAccess Also my settings.py EMAIL_BACKEND = 'django_ses.SESBackend' EMAIL_HOST = 'email-smtp.us-west-2.amazonaws.com' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' Where it's used from django.core.mail import send_mail from django.conf import settings send_mail(email_subject, email_message,'arundeepchohan2009@hotmail.com',['arundeepchohan2009@hotmail.com']) -
Post and Delete vs. Post and Patch for Model's BooleanField?
I'm using Postgres. I've seen threads comparing DELETE and INSERT vs. UPDATE but my use case is slightly different: I want to allow users to "check" and "uncheck" an Item model to be true or false with the default state being false. Does it make more sense to: 1) Post and Delete Create a CheckedItem model (with a ForeignKey to the Item) when they check. Delete that object when they uncheck. If a CheckedItem does not exist, its Item is unchecked. 2) Post and Patch Create a CheckedItem model (with a ForeignKey to the Item) with a check BooleanField as true when they check. Patch the BooleanField to false when they uncheck. If a CheckedItem does not exist or has a false check field, its Item is unchecked. If it matters, there's two other ForeignKeys I would have on every CheckedItem - one for the user and one for the ItemParent. -
HOW to send authentication number by e-mail
I want to send an 8-digit authentication number by e-mail. No matter how hard I try, I don't know what I'm doing wrong. First, I set the smtp. Then, I filled out the form. After creating the view, I created a template. After entering e-mail and username, I pressed the Send button. WHAT? id: email: [29/Mar/2022 09:43:39] "GET /recovery/pw/?email=wlgns000%40gmail.com&username=wlgns HTTP/1.1" 200 2030 However, only these logs appear, and the authentication number does not come by e-mail. How can I send an authentication number by e-mail? #settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.naver.com' EMAIL_PORT = 465 EMAIL_HOST_USER = #email EMAIL_HOST_PASSWORD = #password EMAIL_USE_TLS = True DEFAULT_FROM_MAIL = EMAIL_HOST_USER {% load static %} <!DOCTYPE html> <html lang="KO"> <head> .... <link href="{% static 'users/css/recovery_pw.css' %}" rel="stylesheet"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="{% static 'users/js/recovery_pw.js' %}"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"> <script> $.ajaxSetup({ headers: { "X-CSRFToken": '{{csrf_token}}' } }); </script> </head> <body> {% block content %} <form method="get" enctype="multipart/form-data"> {% csrf_token %} <div class="container"> <div class="inner-box"> ... <div class="input-box"> <div class="id"> <input type="email" placeholder="등록하신 메일로 인증번호가 발송됩니다." name="email" maxlenth="20" autocomplete="off" value="{{ form.email.value|default_if_none:'' }}" required /> </div> <div class="password"> <input type="username" placeholder="아이디를 입력하세요" name="username" maxlength="20" value="{{ form.username.value|default_if_none:'' }}" required /> </div> </div> <div class="btn"> <div class="btn-white" id="btn_white"><button type="submit">send … -
DRF: how to create custom FilterSet to filter nearest users by distance
I'm trying to create custom FilterSet for filtering nearby users by distance. For example if I send GET /api/list/?distance=300, I want to get all nearby users who are lower or equals to 300m far away My model has 2 fields: latitude = models.DecimalField( # [-90.000000, 90.000000] max_digits=8, decimal_places=6, null=True ) longitude = models.DecimalField( # [-180.000000, 180.000000] max_digits=9, decimal_places=6, null=True ) objects = ClientManager() My ClientManager has function for getting coords from model: def get_geo_coordinates(self, pk): """ :param pk: - client id :return: client's coords """ instance = self.get(pk=pk) data = (instance.latitude, instance.longitude) return data` My GetListAPIView class GetClientListAPIView(ListAPIView): """ Returns list with filtering capability Available filter fields: gender, first_name, last_name, distance """ serializer_class = ClientSerializer queryset = Client.objects.all() permission_classes = [IsAuthenticated] filter_backends = [DjangoFilterBackend] filter_class = ClientFilter` My ClientFilter class ClientFilter(FilterSet): distance = filters.NumberFilter(method='get_nearest_clients') def get_nearest_clients(self, queryset, name, value): sender_coords = Client.objects.get_geo_coordinates(pk=self.request.user.id) test_coords = Client.objects.get_geo_coordinates(pk=31) dist = get_great_circle_distance(sender_coords, test_coords) class Meta: model = Client fields = ['gender', 'first_name', 'last_name'] Here I'm using my function for calculating distance between two clients: def get_great_circle_distance(first_coords, second_coords): """ :param first_coords: (first_client_latitude, first_client_longitude) in degrees :param second_coords: (second_client_latitude, second_client_longitude) in degrees :return: distance """ earth_radius = 6_400_000 # in metres la_1, lo_1 = map(radians, first_coords) … -
Include parentheses in django 'layout.html'
I have a line in my layout.html file: <a class="nav-link" href="{% url 'index' %}">Watchlist <span class="badge bg-secondary">{{ user.watchlist.all() | length }}</span></a> But the Django template does not allow () inside of {{ }}. I cannot even do a check in views.py and pass it on in the render function as this is the layout.html file which is not rendered in any view. How do I perform the user.watchlist.all() function then? -
What is the recommended approach to create managed identities in python?
We are trying to use Azure sdk to create managed identities. Seeing the documentation on python sdk on MSI it seems it is the suggested approach. However the last update was 2.5 years ago, we also see managed identities for Azure resources seems to be the new name- "Managed identities for Azure resources is the new name for the service formerly known as Managed Service Identity (MSI)." But I was not able to find SDK for it. What would be the current recommended approach to use python sdk to create managed identities? Any help is appreciated. Thanks! -
Is there something I am doing wrong with my Content Aggregator Website? I cannot get the articles to show up
I followed an online tutorial, but was able to scrape different websites. I cannot get the article headlines to show up. I am not sure if it is a problem with my return function or my HTML file. This is the code for the views.py file from django.shortcuts import render import requests from bs4 import BeautifulSoup as bs4 soup = requests.get("https://www.washingtonpost.com/") content = bs4(soup.content, 'html5lib') headings = content.findAll("div", {"class": "headline relative gray-darkest pb-xs"}) wpnews = [] for span in headings: wpnews.append(span.text) soup2 = requests.get("https://abcnews.go.com/") content2 = bs4(soup2.content, 'html5lib') headings2 = content2.findAll("div", {"class": "News__Content__Container"}) for h2 in headings2: abcnews.append(h2.text) def index(req): return render(req, 'news/index.html', {'Washington Post News': wpnews, 'ABC News': abcnews} And this is the portion of the HTML file that's supposed to show the headlines: <div class="row"> <div class="col-6"> <h3 class="text-centre"> Washington Post News </h3> {% for n in wpnews%} <h5> - {{n}} </h5> <hr> {% endfor %} <br> </div> <div class="col-6"> <h3 class="text-centre">ABC News</h3> {% for htn in abcnews %} <h5> - {{htn}} </h5> <hr> {% endfor %} <br> </div> </div> python html django -
Django pagination and current page with other value currency name button "USD" or "EUR"
I try to pass 2 values in my Django crypto currency project page_number and currency for example USD. Page Load Crypto currencies with defalut converter to price in USD User have possibility to change currency from USD to EUR or JPY or CNY When Im on 1 page it works fine but on second and further takes me back to the first page convert only crypto currencies belonging that page My question is how to convert crypto to USD to EUR or JPY or CNY like on first page that the page I am currently on would be sent(saved) index_buttons.py <div class="row mb-4"> <div class="col-md mb-4"> {% for item in buttons %} <a href="{% url 'index' %}?currency_type={{item.currency_type}}" class="btn btn-outline-dark {{item.active}}" role="button">{{item.display_text}}</a> {% endfor %} </div> </div> views.py def index(request): selected_currency_type = request.GET.get('currency_type', "USD") buttons = [ {"currency_type": "USD", "active": "", "display_text": "USD"}, {"currency_type": "EUR", "active": "", "display_text": "Euro"}, {"currency_type": "CNY", "active": "", "display_text": "Chinese Yuan"}, {"currency_type": "JPY", "active": "", "display_text": "Japanese Yen"}, ] for button in buttons: if button['currency_type'] == selected_currency_type: button['active'] = 'active' currecies_list = load_currencies(selected_currency_type) paginator = Paginator(currecies_list, 12) page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) context = { "user": request.user, "page_obj": page_obj, "buttons" : buttons, "active_currency_name" : selected_currency_type, …