Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect views with forms Django
I have chained dropdown in views py and that`s all showing in html but how am i suppose to send them into my forms.py Bcs where im trying to save that form into database i got an error of validation bcs views functions are not connected to my form Im kinda tired of that function pls help me views.py @login_required def create_work_log(request): if request.method == 'POST': form = WorkLogForm(request.POST, user=request.user) if form.is_valid(): work_log = form.save(commit=False) work_log.author = request.user work_log = form.save() messages.success(request, 'Данные занесены успешно', {'work_log': work_log}) return redirect('create_worklog') else: messages.error(request, 'Ошибка валидации') return redirect('create_worklog') else: if request.user.is_authenticated: initial = { 'author': request.user } else: initial = {} form = WorkLogForm(user=request.user, initial=initial) context = {'form': form} return render(request, 'contractor/create_work_log.html', context) def contractor_object(request): contractor_guid = request.GET.get('contractor_counter') objects = ObjectList.objects.filter(contractor_guid__in=[contractor_guid]) context = {'objects': objects, 'is_htmx': True} return render(request, 'partials/objects.html', context) def contractor_section(request): objects_guid = request.GET.get('object') sections = SectionList.objects.filter(object=objects_guid) context = {'sections': sections} return render(request, 'partials/sections.html', context) forms.py contractor_counter = forms.ModelChoiceField( label='Контрагент', queryset=CounterParty.objects.none(), initial=CounterParty.objects.first(), empty_label='', ) contractor_object = forms.ModelChoiceField( label='Объект', queryset=ObjectList.objects.none(), initial=ObjectList.objects.first(), empty_label='', ) contractor_section = forms.ModelChoiceField( label='Раздел', queryset=SectionList.objects.none(), initial=SectionList.objects.first(), empty_label='', ) template.html <div class="mt-3"> {{ form.contractor_counter.label_tag }} {% render_field form.contractor_counter class='form-select mt-2' autocomplete='off' hx-get='/objects/' hx-trigger='change' hx-target='#objects' %} </div> <div id="objects" class="mt-3"> {% … -
serialiizer return always none. why?
serialiizer return always none. why?? creating custom models time? serialiizer return always none. why?? creating custom models time? views.py print password = None class UserLoginView(APIView): def post(self,request,format=None): serializer=UserLoginSerializer(data=request.data,) if serializer.is_valid(raise_exception=True): email=serializer.data.get('email') password=serializer.data.get('password') **print(password)** print(request.data) print(serializer.data) user=authenticate(email=email,password=password) print(user) return Response({'msg':'successful login'},status=status.HTTP_200_OK) Serializer.py file class UserLoginSerializer(serializers.ModelSerializer): email=serializers.EmailField(max_length=255) class Meta: model=User fields=['email','password',] extra_kwargs={ 'password':{'write_only':True}, } Models.py file class UserManager(BaseUserManager): def create_user(self, email, number,name, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') if not number: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), number=number, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, number,name, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, number=number, password=password, name=name, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) number=models.CharField(max_length=10) name=models.CharField(max_length=30) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','number'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return self.is_admin def has_module_perms(self, app_label): "Does the user have permissions to view … -
Authentication using GitHub is not using the primary email
Recently integrated GitHub authentication in my Django website and noticed that Python Social Auth is registering the users using a non-primary email address. How can that behaviour be modified? -
Why is my Django session working when I use Postman, but not when I use it via my React Frontend?
I'm currently working on a registration component for an application built using React with TypeScript and Tailwind CSS, Django and MongoDB. In my Django backend I have an app called login_register_app, which is used for registration functionality. I want to create a session that stores the id of the document when the document is created so that when the user is asked to add further details on the following page the correct document can be updated. So far, I have the following function for registration: @api_view(['POST']) def create_login(request): # parse json body = json.loads(request.body) # get email and password and confirm password email = body.get('email') password = body.get('password') confirm_password = body.get('confirm_password') email_is_valid = False password_is_valid = False error = '' # password must be at least 8 characters and contain digit 0 - 9, Uppercase, Lowercase and Special # character from list (#?!@$%^&*-) password_validation_pattern = re.compile('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$') # compare password to confirm password and regex pattern if password == confirm_password and re.match(password_validation_pattern, password): password_is_valid = True elif password == confirm_password: error = 'password is not valid. Requires at least one uppercase, lowercase, digit and special character [#?!@$%^&*-]' else: error = 'passwords do not match' # verify email does not already exist … -
Django - VSCode does not recognize foreign key related names and gives error
Post model has a foreign key to User model with posts as its related name. posts = user.posts.all() ^^^^^ Django works fine obviously. But the error in VSCode is annoying. How can I make VSCode know this is not an error? -
Getting 400 'bad request' for deployed django app with apach2 + mod_wsgi
I am running 2 django apps on same server (both are almost the same). First app is running without any issue in virtual env and prod mode. But for the 2nd deployed app I am getting the bad request error even its running in virtual env without any issue. I set 775 for the whole project and www-data as owner. My apache .conf file is <VirtualHost *:80> ServerName prod-domain.de <Directory /opt/myproject/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> Alias /media/ /opt/myproject/mysite/media/ Alias /static/ /opt/myproject/mysite/base/static/ <Directory /static/> Require all granted </Directory> <Directory /media/> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error-myproject.log CustomLog ${APACHE_LOG_DIR}/access-myproject.log combined </VirtualHost> WSGIScriptAlias / /opt/myproject/mysite/mysite/wsgi.py WSGIPythonPath /opt/myproject/mysite/env/lib/python3.8/site-packages My settings.py DEBUG = True ALLOWED_HOSTS = ["prod-domain.de"] [...] STATIC_ROOT = BASE_DIR / 'base/static/' STATICFILES_DIRS = [BASE_DIR / 'myproject/static/', ] STATIC_URL = 'static/' # Base url to serve media files MEDIA_URL = 'media/' # Path where media is stored MEDIA_ROOT = BASE_DIR / 'media/' I played around a lot with apache conf and the settings.py but apache doesn't show any error in the logs and now I am stucked hardly. -
Uploading Files/Form with JQuery File Upload by blueimp
I am trying to understand how to use JQuery File Upload by blueimp. This is my test view with an Input from type file, a progress bar and a submit button. If I am selecting an Image in the Input, the value changes to undefined. What have I to do Upload this Image (and show the progression of the upload)? HTML with JQuery: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> <input type="file" accept="image/png, image/jpeg"> </div> <div> <progress id="progress" value="0" max="100"></progress> </div> <div> <input type="submit"> </div> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="{% static 'blueimp/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'blueimp/jquery.fileupload.js' %}"></script> <script src="{% static 'blueimp/jquery.iframe-transport.js' %}"></script> <script type="text/javascript"> $('#form').fileupload({ url: '{% url 'upload' %}', sequentialUploads: true, dataType: 'json', type: 'POST', add: function (data) { console.log(data, data.result); }, progress: function (data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress').val(progress); if (progress === 50) { console.log('We made it half way...'); } else if (progress === 100) { console.log('We made it...'); } else { console.log(progress + '%'); } }, done: function(data) { console.log(data.result.name); }, fail: function () { console.log('Failed') } }); </script> </body> </html> My Views: def image_upload(request): … -
Python datetime.date.today() not formatting inside sqllite3
In my database query which is executed with the sqlite3 module I insert a new row of data which includes a date field. The problem is when getting todays date with datetime.date.today().strftime('%Y-%m-%d') which outputs '2023-02-06' (expected output), it changes inside the database to '2015'. Why does this happen? This is a Django project so that is where i created the model for the database. models.py class User(models.Model): ... date_joined = models.DateField('%Y-%m-%d') ... database.py def add_user(self, email, password): date = datetime.date.today().strftime('%Y-%m-%d') self.cursor.execute(f""" INSERT INTO App_user ('username','email','password', 'email_preference', 'region', 'date_joined') VALUES ('{username}', '{email}', '{password}', 'All', 'None', {date}) """) self.con.commit() -
Django include custom @property on ORM model into queryset for future use inside customer filters
Hey there and thank you in advance. I have defined custom property on my ORM model: class MyModel(BaseModel): optional_prop_1 = models.ForeignKey(Model, null=True) optional_prop_2 = models.ForeignKey(AnotherModel, null=True) optional_prop_2 = models.ForeignKey(DifferentModel, null=True) @property def external_reference(self): if self.optional_prop_1: return self.optional_prop_1 if self.optional_prop_2: return self.optional_prop_2 ... All those three fields have a common field that I want to access inside my custom filer query, but because external_reference is defined as "virtual" property I know that I cannot access it inside queryset, so when I do this it would actually work: queryset.filter(top_level_relation__my_model__external_reference__common_field="some_value") I think I got an idea that I need to somehow convert my "virtual" property into a field dynamically with custom models.Manager and with queryset.annotate() but this didn't seem to be working. I tried this: def _get_external_reference(model) -> str: if model.optional_prop_1: return "optional_prop_1" elif model.optional_prop_2: return "optional_prop_1" ... return "" def get_queryset(self): external_reference = _get_external_reference(self.model) return super().get_queryset().annotate(external_reference=models.F(external_reference)) But inside my custom filter I always get Related Field got invalid lookup: external_reference telling me that this field doesn't exist on queryset. Any ideas how to convert property (@property) into a field that I could use later inside queryset -
AJAX and Django, AJAX success not working
In an HTML page I have a table where one can drop items into and that is posted to the server via AJAX as follows: function drop(ev, el) { if (ev.target.tagName=="IMG") { return; } ev.preventDefault(); var data = ev.dataTransfer.getData("text"); el.appendChild(document.getElementById(data)); el.style.width = "168px"; var newWidth = document.getElementById(data); $.ajax({ type: 'POST', url: server_url + currentPath, data: { 'version': data }, success() { console.log(data, "ranked "); }, }); } on the same page, users submit an answer using a button which is linked to a function that sends a POST request to the server: function NextPage(){ answer = $("#justification").val(); if (answer.length < 10){ document.getElementById("warning1").innerHTML = "Please provide an answer"; } else { $.ajax({ type: "POST", url: server_url + currentPath, data: {'answer' : answer}, success: function () { window.location.href = server_url+ nextPath; } }); } } I can read the data from the post request on the server side (i.e., version and answer), and it gets saved as well, but then I cannot move to the next page, and there are no error messages; I noticed that the answer is now passed as a parameter on the URL; not sure what that means. I guess it gets stuck because of an error. I … -
Making a django model field readonly
I am creating a django DB model and I want one the fields to be readonly. When creating a new object I want to set it, but later if someone tries to update the object, it should raise an error. How do I achieve that? I tried the following but I was still able to update the objects. from django.db import models as django_db_models class BalanceHoldAmounts(django_db_models.Model): read_only_field = django_db_models.DecimalField(editable=False) Thank you -
Django don't makemigrations my apps after i install app in install applications Ubuntu(linux)
this is my installed applications ubuntu system ` INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stu', 'stu2', ] ` I get this error, if any one have solution, plz help me It is ubuntu system 1. ashish@ashish-MS-1050:~/Desktop/aculance/test1$ python3 manage.py makemigrations stu 1. No installed app with label 'stu'. 1. ashish@ashish-MS-1050:~/Desktop/aculance/test1$ python3 manage.py makemigrations stu2 1. No installed app with label 'stu2'. 1. ashish@ashish-MS-1050:~/Desktop/aculance/test1$ I tried many time to force migrations but it can't reconise my app and send me this error No installed app with label 'stu'. -
Comment relier ma base de données django avec ma page de connexion
Bonjour, Je dois faire un site en django et je dois relier ma abse données que j'ai créer en django avec la page de connexion de mon site c'est à dire que je dois extraire les informations de ma base de données pour pouvoir vérifier si les informations de connexions sont bonnes. MA base de données et composé d'un id , mots de passe , nom_complet Comment je dois m'y prendre Merci Bonjour, Je dois faire un site en django et je dois relier ma abse données que j'ai créer en django avec la page de connexion de mon site c'est à dire que je dois extraire les informations de ma base de données pour pouvoir vérifier si les informations de connexions sont bonnes. MA base de données et composé d'un id , mots de passe , nom_complet Comment je dois m'y prendre Merci -
Django - Reverse for 'index' not found. 'index' is not a valid view function or pattern name
I am new to Django. I have been working based on the template from Mozilla: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website I have created a project called 'debtSettler'. And it has an app called 'home'. I have the following url mappings: ./debtSettler/debtSettler/urls.py: urlpatterns = [ path('home/', include('home.urls')), path('admin/', admin.site.urls), path('', RedirectView.as_view(url='home/')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ./debtSettler/home/urls.py: app_name = 'home' urlpatterns = [ path('', views.index, name='index'), path('clubs/', views.ClubListView.as_view(), name='clubs'), ] And views: ./debtSettler/home/views.py: from django.http import HttpResponse, HttpResponseRedirect def index(request): num_clubs = Club.objects.all().count() # The 'all()' is implied by default. num_members = Member.objects.count() context = { 'num_clubs': num_clubs, 'num_members': num_members, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) class ClubListView(generic.ListView): model = Club def get_context_data(self, **kwargs): # Call the base implementation first to get the context context = super(ClubListView, self).get_context_data(**kwargs) # Create any data and add it to the context context['some_data'] = 'This is just some data' return context In the template, I have two urls that give the error: <a href=" {% url 'index' %} ">Home</a> <a href=" {% url 'clubs' %} ">All clubs</a> Reverse for 'index' not found. 'index' is not a valid view function or pattern name. If I add the my_app:my_view, it … -
Conection between chrome extension and django website
I am developing a Chrome extension that detect when a file is dowloaded, send it to a website (also created by me with Django) and after the website processed it, Chrome extension receives another file with some results. I would like to know how I could connect them. Does someone have any example or name of some technology that allows Chrome extension send and receive files from a website or server? Thank you in advance! -
Use import_export django library to import personnalized export CSV
I have two action in my application. First I export data to CSV using specific resources (see below) to have personalized Headers and Name of specific foreign Key instead Id. It's OK for Export CSV file. For Import this after modification ... An error raises : **Integrity Error: (1048, "Column 'produit_id' cannot be null") ** Below is the Resource Class for Greffons to get specific columns name and ordering columns in Meta. class GreffonResource(resources.ModelResource): comm = fields.Field( column_name='Pre-Commandes', attribute='comm', ) greffons = fields.Field( column_name='Greffons', attribute='greffons', ) objectif = fields.Field( column_name='Objectifs', attribute='objectif', ) realise = fields.Field( column_name='Realises', attribute='realise', ) reussi = fields.Field( column_name='Reussis', attribute='reussi', ) produit = fields.Field( column_name='Produits', attribute='produit', widget=widgets.ForeignKeyWidget(Produit, 'nom') ) rang = fields.Field( column_name='Rangs', attribute='rang', ) class Meta: model = Greffons fields = ('id', 'produit', 'comm', 'greffons', 'objectif', 'realise', 'reussi', 'rang') export_order = ['id', 'produit', 'comm', 'greffons', 'objectif', 'realise', 'reussi', 'rang'] import_id_fields = ('id',) After Export CSV file, I change data inside and import it after but error :( Below is the code to import data after POST. produit_resource = GreffonResource() dataset = Dataset() new_datas = request.FILES['myfile'] imported_data = dataset.load(new_datas.read().decode(), format='csv') if categorie == "GREFFONS": result = produit_resource.import_data(imported_data, dry_run=True, raise_errors=True) -
python add a list of variables as positional arguments for functions
I have a list of variables that need to be passed in a couple of functions that take the same number of arguments. a = 1 b = 'hello' c = 1.9 args = (a, b, c) op = func_a(args) if <cond1> else func_b(args) def func_a(a, b, c): ... def func_b(a, b, c): ... But sending this as a tuple, the tuple is set to arg a and the function expects args b and c as well. How can I pass these tuple as a, b, and crespectively? -
Django TemporaryUploadedFile not rendered if form is invalid
I have a form that contains FileField as one of its fields. Each field in the form is rendered using as_crispy_field. Issue: If I entered all the inputs (including the file), and the form got re-rendered because it is invalid, it shows the same values of all inputs except the file input value. However, I can see the TemporaryUploadedFile value using {{ form.my_file.value }} -
Redis Error - Error 11001 connecting to redis:6379
I have a Django project in Docker compose container. So, when I'm trying to docker-compose up - it's all OK. All containers, including Redis is up. Redis logs 2023-02-06 14:48:50 1:M 06 Feb 2023 11:48:50.519 * Ready to accept connections But when I'm trying to send a POST request to my API from Postman - I'm getting this error. File "c:\Users\django_env\Lib\site-packages\redis\connection.py", line 617, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: Error 11001 connecting to redis:6379. getaddrinfo failed. Anyone knows how to fix it? I'm working on Windows mashine. Thanks) -
I am randomly getting "SystemError: <class 'pyodbc.Error'> returned a result with an error set" while performing sql query
Our sql query inside Django API perform joins and filtering over millions of records in sql server and takes long time to complete. Error occurs randomly in these api calls. This seem to be the bug in pyodbc while decoding. This occurs at random in docker based linux environment. Related issues - github issue 1014, github open issue 640 Traceback - 2023-02-06T08:23:54.206253807Z [2023-02-06 08:23:54 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:34) 2023-02-06T08:23:54.290137374Z Internal Server Error: /get_table_preview 2023-02-06T08:23:54.290184978Z Traceback (most recent call last): 2023-02-06T08:23:54.290193279Z File "/usr/local/lib/python3.9/encodings/utf_16_le.py", line 15, in decode 2023-02-06T08:23:54.290200679Z def decode(input, errors='strict'): 2023-02-06T08:23:54.290208080Z File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/base.py", line 203, in handle_abort 2023-02-06T08:23:54.290214281Z sys.exit(1) 2023-02-06T08:23:54.290219781Z SystemExit: 1 2023-02-06T08:23:54.290225082Z 2023-02-06T08:23:54.290230382Z The above exception was the direct cause of the following exception: 2023-02-06T08:23:54.290235682Z 2023-02-06T08:23:54.290240883Z Traceback (most recent call last): 2023-02-06T08:23:54.290246183Z File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner 2023-02-06T08:23:54.290251684Z response = get_response(request) 2023-02-06T08:23:54.290256884Z File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 220, in _get_response 2023-02-06T08:23:54.290262485Z response = response.render() 2023-02-06T08:23:54.290267685Z File "/usr/local/lib/python3.9/site-packages/django/template/response.py", line 114, in render 2023-02-06T08:23:54.290273786Z self.content = self.rendered_content 2023-02-06T08:23:54.290279286Z File "/usr/local/lib/python3.9/site-packages/rest_framework/response.py", line 70, in rendered_content 2023-02-06T08:23:54.290284586Z ret = renderer.render(self.data, accepted_media_type, context) 2023-02-06T08:23:54.290289787Z File "/usr/local/lib/python3.9/site-packages/rest_framework/renderers.py", line 99, in render 2023-02-06T08:23:54.290296187Z ret = json.dumps( 2023-02-06T08:23:54.290304288Z File "/usr/local/lib/python3.9/site-packages/rest_framework/utils/json.py", line 25, in dumps 2023-02-06T08:23:54.290324390Z return json.dumps(*args, **kwargs) 2023-02-06T08:23:54.290329990Z File "/usr/local/lib/python3.9/json/__init__.py", line 234, in dumps 2023-02-06T08:23:54.290335191Z … -
Django error saying TemplateDoesNotExist at/
I have an error on my Django Project. The templates folder doens't work. I have the project like this: ├── manage.py ├── myProjet │ ├── __init__.py │ ├── settings.py │ ├── templates │ ├── urls.py │ ├── wsgi.py │ └── wsgi.pyc ├── app1 ├── templates So, I want to use the templates forlder. The template filder is on "/myProjet/templates", not on: "/myProjet/myProjet/templates." The settings.py file is this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join( 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And, the error is raised on the signup function. The singup function is: def SignupPage(request): if request.method=='POST': uname=request.POST.get('username') email=request.POST.get('email') pass1=request.POST.get('password1') pass2=request.POST.get('password2') if pass1!=pass2: return HttpResponse("Your password and confrom password are not Same!!") else: my_user=User.objects.create_user(uname,email,pass1) my_user.save() return redirect('login') return render (request,'signup.html') The error information is this. I have tried to change the base_path in a lot of ways but I always have this error : TemplateDoesNotExist at / signup.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.6 Exception Type: TemplateDoesNotExist Exception Value: signup.html Exception Location: /home/myPC/myProject/my_env/lib/python3.8/site-packages/django/template/loader.py, line 19, in get_template Raised during: app1.views.SignupPage Python Executable: … -
Django: byte indices must be integers or slices, not str error
I am trying to get some data from a payload using a webhook, in the response that i sent along side i added the meta data that should return with the payload and this is how i did it (code below), if you take a close look at the keys, there i one called meta, now i am trying to get some of the data that is in the meta from my webhook view like this views.py webhook @csrf_exempt @require_http_methods(['POST', 'GET']) def webhook(request): payload = request.body order_id = payload['meta']['order_id'] print(order_id) return HttpResponse("testing...") Sending the reponse to the payment gateway @csrf_exempt def process_payment(request, name, email, amount, order_id): auth_token = "FLWSECK_TEST-9efb9ee17d8afe40c6c890294a1163de-X" hed = {'Authorization': 'Bearer ' + auth_token} data = { "tx_ref":''+str(math.floor(1000000 + random.random()*9000000)), "amount":amount, "currency":"USD", "order_id":order_id, "redirect_url":f"http://localhost:3000/service-detail/booking/confirmation/{order_id}", "payment_options":"card", "meta":{ "order_id":order_id, "consumer_id":23, "consumer_mac":"92a3-912ba-1192a" }, "customer":{ "email":email, "name":name, "order_id":order_id }, "customizations":{ "title":"ForecastFaceoff", "description":"Leading Political Betting Platform", "logo":"https://i.im.ge/2022/08/03m/FELzix.stridearn-high-quality-logo-circle.jpg" } } url = ' https://api.flutterwave.com/v3/payments' response = requests.post(url, json=data, headers=hed) response=response.json() link=response['data']['link'] return redirect(link) payload { "event": "charge.completed", "data": { "id": 4136234873, "tx_ref": "6473247093", "flw_ref": "FLW-MOCK-b33e86ab2342316fec664110e8eb842a3c2f956", "device_fingerprint": "df38c8854324598c54e16feacc65348a5e446", "amount": 152, "currency": "USD", "charged_amount": 152, "app_fee": 5.78, "merchant_fee": 0, "processor_response": "Approved. Successful", "auth_model": "VBVSECUREertrCODE", "ip": "52.209.154.143", "narration": "CARD Transaction ", "status": "successful", "payment_type": "card", "created_at": "2023-02-06T11:19:45.000Z", … -
How to use FilteredRelation with OuterRef?
I'm trying to use Django ORM to generate a queryset and I can't find how to use an OuterRef in the joining condition with a FilteredRelation. What I have in Django Main queryset queryset = LineOutlier.objects.filter(report=self.kwargs['report_pk'], report__apn__customer__cen_id=self.kwargs['customer_cen_id']) \ .select_related('category__traffic') \ .select_related('category__frequency') \ .select_related('category__stability') \ .prefetch_related('category__traffic__labels') \ .prefetch_related('category__frequency__labels') \ .prefetch_related('category__stability__labels') \ .annotate(history=subquery) The subquery subquery = ArraySubquery( LineOutlierReport.objects .filter((Q(lineoutlier__imsi=OuterRef('imsi')) | Q(lineoutlier__isnull=True)) & Q(id__in=last_5_reports_ids)) .values(json=JSONObject( severity='lineoutlier__severity', report_id='id', report_start_date='start_date', report_end_date='end_date' ) ) ) The request can be executed, but the SQL generated is not exactly what I want : SQL Generated SELECT "mlformalima_lineoutlier"."id", "mlformalima_lineoutlier"."imsi", ARRAY( SELECT JSONB_BUILD_OBJECT('severity', V1."severity", 'report_id', V0."id", 'report_start_date', V0."start_date", 'report_end_date', V0."end_date") AS "json" FROM "mlformalima_lineoutlierreport" V0 LEFT OUTER JOIN "mlformalima_lineoutlier" V1 ON (V0."id" = V1."report_id") WHERE ((V1."imsi" = ("mlformalima_lineoutlier"."imsi") OR V1."id" IS NULL) AND V0."id" IN (SELECT DISTINCT ON (U0."id") U0."id" FROM "mlformalima_lineoutlierreport" U0 WHERE U0."apn_id" = 2 ORDER BY U0."id" ASC, U0."end_date" DESC LIMIT 5)) ) AS "history", FROM "mlformalima_lineoutlier" The problem here is that the OuterRef condition (V1."imsi" = ("mlformalima_lineoutlier"."imsi")) is done on the WHERE statement, and I want it to be on the JOIN statement What I want in SQL SELECT "mlformalima_lineoutlier"."id", "mlformalima_lineoutlier"."imsi", ARRAY( SELECT JSONB_BUILD_OBJECT('severity', V1."severity", 'report_id', V0."id", 'report_start_date', V0."start_date", 'report_end_date', V0."end_date") AS "json" FROM "mlformalima_lineoutlierreport" … -
Connecting to LND Node through a local-running Django Rest API
I am trying to connect to my LND node running on AWS (I know it is not the best case scenario for an LND node but this time I had no other way of doing it) from my local running Django Rest Api. The issue is that it cannot find the admin.macaroon file even though the file is in the mentioned directory. Below I am giving some more detailed information: view.py `class GetInfo(APIView): def get(self, request): REST_HOST = "https://ec2-18-195-111-81.eu-central-1.compute.amazonaws.com" MACAROON_PATH = "/home/ubuntu/.lnd/data/chain/bitcoin/mainnet/admin.macaroon" # url = "https://ec2-18-195-111-81.eu-central-1.compute.amazonaws.com/v1/getinfo" TLS_PATH = "/home/ubuntu/.lnd/tls.cert" url = f"https//{REST_HOST}/v1/getinfo" macaroon = codecs.encode(open(MACAROON_PATH, "rb").read(), "hex") headers = {"Grpc-Metadata-macaroon": macaroon} r = requests.get(url, headers=headers, verify=TLS_PATH) return Response(json.loads(r.text))` The node is running with no problem on AWS. This is what I get when I run lncli getinfo: $ lncli getinfo: { "version": "0.15.5-beta commit=v0.15.5-beta", "commit_hash": "c0a09209782b1c62c3393fcea0844exxxxxxxxxx", "identity_pubkey": "mykey", "alias": "020d4da213770890e1c1", "color": "#3399ff", "num_pending_channels": 0, "num_active_channels": 0, "num_inactive_channels": 0, "uris": [ .... and the permissions are as below: $ ls -l total 138404 -rwxrwxr-x 1 ubuntu ubuntu 293 Feb 6 09:38 admin.macaroon drwxrwxr-x 2 ubuntu ubuntu 4096 Feb 5 14:48 bin drwxr-xr-x 6 ubuntu ubuntu 4096 Jan 27 20:17 bitcoin-22.0 drwxrwxr-x 4 ubuntu ubuntu 4096 Feb 1 16:39 go -rw-rw-r-- 1 … -
How to connect multiple chained dropdown with Django and HTMX
I have a form with counterparty, object and sections i connected them to each other with django-forms-dynamic package but object not connected to sections Counterparty connected to object form but sections are not connected to object how can i fix that? I guess that im wrong with 2 functions in forms.py: section_choices and initial_sections and they`re not connected to objects but dont know how to fix that forms.py class WorkLogForm(DynamicFormMixin, forms.ModelForm): def object_choices(form): contractor_counter = form['contractor_counter'].value() object_query = ObjectList.objects.filter(contractor_guid__in=[contractor_counter]) return object_query def initial_object(form): contractor_counter = form['contractor_counter'].value() object_query = ObjectList.objects.filter(contractor_guid__in=[contractor_counter]) return object_query.first() def section_choices(form): contractor_object = form['contractor_object'].value() section_query = SectionList.objects.filter(object=contractor_object) return section_query def initial_sections(form): contractor_object = form['contractor_object'].value() section_query = SectionList.objects.filter(object=contractor_object) return section_query.first() contractor_counter = forms.ModelChoiceField( label='Контрагент', queryset=CounterParty.objects.none(), initial=CounterParty.objects.first(), empty_label='', ) contractor_object = DynamicField( forms.ModelChoiceField, label='Объект', queryset=object_choices, initial=initial_object, ) contractor_section = DynamicField( forms.ModelMultipleChoiceField, label='Раздел', queryset=section_choices, initial=initial_sections, ) views.py @login_required def create_work_log(request): if request.method == 'POST': form = WorkLogForm(request.POST, user=request.user) if form.is_valid(): work_log = form.save(commit=False) work_log.author = request.user work_log = form.save() messages.success(request, 'Данные занесены успешно', {'work_log': work_log}) return redirect('create_worklog') else: messages.error(request, 'Ошибка валидации') return redirect('create_worklog') form = WorkLogForm(user=request.user, initial=initial) return render(request, 'contractor/create_work_log.html', {'form': form}) def contractor_object(request): form = WorkLogForm(request.GET, user=request.user) return HttpResponse(form['contractor_object']) def contractor_section(request): form = WorkLogForm(request.GET, user=request.user) return HttpResponse(form['contractor_section'])