Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to display a list friend requests
I am currently following a guide on making friends in Django and stumbled upon a problem. As i am fairly new to Django and Python, i am unsure of to display a list of friend requests that has been to a user. I am following this guide https://medium.com/analytics-vidhya/add-friends-with-689a2fa4e41d and i have tried to implement the for loop in Step 5 part 2 as they stated that they can display a list of all friend requests. However, i can not seem to display anything and they have not shown their code on how to do so. Here is my friend_request function in views.py in an attempt to try and gather all friend requests. All my other code are the same as guide previously linked above. So if possible, can anyone guide me on how to display all friend requests that are sent to a user? def friend_requests(request, requestID): all_friend_requests = FriendRequest.objects.get(to_user=requestID) context = { 'all_friend_requests': all_friend_requests } return ('/', context) -
running django project on another pc
I am using mysql as the database of the django project, mysql is installed on the computer I will install, but after the migrate process on the other computer I installed, an error comes up and only django does its own migrate process, the models in my models.py files do not pass to the database. ?:(mysql.w002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's strict mode fixes many data intergity problems in mariadb, such as data truncation upon insertion,by escalating warnings into errors. It is strongly recommended you active it see: https://docs.djangoproject.com/en/ref/databases/mysql-sql-mode enter image description here -
quickbooks-api did not recognize attribute auth
I recently update may Django app which is connected to quickbooks to python 3.9.16. Due to this change, I've an issue : QuickBooks' object has no attribute 'auth_client': My code is : try: auth_client = AuthClient( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, environment=ENV, redirect_uri=REDIRECT_URI, ) except Exception as exc: logging.info('log credentials SELECT Errors: {} - {}'.format(companyId, exc)) chek = 'Nok' # creating the client object to access the QBO account - if not able to connect, make 3 tries dans then stop if chek != 'Nok': tries = 1 logging.info('Trying to connect to QBO') for i in range(tries): try: client = QuickBooks( auth_client=auth_client, refresh_token=REFRESH_TOKEN, company_id=COMPANY_ID, ) # get the refresh token returned refresh_token_new = client.auth_client.refresh_token Error is on last lign. seems that it does not understand: client.auth_client in requirements.txt I have (extract): sqlalchemy intuit-oauth python-quickbooks pandas unidecode gunicorn without version infos.So should be last version -
Javascript file is not working on templates in django?
Static setting is right?My javascript file is not running in django templates? Tried using static file setting and loading static before tags -
How to filter objects by value of one of its fields in django?
I have django application with urls.py: path('<str:slug>/', views.article), When user types name of product in my website, the view is triggered: def article(request, slug): videos = models.Video.objects.filter(article=slug) return render(request, 'videos/at_detail.html', {'videos': videos}) If I add print(slug) somewhere in function it returns the word I entered in url, so this part works. models: class article(models.Model): name = models.CharField(max_length=30, null=True) slug = AutoSlugField(populate_from='name', unique=True, default=None) created_on = models.DateTimeField(default=timezone.now) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, default=None) def __str__(self): return self.name class Meta: verbose_name = "Articles" class Video(models.Model): video_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) title = models.CharField(max_length=50) description = models.CharField(max_length=500) file = models.FileField() article = models.ForeignKey(at, on_delete=models.CASCADE) def __str__(self): return str(self.title) + " - " + str(self.at) class Meta: verbose_name_plural = "Videos" verbose_name = "Video" What doesn't work, and what I'm trying to do, is to get all objects, which have same value 'article', that what I entered in my url. So for example: if I type 127.0.0.1:8000/blueberry/ I will get all objects with field article=blueberry. Is this possible and if it is, how can I do that? -
Django template is rendering in Multi-step form, but context data is not visible
I am working on this problem and somehow resolved it to a very great extent and almost everything is done. But the Django is rendering my template but not the Context. I don't know why I have checked it by debugging and my context is rendering but not showing in frontend. On this template, there is a form with 4 fieldset , I am submitting data in 1st fieldset and the dynamically show o/p accordingly on the second fieldset. I am attaching screenshot to show what is rendering in template(2nd fieldset) before submitting After submitting #views.py def createQuotePage(request): if request.method == "POST": # Getting all the value # saving in Table saveInUnitsTable(-------some code, removed to shorten question ------) saveInCustomerTable(-------some code, removed to shorten question ------) saveInInquiryTable(-------some code, removed to shorten question ------) flight_suggestions =Flight.objects.filter(sourceairportid=1,destinationairportid=51) context = {'flight_suggestions':flight_suggestions,"test":"99999999999999999999999999999999999999"} return render(request,"Freight/create_quote.html",context=context) # <-- here is the PROBLEM if request.method == "GET": print("========================GET=======================") context = {'airport_data' : list(Airport.objects.all()), 'commodity_data':list(Commodity.objects.all()), 'customerType_data':list(Entity.objects.all()), } return render(request,"Freight/create_quote.html",context=context) #scripts.js (function($) { "use strict"; $.backstretch; $('#top-navbar-1').on('shown.bs.collapse', function(){ $.backstretch("resize"); }); $('#top-navbar-1').on('hidden.bs.collapse', function(){ $.backstretch("resize"); }); $('.f1 fieldset:first').fadeIn('slow'); $('.f1 .btn-next').on('click', function() { // var parent_fieldset = $(this).parents('fieldset'); var next_step = true; var current_active_step = $(this).parents('.f1').find('.f1-step.active'); var progress_line = $(this).parents('.f1').find('.f1-progress-line'); // var formData1 … -
Why not use "authentication.views import *" to prevent typing "views." before every call in urls.py?
Why not use: from django.urls import path from authentication.views import * urlpatterns = [ path('login/', login_view, name='auth.login'), } Instead of: from django.urls import path from authentication import views urlpatterns = [ path('login/', views.login_view, name='auth.login'), } I couldn't find much information about it. -
JsTree invisible after reload the page
I have a button to create first node in jstree after submit that form page reload and jstree not visible. **JS:** $(document).on("click", "#templatename", function() { let templatename = $(".template_name").val(); let csr = $("input[name=csrfmiddlewaretoken]").val(); mydata = { templatename: templatename, csrfmiddlewaretoken: csr }; $.ajax({ url: '/templatename/', type: "POST", data: mydata, success: function (data) { let template_name = data.data createJSTree(template_name) }, error: function (e) { console.error(e) } }); }); function for creating jstree: function createJSTree(template_name) { $('#jstree_template').jstree({ "core": { "themes": { "responsive": false }, "check_callback": true, 'data': template_name, }, "types": { "default": { "icon": "fa fa-folder text-primary" }, "file": { "icon": "fa fa-file text-primary" } }, "state": { "key": "demo2" }, "plugins": ["contextmenu", "state", "types"], "contextmenu": { "items": function ($node) { var tree = $("#jstree_template").jstree(true); return { "Create": { "separator_before": false, "separator_after": true, "label": "Create", "action": function (obj) { for (let i = 0; i<template_name.length; i++){ debugger obj_id = obj.reference[0].id.split('_')[0] obj_hastag = obj.reference[0].href.split('/')[3] data_id= `${template_name[i].id}` data_hastag = `${template_name[i].parent}` obj_id_hastag = obj_id + obj_hastag data_id_hastag = data_id + data_hastag if(obj_id_hastag == data_id_hastag) { $('#template_modal').modal('show'); } else if(obj.reference[0].id.split('_').slice(0,2).join('_') == `${template_name[i].id}`){ $('#mode_modal').modal('show'); } else if(obj.reference[0].id.split('_').slice(0,2).join('_') == `${template_name[i].id}_anchor`){ $('#mode_modal').modal('show'); } } } }, "Rename": { "separator_before": false, "separator_after": false, "label": "Rename", "action": function (obj) { tree.edit($node); } … -
Patch Django EmailMultiAlternatives send() in a Celery Task so that an exception is raised
I want to test a Celery Task by raising an SMTPException when sending an email. With the following code, located in: my_app.mailer.tasks from django.core.mail import EmailMultiAlternatives @app.task(bind=True ) def send_mail(self): subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") try: msg.send(fail_silently=False) except SMTPException as exc: print('Exception ', exc) and then running the following test against it: class SendMailTest(TestCase): @patch('my_app.mailer.tasks.EmailMultiAlternatives.send') def test_task_state(self, mock_send): mock_send.side_effect = SMTPException() task = send_mail.delay() results = task.get() self.assertEqual(task.state, 'SUCCESS') The email is sent without error. However, if I turn the task into a standard function (my_app.mailer.views) and then run the following test against it: class SendMailTest(TestCase): @patch('myapp.mailer.views.EmailMultiAlternatives.send') def test_task_state(self, mock_send): mock_send.side_effect = SMTPException() send_mail(fail_silently=False) The string 'Exception' is displayed, but there is no exc information as to what caused the exception. Please, what am I doing wrong? -
How to Close a Modal properly with jquery or javascript from within the injected HTML?
Script to Call Modal, and HTML Skeleton for Modal: (which is working) <script> $(document).on("click", ".addworker", function (e) { e.preventDefault(); var $popup = $("#popup"); var popup_url = $(this).data("popup-url"); $(".modal-content", $popup).load(popup_url, function () { $popup.modal("show"); }); }); </script> <div id="popup" class="modal fade" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> </div> </div> </div> The HTML loaded into modal-content is returned by a django view which sits behind the url. (this part is working too) Inside this HTML i have the Button, which i want to use to then close the modal again. But when the Modal got injected with the HTML and is open, it seems like the modal is out of scope, so i tried to get it back with var $popup = $("#popup");. And i indeed get back the Object, but the $popup.modal("hide"); Method doesnt work. <script> $(document).on("click", ".cancel", function (e) { var $popup = $("#popup"); $popup.modal("hide"); }); </script> <div class="modal-header"> <h1>{{ aoe }} Worker: {{ id }}</h1> </div> <form action="add/" method="post"> {% csrf_token %} <div class="modal-body"> {{ form|crispy }} </div> <div class="modal-footer"> <input type="button" class="btn btn-secondary cancel" value="Cancel"> <input type="submit" class="btn btn-primary" value="Submit"> </div> </form> -
How to run selenium in Docker with Flask?
My goal is to run Selenium with Flask. The problem is that it throws an error. [2022-12-16 11:30:05 +0000] [1] [INFO] Starting gunicorn 20.1.0 [2022-12-16 11:30:05 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [2022-12-16 11:30:05 +0000] [1] [INFO] Using worker: sync [2022-12-16 11:30:05 +0000] [6] [INFO] Booting worker with pid: 6 [WDM] - Downloading: 100%|██████████| 6.96M/6.96M [00:00<00:00, 12.6MB/s] [2022-12-16 11:30:07 +0000] [6] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/app.py", line 2, in <module> from scrapeutil import get_db File "/scrapeutil.py", line 14, in <module> driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), … -
Seperaet the response in DRF
Im returning the summary of orders in which order_total, order_number ,quantity and the payment is repeated but I only want it to be shown one time. Like all the products should be the one only in nested serializer response and other should be shown singly without any repetition #Serializer class OrderSummarySerializer(ModelSerializer): product = ProductSerializer() payment = PaymentSerializer() order_number = SerializerMethodField() order_total = SerializerMethodField() class Meta: model = OrderProducts fields = ["order_number", "payment", "product", "quantity", "order_total"] def get_order_total(self, obj): return obj.order.order_total def get_order_number(self, obj): print(obj) return obj.order.order_number #Views class OrderSummary(APIView): def get(self, request): try: order_number = request.GET.get("order_number") orders = Orders.objects.get(user=request.user, order_number=order_number) order_summary = OrderProducts.objects.filter( user=request.user, order__order_number=order_number, is_ordered=True ) context = { "request": request, } serializer = OrderSummarySerializer( order_summary, many=True, context=context ) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: print(e) return Response( {"error": "Something went wrong"}, status=status.HTTP_400_BAD_REQUEST #Response I get [ { "order_number": "ypVtT1", "payment": { "payment_method": "cod", "amount_paid": "", "status": "Pending", "created_at": "2022-12-16T16:46:30.915646+05:30" }, "product": { "id": 1, "product_name": "Pendant1", "sub_product_name": null, "slug": "pendant-1", "highest_offer_price": 250.0, "category_offer_discount": 1250.0, "product_offer_discount": 2250.0, "base_price": 2500, "stock": 5, "is_available": true, "product_image": "http://127.0.0.1:8000/media/photos/products/pendant3.webp" }, "quantity": 1, "order_total": 2170.0 }, { "order_number": "ypVtT1", "payment": { "payment_method": "cod", "amount_paid": "", "status": "Pending", "created_at": "2022-12-16T16:46:30.915646+05:30" }, "product": { "id": … -
How to change position of endpoints in drf-yasg Django
I'm trying to customize drf api documentation with drf-yasg. I want to change order of display endpoints. For example to change: GET /endpoint/number1/ GET /endpoint/number2/ to GET /endpoint/number2/ GET /endpoint/number1/ in swagger document. How can I do that? -
mptt not linking children and parent - Django
I'm having an issue that I seriously can't wrap my head around. I am using Django MPTT models and evrerything seems to be working fine (i.e. I can run the migrations and insert data in the database), but for some reason the TreeForeignKey table and the TreeManyToManyField table are not linking in the database. Here are the models in question... from mptt.models import MPTTModel, TreeForeignKey, TreeManyToManyField class Category(MPTTModel): name = models.CharField( max_length=100, verbose_name=_('category name'), help_text=_('format: required, max=100'), ) slug = models.SlugField( max_length=150, verbose_name=_('category safe URL'), help_text=_('format: required, letters, numbers, underscore or hyphons'), ) is_active = models.BooleanField(default=True) parent = TreeForeignKey( 'self', on_delete=models.PROTECT, related_name='children', null=True, blank=True, ) class MPTTMeta: order_insertion_by = ['name'] class Meta: verbose_name=_('product category') verbose_name_plural=_('product categories') def __str__(self): return self.name class Product(models.Model): web_id = models.CharField( unique=True, max_length=50, verbose_name=_('product website ID'), ) slug = models.SlugField( max_length=255, verbose_name=_('product safe URL'), help_text=_('format: required, letters, numbers, underscore or hyphons'), ) name = models.CharField(max_length=150) description = models.TextField(help_text='Required') category = TreeManyToManyField(Category) is_active = models.BooleanField( default=False, verbose_name=_('product visibility'), ) created_at = models.DateTimeField( editable=False, auto_now_add=True, help_text=_('format: Y-m-d H:M:S'), ) updated_at = models.DateTimeField(auto_now=True, help_text=_('format: Y-m-d H:M:S')) def __str__(self): return self.name I'm following the documentation verbatum, and really I have no idea why this is not working... If anyone has … -
Django Static Sitemap is not working gives error "Reverse for 'index' not found. 'index' is not a valid view function or pattern name."
I'm trying to implement a Static Sitemap for my app and I get the error "Reverse for 'index' not found. 'index' is not a valid view function or pattern name." even though these views are set up. What could cause this? I have no problem with dynamic sitemaps, just the static one. My views.py def front_page(request): return render(request, 'django_modules_testing_app/front_page.html', { }) def about_us(request): return render(request, 'ihgr_app/about_us.html', { }) def index(request): return render(request, 'django_modules_testing_app/index.html', { }) urls.py from django.urls import path from . import views from . import blocks from django.contrib.sitemaps.views import sitemap from .sitemaps import DjangoModulesTestingApp app_name = 'django_modules_testing_app' sitemaps = { 'main_app':DjangoModulesTestingApp } urlpatterns = [ path('', views.front_page, name='front_page'), path('', views.index, name='index'), path('', views.about_us, name='about_us'), path('category_details/<slug:slug>/', blocks.category_details, name='category_details'), path('search_website/', views.SearchWebsite.as_view(), name='search_website'), path('sitemap.xml', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap') ] sitemaps.py from django.contrib.sitemaps import Sitemap from django.urls import reverse class StaticSitemap(Sitemap): changefreq = 'weekly' priority = 0.8 protocol = 'http' def items(self): return ['front_page','index','about_us'] def location(self, item): return reverse(item) -
Pydantic from_orm to load django model prefetch_related list field
I have django model: class Foo(models.Model): id: int name = models.TextField(null=False) class Bar(models.Model): id: int foo = models.ForeignKey( Foo, on_delete=models.CASCADE, null=False, related_name="bars", ) and a pydantic model as (orm_mode is True): class BarPy(BaseModel): id: int foo_id: int class FooPy(BaseModel): id: int name: str bars: List[BarPy] Now i want to query on model Foo and load it into FooPy, so i wrote this query: foo_db = Foo.objects.prefetch_related("bars").all() pydantic_model = FooPy.from_orm(foo_db) But it gives me this error: pydantic.error_wrappers.ValidationError: 1 validation error for FooPy bars value is not a valid list (type=type_error.list) I am able to do it when explicitly using FooPy constructor and assigning the values manually but i want to use from_orm. -
Jquery Timepicker Disabletimerange not working
Im using version 1.3.5 <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css"> I don't know why the disableTimeRanges is not working. I've tried this one: $('.add-costings-starttime').timepicker({ dynamic: false, dropdown: true, scrollbar: true, 'disableTimeRanges': [ ['1am', '2am'], ['3am', '4:01am'] ] change: function (time) { var time = $(this).val(); var picker = $(this).closest(".costingsRow").find(".add-costings-endtime"); picker.timepicker('option', 'minTime', time); } }) -
How to redirect user from registration page to profile if user is already registered?
I am using Django class-based views for my project and trying to redirect user from registration view if he is already authenticated. I've done it already with LoginView and it was pretty simple and looked just like adding few lines of code: class Login(LoginView): authentication_form = CustomAuthenticationForm redirect_authenticated_user = True LOGIN_REDIRECT_URL = "core:profile" So after going to url for login, user ends up at his profile url. Absolutely simple and works perfectly. However, there is no CBV for registration and therefore CreateView should be used, which doesn`t have any attributes for checking if user is authenticated. The one method of doing something similar is UserPassesTestMixin, but it only gives me 403 Forbidden if user is authenticated, not redirect. Here is my current registration view: class Registration(UserPassesTestMixin, CreateView): form_class = RegistrationForm template_name = "registration/user_form.html" success_url = reverse_lazy("core:profile") def test_func(self): return self.request.user.is_anonymous def form_valid(self, form): print(self.kwargs) self.object = form.save(commit=True) self.object.is_active = True self.object.save() login(self.request, self.object, backend="core.auth_backend.AuthBackend") return HttpResponseRedirect(self.success_url) Maybe somebody have done it already? Would be very grateful for every advice! -
Calculating values from different Django Models
I have 2 similar django models, the difference between them is that one of them has a Foreign key with another model and the other is like a general Model. class Project: name = models.CharField(default='',max_length=100,verbose_name="name") class Article(models.Model): code = models.CharField(default='',max_length=20,verbose_name="Norma") name = models.TextField(default='',verbose_name="Denumire") project = models.ForeignKey(Project,on_delete=models.CASCADE,null=True) quantity = models.FloatField(default=0,verbose_name="Quantity") value = models.FloatField(default=0,verbose_name="Value") class BaseArticle(models.Model): code = models.CharField(default='',max_length=20,verbose_name="Norma") name = models.TextField(default='',verbose_name="Denumire") price = models.FloatField(default=0,verbose_name="Price") I want to calculate the value attribute from Article model, it should be like this: if article.code == basearticle.code: article.value = article.quantiy * basearticle.price How should I do this type of calculations? Should I write the logic in views.py? views.py: class ProjectDetail(LoginRequiredMixin, DetailView): template_name = "proiecte/project_detail.html" context_object_name = "projects" model = Project In the template I use {% for article in projects.article_set.all %} to generate a table that has all the attributes as headers. -
Django-filter is being ignored when query parameter value is non-existing
Code where problem occurs: class GameFilter(FilterSet): release = MultipleChoiceFilter(choices=Game.RELEASE_CHOICES, method='release_filter', widget=CSVWidget, required=True) def release_filter(self, queryset, name, releases): if releases: ... return queryset Lets say in my Game.RELEASE_CHOICES, one of my options is "2", this means this query is working for me http://localhost:8000/games/?release=2 In this case I can reach my breakpoint in release_filter method. BUT When I try to query this URL with non existing query parameter value http://localhost:8000/games/?release=2156 The release_filter is not being executed, cant reach breakpoint at all and all I get in return is: { "count": 0, "results": [], "page_size": 20 } What I would like to achieve is the filter being executed despite of non existing query parameter value. Is it possible? Thank you for all possible answers. -
How to get url string from url using resolve django for RBAC
I have used extract_views_from_urlpatterns method of show_urls management command in django-extenstion package for populating system urls into the DB. Now whenever user requesting to server it will intercept in middleware there i want to check if requested URL found in URLMaster model(all system URL store) but it didn't match due to the requested url not found here I am attaching the code. Populating the URL's urlconf = __import__(settings.ROOT_URLCONF) urls = Command().extract_views_from_urlpatterns(urlconf.urls.urlpatterns) for view, url, url_name in urls: if url_name is None: URLMaster.objects.get_or_create(url=url, defaults=dict(view_name=view.__qualname__, url_name=url_name)) Now currently i am check that URL in view further will check in middleware. from django.contrib.admindocs.views import simplify_regex # for simplifying regex from src.core.models import URLMaster # model has all the url's request_url = request._request.resolver_match.route print(request_url) # will print 'rough/packet-split/(?P<pk>[^/.]+)/packet-list/$' # simplifying the URL print(simplify_regex(request_url)) # will print '/rough/packet-split/<pk>/packet-list/' # The same url I have saved in DB url_master_url = URLMaster.objects.get(id=1216).url print(url_master_url) # will print 'rough/^packet-split/(?P<pk>[^/.]+)/packet-list\\.(?P<format>[a-z0-9]+)/?$' # now simplifying the URL print(simplify_regex(url_master_url)) # will print '/rough/packet-split/<pk>/packet-list\\.<format>/' # now i am comparing is it the same like simplify_regex(url_master_url) == simplify_regex(request_url) # returning false due to the url mismatched I am binding the permission to particular URL. But didn't match therefor Is there any approach to comparing or … -
How to render two views into one template using Django
fair to mention I'm just starting out with learning Django, and I could really use the help. To paint a clear picture, there are two API endpoints that I have to use and each one of them has to be rendered in the same template (HTML file) meaning they have to be in the same URL path as well, but I couldn't figure it out yet, I tried with both the function and class-based views but I got nowhere. views.py: ` class HomePage(TemplateView): template_name = 'home.html' def home(self, request): response = requests.get('https://api.covid19api.com/world/total').json() print('res',response.data) return render(request, 'home.html', {'response': response}) def other(self, request): response= requests.get('https://api.covid19api.com/country/south-africa/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z').json() return render(request, 'home.html', {'response': response}) ` urls.py: ` urlpatterns = [ path('home', HomePage.as_view(), name='home') ] ` home.html: ` {% extends '_base.html' %} {% block page_title %} Covid19 Statistics {% endblock %} {% block content %} <br> <br> <h3 class="text-center">World Total Statistics </h3> <br> <!-- <div class="container"> <div class="card-group"> <div class=" col-md-4"> <div class="card text-white bg-secondary mb-3" style="max-width: 20rem;"> <div class="card-body"> <h5 class="card-title text-center">Total Confirmed: {{response.TotalConfirmed}}</h5> </div> </div> </div> <div class=" col-md-4"> <div class="card text-white bg-secondary mb-3" style="max-width: 20rem;"> <div class="card-body"> <h5 class="card-title text-center">Total Deaths: {{response.TotalDeaths}}</h5> </div> </div> </div> <div class=" col-md-4"> <div class="card text-white bg-secondary mb-3" style="max-width: … -
How to get rid of this error? SynchronousOnlyOperation: You can't call this from an asynchronous context - use a thread or sync_to_async
I use asynchrony in django and I ran into the following problem: It is possible to execute a aget() request for the AccountUser model, but the CabinetUser model is not. When executing a aget() request for the CabinetUser model, I get an error: SynchronousOnlyOperation: You cannot call this from an asynccontext - use a thread or sync_to_async. My mоdels: class AccountUser(AbstractUser): """Модель для пользователей""" username_validator = UnicodeUsernameValidator() id = models.UUIDField( primary_key=True, default=uuid.uuid4(), editable=False) username = models.CharField( gettext_lazy("username"), max_length=150, unique=True, help_text=gettext_lazy( "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." ), validators=[username_validator, validate_phone_number], error_messages={ "unique": gettext_lazy("A user with that username already exists."), }, ) class Meta: db_table = 'account_user' verbose_name = 'Пользователь' verbose_name_plural = 'Пользователи' def __str__(self): return f'Пользователь -> {self.username}' class CabinetUser(models.Model): """ Модель кабинета пользователя""" WORK_STATUS_WORKING = 'working' WORK_STATUS_FIRED = 'fired' WORK_STATUS_VACATION = 'vacation' WORK_STATUS_CHOICES = ( (WORK_STATUS_WORKING, 'Работает'), (WORK_STATUS_FIRED, 'Уволен'), (WORK_STATUS_VACATION, 'В отпуске') ) id = models.UUIDField( primary_key=True, default=uuid.uuid4(), editable=False) is_payment = models.BooleanField( default=True, verbose_name='Выплаты включены' ) work_rules = models.ForeignKey( to=WorkRules, verbose_name='Условия работы', on_delete=models.CASCADE, related_name='cabinet_user', ) role = models.CharField( max_length=20, choices=[ ('Director', 'Директор'), ('Operator', 'Оператор'), ('Driver', 'Водитель'), ('Courier', 'Курьер'), ], verbose_name='Должность',) # Для миграций cabinet_park = models.ForeignKey( to='partner.CabinetPark', related_name='cabinet_user', verbose_name='Кабинет парка', on_delete=models.CASCADE, blank=True, null=True ) group_commission = … -
What is difference between factory and factoryboy package?
I am new to the factoryboy package i want to use this for unit testing of my django app, previously i used factory package, i want to know the exact difference between this 2 package becuase syntax and structure is almost same in both package -
Django SAML logout failing
In my Django project I use python3-saml to login with SSO. The login works like expected but the logout is failing with an error message 'No hostname defined'. I really don't know how to solve this as the only parameter passed to logout is the request and request is missing 'http_host' and 'server_name', read here. My logout part looks like following: def get(self, request, pkuser=None): try: get_user_model().objects.get(pk=pkuser) except get_user_model().DoesNotExist: return redirect('HomePage') logger = logging.getLogger('iam') logger.info('IAM logout') auth = OneLogin_Saml2_Auth(request, custom_base_path=settings.SAML_FOLDER) logger.info('account logout') # OneLogin_Saml2_Utils.delete_local_session() try: auth.logout( name_id=request.session['samlNameId'], session_index=request.session['samlSessionIndex'], nq=request.session['samlNameIdNameQualifier'], name_id_format=request.session['samlNameIdFormat'], spnq=request.session['samlNameIdSPNameQualifier'] ) logger.info('account logout success') OneLogin_Saml2_Utils.delete_local_session() logger.info('account logout: deleted local session') except Exception as e: logger.info('account logout failed: {}'.format(str(e))) logout(request) return redirect('HomePage') Maybe I'm using the wrong package...? Any help or advice will be appreciated.