Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display blog post description structured correctly for a Django blog?
I am creating a blog where it displays the post description in a blog post. But the post data is displaying odd or continues text. I want post description to display same in a proper format that is given as an input. In Urls.py path('blog_single/<str:title>/', views.blog_single, name = 'blog_single'), In Views.py def blog_single(request, title): posts = Post.objects.get(title = title) recent_posts = Post.objects.all().order_by('-posted_at')[:5] Categories = Category.objects.all() context = {'posts':posts, 'recent_posts':recent_posts , 'Categories': Categories} return render(request, 'blog-single.html', context) In blog-single.html <div class="entry-img"> <img src="{{posts.thumbnail.url}}" alt="" class="img-fluid"> </div> <h2 class="entry-title"> <a href="#">{{posts.title}}</a> </h2> <div class="entry-meta"> <ul> <li class="d-flex align-items-center"><i class="bi bi-person"></i> <a href="blog-single.html">{{posts.user}}</a></li> <li class="d-flex align-items-center"><i class="bi bi-clock"></i> <a href="blog-single.html"><time datetime="2020-01-01">{{posts.posted_at}}</time></a></li> <!-- <li class="d-flex align-items-center"><i class="bi bi-chat-dots"></i> <a href="blog-single.html">12 Comments</a></li> --> <li class="d-flex align-items-center"><i class="bi bi-list"></i> <a href="blog-single.html">{{posts.category}}</a></li> </ul> </div> <div class="entry-content"> <p class="post__description"> {{posts.description|safe}} </p> </div> <div class="entry-footer"> <i class="bi bi-folder"></i> <ul class="cats"> <li><a href="#">Business</a></li> </ul> <i class="bi bi-tags"></i> <ul class="tags"> <li><a href="#">Creative</a></li> <li><a href="#">Tips</a></li> <li><a href="#">Marketing</a></li> </ul> </div> </article><!-- End blog entry --> In Models.py file class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name = 'categories') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users') title = models.CharField(max_length =255) thumbnail = models.ImageField(upload_to = 'post/thumbnail') description = models.TextField() tags = models.CharField(max_length=255) posted_at = models.DateField(default = datetime.now) is_published … -
How to put a warped image on top of another using Python PIL?
Here's an example: (you can test it as a site user in the URL below) https://placeit.net/c/mockups/stages/t-shirt-mockup-of-a-cool-man-posing-in-a-dark-alley-2357-el1?iref=apparel-mockups-best-sellers-output User will upload an image and it will be applied as tshirt design on the mockup. I am not expecting to be able to develop a mega website such as Placeit but I would like to learn if similar to this very webpage in the url above. My initial idea is to use PIL lib of Python and then Django. If not, could you give me Python libraries that are more suitable? or other workaround? I understood that it includes atleast 2 images. First image is the tshirt with guy that I can do in photoshop with transparent layer on the shirt part along with shadows to make it look realistic (the folds in the shirt). Second image is the user's uploaded image. And yeah, the combining of two image is what I would like to know, esp the warped part. Tried PIL in combining the 2 images but it is only one on top of another, the warped part is the hard part. I guess its not only PIL but no idea which API or library to use. -
Convert a List of dict to single dict and it's key and value
data = [{ "January": {"China": 6569.4, "Japan": 49448.61,"Norway": 28000.0,"Poland": 3525.427,"Singapore": 33190.231851,"United States": 25976.4,"Taiwan": 15363.884885}}, {"February": {"Japan": 2540.32,"Poland": 14750.0,"Singapore": 16044.473973}}] Expecting Result data = [{ "January": {"China": 6569.4, "Japan": 49448.61,"Norway": 28000.0,"Poland": 3525.427,"Singapore": 33190.231851,"United States": 25976.4,"Taiwan": 15363.884885}, "February": {"Japan": 2540.32,"Poland": 14750.0,"Singapore": 16044.473973}}] -
get_absolute_url is not changing template?
get_absolute_url is redirecting to the page im already on (forum_list.html instead of thread_list.html)? models.py class Thread(models.Models): (...) def get_absolute_url(self): return reverse('forum:thread_list', args=[self.created.year, self.created.month, self.created.day, self.slug]) urls.py path('<int:year>/<int:month>/<int:day>/<slug:slug>/', views.ThreadListView.as_view(), name='thread_list'), views.py class ThreadListView(ListView): querytext = Thread.published.all() context_object_name = 'threads' paginate_by = 20 template_name = 'forum/thread_list.html' forum_list.html {% extends 'forum/base.html' %} {% block content %} <a href="{{ forum.get_absolute_url }}>Read</a>" {% endblock content %} what am i doing wrong? the url in the adress bar changes but the template doesnt.. It refreshes the same page but the URL changes. -
PermissionError: [Errno 13] Permission denied: 'E:\\SpeechRecongnition\\uploads\\tmpbkl0c5oc.wav' flask
I'm trying to use the Vosk library in Python to extract text from audio files. To do this, I'm using the wave module to read a temporary WAV file created from an MP3 or video file using the pydub and ffmpeg libraries. But it keeps giving me the error permmision denied even after giving the privileges Here is my code: from flask import Flask, render_template, request, send_file from werkzeug.utils import secure_filename import os import wave import json import tempfile import subprocess from pydub import AudioSegment import stat import vosk app = Flask(__name__,template_folder='template') # Set up Vosk model and recognizer model = vosk.Model("\SpeechRecongnition\model\EnglishIN") rec = vosk.KaldiRecognizer(model, 16000) UPLOAD_FOLDER = 'uploads' # Set up app config app.config['MAX_CONTENT_LENGTH'] = 70 * 1024 * 1024 # 70 MB max for audio files app.config['UPLOAD_EXTENSIONS'] = ['.wav', '.mp3', '.mp4', '.avi', '.mkv'] app.config['UPLOAD_PATH'] = UPLOAD_FOLDER @app.route('/') def index(): return render_template('index.html') @app.route('/transcribe', methods=['POST']) def upload_file(): # Check if file was submitted text="" if 'file' not in request.files: return 'No file uploaded' # Get file from request and check if it has a valid extension file = request.files['file'] if not file.filename.lower().endswith(tuple(app.config['UPLOAD_EXTENSIONS'])): return 'Unsupported file format' # Save file to disk filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_PATH'], filename)) text = transcribe_audio(os.path.join(app.config['UPLOAD_PATH'], filename)) … -
NoReverseMatch at /reset/done/ 'user' is not a registered namespace
I am trying to finalize the password reset process and after the user changes the password and click on save changes I keep getting this error: NoReverseMatch at /reset/done/ 'user' is not a registered namespace Here is the main urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), path('users/', include('users.urls'), ), path('admin/', admin.site.urls),] Here is the users urls.py app_name = 'users' urlpatterns = [ path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html', success_url=reverse_lazy('users:password_reset_done')), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html',success_url=reverse_lazy('users:password_reset_done'),post_reset_login=True),name='password_reset_confirm',), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'), ] My question I guess the reason for these new errors showing up is due to Django or python version however when the user clicks on forget password and inserts the email they receives an email and when the click on the email link to reset the password it takes them to a Django Admin page (for some reason I am trying to figure out anyways) and when they insert the new password and click on the save changes it shows this error. The error is Raised during: django.contrib.auth.views.PasswordResetCompleteView here is the traceback: Internal Server Error: /reset/done/ Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\urls\base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", … -
How to use safe filter on custom Django tag?
I'm trying to implement a custom Django tag that will formulate an import statement in Javascript to load my vue3 app as well as its components template html files using a get request in axios. The custom tag in my templatetags directory looks like this: templatetags/vuecomponents.py from django import template from django.templatetags.static import static register = template.Library() @register.simple_tag def v_load_app_component(app_name, script_name, components): components = components.strip("[]").split(", ") app_script = static(f"js/{script_name}.js") comps = [static(f"components/{name}.html") for name in components] return f"import {{{ app_name }}} from \"{app_script}?{components[0]}={comps[0]}\"" Right now it only loads the first component as I just want a prototype. The only issue is when I drop this into a template like so: createpost.html <script type="module"> {% v_load_app_component "creator" "internalpostform" "[internalpostform]" %} // OUTPUTS: // import { creator } from &quot;static/js/internalpostform.js?internalpostform=internalpostform.html&quot; creator.mount("#app") </script> It outputs the relevant import statement as: import { creator } from &quot;static/js/internalpostform.js?internalpostform=internalpostform.html&quot; With the double quotes escaped. Even when I tried to apply the safe filter ({% v_load_app_component "creator" "internalpostform" "[internalpostform]"|safe %}) it still escaped the output of my custom tag function. How can I make it to where the output of my custom tag doesn't automatically have symbols converted to html entities? -
Converting string data to python doctionary is raising exception
I am implementing real time notification feature in my Django project using django channels and web sockets. This is my code for comsumers.py: class MySyncGroupAConsumer(SyncConsumer): def websocket_connect(self,event): print("Web socket connected", event) self.send({ 'type':'websocket.accept' }) print("Channel layer ",self.channel_layer) print("Channel name", self.channel_name) async_to_sync(self.channel_layer.group_add)("notification", self.channel_name) def websocket_receive(self,event): print("Web socket recieved",event['text']) print(event['text']) data = json.loads(event['text']) async_to_sync(self.channel_layer.group_send)( 'notification', { 'type': 'notification.send', 'message': event['text'] } ) #event handler, which is sending data to client def notification_send(self, event): print('Event...', event) print('Actual msg..', event['message']) self.send({ 'type':'websocket.send', 'text':event['message'] }) def websocket_disconnect(self,event): print("Web socket disconnect", event) async_to_sync(self.channel_layer.group_discard)("notification", self.channel_name) raise StopConsumer() In websocket_receive function,I am trying to convert a string data event['text'] to python dictionary using json.loads(event['text']),but it raises following exception: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) WebSocket DISCONNECT /ws/scgg/ [127.0.0.1:57052] I have printed the type and actual data of event["text"]. It is something like this: print(event['text']) prints this: {"msg":"hi"} print(type(event['text'])) prints this: <class 'str'> I can't figure out the problem. Can anyone guide? -
Why does it say "ModuleNotFoundError: No module named 'django'" whn i have django installed, when installing mobsf?
C:\Windows\system32>cd C:\Users\DAS\Desktop\K\Pentesting Android\Mobile-Security-Framework-MobSF-master C:\Users\DAS\Desktop\K\Pentesting Android\Mobile-Security-Framework-MobSF-master>setup.bat [INSTALL] Checking for Python version 3.8+ [INSTALL] Found Python 3.10.4 [INSTALL] Found pip Requirement already satisfied: pip in c:\users\das\appdata\local\programs\python\python310\lib\site-packages (23.0.1) [INSTALL] Found OpenSSL executable [INSTALL] Found Visual Studio Build Tools [INSTALL] Creating venv Requirement already satisfied: pip in c:\users\das\desktop\k\pentesting android\mobile-security-framework-mobsf-master\venv\lib\site-packages (22.0.4) Collecting pip Using cached pip-23.0.1-py3-none-any.whl (2.1 MB) Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 22.0.4 Uninstalling pip-22.0.4: Successfully uninstalled pip-22.0.4 Successfully installed pip-23.0.1 [INSTALL] Installing Requirements Collecting wheel Downloading wheel-0.38.4-py3-none-any.whl (36 kB) Installing collected packages: wheel Successfully installed wheel-0.38.4 Ignoring gunicorn: markers 'platform_system != "Windows"' don't match your environment Collecting Django>=3.1.5 Downloading Django-4.1.7-py3-none-any.whl (8.1 MB) ---------------------------------------- 8.1/8.1 MB 12.6 MB/s eta 0:00:00 Collecting lxml>=4.6.2 Downloading lxml-4.9.2-cp310-cp310-win_amd64.whl (3.8 MB) ---------------------------------------- 3.8/3.8 MB 12.7 MB/s eta 0:00:00 Collecting rsa>=4.7 Downloading rsa-4.9-py3-none-any.whl (34 kB) Collecting biplist>=1.0.3 Downloading biplist-1.0.3.tar.gz (21 kB) Preparing metadata (setup.py) ... done Collecting requests>=2.25.1 Downloading requests-2.28.2-py3-none-any.whl (62 kB) ---------------------------------------- 62.8/62.8 kB ? eta 0:00:00 Collecting bs4>=0.0.1 Downloading bs4-0.0.1.tar.gz (1.1 kB) Preparing metadata (setup.py) ... done Collecting colorlog>=4.7.2 Downloading colorlog-6.7.0-py2.py3-none-any.whl (11 kB) Collecting macholib>=1.14 Downloading macholib-1.16.2-py2.py3-none-any.whl (38 kB) Collecting whitenoise>=5.2.0 Downloading whitenoise-6.3.0-py3-none-any.whl (19 kB) Collecting waitress>=1.4.4 Downloading waitress-2.1.2-py3-none-any.whl (57 kB) ---------------------------------------- 57.7/57.7 kB ? eta 0:00:00 Collecting psutil>=5.8.0 Downloading psutil-5.9.4-cp36-abi3-win_amd64.whl (252 … -
ModuleNotFoundError: No module named 'django.config' when running test in Django 4.1
I have a django (v4.1) project with no tests defined. Before I started writing tests, I ran python manage.py test, expecting to get something like: Found 0 test(s). System check identified no issues (0 silenced). .... ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK But instead I got this: Found 1 test(s). System check identified no issues (0 silenced). E ====================================================================== ERROR: django.config (unittest.loader._FailedTest.django.config) ---------------------------------------------------------------------- ImportError: Failed to import test module: django.config Traceback (most recent call last): File "/usr/local/lib/python3.11/unittest/loader.py", line 440, in _find_test_path package = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/unittest/loader.py", line 350, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'django.config' ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) I've checked this question but it seems more to do with a migration problem from Django 2 to 3 and how to run tests. Clarifications: When I say there are no tests defined, I mean that there are the auto-generated test.py files created by manage.py startapp in three applications, but I've commented out the standard import statement # from django.test import TestCase. I tried searching for any instances of django.config using grep -r "django.config" . from the repo directory (which is above django's BASE_DIRECTORY and there are no instances of that in any of … -
Django migrate naive DateTimeField
I am very sad: Every time I migrate the database, Django calls me naive: $ python manage.py migrate RuntimeWarning: DateTimeField Book.released received a naive datetime (2023-02-17 22:59:29.126480) while time zone support is active. ...and the worst part is: It's impossible to fix it! Steps to reproduce: $ python -V Python 3.10.6 $ pipenv --version pipenv, version 2022.11.11 $ mkdir naive-django $ cd naive-django $ pipenv install django $ pipenv shell $ python -m django --version 4.1.7 $ django-admin startproject naive_project $ cd naive_project $ python manage.py startapp naive_app $ vim naive_project/settings.py ... INSTALLED_APPS = [ 'naive_app.apps.NaiveAppConfig', ... $ vim naive_app/models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=100) $ python manage.py makemigrations $ python manage.py migrate No problem so far. Let's add a DateTimeField now: $ vim naive_app/models.py from datetime import datetime from django.db import models class Book(models.Model): title = models.CharField(max_length=100) released = models.DateTimeField(default=datetime.now) $ python manage.py makemigrations $ python manage.py migrate RuntimeWarning: DateTimeField Book.released received a naive datetime (2023-02-17 22:59:29.126480) while time zone support is active. Oh no! I made a terrible mistake! If only it was not impossible to fix it... Let's try anyway: $ vim naive_app/models.py from django.utils import timezone # timezone instead of datetime from … -
How to delete one of the items of a field in the table?
I am trying to delete one of the items of a field in the table. For example, I want to remove the 'hadi', shown in the image, from the table. I make query to filter and exclude instanse but in final part, delete() query does not accept input such as id or variable to remove specific thing in one field. models.py class Expense(models.Model): expenser = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) debtors = models.ManyToManyField( CustomUser, related_name='debtors', ) amount = models.PositiveIntegerField() text = models.TextField() date = models.DateField(null=True) time = models.TimeField(null=True) def get_debtors(self): return ", ".join([str(d) for d in self.debtors.all()]) def who_has_no_paid(self): return ", ".join([str(d) for d in self.debtors.all() if str(d) != str(self.expenser)]) def debt(self): return int(float(self.amount/self.debtors.all().count())) def get_absolute_url(self): return reverse('expense_detail', args=[self.id]) Now what is the query that should be used in view? -
Decrement/increment for qty and the value field
I am trying to create a cart page with the ability to use the add or minus buttons to decrement or increment the value of the input but the eventlisteners don't seem to be working and I have tried many different solutions online for this and get it to work properly. {% extends "base.min.html" %} {% block body_block %} {% load static %} <div class='container'> <a class='back-link' href="/"> Back to Catalog</a> <h1 class='cart-h1'>Cart </h1> <div class='cart'> <div class='requests'> <div class='request'> <img src='https://developers.elementor.com/docs/assets/img/elementor-placeholder-image.png' alt='request image'> <div class='request-info'> <p class='request-name'>Request: {{ requestName }}</p> <p class='request-details'>Details: {{ requestDetails }}</p> <p class='request-qty'>Qty: {{ requestQty }} <div class='qty-container'> <input type='button' value='+' class='qtyplus' id='plus' field='quantity' /> <input type='text' name='quantity' value='0' class='qty' id='inputQty' /> <input type='button' value='-' class='qtyminus' id='minus' field='quantity' /> </div> </p> <p class='qty-remove'></p> <span class='remove'>Remove</span> </div> </div> </div> </div> </div> </br> <div class='hidden-container'> <p>Checkout Confirmation #: {{confirmNum}}</p> </div> <script type="module" src="{% static '\js\supplyshop\pageload\RequestManagementLoad.min.js' %} " type ="text/javascript"></script> {% endblock %} const plusBtn = document.querySelector('#plus') const minusBtn = document.querySelector('#minus') const inputQty = document.querySelector('#inputQty') // increment/decrement value on input field // add eventlisteners on +/- buttons to update the value field plusBtn.addEventListener('click', e => { e.preventDefault() inputQty.value = parseInt(inputQty.value) + 1 }) minusBtn.addEventListener('click', e => { e.preventDefault() … -
CSRF fails on Route 53 redirect
I have two EC2 instances, which one has main Django-based backend app and another one has separate React-based frontend app using some of backend data. The backend app has its own views and endpoints and some frontend separate from the app in another EC2 instance. I got a new domain in AWS Route 53 which redirects to the frontend app and its location is configured on nginx. The missing thing are session cookies and csrftoken from the backend to make use of database. What may be useful is the frontend app is already reachable from the redirect set up in Django view but from the base server. In the example code below I don't paste the whole config but just the concept what I want to reach. Is there a way to redirect domain traffic to frontend app but through the backend to retrieve the cookies required to reach the backend data? Or should I think about other solution to make use of the domain? server { ... some server data ... $backend = "aws-backend-dns"; $frontend = "aws-frontend-dns"; location @backend { proxy_pass http://$backend; return @frontend; # but with some magic to keep the cookies! } location @frontend { proxy_pass http://$frontend; … -
Install GDAL x86_64 version on M1Max
For a given Django Project (to which I'm new) I need to install GDAL version: x86_64 because whenever I try python manage.py migrate on my Django project I get the following error: OSError: dlopen(/Users/name/lib/libgdal.dylib, 0x0006): tried: '/Users/name/lib/libgdal.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')).... I tried to switch the architecture of the terminal from arm64 to i386 and download it with the that architecture but I get the same error. In my settings.py the libraries GDAL and GEOS variable are declared as follows: GDAL_LIBRARY_PATH = '/opt/homebrew/opt/gdal/lib/libgdal.dylib' GEOS_LIBRARY_PATH = '/opt/homebrew/opt/geos/lib/libgeos_c.dylib' I searched and tried a lot of things, but nothing worked - have anyone had the same problem? -
How to delete one of the items of a field in the model?
I am trying to delete one of the items of a field in the model. For example, I want to remove the 'hadi', shown in the image , from the table. models.py class Expense(models.Model): expenser = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) debtors = models.ManyToManyField( CustomUser, related_name='debtors', ) amount = models.PositiveIntegerField() text = models.TextField() date = models.DateField(null=True) time = models.TimeField(null=True) def get_debtors(self): return ", ".join([str(d) for d in self.debtors.all()]) def who_has_no_paid(self): return ", ".join([str(d) for d in self.debtors.all() if str(d) != str(self.expenser)]) def debt(self): return int(float(self.amount/self.debtors.all().count())) def get_absolute_url(self): return reverse('expense_detail', args=[self.id]) What is the query that should be used in view? -
Image is not showing on my html page, using but only a link (path to image)
I have created an HTML(dashboard.html) page containing a div to display newly registered users' names, registration dates, and the user's pictures. div shows user names, and registration dates, but not the user's picture. Here is just a link to the image: Here are the files and their contents: podcast_user.models.py: class PodcastUser(AbstractUser): user_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) username = models.CharField(max_length=30,unique=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',message="Phone number must be in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True, null=True, unique=True, default='+') date_of_birth = models.DateField(blank=True, null=True) date_of_join = models.DateField(blank=True, null=True,default=date.today) address = models.CharField(max_length=100,blank=True, null=True) country = models.ForeignKey(Country, on_delete=models.CASCADE,blank=True, null=True) image = models.ImageField(upload_to='user_images/', blank=True, null=True) city_name = models.CharField(max_length=30, blank=True, null=True) postal_code = models.CharField(max_length=10,blank=True, null=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) email = models.EmailField(max_length=30, validators=[RegexValidator(regex="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.["r"a-zA-Z0-9-.]+$", message='please enter the correct format')],unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name','username'] def create_superuser(self, email, password, **extra_fields): if self.filter(is_superuser=True).exists(): raise ValueError('Superuser already exists') # set some default values for the superuser extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) # create the superuser with the provided email and password return self._create_user(email=email, password=password, **extra_fields) def __str__(self): return f"{self.username} ({self.user_id})" podcast_user.views.py: def PodcastDashboard(request): thirty_days_ago = datetime.now() - timedelta(days=30) new_users = PodcastUser.objects.filter(date_of_join__gte=thirty_days_ago) return render(request, 'pages/podcast_dashboard.html', {'new_users': new_users}) … -
I want to connect to the silicon pay API but am not sure how to handle the callback URL to obtain the status of the transaction
am trying to connect silicon pay, a payment API but I have failed to under how to handle the callback URL to check if the transfer was successful or not in order to give value to my customers @login_required(login_url='accounts:login') def mobile_deposit(request): if request.method == 'POST': form = MobileDepositForm(request.POST or None) if form.is_valid(): pending_amount = form.cleaned_data.get('pending_amount') if pending_amount >= 37000: account = Account.objects.get(user=request.user) data_req = { "req": "mobile_money", "currency": "UGX", "phone": str(account.user.phone_number), "encryption_key": "", "amount": str(pending_amount), "emailAddress": str(account.user.email), 'call_back': "https://41ab-137-63-181-131.in.ngrok.io/callback", "txRef": generate_txRef() } account.txRef = data_req['txRef'] account.save() headers = { 'Content-Type': 'application/json' } response = requests.post('https://silicon-pay.com/process_payments', data=json.dumps(data_req), headers=headers) print(response.text) account.save() messages.success(request, "Please confirm your Transaction on your phone") return redirect("accounts:mobile-deposit") else: messages.warning(request, "Minimum deposit is UGX 37000") return redirect('accounts:mobile-deposit') else: messages.warning(request, "Form error") return redirect('accounts:mobile-deposit') else: form = MobileDepositForm(request.POST or None) context = { 'form':form } return render(request, "mobile_deposit.html", context) def generate_txRef(): return "CTF-"+str(random.randrange(111111,999999)) I have tried reading the documentation on silicon pay but its in PHP yet am implementing mine in python. My solution has crushed the site -
Brew install watchman on mac does run the service
I am on Mac ventura 13.0.1 (22A400) I am trying to install watchman however it is not getting installed as a service that can be run in service/daemon mode brew install watchman ==> Downloading https://formulae.brew.sh/api/cask.json Warning: watchman 2023.02.13.00 is already installed and up-to-date. To reinstall 2023.02.13.00, run: brew reinstall watchman However, it says that it cannot be run and loadable brew services info watchman watchman (homebrew.mxcl.watchman) Running: ✘ Loaded: ✘ Schedulable: ✘ Brew services list brew services list Name Status User File memcached started xxx ~/Library/LaunchAgents/homebrew.mxcl.memcached.plist rabbitmq started xxx ~/Library/LaunchAgents/homebrew.mxcl.rabbitmq.plist redis none stunnel none However I can use watchman in command line mode, but other programs that need to find watchman can't use it -
Best practices for storing encrypted data that needs to be decrypted
I have a use case where I need to store userIDs and passwords to access other systems in my DRF App with a PostgreSQL DB. I must be able to retrieve this information, but I don't want to store it in plain text in the data base. The credentials will be used to login to other systems to collect data. Hashing is not an option as I need to be able to decrypt the encrypted passwords as they will be used to log into other systems. I was thinking using a vault (hashicorp), but then I need to store the keys to access the vault. That seems just shifting the problem, but not a solution. I am looking for a encryption/decryption that has not more than 2 secrets (key and vector) that could be the same for all credentials and provides a single string per password that can be stored in the DB. No fancy PostgreSQL features that are not supported by Django/DRF. I am not looking for long explanations about that you should not store a userID/Password information in a DB! -
'POST' or 'PUT' or 'DELETE' is not working
Here the class WriteByAdminOnlyPermission is not working perfectly. This if request.method == 'GET': working but remaining condition is not working. My target is, only the admin can change information and the other people just can see. How can I do it? And where I did do wrong? please give me a relevant solution😥 views.py: class WriteByAdminOnlyPermission(BasePermission): def has_permission(self, request, view): user = request.user if request.method == 'GET': return True if request.method in['POST' or 'PUT' or 'DELETE'] and user.is_superuser: return True return False class ScenarioViewSet(ModelViewSet): permission_classes=[WriteByAdminOnlyPermission] serializer_class = ScenarioSerializer queryset = Scenario.objects.all() models.py: class Scenario(models.Model): id = models.CharField(primary_key=True, max_length=10, default=uuid.uuid4, editable=False) Title = models.CharField(max_length=350, null=True, blank=False) film_id = models.OneToOneField(Film, on_delete=models.CASCADE, related_name="ScenarioFilmID", null=True) serializer.py: class ScenarioSerializer(ModelSerializer): class Meta: model = Scenario fields = "__all__" urls.py: router.register(r"scenario", views.ScenarioViewSet , basename="scenario") -
Django Authentication to use both email and username in exiting app
I am struggling with adding custom AUTHENTICATION_BACKENDS for my exiting app. I have all done with my app but now want to login with username or EmailID. I am successfully able to login with username and password. now just want to add EmailID as well. I tried adding below code in my settings.py AUTHENTICATION_BACKENDS = ( 'authentication.backends.EmailOrUsernameModelBackend', 'django.contrib.auth.backends.ModelBackend', ) and in \authentication\backends.py I have from django.conf import settings from django.contrib.auth.models import User class EmailOrUsernameModelBackend(object): def authenticate(self, username=None, password=None): print("Inside EmailorUsernameModelBackend") if '@' in username: print("User with Email") kwargs = {'email': username} else: print("User with Username") kwargs = {'username': username} try: user = User.objects.get(**kwargs) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None where my \authentication\views.py def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) print("User=",user) if user is not None: login(request, user) return redirect("dashboard") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "/login.html", {"form": form, "msg": msg}) I am trying to print some statement if authenticate method call from EmailOrUsernameModelBackend but none printing, so I guess for some … -
JAVASCRIPT: After sending Item to Database (POST) the window.location.reload() does not work. How to refresh the Data in HTML-Template?
I recode a Tutorial on Youtube. Django, Python, HTML an Javascript. Everthing works fine exept the window.location.reload() function. I try some workarounds with windows.reload(true), window.href = window.href location = self.location and some more. I have a hunch that the reload is executed before or during the code before the reload. But I do not know. The goal is to send the data from the input to the database and only then refresh the page. This ist the Code from the tutorial: index.html (shortened) <body> <header> <h1>Shoppinglist</h1> <div id="input-field"> <label for="item-input">Was möchtest du einkaufen?</label> <input type="text" name="item" id="item-input"> </div> <button id="btn" onclick="addItem()">+</button> </header> <div id="item-table"> {% for row in all_items %} <div class="list-item"> <input type="checkbox"> {{row.name}} </div> {% endfor %} </div> <script> function addItem(){ let itemName = document.getElementById("item-input").value; let formData = new FormData(); let token = '{{csrf_token}}'; formData.append('itemName', itemName); formData.append('csrfmiddlewaretoken', token); fetch('/mylist/', { method: 'POST', body: formData }); window.location.reload(); }; </script> </body> </html> views.py from django.shortcuts import render from .models import ShoppingItem # Create your views here. def mylist(request): if request.method == 'POST': print('Received date: ', request.POST['itemName']) ShoppingItem.objects.create(name = request.POST['itemName']) all_items = ShoppingItem.objects.filter(done = 0) return render(request, 'index.html', {'all_items':all_items}) models.py from django.db import models from datetime import date #Create your models … -
Multiple signin in django
I want to multiple role in django. I also create default auther user. But i want add login in second database table. I try to authenticate(username='john', password='secret') function but it is working only django default author. I want to use second database table then how can i authenticate the second user and login to the site. Please advice currently working django 4.1 version. -
Django Rest Framework get filtered queryset in custom get function
So I have an APIView like this: from rest_framework.views import APIView class MyAPIView(APIView): queryset = MyObject.objects.all() filter_backends = [MyCustomFilterBackend, DjangoFilterBackend] filterset_fields = ["field1", "field2"] def get(self, request): s = StatManager(self.queryset) return Response(s.dashboard()) where I filter bunch of stuff using MyCustomFilterBackend and DjangoFilterBackend. My goal is to give the filtered queryset to StatManager so it generates stats for the dashboard. Currently, s = StatManager(self.queryset) does not take filters into account. How can I provide the filtered queryset in my get function? I read the DRF documentation. I was expecting for APIView to have some function like get_filtered_queryset(). I read Filters of Django REST Framework inside GET function? and DJango filter_queryset but they have no adequate answers.