Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Paypal webhook event on re-subscription
I have implemented a Paypal webhook in Django. I have difficulty keeping track of resubscription on Paypal. I am trying to use the "PAYMENT.SALE.COMPLETED" event and I have seen other questions which suggest using the same event but the next billing date (next_billing_date) in my database does not change. Please see the code below, can you tell me what I am doing wrong or do I need to use some other event. def paypal_webhooks(request): try: if "HTTP_PAYPAL_TRANSMISSION_ID" not in request.META: return Response(status=400) auth_algo = request.META['HTTP_PAYPAL_AUTH_ALGO'] cert_url = request.META['HTTP_PAYPAL_CERT_URL'] transmission_id = request.META['HTTP_PAYPAL_TRANSMISSION_ID'] transmission_sig = request.META['HTTP_PAYPAL_TRANSMISSION_SIG'] transmission_time = request.META['HTTP_PAYPAL_TRANSMISSION_TIME'] event_body = request.body.decode(request.encoding or "utf-8") valid = notifications.WebhookEvent.verify( transmission_id=transmission_id, timestamp=transmission_time, webhook_id=webhook_id, event_body=event_body, cert_url=cert_url, actual_sig=transmission_sig, auth_algo=auth_algo, ) if not valid: return Response(status=400) webhook_event = json.loads(event_body) event_type = webhook_event["event_type"] # payment completed if event_type == "PAYMENT.SALE.COMPLETED": subscription_id = webhook_event['resource']['id'] subscription = Subscriptions.objects.filter(subscriptionID=subscription_id).last() if subscription: subscription.active = True subscription.active_billing = True subscription.next_billing_date = webhook_event['resource']['billing_info']['next_billing_time'][:10] subscription.save() # subscription cancelled if event_type == "BILLING.SUBSCRIPTION.CANCELLED": subscription_id = webhook_event['resource']['id'] subscription = Subscriptions.objects.filter(subscriptionID=subscription_id).last() if subscription: subscription.active_billing = False subscription.save() # subscription failed if event_type == "BILLING.SUBSCRIPTION.PAYMENT.FAILED": subscription_id = webhook_event['resource']['id'] subscription = Subscriptions.objects.filter(subscriptionID=subscription_id).last() if subscription: subscription.active = False subscription.active_billing = False subscription.save() PaymentMethods.resub_free(subscription.user) return Response({"success": True}, status=200) except Exception as e: return … -
Is it standard to set is_authenticated to True in Django?
I'm fairly new to Django and I use Django 4.2. I am making a website and I've been stuck in the logout logic. I'm confused as to whether I should have set the is_authenticated field to True by default in the models.py file. I've googled a lot but I run don't understand how to really authenticate users in login and logout. Can anyone help me understand the logic? Where do I use login decorators and how do I set the field is_authenticated to true during login and false during logout -
django-dotenv not working in Django version> 4.0
When i try to import django-dotenv module it's throwing error like "No Module Named 'dotenv'". even after installing the module using pip install django-dotenv in my virtual environment (OS: Win10). enter image description here I go through some of the documentation where they mention this error will occurs when you are using both 'python-dotenv' & 'django-dotenv'. but in my case i have only installed 'django-dotenv' package. Please let me know for how to get rid of this issue. Thanks! -
time data '2023-04-15T16:22:03.721461+05:00' does not match format "%Y-%m-%dT%H:%M:%S.%f+%Z'"
I get my data from drf as json and ther my datetime looks like: `'2023-04-15T16:22:03.721461+05:00'` but i want show datetime in template like: `'15-04-2023 16:22'` so i use tamplatetag: # app/templatetags/event_extras.py @register.filter(expects_localtime=True) def parse_iso(value): return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f+%Z'") and html like: {% load event_extras %} <th>{{r.datetime|parse_iso}|date:'d/m/Y H:M'}</th> but got this error: time data '2023-04-15T16:22:03.721461+05:00' does not match format "%Y-%m-%dT%H:%M:%S.%f+%Z'" -
Fetching API from django rest framework for functionality
I have probably jumped the gun by doing this with my current knowledge, but I have built a an API on the back end of my app with django rest frame work. I have built all the front end templates etc, the only thing I am missing is fetching the API for functionality. I am looking for some one to point me in the right direction as to what i do next, for example how to make my cart functional on the font end. My current code for my Cart: API VIEWS: class CartViewSet(CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, GenericViewSet): queryset = Cart.objects.prefetch_related('items__product').all() serializer_class = CartSerializer class CartItemViewSet(ModelViewSet): http_method_names = ['get', 'post', 'patch', 'delete'] def get_serializer_class(self): if self.request.method == 'POST': return AddCartItemSerializer elif self.request.method == 'PATCH': return UpdateCartItemSerializer return CartItemSerializer def get_serializer_context(self): return {'cart_id': self.kwargs['cart_pk']} def get_queryset(self): return CartItem.objects \ .filter(cart_id=self.kwargs['cart_pk']) \ .select_related('product') SERIALIZERS class CartItemSerializer(serializers.ModelSerializer): product = SimpleProductSerializer() total_price = serializers.SerializerMethodField() def get_total_price(self, cart_item:CartItem): return cart_item.quantity * cart_item.product.price class Meta: model = CartItem fields = ['id', 'product', 'quantity', 'total_price'] class CartSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) items = CartItemSerializer(many=True, read_only=True) total_price = serializers.SerializerMethodField() def get_total_price(self, cart): return sum([item.quantity * item.product.price for item in cart.items.all()]) class Meta: model = Cart fields = ['id', 'items', 'total_price'] … -
How to make htmx colour animations work with Django?
I have a simple Django project. I'm trying to get this example HTMX colour changing element working. https://htmx.org/examples/animations/ I have copied and pasted the exact code they use into my Django index.html file: <style> .smooth { transition: all 1s ease-in; } </style> <div id="color-demo" class="smooth" style="color:red" hx-get="/colors" hx-swap="outerHTML" hx-trigger="every 1s"> Color Swap Demo </div> <script> var colors = ['blue', 'green', 'orange', 'red']; onGet("/colors", function () { var color = colors.shift(); colors.push(color); return '<div id="color-demo" hx-get="/colors" hx-swap="outerHTML" class="smooth" hx-trigger="every 1s" style="color:' + color + '">\n'+ ' Color Swap Demo\n'+ '</div>\n' }); </script>``` This prints out the following: https://i.stack.imgur.com/VOJny.png But unlike what is shown in the demo, it doesn't change colours every 1 second. My command line for the Django server keeps throwing this error every 1 second: https://i.stack.imgur.com/TrZoo.png Why is this happening and how can I fix this? -
How can I display photos stored on Amazon S3 with Subquery code of Django?
I deployed a Web App made by Django to AWS and stored media files to Amazon S3. But when I use Subquery code I wrote below, I can not get the media files and correct urls of Amazon S3. What should I change my code? user = get_object_or_404(MyUser, pk=5) subqs = ItemPhoto.objects.filter(item=OuterRef('item')).filter(priority=1) queryset = Order.objects.prefetch_related( Prefetch( 'orderdetail_orderid', queryset=OrderDetail.objects.select_related('order', 'item').annotate( item_photos=Subquery(subqs.values('photo')), ), to_attr='oor', ), ).filter(user=user).order_by('-created_at') photos1 = [item.item_photos for order in queryset for item in order.oor] #[sh/Gold Ship/76e91e2d048147c9939d099224e09554.jpg, sh/Epiphaneia/9476dcb430754049b16c62949ecd3839.jpg] photos2 = [item.item_photos.photo for order in queryset for item in order.oor] # Traceback (most recent call last): # File "<console>", line 1, in <module> # File "<console>", line 1, in <listcomp> # AttributeError: 'str' object has no attribute 'photo' item_photos = ItemPhoto.objects.all() photos3 = [p.photo for p in item_photos] #[<ImageFieldFile: sh/Gold Ship/76e91e2d048147c9939d099224e09554.jpg>, <ImageFieldFile: sh/Epiphaneia/9476dcb430754049b16c62949ecd3839.jpg>] photos4 = [p.photo for p in item_photos] # templates can display photos with these urls #['https://xxxxx.s3.xxxxx.amazonaws.com/media/sh/Gold%20Ship/76e91e2d048147c9939d099224e09554.jpg, 'https://xxxxx.s3.xxxxx.amazonaws.com/media/sh/Epiphaneia/9476dcb430754049b16c62949ecd3839.jpg'] models.py def get_itemimage_path(instance, filename): prefix = 'sh{}{}{}'.format(os.sep, instance.item, os.sep) name = str(uuid.uuid4()).replace('-', '') extension = filename.split('.')[-1] return '{}{}.{}'.format(prefix, name, extension) class ItemPhoto(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="item_photo", verbose_name="item_id",) photo = models.ImageField("item_photo", blank=True, upload_to=get_itemimage_path) priority = models.IntegerField("priority",) template.html <img src="{{ item.item_photos }}"> # src="sh/Gold Ship/76e91e2d048147c9939d099224e09554.jpg" <- I can not get photo with … -
showing identation fault even though it is idented
def gen_frames(): cap = cv2.VideoCapture(0) while True: success, frame = cap.read() if not success: break ret, buffer = cv2.imencode('.jpg', frame) frame = buffer.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') if request.method == 'POST': msg = request.POST.get('msg') if msg: save_path = os.path.join(save_folder, "captured_image.jpg") cv2.imwrite(save_path, frame) print(request.headers) return render(request,"account/captured.html",{}) cap.release() It keeps on saying TabError: inconsistent use of tabs and spaces in indentation The identation fault is at if request.method == 'POST': -
Any way to optimize my file and folder pattern
I am writing app, where i have folders and files component. I think the way it works is slow. I have 2 models: BookmarkFolder and Bookmark, they're connected through ForeignKey so each folder could have multiple bookmarks. In my template I've listed folders and I can open each by clicking on "Extend" button, it renders all files under it (I use htmx). list of folders. The problem is every time I open folder it makes query to database and it seems slow to me. How can I optimize it to work faster or maybe there's better ways to implement this folder and files pattern without using JS framework? -
In Django Template: display the sum of calculated variables
right now I wonder if there is a way to show up the sum of variables in a Django-Template. What I mean is, if i have variables of the same kind, is there a template-sided function to add them? I know, that the "logic" should be normally outside a template, so i wrote a function that does the calculation i want to see in the template: def mission_duration(self): duration = self.end - self.begin return duration.days and use it in template by {{ mission.mission_duration }} and it works fine. But if i have several of these variables in a template, is there an easy way to sum their values up and show the result? Right now, the variables are displayed by querying the database going through a for-loop. The result is likely to be displayed outside of the loop elswhere in the template... or on the other side: how can i put this on model/view.py to solve the problem outside the template? missions are in an oneToMany relationship table to "employees"...and normally data of employees are displayed. so for a model/view solution i have no idea at the moment, how to cycle to alle mission entries of an employee to build … -
Django filter - filter a property of a model through a range of values
I have this model class Person(models.Model): name = models.CharField(max_length=150) date_birth = models.DateField() and this property to calculate years and months of birth @property def eta_annimesi(self): date2 = datetime.combine(self.date_birth , datetime.min.time()) now = datetime.now() duration = (now.year - date2.year) * 12 + now.month - date2.month years = duration // 12 months = duration % 12 if years > 0: if months > 0: msg_anni = years.__str__() + ' anni ' +months.__str__() +' mesi' else: msg_anni = years.__str__() + ' anni' else: if months > 0: msg_anni = months.__str__() +' mesi' else: msg_anni = 'Appena nato' return msg_anni I need to create filters on an html page that allow me to create a range between two integer values. (e.g. from 0 to 2 years) If it were possible even months but it's not important. I managed it by giving the possibility to enter the range of two dates but that's not what I need. Ideas and suggestions? Thanks in advance to anyone who wants to give me a hand. I need to create filters on an html page that allow me to create a range between two integer values. (e.g. from 0 to 2 years) If it were possible even months but … -
picking django template variable from rendered template to use in javascript
I am still new to django and struggling with this issue : I have a price slidebar in html that i picked up from a template. In html, the bar looks like this : <div class="price-range ui-slider ui-corner-all ui-slider-horizontal ui-widget ui-widget-content" data-min="33"" <!-- to replace with :{{ price_max.product_price__max }}" --> data-max="15" ></div> <div class="range-slider"> <div class="price-input"> <p>Prix:</p> <input type="text" id="minamount" /> <input type="text" id="maxamount" /> </div> </div> </div> <a href="#">Filter</a> I upload price_max and also price_min correctly from the view as they can be directly displayed on the webpage as text. But the slidebar uses javascript to be rendered and picks up those data-min and data-max values to display the dynamic result like this : enter image description here the javascript: /*------------------- Range Slider --------------------- */ var rangeSlider = $(".price-range"), minamount = $("#minamount"), maxamount = $("#maxamount"), minPrice = rangeSlider.data('min'), maxPrice = rangeSlider.data('max'); rangeSlider.slider({ range: true, min: minPrice, max: maxPrice, values: [minPrice, maxPrice], slide: function (event, ui) { minamount.val( ui.values[0]+'€'); maxamount.val( ui.values[1]+'€'); } }); minamount.val( rangeSlider.slider("values", 0)+'€'); maxamount.val( rangeSlider.slider("values", 1)+'€'); replacing data-min and data-max by django templates variables doesn't work, i'm still unclear exactly why but i suppose it has to do with django rendering order. Another difficulty is that i … -
Trigger function when input field is changed programmatically
I have a slider which changes the value of the input fields named 'workload1' and 'workload2'. Having adjusted the slider, the form 'test-form1' should be submitted. (I do not have any submit button, and all my filtering option work with event listeners) After submitting the form, the page is reloaded, and the slider has to be set to the values the user has manually adjusted. So if someone moves the slider, the page is reloaded and the slider is at the same position as the person has moved it. In order to make this happen, I pass the 'workload_min' and 'workload_max' back to my template 'myfile.html'. Now the question is, how can I trigger the trigger the event listener when the slider is moved? I have tried with dispatchEvent(event), however, since the values are passed back to the template, the dispatchEvent(event) will be triggered again and again, in a endless reloading of the page. I have also tried with simple addEventListener('input', function ()) but the change of the input field, trough movement of the slider is not detected. Does someone know how to handle this problem? html: <input form="test-form1" type="text" name="workload1" id="workload1" readonly="readonly"> <input form="test-form1" type="text" name="workload2" id="workload2" readonly="readonly"> <div … -
How can I set this?
I am new to django. it is very important that django.contrib.staticfiles.finders.AppDirectoriesFinder be there in your STATICFILES_FINDERS. resource:https://django-admin-tools.readthedocs.io/en/latest/quickstart.html#installing-django-admin-tools Where are STATICFILES_FINDERS django.contrib.staticfiles.finders.AppDirectoriesFinder -
Django REST Framework - Weird Parameter Shape due to JSON Parser?
Currently I'm contacting my APIViews through AJAX requests on my frontend. config = { param1: 1, param2: 2, param3: 3 } $.ajax(APIEndpoints.renderConfig.url, { type: APIEndpoints.renderConfig.method, headers: { "X-CSRFToken": csrfToken }, data: { "config": config, "useWorkingConfig": true } } However, when I receive the data in my APIView, I get an object with the following shape: { "config[param1]": 1, "config[param2]": 2, "config[param3]": 3, "useWorkingConfig": true } According to different sources that I have checked, DRF does support nested JSON objects, so what am I missing? Is this something to do with the default behavior of the JSON Parser? It doesn't seem to be very useful, as you would basically need to preprocess the data before using your serializers (since they expect a nested structure). The same happens with lists, with your parameters being received as list_param[] instead of list_param. If its useful for anything, these are my DRF settings REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'EXCEPTION_HANDLER': 'django_project.api.exception_handler.custom_exception_handler', # Camel Case Package Settings 'DEFAULT_RENDERER_CLASSES': ( 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', 'djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer', ), 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'djangorestframework_camel_case.parser.CamelCaseFormParser', 'djangorestframework_camel_case.parser.CamelCaseMultiPartParser', 'djangorestframework_camel_case.parser.CamelCaseJSONParser', ], 'JSON_UNDERSCOREIZE': { 'no_underscore_before_number': True, }, } Its very probable that Im just missing something or its an intended behavior that Im not aware of. -
Modify the value of a model field during serialization
I have a system that is deployed on 7 servers, one of them we consider as the main server. For statistical reasons now I must synchronize the data. This presents a peculiarity, since one of the data of the model in the server has a value but in the other servers it is different. Example: clinic = 10 on the main server, but on the second server clinic = 34 I made an endpoint that will load the data from the other servers to the main server, for which I am getting the value of the clinic from an environment variable. I require that when serializing the data from the other servers, the clinic value is that of the environment variable and not that of the database. Main server models.py class MyModel(models.Model): clinic = models.IntegerField(verbose_name='Clinic', null=True, blank=True) profesional = models.CharField(max_length=12, blank=True, null=True, verbose_name='Profesional') user = models.ForeignKey(Users, verbose_name='User RCF', on_delete=models.PROTECT) creation_date = models.DateTimeField(auto_now_add=True, verbose_name='creation date') serializers.py class BaseSerializer(serializers.ModelSerializer): creation_date = serializers.DateTimeField() class Meta: extra_kwargs = { 'id': {'required': False} } class MyModelSerializer(AuditoriaBaseSerializer): class Meta(BaseSerializer.Meta): model = MyModel fields = '__all__' views.py class CreateManyMixin(CreateModelMixin): def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) … -
Delete an object from a Many-to-Many relationship
How can I delete an object from a Many-to-Many relationship with fetch? how can I change it? I have a model for users which has many-to-many field users that presents the followers of the same user: (followers = models.ManyToManyField("User", related_name="follow")) I'm trying to create a button in the profile of a person that other people can click on, and unfollow or follow. I have an event listener on that button, and let's say, this is the unfollow button and I want to remove the requesting user, who is saved in the variable user, from the followers' list of the user whose profile belongs to him. And the followers' list I can get when I am doing a fetch, and then I am getting all the info of the person whose profile belongs to him (the post.user) that the requesting user, the log-in one, wants to unfollow. My purpose is to update the people who follow after the post.user, - remove the requesting user that wants to unfollow, but still saves all the other people who follow: element2.querySelector('button').addEventListener('click', function() { fetch(`users/${post.user}`, { method: 'PUT */ or DELETE ?*', body: JSON.stringify({ followers: ??? }) }) }) I just want to do with … -
In Django html page coding I'm unable to reach another html page when i give this:
<a href="http://localhost:1234/signin/"><input type="submit" onclick="logged()" value="LOGIN" style="border:none;width: 103%; height: 30px; font-weight: bold; background-color: #5aa0f0;"></a> And it shows no error. Why am I not able to go to another web page when I click on the button. -
Get how many fields are null or empty string in DJANGO model
I've the next model: class Iniciativa(models.Model): iniciativa = models.CharField(max_length=150) canal = models.ForeignKey(Canales, blank=True, null=True, on_delete=models.CASCADE) territorio = models.JSONField(default=list, blank=True, null=True) bigbet = models.ForeignKey(BigBet, blank=True, null=True, on_delete=models.CASCADE) objetivo = models.TextField(blank=True, null=True) call2action = models.TextField(blank=True, null=True) dialogo_valor = models.TextField(blank=True, null=True) cobertura = models.TextField(blank=True, null=True) kpi_medicion = models.TextField(blank=True, null=True) I made a command to pass the information from a file to the database, there is a field that carries the % of the filling progress, from the front I manage it with an event every time something changes but I don't know how to emulate that behavior from my command I thought if there is a simpler way other than manually checking each field to see the progress? -
Django: 'bool' object is not subscriptable when trying to get value from queryset
I am trying to get a value from a queryset, but i keep getting this error that says 'bool' object is not subscriptable. I have a queryset that looks like this tax_rate_fee = TaxRate.objects.filter(country=cartorder.country).exists() and i am checking to see if a specific country exists in the Queryset, then i want to grab a value from the queryset and perform some operation. This is my code tax_rate_fee = TaxRate.objects.filter(country=cartorder.country).exists() if tax_rate_fee: cartorderitem.vat = 5 * tax_rate_fee['rate'] this is the tax rate fee model class TaxRate(models.Model): country = models.CharField(max_length=200) rate = models.IntegerField(default=5, help_text="Numbers added here are in percentage (5 = 5%)") active = models.BooleanField(default=True) -
'dict' object has no attribute 'pk' error while using UpdateView in Django
I'm trying to use the UpdateView for editing a product (model), but it seems it doesn't identify my pk (id) parameter in the url. here's my setup in my views.py from django.views.generic import UpdateView class ProductDetail(UpdateView): model = Product form_class = ProductForm template_name="inventory/product-detail.html" success_url = "new-product/success" fields = "__all__" def get_queryset(self, **kwargs): id = int(kwargs.pk) product = Product.objects.get(pk=id) return product in my urls.py urlpatterns = [ path('<pk>/update/', views.ProductDetail.as_view(), name='product-detail'), ] here's the traceback log: Traceback (most recent call last): File "C:\Users\Dave\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "C:\Users\Dave\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dave\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Dave\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\views\generic\base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Dave\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\views\generic\edit.py", line 203, in get self.object = self.get_object() File "C:\Users\Dave\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\views\generic\detail.py", line 31, in get_object queryset = self.get_queryset() File "D:\pythonDjango\BHM Inventory System\inventory\views.py", line 45, in get_queryset id = int(kwargs.pk) Exception Type: AttributeError at /products/2001/update/ Exception Value: 'dict' object has no attribute 'pk' It seems on python views generic\edit.py it was able to read the 'pk' in the kwargs but not in my views that i have extended the UpdateView. as you can see on the ff. screenshot with the variables django … -
Django-Admin startproject command line not working
I updated my Python version to the latest version of 3.11.3 and updated my Django version to 4.2. When I try to make a new project the django-admin startproject command line doesn't work. I tried running my gitbash in admin and resetting my pc. -
Pyppeteer AsyncHTMLSession never returns Arender when ran on Ubuntu + Django + Celery in async
I have a scraping function that takes a URL and uses a AsyncHTMLSession to scrape generative content off websites - the sites I'm accessing are JS heavy so this is necessary. I've also added asynchronous debugging lines to the function that log to the database as this made checking the status of the code far easier. import pyppeteer import requests from celery import shared_task from requests_html import AsyncHTMLSession async def load_page_helper(url: str): # THE ASYNC PAGE LOADER set_state_async.delay("load_page_helper 1") session = AsyncHTMLSession() set_state_async.delay("load_page_helper 2") browser = await pyppeteer.launch({ 'ignoreHTTPSErrors': True, 'headless': True, 'handleSIGINT': False, 'handleSIGTERM': False, 'handleSIGHUP': False }) set_state_async.delay("load_page_helper 3") session._browser = browser resp = await session.get(url) set_state_async.delay("load_page_helper 4 - should time out by 100 seconds") await resp.html.arender(timeout=100) set_state_async.delay("load_page_helper 5") await session.close() set_state_async.delay("load_page_helper 6") return resp @shared_task def set_state_async(state): # FUNCTION FOR ASYNC DB LOGGING db.set_state(state) @shared_task def scrape_data_async(): # AN EXAMPLE OF HOW THE FUNCTION IS CALLED ASYNC (1/2) base_link = "example.com" scrape_data_async.delay() # AN EXAMPLE OF HOW THE FUNCTION IS CALLED ASYNC (2/2) I ran this code 3 times with a URL that is pingable using traceroute from my Ubuntu server. The resulting output to the DB is shown below: # TEST 1 2023-04-14 21:44:24.031933 - load_page_helper … -
What is the response from google calendar api channels?
I am trying to sync my django server with Google Calendar API, and I want to add an event in the calendar and receive it in my django server. My server looks like that: the code where i get my google credentials, according to my calendar, and create a channel that will access my endpoint from google.oauth2.credentials import Credentials from googleapiclient.discovery import build from googleapiclient.errors import HttpError creds = Credentials.from_authorized_user_info(user_credentials, SCOPES) service = build('calendar', 'v3', credentials=creds) # Defina a URL do webhook webhook_url = 'https://myserver.com/webhook/' # Defina os parâmetros da solicitação de watch watch_request = { 'id': str(uuid.uuid4()), 'type': 'web_hook', 'address': webhook_url } # Registre o webhook para o calendário do usuário try: calendar_id = 'primary' # ID do calendário do usuário watch_response = service.events().watch(calendarId=calendar_id, body=watch_request).execute() print(f'Webhook registrado com sucesso: {watch_response}') except HttpError as error: print(f'Erro ao registrar o webhook: {error}') urls.py from django.urls import path from . import views urlpatterns = [ path('webhook/', views.webhook_handler, name='webhook_handler'), ] something like my views.py from django.http import HttpResponseBadRequest, HttpResponse import json def webhook_handler(request): # Verifique se a solicitação é válida if request.method != 'POST': return HttpResponseBadRequest('Somente solicitações POST são aceitas') # Obtenha o corpo da solicitação print('request headers', request.headers) print('request type', request.content_type) print('request … -
Django login does not recognize the sent data
I need help. I'm building a web application with Django and React. I'm working on the registration and login functionality, and so far the registration works well and creates a user in the database. However, when I try to log in, it always returns a 401 error, even though the user is in the database. This is the Django code: from django.contrib.auth.hashers import check_password from django.db import models class Usuario_aplicacion(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) email = models.EmailField() def __str__(self): return self.username def check_password(self, raw_password): return check_password(raw_password, self.password) views.py: import bcrypt from django.contrib.auth import authenticate, login from rest_framework.decorators import api_view from rest_framework.response import Response from django.views.decorators.csrf import csrf_exempt from .UsuarioSerializer import UsuarioSerializer from .models import Usuario_aplicacion @api_view(['POST']) @csrf_exempt def registro(request): serializer = UsuarioSerializer(data=request.data) if serializer.is_valid(): usuario = serializer.save() hashed_password = bcrypt.hashpw(usuario.password.encode('utf-8'), bcrypt.gensalt()) usuario.password = hashed_password.decode('utf-8') usuario.save() return Response({'message': 'User created'}, status=201) return Response(serializer.errors, status=400) @api_view(['POST']) @csrf_exempt def login_user(request): username = request.data.get('username') password = request.data.get('password') try: usuario = Usuario_aplicacion.objects.get(username=username) if usuario.check_password(password): user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response({'success': True}) except Usuario_aplicacion.DoesNotExist: pass return Response({'success': False}, status=401) UsuarioSerializer.py: from django.contrib.auth.hashers import make_password from rest_framework import serializers from users.models import Usuario_aplicacion class UsuarioSerializer(serializers.ModelSerializer): class Meta: …