Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve "Fatal Python error: Cannot recover from stack overflow."?
I'm new at Python and Django Web Framework and I am working on a small project to create a simple website. But while building the templates I had a problem when I want to run the web page. In my terminal it shows: Fatal Python error: Cannot recover from stack overflow. I think this is a python bug but I do not know how to fix it. Fatal Python error: Cannot recover from stack overflow. Thread 0x00001048 (most recent call first): File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589 in readinto File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 182 in handle_one_request File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 172 in handle File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720 in __init__ File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360 in finish_request File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650 in process_request_thread File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870 in run File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926 in _bootstrap_inner File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\threading.py", line 890 in _bootstrap Current thread 0x00000730 (most recent call first): File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\functional.py", line 204 in <genexpr> File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\functional.py", line 204 in wrapper File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 781 in __init__ File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 640 in __init__ File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 562 in compile_filter File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader_tags.py", line 265 in do_extends File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 475 in parse File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 194 in compile_nodelist File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 156 in __init__ File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loaders\base.py", line 30 … -
Separate profile for each user in django
I am very new in django and I have created the todo list web app but the problem is that the todo list created by user 1 can be seen by a user 2 and he can delete it and add items in list but I want separate todo list for each user -
Retrieve relationship properties with graphene-django and graphql from a graph (neo4j) database
Im trying to create a simple application (to create a graphql api using django and python). It's going well but im stuck with 1 problem and i have no idea how to go about it (ive been searching for days, but i simply give up) so i was hoping someone here could assist (see below what i have). Im using Django with graphene-django and neo4j as (graph)database. Also im using the relay schema. With graphql i can query all the properties of the products and its also possible to query over the relations (which product belongs to which category and vice versa). Now my problem is the following: In neo4j relations also have their own properties but i have no idea how to get these properties (for example i want to see when the relation was created, this is a property on the relation). I currently have 2 node types: Category and Product See models(models.py) below: class Category(StructuredNode): name = StringProperty() shortname = StringProperty() product = Relationship('Product','IN_CATEGORY') class Product(StructuredNode): name = StringProperty() price = StringProperty() description = StringProperty() category = Relationship('Category','IN_CATEGORY') Below is the graphene-django code that i use(schema.py): class CategoryType(DjangoObjectType): class Meta: model = Category neomodel_filter_fields = { 'name': … -
list comperhension error related object not found in my model
hello guys i have this script that update my table through ajax the data that it send through ajax its from my list comperhension but it seems i got this error "usermanager.models.mikrotik_new_client.id_line_client.RelatedObjectDoesNotExist:" i know it because it cant retrive the data from the class, because i set the id_line_client to Null, i do this so that the admin can confirm every new user in network, i try to set condition in the list comperhension to if the user id_line_client is not Null it can send the data, but it seems its not working at all, can anyone give me a tips how can i fix this condition in my list comperhension? thanks mate! here is my code. view.py def update_table_adduser(request): update_client = [{'id':data.id,'username':data.username,'waktu_pengajuan':str(data.waktu_pengajuan),'line_id':data.id_line_client.line_id} for data in mikrotik_new_client.objects.all() if data.id_line_client.line_id is not None] return HttpResponse(json.dumps(update_client)) model.py class mikrotik_new_client(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) money = models.IntegerField() waktu_pengajuan = models.DateTimeField(auto_now_add=True) id_line_client = models.ForeignKey(UserMessage,on_delete=models.CASCADE,blank=True) confirm_by_admin = models.BooleanField(default=False) def __str__(self): return self.username -
Django - UTC to Local Time Conversion fails
i want to convert my UTC time to my local time my settings.py TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True my models.py class UnauthorizedAccess(models.Model): UnauthorizedAccessId = models.AutoField(primary_key=True, db_column='UnauthorizedAccessId') Camera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='CameraId') AccessTime = models.DateTimeField() Description = models.CharField(max_length=250) class Meta: db_table = "UnauthorizedAccess" views.py from datetime import date, datetime from django.utils import timezone from tzlocal import get_localzone import pytz @api_view(['POST']) @permission_classes([]) def push_notification(request): cam_id = request.data.get("CameraId").strip() camera_ob = Camera.objects.get(CameraId=cam_id) unauthorized_entry = UnauthorizedAccess( Camera=camera_ob, AccessTime=timezone.now(), Description=unauthorized_access, ) unauthorized_entry.save() return Response({msg: validation["FDP25"]}, status=status.HTTP_200_OK) except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST) while saving i tried AccessTime=datetime.now(tz=timezone.utc) and AccessTime=datetime.now() now i am using timezone.now() my data base saved the data and i tried retrieving my data my views.py from datetime import date, datetime from django.utils import timezone from tzlocal import get_localzone import pytz @api_view(['GET']) @permission_classes([]) def notification(request): try: unauthorizedaccess_details = list() tz = get_localzone() notification_ob = UnauthorizedAccess.objects.all().order_by('-AccessTime')[:50] for ob in notification_ob: dev = Device.objects.get(Camera=ob.Camera) tz = get_localzone() localtz = ob.AccessTime.replace(tzinfo=pytz.utc).astimezone(tz) date_time = localtz.strftime("%d/%m/%Y %I:%M:%S %p") tz1 = ob.AccessTime.replace(tzinfo=pytz.UTC) localtz1 = tz1.astimezone(timezone.get_current_timezone()) date_time1 = localtz1.strftime("%d/%m/%Y %I:%M:%S %p") unauthorizedaccess_info = { 'id': ob.UnauthorizedAccessId, 'DeviceName': dev.DeviceName, 'Date': date_time, 'Date1': date_time1, 'Date2': ob.AccessTime, 'Date3': ob.AccessTime.strftime("%d/%m/%Y %I:%M:%S %p"), 'Access': ob.Description, 'Type': … -
Django Rest Framework - Filtering against the URL - get() got an unexpected keyword argument 'username'
I have a django model Messages and I want to filter the messages against a url parameter: the username of the author of the message. But I get: TypeError at /inbox-data/johndoe/ get() got an unexpected keyword argument 'username' url(r'^inbox-data/(?P<username>.+)/$', InboxApiView.as_view()) class InboxApiView(ListAPIView): def get(self, request, format=None): url_param = self.kwargs['username'] own_mx = Message.objects.filter(sender=url_param) mx_serializer = MXSerializer(own_mx, many=True) message_data = mx_serializer.data data = { 'message_data': [{ 'content' : md['content'], 'sender' : md['sender'], 'recipient' : md['recipient'], 'sent_at' : md['sent_at'], 'read_at' : md['read_at'] } for md in message_data], } return Response(data) class MXSerializer(ModelSerializer): sender = SerializerMethodField() recipient = SerializerMethodField() class Meta: model = Message fields = '__all__' def get_sender(self,obj): return str(obj.sender.username) def get_recipient(self,obj): return str(obj.recipient.username) I am following this documentation: https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-url Traceback (most recent call last): File "/Library/Python/3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Python/3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Python/3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Python/3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Python/3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Library/Python/3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/Library/Python/3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/Library/Python/3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/Library/Python/3.7/site-packages/rest_framework/views.py", line 502, in … -
Why does posting Image with data using axios to django-rest-framework gives 404 error?
1 I am using django-rest-framework and posting the data but it gives me 404 error only if I add image to it. Without image, the data is posted and modelviewset works perfectly but with a image it returns me 404 as shown in picture My urls.py: router = routers.SimpleRouter() router.register(r'users', UserView, 'user') router.register(r'teachers', TeacherView, 'teacher') router.register(r'students', StudentView, 'student') router.register(r'classes', ClassView, 'class') router.register(r'subjects', SubjectView, 'subject') router.register(r'institutes', InstituteView, 'institute') router.register(r'enrolls', EnrolledView, 'enrolled') router.register(r'quizes', QuizView, 'quizes') router.register(r'questions', QuestionView, 'questions') router.register(r'options', OptionView, 'options') router.register(r'answers', AnswerView, 'answers') router.register(r'attemptedQuestions', AttemptedQuestionView, 'attemmptedQuestion') router.register(r'attemptedQuizes', AttemptedQuizesView, 'attemptedQuizes') urlpatterns = router.urls My views.py: class QuizView(viewsets.ModelViewSet): serializer_class = QuizSerializer queryset = Quiz.objects.all() class QuestionView(viewsets.ModelViewSet): serializer_class = QuestionSerializer queryset = Question.objects.all() class OptionView(viewsets.ModelViewSet): serializer_class = OptionSerializer queryset = Option.objects.all() class AnswerView(viewsets.ModelViewSet): serializer_class = AnswerSerializer queryset = Answer.objects.all() class AttemptedQuizesView(viewsets.ModelViewSet): serializer_class = AttemptedQuizesSerializer queryset = attempted_quizes.objects.all() class AttemptedQuestionView(viewsets.ModelViewSet): serializer_class = AttemptedQuestionSerializer queryset = attempted_question.objects.all() -
How to increase expiry date/time of Google Cloud Storage Objects in Django
I have a Django REST API that uses the storages.backends.gcloud.GoogleCloudStorage as its DEFAULT_FILE_STORAGE. I noticed that media files (e.g. profile pictures of users) retrieved from any API has an Expires value in the URL. Here's a sample URL to a file: https://storage.googleapis.com/<BUCKET_NAME>/users/a96db2f0-99a0-4691-aadb-708dc5268f77.png?Expires=1597840065&GoogleAccessId=<ACCESS_ID>&Signature=<SIGNATURE> If I convert that to an actual date, it's actually 24 hours from the time it was requested. How do I increase that to a very big time (e.g. 1 year)? -
How to check for available rooms in hotel by checking for the non booked rooms first [closed]
I have already create the function but I blame is I can booked for the same room for a same window of time . I seems like the function is ignoring the new bookings enter by the user. -
Celery scheduling performance with Django and multi-tenancy
I am working on a project and am looking for the best way to implement the following: our customers need to be able to specify an action that happens anywhere in the future. They also need to be able to cancel it (before it runs). It is a large task so it needs to be asynchronous. The frequency of this happening would be once every few days at most. I made a periodic task that looks at the database every hour if there are upcoming actions we need to perform in the next 2 hours (1 hour overlap). If an action is found I call apply_async and specify an ETA to schedule a task. I don't do it once daily because we use Redis and Redis cannot handle task scheduling further than 12 hours in advance because of the visibility timeout. The problem I see with this approach is that it's a bit complex and I need to implement a way to cancel an already scheduled task (revoke). Handling crashed wouldn't be such a big problem since the tasks are persistent. An alternative is to just run a periodic task every minute that immediately schedules a task (just in time). … -
celery task calls another microservice api - authentication
I have a Django system that contains several microservice projects. I'm using djangorestframework-sso for authentication between them. In one of my microservices I have a celery task that calls an api function from another microservice. The call fails because the authentication headers are not provided. I tried using the celery task to inject the wanted headers but it didn't help: class MyTask(Task): abstract = True def apply_async(self, args=None, kwargs=None, task_id=None, producer=None, link=None, link_error=None, **options): """ invoked either directly or via .delay() to fork a task from the main process """ token = 'XXX' options['headers'] = options.get('headers', {}) options['headers'].update({ 'Authorization': 'Bearer ' + token, }) return super(MyTask, self).apply_async( args, kwargs, task_id, producer, link, link_error, **options) The requests are made using python's requests library. So I thought trying to catch all requests and inject the headers before they are executed. Don't know how to do that. Any help will be appreciated. -
How to properly test my consumer class, so a user can log in, using selenium, pytest-asyncio and pytest-django?
I want to test my consumer class. So I have followed Django Channels doc on testing consumers. I have installed pytest-django and pytest-asyncio. But I need to log in before I connect to the site. So I am trying to use selenium and Django client to login and put the cookie in the headers of the consumer. But I am missing something because django.core.exceptions.SynchronousOnlyOperation is raised. I am using database_sync_to_async when I am creating user with FactoryBoy in a fixture. In my test function I am trying to use the database_sync_to_async marker before calling client.login. But that raises the error. When I mark the function with database_sync_to_async instead pytest does not collect my test. And when I logged in and tried to add the cookie to selenium in the fixture and then put it in the header in the test function I get keyerror: sessionid. (The outcommented code). So how to properly test my consumer class, so a user can log in? My code is the following: 1 import pytest 2 from channels.db import database_sync_to_async 3 from asgiref.sync import sync_to_async 4 from channels.testing import WebsocketCommunicator 5 from django.test import Client 6 7 from selenium.webdriver.firefox.webdriver import WebDriver 8 from selenium.webdriver.support.wait import … -
Post JSON data in five different models with single api call in django rest framework - Modelviewset
I have json data, which has to be posted on 5 different models with one API call, can we do it with modelviewset. { nesting : { nesting_id = "<id_onlyForEDIT>", nesting_description = "<CharField_notnull>", nesting_plan_date = "<DateField_nullOK>", nesting_file = "<ImageField_nullOK>", project = "<FK_project_id_notnull>", burning_weight = "<DecimalField_nullOK>", is_production_ready = "<BooleanField_nullOK>" } plan_raw_material : { plan_raw_material_id = "<id_onlyForEDIT>", nesting = "<FK_project_id_notnull>", raw_material_grade = models.ForeignKey(MaterialGrade, models.DO_NOTHING, blank=True, null=True) raw_material_project = models.ForeignKey('Project', models.DO_NOTHING, blank=True, null=True) raw_material_facility = models.ForeignKey(Facility, models.DO_NOTHING, blank=True, null=True) part_type = models.ForeignKey(PartType, models.DO_NOTHING) material_type_id = models.CharField(max_length=50) raw_material_name = models.CharField(max_length=100) raw_material_description = models.CharField(max_length=200, blank=True, null=True) raw_material_diameter = models.DecimalField(max_digits=15, decimal_places=3, blank=True, null=True) raw_material_length = models.DecimalField(max_digits=15, decimal_places=3, blank=True, null=True) raw_material_width = models.DecimalField(max_digits=15, decimal_places=3, blank=True, null=True) raw_material_thickness = models.DecimalField(max_digits=15, decimal_places=3, blank=True, null=True) raw_material_unit_quantity = models.DecimalField(max_digits=15, decimal_places=3, blank=True, null=True) raw_material_uom = models.CharField(max_length=25, blank=True, null=True) } plan_scrap : { plan_scrap_id = models.AutoField(primary_key=True) nesting = models.ForeignKey(NestingPlan, models.DO_NOTHING, blank=True, null=True) plan_raw_material = models.ForeignKey(PlanRawMaterial, models.DO_NOTHING, blank=True, null=True) scrap_desc = models.CharField(max_length=250) scrap_weight = models.DecimalField(max_digits=15, decimal_places=3, blank=True, null=True) scrap_image = models.BinaryField(blank=True, null=True) } plan_part : { planning_part_id = models.AutoField(primary_key=True) nesting = models.ForeignKey(NestingPlan, models.DO_NOTHING, blank=True, null=True) plan_part = models.ForeignKey(Part, models.DO_NOTHING, blank=True, null=True) plan_raw_material = models.ForeignKey('PlanRawMaterial', models.DO_NOTHING, blank=True, null=True) } plan_offcut : { plan_offcut_id = models.AutoField(primary_key=True) nesting = models.ForeignKey(NestingPlan, models.DO_NOTHING, blank=True, null=True) plan_raw_material = models.ForeignKey('PlanRawMaterial', models.DO_NOTHING, … -
How to upload images to S3 using django
I am trying to upload an image from the django admin interface to AWS S3. AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID ') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY ') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME ') AWS_S3_REGION_NAME = 'us-west-2' AWS_S3_CUSTOM_DOMAIN = '%s.s3.us-west-2.amazonaws.com' % (AWS_STORAGE_BUCKET_NAME) AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } STATICFILES_STORAGE = 'kti.storages.S3Storage' AWS_S3_FILE_OVERWRITE = False AWS_DEFUALT_ACL = None STATICFILES_DIRS = [ os.path.join(AWS_S3_CUSTOM_DOMAIN, 'mysite/static'), ] STATIC_URL = 'https://%s' % (AWS_S3_CUSTOM_DOMAIN) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' This is what I have in my settings.py and when I upload an image the URL it gets is perfectly fine when I checked it but the image isn't uploaded in S3. I followed a couple of tutorials such as this and this, but all were in vain. I know it is an easy fix but cant figure it out. Thanks! -
Docker Database acces denied
I'm trying to run Pretix on my server using this docker-compose.yml. I've just changed the the traefik labels to my nginx environment variables and adjusted the external network to match with my nginx network, but everything else is the same. But when I go to my website, I just see the pretix logo with an internal server error message. When I browse my logs, I see that the pretix_app cannot connect to the database, but I don't really understand why. pretix_app | django.db.utils.OperationalError: (1045, "Access denied for user 'db'@'172.20.0.24' (using password: YES)") Full logs: db_1 | 2020-08-18 11:22:37+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 1:10.5.5+maria~focal started. db_1 | 2020-08-18 11:22:37+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql' db_1 | 2020-08-18 11:22:37+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 1:10.5.5+maria~focal started. db_1 | 2020-08-18 11:22:38 0 [Note] mysqld (mysqld 10.5.5-MariaDB-1:10.5.5+maria~focal) starting as process 1 ... db_1 | 2020-08-18 11:22:38 0 [Note] InnoDB: Using Linux native AIO db_1 | 2020-08-18 11:22:38 0 [Note] InnoDB: Uses event mutexes db_1 | 2020-08-18 11:22:38 0 [Note] InnoDB: Compressed tables use zlib 1.2.11 db_1 | 2020-08-18 11:22:38 0 [Note] InnoDB: Number of pools: 1 db_1 | 2020-08-18 11:22:38 0 [Note] InnoDB: Using SSE4.2 crc32 instructions … -
Django Filter - Page not found (404)
Trying to use the django filter on my project but it gives me a 404 error. The views.py def produktside(request, pk, sk, lk): under_kategori = UnderKategori.objects.get(navn=lk) produkter = Produkt.objects.filter(under_kategori=under_kategori) leverandor_filter = ProduktFilter(request.GET, queryset=produkter) produkter = leverandor_filter.qs paginator = Paginator(produkter, 6) page = request.GET.get('page') paginator_produkter = paginator.get_page(page) context = {'produkter': produkter, 'leverandor_filter': leverandor_filter, 'paginator_produkter': paginator_produkter, } return render(request, 'frontend/produkt_side.html', context) The urls.py from django.urls import path from frontend.views import * urlpatterns = [ #Consept path('', startside, name='startside'), path('bygg/<str:pk>/', mellomkategori, name='mellom_kategori'), path('bygg/<str:pk>/<str:sk>/', underkategori, name='under_kategori'), path('bygg/<str:pk>/<str:sk>/<str:lk>/', produktside, name='produkt_side'), ] The filters.py import django_filters from frontend.models import Produkt class ProduktFilter(django_filters.FilterSet): class Meta: model = Produkt fields = '__all__' Ive folowed a tutorial but the diffence is that im using a paginator. Is it something to do with the paginater? Thanks for any answers! -
How to display product in POPup in Django?
I have some product lists, and there are a icon. If i click on icon then it's open a popup after click and each time single product is opening. Please let me know how i can display the clickable product in POPups. here is my views.py file... def product_view(request, slug): subcategories = SubCategory.objects.all() product = Product.objects.select_related('subcategory').get(slug=slug) response = {'subcategories':subcategories, 'product':product} return response and here is html code when i click on this icon then it's open a popup.. <a href="#" data-product={{mainproduct.id}} data-toggle="modal" data-target="#quick-view" title="Quick View"><i class="ti-search" aria-hidden="true"></i></a> here is popup code where i want to display the popup product after click....this is my base.html file..it's calling in all website pages <div class="col-lg-6 rtl-text"> <div class="product-right"> <h2>Product Name</h2> <h3>$ 65.00</h3> <ul class="color-variant"> <li class="bg-light0"></li> <li class="bg-light1"></li> <li class="bg-light2"></li> </ul> <div class="border-product"> <h6 class="product-title">product details</h6> <p>Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium</p> </div> <div class="product-description border-product"> <div class="size-box"> <ul> <li class="active"><a href="javascript:void()">s</a></li> <li><a href="javascript:void()">m</a></li> <li><a href="javascript:void()">l</a></li> <li><a href="javascript:void()">xl</a></li> </ul> </div> <h6 class="product-title">quantity</h6> <div class="qty-box"> <div class="input-group"><span class="input-group-prepend"><button type="button" class="btn quantity-left-minus" data-type="minus" data-field=""><i class="ti-angle-left"></i></button> </span> <input type="text" name="quantity" class="form-control input-number" value="1"> <span class="input-group-prepend"><button type="button" class="btn quantity-right-plus" data-type="plus" data-field=""><i class="ti-angle-right"></i></button></span></div> </div> </div> <div class="product-buttons"><a href="javascript:void()" class="btn btn-gradient btn-solid">add … -
LDAP settings from nginx to django
How to transfer ldap settings from nginx to django-auth-ldap? nginx settings: ldap_server YADRO { url ldap://testserver.com:389/dc=corp,dc=yadro,dc=com?sAMAccountName?sub?(objectClass=person); binddn "USERNAME"; binddn_passwd PASSWORD; group_attribute uniquemember; #group_attribute_is_dn on; #require valid_user; #require group "CN=Users,DC=yadro,DC=com"; connections 10; satisfy any; max_down_retries_count 10; referral off; my django settings: AUTH_LDAP_SERVER_URI = "ldap://testserver.com:389" AUTH_LDAP_BIND_DN = "USERNAME" AUTH_LDAP_BIND_PASSWORD = "PASSWORD" # AUTH_LDAP_USER_DN_TEMPLATE = 'dc=corp,dc=yadro,dc=com,uid=%(user)s' AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=corp,dc=yadro,dc=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email":"mail" } AUTHENTICATION_BACKENDS = [ "django_auth_ldap.backend.LDAPBackend", "django.contrib.auth.backends.ModelBackend", ] This does not work. Could you tell me exactly how I need to update the settings for authentication to work? -
How to post data to Django rest API
I have a Django model that looks like the following: [ { "ticker": "AAPL", "balance_sheet": [], "income_statement": [], "cash_flows": [] }, { "ticker": "MSFT", "balance_sheet": [], "income_statement": [], "cash_flows": [] } ] I want to add in the income_statement data using the requests.post function but cannot figure out how the data should be structured. I get a 400 BAD REQUEST response from the server. What is the problem ? r = requests.post('http://localhost:8000/stocks/', data={ 'ticker': 'MSFT', 'income_statement': [{ 'annualNetIncomeContinuousOperations': 45687000000, 'annualTaxEffectOfUnusualItems': 0, 'annualNetIncomeFromContinuingOperationNetMinorityInterest': 45687000000, 'annualTotalOperatingIncomeAsReported': 60024000000, ... , ... , ... }] } ) -
NOT NULL constraint failed: statussaver_post.user_id
class post(models.Model): content=models.TextField(null=True,blank=True) title = models.CharField(max_length=200,null=True,blank=True) vedio = models.FileField(upload_to='vedios', blank=True, null=True) img = models.ImageField(upload_to='images', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__(self): return self.title def userpost(request): if request.method=='POST': form=uploadform(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('home') else: form=uploadform() return render(request,'statussaver/u.html',{'form':form,}) from django import forms from .models import post class uploadform(forms.ModelForm): class Meta: model=post fields= 'all' enter code here -
Django, connecting channels websocket with signals
I have a Channels web socket, I'm trying to add a signal from another app so when an event is created the WebSocket would send a message according to the logic it has. When I first connect the WebSocket the function runs properly, when I'm adding a new object of the sender model I get an error. consumer: class CameraOnlineConsumer(JsonWebsocketConsumer): def connect(self): self.accept() return self.send(json.dumps({"type": "websocket.accept", "send": "Connected Successfully"})), self.camera() def camera(self): result = self.check_events() print("new event") return self.send(json.dumps({ "type": "websocket.send", "send": result })) def get_events(self): return PastureEvent.objects.filter(result=8, farm_id='1', processed=False).order_by('-time_stamp')[:2] def check_events(self): minute_delta = timedelta(seconds=60) query_set = self.get_events() if not query_set: result = {'camera status': CameraOffline.default_detail, } return result elif len(query_set) == 1: # means that no new events has been recorded since last check. result = {'camera status': CameraOnline.default_detail, 'first time_stamp': str(query_set[0].time_stamp)} return result elif len(query_set) >= 2: # two relevant events received. difference = query_set[0].time_stamp - query_set[1].time_stamp if difference <= minute_delta: if query_set[1]: # query_set[1].processed = True & query_set[1].save() didn't work, why? PastureEvent.objects.select_for_update().filter(id=query_set[1].id).update(processed=True) else: pass # time difference between them is under/equal to the desired time difference between events. result = {'camera status': CameraOnline.default_detail, 'first time_stamp': str(query_set[0].time_stamp), 'last time_stamp': str(query_set[1].time_stamp)} return result else: if query_set[1]: PastureEvent.objects.select_for_update().filter(id=query_set[1].id).update(processed=True) else: pass … -
How to create a log database in django to record the user that created, updated or deleted an object?
I'm facing a difficulty recording the user in database who created, updated or deleted an object. I've found a simple solution with threadlocal and a logging abstract class that is not usually recommended here: Why is using thread locals in Django bad? . Here the main problem with this solution is it is extremely difficult writing any test case. So what would be a perfect solution. -
MainList is missing a QuerySet. Define MainList.model, MainList.queryset, or override MainList.get_queryset()
Hi there I am trying to have a homepage where I can list from a model called Lecturer and create forms from a model called DistributionForm. I tried it with the CreateView but I got the error MainList is missing a QuerySet. Define MainList.model, MainList.queryset, or override MainList.get_queryset(). in the that the queryset is missing. Can you please help me. Views.py class MainList(generic.CreateView): template_name='home.html' form=DistributionForm models=Lecturer fields=['distribution','semester','lecture','lecturer'] success_url = "/home" def form_valid(self,form): form.instance.author=self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context ['lecturer_list'] = Lecturer.objects.order_by('lecturer') return context urls.py from django.urls import path from . import views from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name='distribution' urlpatterns=[ path('home/',views.MainList.as_view(),name='home'), path('hocalar/<slug:slug>/',views.LecturerDistribution.as_view(),name='lecturer_distribution'), path('dersler/<slug:slug>/',views.LectureDistribution.as_view(),name='lecture_distribution'), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and my home.html {% extends "base.html" %} {%block content%} {% load crispy_forms_tags %} <div class="container"> <div class="form-group pull-right"> <input type="text" class="search form-control" placeholder="Ara"> </div> <span class="counter pull-right"></span> <table class="table table-hover results"> <thead> <tr> <th >Hoca</th> <th >Ders</th> </tr> <tr class="warning no-result"> <td><i class="fa fa-warning"></i> Sonuç Yok</td> </tr> </thead> <tbody> {%for lec in lecturer_list%} <tr> <td> <p ><a style="text-decoration:none" href="{% url 'distribution:lecturer_distribution' slug=lec.slug%}">{{lec.lecturer}}</a></p> </td> <td> {%for ders in lec.lecture.all%} <a style="text-decoration:none" href="{% url 'distribution:lecture_distribution' slug=ders.slug%}">{{ders.lecture}}</a>, {% endfor%} </td> </tr> {%endfor%} … -
Django #hashtags in url
Sooo what am trying to do is a link on CONTACT to redirect to HOME and scroll down to some content, but dont know how to pass # in urls in django. Any help appreciated. The scroll is fine on home but cant get it to work from contact. URL path('/#products', HomeView.as_view(), name='products'), CONTACT.html <a class="nav-link" href="{% url 'core:products' %}">Produkty</a> HOME.html this is in navbar <a class="nav-link" style="cursor: pointer" onclick="window.location.href='#products'">Products</a> this is where i want it scrolled <a class="anchor" id="products"></a> -
Python-social-auth cannot refresh token
I use social-app-django(Spotify) and recently this piece of code started throwing an error: strategy = load_strategy() social.refresh_token(strategy) Gives error: requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.spotify.com/api/token How to fix?