Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: converting view function to class-based view. Error during login to Admin panel: matching query does not exist
I'm learning how to convert old view.py functions to class-based views. I started with a simple function that displayed a page with my essays, plus, I had a newsletter form and a draft of a comment form (but not attached to DB). I decided to not develop this comment form further in a simple function, but to rebuild all of it to class-based view to learn a better and cleaner approach. I've encountered a problem that I have no idea how to solve. Error: matching query does not exist. And Exception Value: EssayCls matching query does not exist. Most likely I break the logic that connects my model to my DB. I'm looking for suggestions on how to solve issues in my code and suggestions about topics I should learn more about to make this kind of development less cumbersome. Before I rebuild my view, things were working fine and looked like this: views.py: from django_user_agents.utils import get_user_agent from .models import EssayCls, SendMeMessage from .forms import CommentForm def my_essays(request, home_view_author_slug): user_agent = get_user_agent(request) try: selected_essay = EssayCls.objects.get(slug=home_view_author_slug) if request.method == 'GET': user_feeDBack = UserFeeDBack() else: """ The incoming request from Django will have a POST property which contains any submitted … -
Search results doesn't show in the template (Django)
I am new to Django and I am creating a very simple project. However, the "search" part of my project is having some issues. Every time I try to search, it redirect me to the search template but not showing the data from the database. No error message. Here's my code... models.py class Event(models.Model): eventname = models.CharField(max_length = 100) class months(models.TextChoices): JANUARY = 'January', _('January') FEBRUARY = 'February', _('February') MARCH = 'March', _('March') APRIL = 'April', _('April') MAY = 'May', _('May') JUNE = 'June', _('June') JULY = 'July', _('July') AUGUST = 'August', _('August') SEPTEMBER = 'September', _('September') OCTOBER = 'October', _('October') NOVEMBER = 'November', _('November') DECEMBER = 'December', _('December') month = models.CharField( max_length= 10, choices=months.choices, default=months.JANUARY, ) day = models.IntegerField() year = models.IntegerField() area = models.ForeignKey(Area, related_name = 'events', blank=True, null=True, on_delete = models.CASCADE) guest = models.ForeignKey(Guest, related_name = 'events', on_delete = models.CASCADE) recorded_by = models.ForeignKey(Userprofile, related_name = 'events', on_delete = models.CASCADE) def __str__(self): return self.eventname search_bar.html #the search bar in the template <div class="search"> <form method="post" action="{% url 'event_search' %}" autocomplete="off"> <br> {% csrf_token %} <input type="text" name="event_srch" placeholder="Search Event"> <input type="submit" name="submit" value="Search" style="width: 24%"></p> </form> </div> views.py def event_search(request): if request.method == "POST": event_search = request.POST.get('event_srch') events … -
How do i show related foreign key in django query set?
I'm new to django, and i want to show field that related to foreign key in another table. this is the table. i want to career table got the career_tag_name and hex_code from table color. i've tried the Career.objects.raw() this is the query in views.py: careers = Career.objects.raw('''SELECT website_career_tag.career_tag_name,website_color.hex_code, website_career.* from website_career INNER JOIN website_career_tag on website_career_tag.id = website_career.career_tag_id_id LEFT JOIN website_color on website_career_tag.color_id_id = website_color.ID''') it works perfectly, until i want to use filter() by career_tag_name. when i use query set it's more easy than make it raw to filter. how do i make those raw query to query set? -
Django keyword error but print kwargs shows the key
I have this URL and I send the currently logged in user's id (viewer (33)) and the id of the user being looked at (user (1)) in the URL: path("users/<int:viewer>/<int:user>/profile/", OtherProfile.as_view()), Here is the view handling that URL: class OtherProfile(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = ProfileSerializer name = "other-profile" lookup_field = "user" def get_queryset(self): breakpoint() viewer = self.kwargs["viewer"] user = self.kwargs["user"] return Profile.objects.all().filter(user_id=user) There is a breakpoint here and the result of print(self.kwargs["viewer"]) gives 33 which is correct print(self.kwargs["user"]) gives 1 which is also correct Here is the profile serializer as specified in the serializer_class: class ProfileSerializer(serializers.ModelSerializer): location = serializers.SerializerMethodField() user = UserSerializer() followers = serializers.SerializerMethodField() class Meta: model = Profile fields = [ "id", "background", "photo", "first_name", "middle_name", "last_name", "birthdate", "gender", "bio", "occupation", "is_verified", "verification", "website", "location", "user", "followers", "created_at", "updated_at", ] def get_location(self, obj): location_obj = Location.objects.filter(profile=obj.id) if location_obj: location_obj = Location.objects.get(profile=obj.id) location = LocationSerializer(location_obj) return location.data def get_followers(self, obj): breakpoint() followers = Follow.objects.filter(followee=obj.user.id) return followers.count() I put a breakpoint on the get_followers method so I can look at the data. print(self.context["view"].kwargs) - prints ["viewer", "user"] My question: Why does print(self.context["view"].kwargs["user"]) print 33 when on the view the kwargs user should be 1? Why does it give me … -
I can´t publish MQTT messages after a few days
I'm using "mqttasgi" as library with Django justo to listen and posting many messages. However, for some reason after a few days it is no longer possible to continue posting messages. It should be noted that I am using the amazon login with "mqttasgi" and a level 1 of QO(because AWS doesn't allow a level 2 of QO). This is my procfile mqttasgi -H $MQTT_URL -p $MQTT_PORT -v 2 -C $TLS_CERT -K $TLS_KEY -S $TLS_CA iot_stracontech.asgi:application``` and this is my consumer.py from mqttasgi.consumers import MqttConsumer from mqtt_handler.tasks import processmqttmessage import json class MyMqttConsumer(MqttConsumer): async def connect(self): await self.subscribe('tpx/things/+/uplink', 0) await self.channel_layer.group_add("stracontech", self.channel_name) async def receive(self, mqtt_message): print('Received a message at topic:', mqtt_message['topic']) print('With payload', mqtt_message['payload']) print('And QOS:', mqtt_message['qos']) dictresult = json.loads(mqtt_message['payload']) jsonresult = json.dumps(dictresult) processmqttmessage.delay(jsonresult, mqtt_message['topic']) pass async def publish_results(self, event): data = event['result'] await self.publish("stracontech/procesed/" + event['result']['device_id'] + "/result", json.dumps(data).encode('utf-8'), qos=1, retain=False) async def disconnect(self): await self.unsubscribe('tpx/things/+/uplink') I want to know if exist a way to know why does it stop publishing messages, anyway to do a debug or see the logs? Pd: @Santiago Ivulich maybe you can give me a hand with that. -
how can i filter variants (size - color ) when select size product show color product ,who saved in database in django?
yacine amateur in django welcome everybody I'm about to complete my first project, in webbing I ran into a problem, frankly, that I couldn't solve I simply face a problem when I open the page for a specific product, and select a specific size, the colors do not change according to what is stored in databases according to each size for example **product 1** **size**: s l m xl **color**: red black yellow if i save variant for **product 1** as **size**: xl with **color**: red when i select **size** in product-sidebare.html i can not show just **color** red that is my code model.py class Add_Product(models.Model): STATUS = ( ('True', 'True'), ('False', 'False'), ) VARIANTS = ( ('None', 'None'), ('Size', 'Size'), ('Color', 'Color'), ('Size-Color', 'Size-Color'), ) article_author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, max_length=200, on_delete=models.CASCADE) title = models.CharField('العنوان', max_length=9500) slug = models.SlugField(max_length=250, allow_unicode=True, unique =True) image = models.FileField( upload_to = 'Images', blank=True) price = models.DecimalField(max_digits=12, decimal_places=2,default=0) variant=models.CharField(max_length=10,choices=VARIANTS, default='None') posted_on = models.DateTimeField(auto_now=False, auto_now_add=True) updated_on = models.DateTimeField(auto_now=True, auto_now_add=False) read = models.PositiveIntegerField(default=0, verbose_name='Vu') publish = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Add_Product, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('home:show_product', kwargs={'id':self.id, 'slug': self.slug}) class PostImage(models.Model): post_images … -
Django, create action over a model with m2m field linked to a model with custom private key
I've these two models: class Vehicle(models.Model): """Vehicle object.""" plate = models.CharField(max_length=255, primary_key=True) brand = models.CharField(max_length=255) model = models.CharField(max_length=255) owner = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) class Center(models.Model): """Center object.""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) name = models.CharField(max_length=255) vehicles = models.ManyToManyField('Vehicle', related_name='vehicle_plate') In my unit test, if I do: def test_create_center_with_existing_vehicles(self): """Test creating a center with existing vehicle.""" vehicle_1 = Vehicle.objects.create(user=self.user, plate='ab123cd', brand='brand', model='model', owner='bla bla') payload = { 'name': 'first center', 'vehicles': [{'plate': 'ab123cd', 'brand': 'brand', 'model': 'model', 'owner': 'bla bla'}] } res = self.client.post(CENTERS_URL, payload, format='json') I get an error: {'vehicles': [{'plate': [ErrorDetail(string='vehicle with this plate already exists.', code='unique')]}, {}]} I can't intercept the flow in my CenterView, perform_create() is not interpelled neither the serializer. Is there a validation step ? Could I override them, like the method 'get_or_create()' ? Thanx, I'm a beginner ... A way to intercept the validation step, by overriding. -
Django query __startswith is not case sensitive
I have been testing user searching with sorted results and I found this strange behavior >>> User.objects.filter(username__istartswith="AbC") <QuerySet [<User: AbC>, <User: AbCuuu>, <User: abc>, <User: abcuuu>]> >>> User.objects.filter(username__startswith="AbC") <QuerySet [<User: AbC>, <User: AbCuuu>, <User: abc>, <User: abcuuu>]> Shouldn't __startswith only have 2 of those results? I need to actually search with case sensitivity, how do I do that? I expect __startswith to be case sensitive and __istartswith to be case insensitive, but both return the same, case insensitive QuerySet -
How to aggregate over Django Jsonfield values?
I have a JsonField (col1) in a Model (model1) which contains values like below: {"key_1":"val_1", "key_2":"{\"sub_key1\":sub_val1, \"sub_key2\":sub_val2}"} I would like to aggregate sub_key1 and sub_key2. I tried below in Python but it does not work. from django.db.models import FloatField, JSONField from django.db.models import Sum, Value from django.db.models.functions import Cast ## try 1 model1.objects.annotate(val=Cast('col1__key_2__sub_key1', FloatField())).aggregate(op=Sum('val')) ## try 2 model1.objects.annotate( val=Cast('col1__key1', JSONField())).annotate( val_2=Cast('val__sub_key1', FloatField())).aggregate(op=Sum('val_2')) Is there a way I can aggregate over these sub keys? -
Handling user images in a web app - format, rotate?
everyone, in my web app (Python - Django) users should be able to upload pictures in the future, which will then be displayed in their own profile (like a Facebook picture post). Accordingly, there will be a file input in which the user can select his image. The image must then be displayed directly, as the user may want to upload several images. Since I'm not familiar with image editing, I'm asking myself a few questions. Currently I send the image to my server via Ajax, compress it and scale it to 400x400 px. if the picture doesn't fit the format, i crop it accordingly, certainly not the prettiest option, because if it doesn't fit, i crop from the middle. Then I save the image, and return the URL and render it. Everything works as desired, I'm just not sure if it's really good. For example, how do I deal with images in landscape format? How do I let the user rotate the picture? For this I would have to save it unchanged, render it and then ask the user? How can I open the "Open camera" function for smartphones? Is this possible in a "normal" mobile website version (or … -
Django modules errors and tests
I have some problems with Django. My application works fine but my IDE (Pycharm) considers it a mistake. To be clear all of the applications are added to INSTALLED_APPS in settings.py enter image description here For example: enter image description here **And when I run the command ** > py manage.py test I am getting a list of errors in every application. I haven't written any tests. Even when I am adding some simple test like this: from django.test import TestCase class TestSimpleComponent(TestCase): def test_basic_sum(self): assert 1+1 == 2 It doesn't work and the output is still the same. Found 10 test(s). System check identified no issues (0 silenced). EEEEEEEEEE ====================================================================== ERROR: myshop.accounts (unittest.loader._FailedTest) ImportError: Failed to import test module: myshop.accounts Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\unittest\loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\unittest\loader.py", line 377, in _get_module_from_name import(name) ModuleNotFoundError: No module named 'myshop.accounts' ====================================================================== ERROR: myshop.api (unittest.loader._FailedTest) ImportError: Failed to import test module: myshop.api Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\unittest\loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\unittest\loader.py", line 377, in _get_module_from_name import(name) ModuleNotFoundError: No module named 'myshop.api' ====================================================================== ERROR: myshop.cart (unittest.loader._FailedTest) ImportError: Failed to import test module: myshop.cart Traceback … -
How can I implement polling the table and keep the filter applied to it? [Django-filter] [HTMX]
I need to filter my database while live updating it too. However, the current rendering doubles the form and resets the filter to show all the data. How can I filter my data and update it at the same time filter my data and update it at the same time filters.py import django_filters from django_filters import DateFilter from .models import CheckingStatus, Participant from django.db.models import Q class ParticipantFilter(django_filters.FilterSet): class Meta: model = Participant fields = '__all__' views.py def display_view(request): myFilter = ParticipantFilter(request.GET, queryset=Participant.objects.all()) data = myFilter.qs return render(request, 'display.html', {'data': data, 'myFilter': myFilter}) HTML <body> <form method ="get"> {{myFilter.form}} <button class "btn btn-primary" type = "Submit"></button> </form> <br><br> <div id="table-results" hx-get="/display" hx-trigger="every 2s"> <table border="1" class="table table-dark table-hover"> <thead> <th>First_name</th> <th>Last_name</th> <th>Age</th> <th>Checking Status</th> <th>Time</th> <th>Date</th> </thead> {% for k in data %} <tr> <td>{{k.first_name}}</td> <td>{{k.last_name}}</td> <td>{{k.age}}</td> <td>{{k.checking.checking_status}}</td> <td>{{k.checking.time}}</td> <td>{{k.checking.date}}</td> </tr> {% endfor %} </table> </div> </body> Thanks for your time -
How to create model's tables in MySQL?
I'm trying to replicate a PHP/Symfony project in Python/Django as a python learning exercise. Platform = Windows 10. The expected result is that a migrate command will add tables related to all of the entries in settings.py INSTALLED_APPS{...}. Instead, the migrate command adds all Django tables but none of the tables of models.py. What, then, must be done to allow migrate to add the 5 MySQL tables? Result: mysql> use diet_py; Database changed mysql> show tables; +----------------------------+ | Tables_in_diet_py | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | django_admin_log | | django_content_type | | django_migrations | | django_session | +----------------------------+ Following Django tutorial documentation, with slight modifications, I have these directories & files: Tree: ...DB1-PROJECT │ db.sqlite3 │ manage.py │ ├───diet │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ __init__.cpython-311.pyc │ │ │ └───__pycache__ │ admin.cpython-311.pyc │ apps.cpython-311.pyc │ models.cpython-311.pyc │ __init__.cpython-311.pyc │ └───mysite │ asgi.py │ settings.py │ urls.py │ wsgi.py │ __init__.py │ └───__pycache__ settings.cpython-311.pyc urls.cpython-311.pyc wsgi.cpython-311.pyc __init__.cpython-311.pyc ..\diet\models.py from … -
How to represent SVG polygon in HTML using deffinition coming from POSTGIS ST_AsSVG function
In my django app I have postgis database. I tried to get a polygon as a SVG, so I could represent that polygon in HTML using the SVG standard. I use the following query: SELECT ST_AsSVG(geom) from country_limit cl where cl.id=3; And It returned the following result: M -85.941653 -12.285635 L -85.941653 -12.291673 -85.927577 -12.291673 -85.927577 -12.285635 Z But when I try to represent that result inside an SVG, in HTML, It does not display the polygon. Here is my code. <svg height="210" width="400"> <path d="M -85.941653 -12.285635 L -85.941653 -12.291673 -85.927577 -12.291673 -85.927577 -12.285635 Z" /> </svg> How can I use the result from postgis ST_AsSVG to represent a geometry as SVG in HTML -
How can I send scrapy result to django views so that frontend can get scrapy result by axios?
I am planning making backend using django + scrapy. my goal is this. frontend(react) send 'get' methods by axios to django views endpoint. this activate scrapy to start crawling (spiders) send scraping result to django views. frontend get json result (scraped result, not jobid or log file) from twisted.internet import reactor import scrapy from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from scrapyApp.items import ScrapyappItem from scrapy.utils.project import get_project_settings class MySpider(scrapy.Spider): name = "quotes" def start_requests(self): urls = [ 'https://www.google.com', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): item = ScrapyappItem() item['title'] = response.css('title::text').get() yield item def show1(request): # configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s'}) configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s'}) runner = CrawlerRunner() d = runner.crawl(MySpider) d.addBoth(lambda _: reactor.stop()) reactor.run() # the script will block here until the crawling is finished return HttpResponse({"result":d}) -
Django 4 with Apache 2.4 on Ubuntu 22.04 initially loading but then stops working until Apache restart
I deployed my Django 4 project with a SQLITE3 DB using python 3.10 on an Ubuntu 22.04 Server instance on a virtual machine on my Synology NAS. I am using the WSGI module, which is to my knowledge the only way to do this, right? My Synology NAS has an Intel Celeron processes and 10GB RAM (2 cores and 6 GB are available to the virtual machine, I also tried first with 4 GB) Now after I managed that my website can be called and is displayed I am facing the issue that I can call any page initially I want and it displays as expected BUT then the browser tab indicates by a moving circle that still something is loading and I cannot navigate to any other URL within my application. even the language is displayed correctly depending on the browser language. It also happens that after I restarted apache the next page loaded. Doing this I was even able to login to the admin UI in 2 steps, so the database is obviously accessible. Meanwhile increased the log level to trace1 of the Apache server and now can see that after 5 minutes the process gets killed and … -
Django deploy beget.ru
I'm getting an error when I deploy my django project to beget.ru hosting enter image description here enter image descsription here -
Using Wagatil Admin widgets on Public Front end
I have Streamfields and some custom StructBlocks, StreamBlocks and RichText on wagatil Pages & Models. Which are very easy to edit when I'm logged in as an Admin. However I would like my end users to create and Edit these fields using the widgest available to me in the admin. How do i expose them to the public without giving them the ability to login to my admin? I cam across this article that looked promising but ultimatley I got an error and couldn't test. from wagtail.admin.forms.models import WagtailAdminModelForm class FeaturedImage(models.Model): date = models.DateField() class FeaturedImageForm(WagtailAdminModelForm): class Meta: model = FeaturedImage fields = ['date'] raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. What i want to know is am i working in the correct direction? If so how do I resolve the above error? -
DRF: Upload many similar files
I have created a user API for uploading documents. The link to the file is stored in license_* type fields, the document status is stored in license_*_status. models.py @deconstructible class User_directory_path(object): def __init__(self, prefix): self.prefix = prefix def __call__(self, instance, filename): return f'{instance.id}/{self.prefix}_{filename}' class Profile(models.Model): class DocumentStatus(models.TextChoices): NOT_UPLOADED = 'NOT_UPLOADED' ON_REVIEW = 'ON_REVIEW' ACCEPTED = 'ACCEPTED' id = models.CharField(primary_key=True, max_length=36, default=uuid.uuid4) license_0 = models.FileField(verbose_name='License(1)', storage=MinioBackend(bucket_name='django-backend-profiles-private', replace_existing=True), upload_to=User_directory_path('license_0'), max_length=255, null=True, blank=True) license_0_status = models.CharField(verbose_name='License(1) Status', max_length=15, choices=DocumentStatus.choices, default=DocumentStatus.NOT_UPLOADED) license_1 = models.FileField(verbose_name='License(2)', storage=MinioBackend(bucket_name='django-backend-profiles-private', replace_existing=True), upload_to=User_directory_path('license_1'), max_length=255, null=True, blank=True) license_1_status = models.CharField(verbose_name='License(2) Status', max_length=15, choices=DocumentStatus.choices, default=DocumentStatus.NOT_UPLOADED) license_2 = models.FileField(verbose_name='License(3)', storage=MinioBackend(bucket_name='django-backend-profiles-private', replace_existing=True), upload_to=User_directory_path('license_2'), max_length=255, null=True, blank=True) license_2_status = models.CharField(verbose_name='License(3) Status', max_length=15, choices=DocumentStatus.choices, default=DocumentStatus.NOT_UPLOADED) license_3 = models.FileField(verbose_name='License(4)', storage=MinioBackend(bucket_name='django-backend-profiles-private', replace_existing=True), upload_to=User_directory_path('license_3'), max_length=255, null=True, blank=True) license_3_status = models.CharField(verbose_name='License(4) Status', max_length=15, choices=DocumentStatus.choices, default=DocumentStatus.NOT_UPLOADED) license_4 = models.FileField(verbose_name='License(5)', storage=MinioBackend(bucket_name='django-backend-profiles-private', replace_existing=True), upload_to=User_directory_path('license_4'), max_length=255, null=True, blank=True) license_4_status = models.CharField(verbose_name='License(5) Status', max_length=15, choices=DocumentStatus.choices, default=DocumentStatus.NOT_UPLOADED) In this example, the user can submit 5 licenses. The field names are similar, only the postfix changes. Should I use this approach when uploading a large number of similar files? -
Hi guys, i'm new in python, why i can't call fuctions two time(in if and in else)?
class Get_Cost_Mixin: def get_name(self): if len(list(self.ingredients.split())) <= 1: call.get_cost() <------ call.get_price() <------ print(str(self.ingredients) + ' Smoothie') else: call.get_cost() <------ call.get_price() <------ print(str(self.ingredients) + ' Fusion') Hi guys, i'm new in python, why i can't call fuctions two time(in if and in else)? -
Django - models with relations to possibly nonexisting users
I am working on an enterprise LMS powered by Django REST framework. Authentication is done via Google OAuth 2.0 using the package drf-social-oauth2, and the target organizations for my software are schools and universities. Some models have foreign keys to the user model; however, due to the nature of my application, oftentimes a user may want to reference a user that isn’t present in the database yet. This happens because users are created in the database upon their first login in the application via OAuth, yet the person who wants to create a specific model instance referencing another user may want to do so before they’ve logged in for the first time: for example, a teacher may want to pre-enroll a list of students into their new course, but those users might not have logged in for the first time yet, and therefore might not exist in the database. I’ll give a concrete example with a model in my application: class UserCoursePrivilege(models.Model): """ Represents the administrative permissions a user has over a course. See logic.privileges.py for the available permissions. """ user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="privileged_courses", ) course = models.ForeignKey( Course, on_delete=models.CASCADE, related_name="privileged_users", ) allow_privileges = models.JSONField(default=list, blank=True) deny_privileges = … -
How to force link opening oustide of embedded browser / webview?
I setup a simple authentication system using python-social-auth-django. Everything is working fine on my computer and my mobile phone, but when I try to open login link from Messenger app with another phone (Huawei brand), the link opens inside Messenger's embedded browser and I get belows (same for Facebook and Google oauth). Searching around it has something to do with new policy disabling authentication from embedded browser such as Messenger embedded browser. What should I do either to force my login link to open outside of Messenger embedded browser or allow login with Facebook/Google oauth from WebViews browser ? You can't sign in from this screen because this app doesn't comply with Google's secure browsers policy. If this app has a website, you can open a web browser and try signing in from there. From my browser and own phone I open home link (from messenger app). This opens a browser window and login works fine. From another phone, when I click the messenger link, it opens in embedded browser. -
Next13 fetch to localhost:8000 does not work
Somehow the fetch from next13 doesnt work with Django on localhost:8001. I get the following error: TypeError: fetch failed at Object.processResponse (node:internal/deps/undici/undici:7188:34) at node:internal/deps/undici/undici:7516:42 at node:internal/process/task_queues:140:7 at AsyncResource.runInAsyncScope (node:async_hooks:202:9) at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { cause: Error: [object Object] at makeNetworkError (node:internal/deps/undici/undici:6317:51) at httpNetworkFetch (node:internal/deps/undici/undici:7810:16) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async httpNetworkOrCacheFetch (node:internal/deps/undici/undici:7703:33) at async httpFetch (node:internal/deps/undici/undici:7557:37) at async schemeFetch (node:internal/deps/undici/undici:7489:18) at async node:internal/deps/undici/undici:7342:20 at async mainFetch (node:internal/deps/undici/undici:7338:20) { [cause]: undefined } } TypeError: fetch failed at Object.processResponse (node:internal/deps/undici/undici:7188:34) at node:internal/deps/undici/undici:7516:42 at node:internal/process/task_queues:140:7 at AsyncResource.runInAsyncScope (node:async_hooks:202:9) at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { digest: '1117663215' with this code: import './globals.css' export default async function RootLayout({ children, }: { children: React.ReactNode }) { // const data = await fetch(`https://dummyjson.com/products/1`, { cache: 'force-cache' }); const data = await fetch(`http://localhost:8001/board/`, { method: 'GET', headers: { 'Accept': 'application/json', "Content-Type": "application/json" }, redirect: 'follow', cache: 'force-cache' }); console.log(data) return ( <html lang="en"> <head /> <body> <h1></h1> <div>{children}</div> </body> </html> ) } Fetching from any other public api works. CORS is enabled and CORS_ORIGIN_ALLOW_ALL = True is set in the Django settings.py Any idea how I can fix this? Thanks -
django queryset error when use len(qs) TypeError: argument must be int or float
I dont know what happened with my db but now I can not len my queryset. I can make a qs with a lot of obj with qs.SignalSma.objects.all() But somehow I can not use len(qs) on that qs or make a loop with that qs I am getting in this error if I try to do so. In [9]: len(qs) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[9], line 1 ----> 1 len(qs) File ~\OneDrive\Desktop\dev-2023\signal\lib\site-packages\django\db\models\query.py:262, in QuerySet.__len__(self) 261 def __len__(self): --> 262 self._fetch_all() 263 return len(self._result_cache) File ~\OneDrive\Desktop\dev-2023\signal\lib\site-packages\django\db\models\query.py:1324, in QuerySet._fetch_all(self) 1322 def _fetch_all(self): 1323 if self._result_cache is None: -> 1324 self._result_cache = list(self._iterable_class(self)) 1325 if self._prefetch_related_lookups and not self._prefetch_done: 1326 self._prefetch_related_objects() File ~\OneDrive\Desktop\dev-2023\signal\lib\site-packages\django\db\models\query.py:68, in ModelIterable.__iter__(self) 59 related_populators = get_related_populators(klass_info, select, db) 60 known_related_objects = [ 61 (field, related_objs, operator.attrgetter(*[ 62 field.attname (...) 66 ])) for field, related_objs in queryset._known_related_objects.items() 67 ] ---> 68 for row in compiler.results_iter(results): 69 obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) 70 for rel_populator in related_populators: File ~\OneDrive\Desktop\dev-2023\signal\lib\site-packages\django\db\models\sql\compiler.py:1122, in SQLCompiler.apply_converters(self, rows, converters) 1120 value = row[pos] 1121 for converter in convs: -> 1122 value = converter(value, expression, connection) 1123 row[pos] = value 1124 yield row File ~\OneDrive\Desktop\dev-2023\signal\lib\site-packages\django\db\backends\sqlite3\operations.py:313, in DatabaseOperations.get_decimalfield_converter.<locals>.converter(value, expression, connection) 311 def converter(value, expression, connection): 312 … -
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
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 When I create a new django project, everything works as it should, but as soon as I change something, I get this error on any command in terminal. For example python manage.py runsever or python manage.py makemigrations....Any ideas?