Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm using pinax-referral but when I follow through I'm getting raise.self.model.DoesNotExist and also Value error for unable to configure logger
I'm trying to use pinax-referral but when I follow through I'm getting raise.self.model.DoesNotExist and also Value error for unable to configure logger This my logger that its triggering the ValueError: Unable to configure handler 'debug' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '[%(asctime)s] | %(levelname)s | %(message)s', 'datefmt': '%d/%b/%Y %H:%M:%S', }, }, 'handlers': { 'debug': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logging/debug.log', 'maxBytes': 1024*1024*5, 'formatter': 'simple', }, 'error': { 'level': 'ERROR', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logging/error.log', 'maxBytes': 1024*1024*5, 'formatter': 'simple', }, }, 'loggers': { 'django': { 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'handlers': ['debug', 'error'], }, }, } the other issue its saying raise self.model.DoesNotExist( App1.models.Profile.DoesNotExist: Profile matching query does not exist. and when I counter check I find this File "C:\Users\n\PycharmProjects\Elijahs_Agnes\App1\views.py", line 76, in get_context_data profile = Profile.objects.get(user=self.request.user) this the part class DashboardView(TemplateView): template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Current user context['user'] = self.request.user # The user who brought the current user to the system profile = Profile.objects.get(user=self.request.user) if profile.parent: context['parent'] = profile.parent.user parent_amount = (int(PRICE) * 5) / 100 else: context['parent'] = None parent_amount = 0 -
Asyncwebsocketconsumer disconnect methods runs after some delay
I am running into a major issue while working on a app. The issue is that when the user loses internet connection the disconnect method of asyncwebsocketconsumer is expected to run. It does run but after some delay of around 10-15 seconds. Is there any way to reduce this delay? -
Django Using oembed to convert url to embed url(VIMEO)
I try to convert video url to embed url... with using oEmbed But enter image description here When I print(video_url_api_data) it keep returning <Response [404]> I checked it with using url in google https://vimeo.com/api/oembed.json?url=https://vimeo.com/570924262 What did i do wrong with my code? and What am i have to put at the status part( vimeo_authorization_url = v.auth_url( ['private'], 'http://127.0.0.1:8000/', 1 #status ) this status part! I put 1 for random... and it works.. in advance import json, vimeo, requests class article_upload(View): def post(self ,request, *args, **kwargs): v = vimeo.VimeoClient( token='****', key='****', secret='****' ) file_data = request.FILES["file_data"] path = file_data.temporary_file_path() try: vimeo_authorization_url = v.auth_url( ['private'], 'http://127.0.0.1:8000/', 1 #status ) video_uri = v.upload(path, data={'name': '비디오 제목', 'description': '설명'}) video_data = v.get(video_uri + '?fields=link').json() video_url = video_data['link'] params={"url": video_url} video_url_api_data = requests.get('https://vimeo.com/api/oembed.json', params=params) return render(request, 'account/myvideopage.html', {context(I made it)}) except vimeo.exceptions.VideoUploadFailure as e: print("ohohohohohoh...vimeo error") finally: file_data.close() # Theoretically this should remove the file if os.path.exists(path): os.unlink(path) # But this will do it, barring permissions -
pip install virtualenv error python django
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000000048A65E0>, 'Connection to 10.8.0.1 timed out. (connect timeout=15)')': /simple/virtualenv/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000000048A6610>, 'Connection to 10.8.0.1 timed out. (connect timeout=15)')': /simple/virtualenv/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000000048A6460>, 'Connection to 10.8.0.1 timed out. (connect timeout=15)')': /simple/virtualenv/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000000048A62E0>, 'Connection to 10.8.0.1 timed out. (connect timeout=15)')': /simple/virtualenv/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000000048A60A0>, 'Connection to 10.8.0.1 timed out. (connect timeout=15)')': /simple/virtualenv/ -
is there a way to generate unique payment urls for each customers in python api using stripe? [closed]
I need to generate unique payment urls which will be forwarded to the customer ,through which customer can pay the amount in stripe. I would like to implement this in python django. -
How do you add Vue to Django?
I'm am trying to add a reactive Vue js on the frontend and have Django serve the different pages on the backend. But how do you add these guys together?? I have found different ways to do so, but I can't find a good explanation on the why they are tying them together that way. I was hoping for a comprehensive explanation as to how these 2 are added together but also the why? I am still new to both of these frameworks so I am trying to understand not only how to do something but the reason for my doing them. Thanks in advance. -
Slug filed is not showing in Django Admin
I am working on a Django application, In my models, I have a product class with SlugField but it is not showing in Django Admin Panel. class Product(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True), price = models.DecimalField(max_digits=6, decimal_places=2) description = models.TextField() image = models.ImageField(upload_to=product_directory_path, blank=True) featured = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) category = models.ForeignKey( Category, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: ordering = ('name',) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('name',)} [![enter image description here][1]][1] when I am adding prepopulated fields in admin.py it is showing me this error. ERRORS: <class 'shop.admin.ProductAdmin'>: (admin.E027) The value of 'prepopulated_fields' refers to 'slug', which is not an attribute of 'shop.Product'. I have tried migrations but it tells me 'No Changes detected'. The below Image shows that Django Admin isn't detecting my slug field. Image -
Django SQLite3, attempt to write a readonly database
Im using sqlite3 as a database to my project, it's working when i manually serve a temporary port by typing python manage.py runserver however the exception throws after deploying in apache server shown in figure below. at first i thought this is a file permission issue and when i ran commands in django e.g. python manage.py runserver, python manage.py mycommand, python manage.py createsuperuser the error not occur and working but when i use the designated port that i created in /etc/apache2/sites-enabled/000-default.conf the error comes. I am using ubuntu 20.04 and apache 2.4.41 as my environment and the virtual host configuration below is my port designate to my project. Listen 112 <VirtualHost *:112> Alias /assets /home/yuan04/Projects/Lotto/assets <Directory /home/yuan04/Projects/Lotto/assets> Require all granted </Directory> <Directory /home/yuan04/Projects/Lotto/lotto> <Files wsgi.py> Require all granted </Files> <Files db.sqlite3> Require all granted </Files> </Directory> WSGIDaemonProcess lotto python-home=/home/yuan04/Projects/Lotto/venv python-path=/home/yuan04/Projects/Lotto WSGIProcessGroup lotto WSGIScriptAlias / /home/yuan04/Projects/Lotto/lotto/wsgi.py </VirtualHost> -
django app is not able to find a url using slugs
I have a simple blog app that has a blog home and the details. I am using slug for detail URLs and prepopulating the slug field with the post title. everything works fine local but after I deployed the app online, when I click the post to go to its' blog detail it won't find the page. this is my post models: class PostManager(models.Manager): def get_queryset(self): return PostQuerySet(self.model, using=self._db) def search(self, query=None): return self.get_queryset().search(query=query) class Post(models.Model): objects = PostManager() title = models.CharField(max_length=150) paragraph = models.TextField(blank=True) published = jmodels.jDateField() tags = TaggableManager() slug = models.SlugField(max_length=200, unique=True, allow_unicode=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) this is my urls: path('maghaalaat/', views.MaghaleMain.as_view(), name="blog-page"), path('maghaalaat/tags/<slug:tag_slug>/', views.MaghaleTags.as_view(), name="tagged"), re_path(r'maghaalaat/(?P<the_slug>[-\w]+)/', views.MaghaleDetail.as_view(), name='post-detail'), this is my views: class MaghaleMain(ListView): model = MaghaalaatPost template_name = 'Blog/Blog-elmi.html' queryset = MaghaalaatPost.objects.all() context_object_name = 'posts' ordering = ['-published'] paginate_by = 3 def get_context_data(self, **kwargs): context = super(MaghaleMain, self).get_context_data(**kwargs) context['tags'] = MaghaalaatPost.tags.all() return context class MaghaleTags(ListView): model = MaghaalaatPost template_name = 'Blog/Blog-elmi.html' context_object_name = 'posts' def get_queryset(self): return MaghaalaatPost.objects.filter(tags__slug=self.kwargs.get('tag_slug')) def get_context_data(self, **kwargs): context = super(MaghaleTags, self).get_context_data(**kwargs) context['tags'] = MaghaalaatPost.tags.all() return context class MaghaleDetail(DetailView): model = MaghaalaatPost template_name = 'Blog/Blog-elmi-detail.html' context_object_name = 'maghaale' slug_url_kwarg = 'the_slug' slug_field = 'slug' def … -
Adding foreign_key on before_import
I have a model, which has two foreign keys that are not technically part of the CSV. The customer model should be a foreign key of monthly_bill but the CSV only contains customer information instead of dumping everything on monthly_bill, I extracted the customer info into a separate table. So Ideally I need to do a get_or_create. The other field is just a company that should be derived from the token of the user that uploaded the CSV. I tried overriding the before_import_row and before_import but it still says null-constraint on customer_id. I did do it like this row["customer_id"] = customer.id but still nothing. Any ideas? Here is the snippet of my before_import def before_import(self, dataset, using_transactions, dry_run, **kwargs): for row in dataset.dict: """ Get the correct organization """ # TODO: should be dynamic organization = Organization.objects.get(name="JBA") account_number = row.get("account_number") name = row.get("customer_name") address_line_1 = row.get("address_line_1") address_line_2 = row.get("address_line_2") city = row.get("city") state = row.get("state") zip_code = row.get("zip") property_size = row.get("lot_size") customer, created = Customer.objects.get_or_create( name=name, account_number=account_number, defaults={ "name": name, "organization": organization, "account_number": account_number, "address_line_1": address_line_1, "address_line_2": address_line_2, "city": city, "state": state, "zip_code": zip_code, "property_size": property_size } ) row["organization_id"] = organization.id row["customer_id"] = customer.id return dataset -
Adding a second or multiple device for a user django two factor authentication
I am using two-factor authentication for a django project. It is working fine but I want to implement few more features in my code. But I am unable to implement Expected Behavior: I want that a user has to face a 2F authentication prompt whenever the user logins from a new device. Also I want to increase code validation time. Current Behavior: Currently, if a user logins for the first time, the user is shown an authentication prompt. But when the user logins from a new device, the user is not shown an authentication and easily logs in. But I want that the user has to face 2F from every new device. Also Whenever I change step the validate code does not valid. For example if i give step=60, then the validation code get invalid. I am unable to increase time for code validation. I checked TOTPDevice model in the database. It shows that now new key is not generating for new device. I am using the below codes. def get_user_totp_device(self, user, confirmed=None): """ Gets user's time based one time password devices """ devices = devices_for_user(user, confirmed=confirmed) for device in devices: if isinstance(device, TOTPDevice): return device class TOTPCreateView(APIView): permission_classes = … -
Is it possible to create login in Django with HTML forms?
I am new to Django and I am creating a simple register and login functionality. I followed a youtube tutorial where the person used Django forms. I am trying to use just HTML forms for login and registration. The registration part is done and I see data on admin url. For login I am getting None on this line: user = authenticate(request, username=username, password=password) Which is why I am not able to pass the if user is not None condition. Can anyone help? Here is the code: This is the register part: def createUser(request): if request.method == 'POST': if request.POST.get('username') and request.POST.get('password'): post = FormDetails() post.register_email = request.POST.get('username') post.register_pass = request.POST.get('password') post_save = post.save() print("data posted and saved") return redirect('login') messages.success( request, f'Your account has been created ! You are now able to log in') return render(request, 'users/register.html') FormDetails is my model with email and password field(That's why i am seeing the password as plain text in admin page). The login is: def loginScreen(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') print("username={}".format(username)) user = authenticate(request, username=username, password=password) print("user={}".format(user)) if user is not None: login(request, user) messages.success(request, f' welcome {username} !!') print("here") return HTTPResponseRedirect('index') else: messages.info(request, f'account done … -
How can I delete a request.session variable inside the Django HTML template?
Code: {% if request.session.message %} <div class="alert alert-warning alert-dismissible fade show" role="alert"> <i class="bi bi-check2-circle"></i> {{request.session.message}} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endif %} {% request.session.remove('message') %} Error: TemplateSyntaxError at / Could not parse the remainder: '('message')' from 'request.session.remove('message') -
NoReverseMatch at /edit_profile/ Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['profile/(?P<username>[^/]+)$']
I am trying to build a blog website. In the profile update section I am getting this error. NoReverseMatch at /edit_profile/ Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['profile/(?P[^/]+)$'] I understand the error but I don't know how solve it. Please help me. models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image GENDER = ( (None, 'Choose your gender'), ('male', 'Male'), ('female', 'Female'), ('custom', 'Custom'), ('Prefer Not To Say', 'Prefer Not To Say'), ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_default.png', upload_to= 'profile_pics') bio = models.TextField(max_length=50, blank=True) gender = models.CharField(max_length=50, choices=GENDER, verbose_name="gender", blank=True) def __str__(self): return f'{self.user}\'s Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.width > 300 or img.height > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py class UserEditForm(forms.ModelForm): first_name = forms.CharField(label='Full Name' ,max_length=150) email = forms.EmailField() class Meta: model = User fields = ['first_name', 'username', 'email'] class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['gender','image', 'bio'] widgets = { forms.Select(attrs={'class': 'custom-select md-form'}) } urls.py urlpatterns = [ path('admin/', admin.site.urls), # post_stuff urls path('', include('post_stuff.urls')), # user urls path('signup/', user_views.signup, name='signup'), path('login/', user_views.Login.as_view(template_name='user/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='user/logout.html'), name='logout'), path('profile/<str:username>', user_views.profile, name='profile'), path('edit_profile/', user_views.edit_profile, name='edit_profile') ] … -
url path is matching the wrong view in drf viewsets
Django beginner here, I have two similar endpoints as shown below, they differ in their url_path of the action decorator and the request parameters requester_id and approval id The problem both /workflow_approvals/{requester_id}/ and /workflow_approvals/{approval_id}/ are routing to the requester method view(the first below) @action(methods=['GET'], detail=False, serializer_class=WorkflowRequesterActivitySerializer, url_path='(?P<requester_id>[^/.]+)') def requester_activities(self, request, requester_id, pk=None): try: approval = WorkflowApproval.objects.filter(requester=requester_id).first() if approval is None: return Response({'success': False, 'errors': 'No workflow for specified requester'}, status=status.HTTP_404_NOT_FOUND) activities = WorkflowActivity.objects.filter( workflowapproval=approval ) serializer = self.get_serializer(activities, many=True) return Response({'success': True, 'data': {'total_count': activities.count(), 'activities': serializer.data}}, status=status.HTTP_200_OK) except Exception as e: return Response({'success': False, 'errors': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @action(methods=['GET'], detail=False, serializer_class=WorkflowActivitySerializer, url_path='(?P<approval_id>\w+)',) def approval_activities(self, request, approval_id, pk=None): try: approval = WorkflowApproval.objects.filter(id=approval_id).first() if approval is None: return Response({'success': False, 'errors': 'Workflow Approval does not exist'}, status=status.HTTP_404_NOT_FOUND) activities = WorkflowActivity.objects.filter( workflowapproval=approval) serializer = self.get_serializer(activities, many=True) return Response({'success': True, 'data': {'total_count': activities.count(), 'activities': serializer.data}}, status=status.HTTP_200_OK) except Exception as e: return Response({'success': False, 'errors': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) my urls.py file looks like this from django.urls import include, path from rest_framework.routers import DefaultRouter from .views import WorkflowApprovalsViewset app_name = "workflow_approvals" router = DefaultRouter() router.register("", WorkflowApprovalsViewset) urlpatterns = [ path("", include(router.urls)), ] -
How to sort by decending order in django by timestamp
Model.py createdAt = models.DateTimeField(auto_now_add=True) views.py @api_view(['GET']) def getProducts(request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) So how can I sort this product list by decending order so that there show latest products -
Handle Paypal Payments/Checkout in a Django Rest Framework
I want to implement payment/checkout, preferably the user stays on my website (Angular frontend). I have been wandering around the docs of paypal for weeks, and googling too, but I don't seem to find an EFFECIENT way to do it (lack of drf tutorials and guides). I also have seen django-payments, django-paypal, dj-paypal. but none of them has a clear docs about an integration with DRF... I feel like I'm lost here. any help? hints? -
username saving as null in django custom model
when i am sending post request to register new user from postman, username saves as blank/dash . why username saving as blank i dont get it. but when i add from django admin it saves correctly. here is postman image postman post request image and here is the result django result after sending post request Custom Account Manager class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_active', True) other_fields.setdefault('is_admin', True) other_fields.setdefault('is_superuser', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, password, **other_fields) def create_user(self, email, username, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) if not username: raise ValueError(_('You must provide an username')) if " " in username: raise ValueError(_('Username should not contain space')) email = self.normalize_email(email) user = self.model(email=email, username=username, **other_fields) user.set_password(password) user.save() return user Custom User Model class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True, null=False, blank=False) username = models.CharField(max_length=150, unique=True, null=True) first_name = models.CharField(max_length=150, blank=True) objects = CustomAccountManager() # more class Meta: verbose_name = 'NewUser' USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return str(self.username) model serializer class RegisterNewUserSerializer(serializers.ModelSerializer): class … -
I can't upload files on MySQL server while using Firebase APIs and it shows: V/FA: Inactivity, disconnecting from the service
I'm working on Firebase real time database and APIs. But in the same activity, I tried to upload files on MySQL database, but it didn't work at all, just with showing this log: V/FA: Inactivity, disconnecting from the service. Other APIs worked but just I can't upload files on server in the same case. Can you please help me? -
Understanding Django (Python) and databases
new to Django and hope someone can help me understand. I see how in Django you can set up models that become tables in say PostgreSQL. Great. What approach should I use where the schema and tables already exist in a database? I don't want to change the tables in anyway but use the data in views. I would normally think 'make an SQL statement to return the data I want and join tables where needed'. Lets say the tables are Orders and Customers and I would use an SQL: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; What is the approach for: the abstraction in django for this SQL any best practices makemigrations / migrate so I don't interfere with the source tables but keep my models up to date in the DB join to a table that is a django model? Much appreciated! -
Upload multiple files Django
models.py file_1 = models.FileField(blank=True, upload_to='PN_files/%Y/%m/%d/', verbose_name="File 1", validators=[validate_file_size], help_text="Allowed size is 50MB") views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'file_1'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) HTML code: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Fill the form</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> I use this code to upload a file in my form. Now I need to upload multiple files, but when I follow the examples on Django Uploading multiple files, I can't get it to works. My views.py now looks like (and none of 3 examples work for me): class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'file_1'] def form_valid(self, form): form.instance.author = self.request.user widgets = {'file_1': form.ClearableFileInput(attrs={'multiple': True})} form.instance.file_1 = form.FileField(widget=form.ClearableFileInput(attrs={'multiple':True})) form.instance.file_1 = form.FileField(widget=form.FileInput(attrs={'multiple': True})) return super().form_valid(form) -
get dictionary value sent from Django in Vuejs row
I have used Django to develop a web app. The front end is vuejs. I want to render the dictionary in vuejs table. I have tried to access the dictionary using the dictionary name in vue, but failed to get the vaule. view.py: def Browse_and_adopt(request): query_results_book = Title.objects.values() return render(request, 'main.html', { "query_results_book": query_results_book }) HTML: <div id="app"> &emsp;&nbsp;Search: <input type="text" placeholder="By title, iSBN, VBID, publisher, Author, course code" v-model="filter" size="45"/> <br> <table> <thead> <tr> <th>Course Material Title</th> <th>Author/Editor</th> <th>Edition</th> <th>Publisher</th> <th>iSBN</th> <th>e-iSBN/VBID</th> <th>Category</th> <th>Material Format</th> <th>Distribution Mode</th> <th>Course Codes using title</th> <th>Adopt: Course Code</th> <th>Adopt: Starting Semester</th> </tr> </thead> <tbody data="{{ json_data }}"> <tr v-for="(row, index) in filteredRows" :key="`iSBN-${index}`"> <td>{{ row.title }}</td> <td>{{ row.author }}</td> </tr> </tbody> </table> </div> <script> const app = new Vue({ el: '#app', data: { filter:'', rows: [ { title: query_results_book.title, author: query_results_book.author } ] }, query_results_book: { type: Object, required: true, }, }); In this line: title: query_results_book.title, I get error: query_results_book not defined. How to pass my dictionary to row in vue? -
how to change two dates to number of days and hours jango
i'm trying to change two dates check_in and check_out to days and hours my models.py check_in = models.DateTimeField(default=datetime.now) check_out = models.DateTimeField() i tried this check_in_date = obj.check_in check_out_date = obj.check_out days = check_in_date - check_out_date day = days.days hour = days.seconds / 60 for the day it works as i expect except that when i select this two dates check_in=05-07-2021 04:46 PM to check_out=05-07-2021 10:46 PM i want to show 0 days 6 hours but it show 1 days 1080.0 hours ! is it possible to return such date format -
Django Paypal: 'VALIDATION_ERROR' 'MALFORMED_REQUEST_JSON'
I am trying to verify my webhooks but i am getting a key error: verification_status. This is because the response of the api call is giving an error instead of the json dump i should be getting. The error from the response is {'name': 'VALIDATION_ERROR', 'message': 'Invalid request - see details', 'debug_id': 'd303f5f9323d6', 'details': [{'field': '/webhook_event', 'location': 'body', 'issue': 'MALFORMED_REQUEST_JSON'}], 'links': []} which shows that the error is in the webhook event i think. What do i have to change to fix this? headers = { "Content-Type": "application/json", "Authorization": bearer_token, } print(request.body) print('') data = { "auth_algo": request.headers["PAYPAL-AUTH-ALGO"], "transmission_id": request.headers["PAYPAL-TRANSMISSION-ID"], "transmission_sig": request.headers["PAYPAL-TRANSMISSION-SIG"], "transmission_time": request.headers["PAYPAL-TRANSMISSION-TIME"], "webhook_id": id_is_here, "webhook_event": request.body, "cert_url": request.headers["PAYPAL-CERT-URL"], } data["webhook_event"] = data["webhook_event"].decode("utf-8") print(data["webhook_event"]) response = requests.post('https://api-m.sandbox.paypal.com/v1/notifications/verify-webhook-signature', headers=headers, json=data).json() print('worked') print(response) if response["verification_status"] == "SUCCESS": print('success') if [i["event_type"] for i in request.body] == "BILLING.SUBSCRIPTION.CREATED": print('sub created') elif [i["event_type"] for i in request.body] == "BILLING.SUBSCRIPTION.CANCELLED": print('sub cancelled') -
How to make the user able to filter on certain field in a model (Django)
Say I have a model of cars #models.py class Car(models.Model): user = models.ForeingKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) n_doors = models.IntegerField(default=5) name = models.CharField(max_length=16) and a user has created 6 Car, where 3 have 5 doors, 2 have 4 doors and 1 have 1 door. Is there a way I can let the user filter on, say, n_doors either by a choice-list of available numbers ([5,4,1]), or by letting the user write numbers theirself?