Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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']) -
as_crispy_field cannot re-render the uploaded FileField data from return POST request of Django formset
I have a Django formset that receives the POST request data once submitted, and it saves it (including the uploading file) normally to my database, but if the form is invalid, the page renders again with the same values but missing the selected uploaded file. I am passing the data to the formset as: fs = MyFormset(request.POST, request.FILES, .......) and I am rendering the fields of each form one by one. So, the file field data is: <div class="col-md-10"> {{ form.included_documents|as_crispy_field }} </div> When I submit a new form but it fails in one of the validation criteria, it returns with no file chosen although there was a file chosen. But, if I have a saved form, it renders the uploaded file normally. Failed Tested Workaround: According to this Github issue answer, I tested it and it parsed the file input with a better look, but it still fails with parsing the TemporaryUploadedFile. To make sure that I have the value in my form, I added the below, and it showed the value correctly in the span element not the crispy field element: <div class="col-md-10"> {{ form.included_documents|as_crispy_field }} <span>{{ form.included_documents.value }}</span> </div> What am I missing here to render the … -
Create this model instance automatically after creating the User model instance
I want the UserProfile model object to be created automaticaly when User object is created. Models.py class UserManager(BaseUserManager): def create_user(self, email, username,password=None,passwordconfirm=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None): user = self.create_user( email, username=username, password=password ) user.is_admin = True user.is_staff=True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username=models.CharField(verbose_name='username', max_length=255, unique=True,) password=models.CharField(max_length=100) account_created=models.DateField(auto_now_add=True,blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','password'] def __str__(self): return self.username def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin class UserProfile(User): joined_forums=ArrayField(models.CharField(max_length=100),default=None,blank=True) user_profile_picture=models.ImageField(upload_to="profile_pictures/",default='user-profile-icon.png') recent_interactions=ArrayField(ArrayField(models.CharField(max_length=200),size=2,blank=True),blank=True) Before I had the User instance as foreign key.Now i have removed that and inherited the User class in UserProfile as Multi-table inheritance.Now I am unable to migrate and its asking for default values for the pointer … -
Python django / flask deployment
What is a good way to daploy a django or a flask website, I have a website i want to deploy but don't know how to get a website or something that helps me solve my problem -
I need help installing python3 centos7
I need help installing python3 centos7.NumPy, Requests, BeautifulSoup, matplotlib, Speech Recognition, Scarpy Packages like this are required to be installed. What I want to do is an automatic installation where I can work first locally and then live by using these packages. Can those who have information on this subject contact me on the Whatsapp line at +905315425877? Actually, I tried to install Python3 and django, but I keep getting errors. -
'str' object has no attribute 'chunks'
I have this error when try to save image in folder and in mongo db how i can solve it # Save image file to the static/img folder image_path = save_image_to_folder(value) # Save image to MongoDB using GridFS image_id = fs.put(value, filename=value, content_type=value.content_type) # Return the image id and path for storage in MongoDB and Django folder return {'id': str(image_id), 'path': image_path} def save_image_to_folder(value): # Create the file path to save the image in the Django static/img folder image_name = value image_path = f'decapolis/static/img/{image_name}' # Open the image file and save it to the folder with open(image_path, 'wb+') as destination: for chunk in value.chunks(): destination.write(chunk) # Return the image path return image_path am try to solve it in many way but not working -
Django REST Framework JSON API show an empty object of relationships link when use relations.HyperRelatedField from rest_framework_json_api
I'm create the REST API for space conjunction report, I want the conjunction to be a child of each report. My models: from django.db import models from django.utils import timezone class Report(models.Model): class Meta: managed = False db_table = 'report' ordering = ['-id'] predict_start = models.DateTimeField(null=True) predict_end = models.DateTimeField(null=True) process_duration = models.IntegerField(default=0, null=True) create_conjunction_date = models.DateTimeField(null=True) ephe_filename = models.CharField(max_length=100, null=True) class Conjunction(models.Model): class Meta: managed = False db_table = 'conjunction' ordering = ['-conjunction_id'] conjunction_id = models.IntegerField(primary_key=True) tca = models.DateTimeField(max_length=3, null=True) missdt = models.FloatField(null=True) probability = models.FloatField(null=True) prob_method = models.CharField(max_length=45, null=True) norad = models.OneToOneField(SatelliteCategory, to_field='norad_cat_id', db_column='norad', null=True, on_delete=models.DO_NOTHING) doy = models.FloatField(null=True) ephe_id = models.IntegerField(null=True) pri_obj = models.IntegerField(null=True) sec_obj = models.IntegerField(null=True) report = models.ForeignKey(Report, related_name='conjunctions', null=True, on_delete=models.DO_NOTHING) probability_foster = models.FloatField(null=True) probability_patera = models.FloatField(null=True) probability_alfano = models.FloatField(null=True) probability_chan = models.FloatField(null=True) My serializers: class ConjunctionSerializer(serializers.ModelSerializer): class Meta: model = Conjunction fields = '__all__' class ReportSerializer(serializers.ModelSerializer): conjunctions = relations.ResourceRelatedField(many=True, read_only=True) class Meta: model = Report fields = '__all__' My views: from rest_framework import permissions from rest_framework_json_api.views import viewsets from .serializers import ReportSerializer, ConjunctionSerializer from .models import Report, Conjunction class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer permission_classes = [permissions.AllowAny] class ConjunctionViewSet(viewsets.ModelViewSet): queryset = Conjunction.objects.all() serializer_class = ConjunctionSerializer permission_classes = [permissions.AllowAny] My urls.py from django.contrib import … -
Extending django's core admindoc library
I want to add some more functionality to the Django admindoc, specifically this function - class ModelDetailView(BaseAdminDocsView): template_name = 'admin_doc/model_detail.html' def get_context_data(self, **kwargs): pass Should I copy the whole module and paste it over a separate app and then do the changes and then include it in my project? But with this approach, I am adding redundancy to my Django project as I already have all this by default and my usecase is to just extend this function and not everything else. -
Get only one filed from a nested serializer
Her it is my django serializer: class ShopSerializer(serializers.ModelSerializer): rest = RestSerializer(many=True) class Meta: model = RestaurantLike fields = ('id', 'created', 'updated', 'rest') This will wrap whole RestSerializer inside ShopSerializer on response. How can I get only one or two fields from RestSerializer instead of having all the fields inside ShopSerializer? Get only two field of RestSerializer instead of whole RestSerializer -
Nginx Error 413 Entity too large on AWS ELB
So,I am using Django for my backend application deployed on AWS Elastic Beanstalk (EC2 t2.micro, Amazon Linux 2). When I am trying to submit files (.mp4, pdf) that are obviously larger than 1MB, I get Nginx Error 413: Entity too large. The problem is that everything I have tried works for a few hours, before everything is getting reset to the default configurations. As far as I understood there is an auto-scaling functionality that resets everything after each new deploy and sometimes even without deploy.I know that a lot of people had faced this kind of problem, and for some of them actions described in other posts solved the problem. However, for me everything resets either immediately after deploy, or in a couple of hours. I have already tried, as suggested in other posts on Stackoverflow, changing the nginx file from the EC2 console, adding my own configuration file in source code (.ebextensions folder), applied some changes to my S3 bucket, and many other options. ***NOTE: I have also created a custom function for handling large files in Django itself, but I think it is irrelevant to the Nginx error that I get. Thanks. -
How to access value with in change_form file of django admin?
Hy there, I want to access value and apply position ordering on related field with in change_form file of django admin. I have two model from django.db import models from django.contrib.auth import get_user_model User = get_user_model() PRODUCT_TYPE_CHOICES=[(1,'New'),(2,'Old')] CURRENCY_TYPE_CHOICES=[(1,'USD'),(2,'INR')] class Product(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) product_category = models.ForeignKey( ProductCategory, on_delete=models.SET(get_default_category) ) product_type = models.IntegerField(choices=PRODUCT_TYPE_CHOICES,blank=True, null=True) currency_type=models.IntegerField(choices=CURRENCY_TYPE_CHOICES,blank=True, null=True) country = CountryField(max_length=10, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=255, blank=True, null=True) price = models.FloatField(max_length=255,blank=True, null=True) class Comment(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) forum = models.ForeignKey( Product, on_delete=models.CASCADE,related_name="product_comments") In admin panel I want to display comment of particular product under the user field as shown in below image. Can you guys help me how do i solve this scenario. -
Sitemaps not showing after git push
I have created a sitemaps for my django project but the sitemaps.py file doesn't reflect in the git repository even after i push. i tried creating the file from git but the changes are still not reflecting -
Can't I set the number with a decimal part to "MinMoneyValidator()" and "MaxMoneyValidator()" in "MoneyField()" with Django-money?
I use Django-money, then I set 0.00 and 999.99 to MinMoneyValidator() and MaxMoneyValidator() respectively in MoneyField() as shown below: # "models.py" from django.db import models from djmoney.models.fields import MoneyField from djmoney.models.validators import MinMoneyValidator, MaxMoneyValidator class Product(models.Model): name = models.CharField(max_length=50) price = MoneyField( # Here max_digits=5, decimal_places=2, default=0, default_currency='USD', validators=[ # Here # Here MinMoneyValidator(0.00), MaxMoneyValidator(999.99), ] ) Then, I added a product as shown below: But, I got the error below: TypeError: 'float' object is not subscriptable So, I set 0 and 999 to MinMoneyValidator() and MaxMoneyValidator() respectively in MoneyField() as shown below, then the error above is solved: # "models.py" from django.db import models from djmoney.models.fields import MoneyField from djmoney.models.validators import MinMoneyValidator, MaxMoneyValidator class Product(models.Model): name = models.CharField(max_length=50) price = MoneyField( max_digits=5, decimal_places=2, default=0, default_currency='USD', validators=[ # Here # Here MinMoneyValidator(0), MaxMoneyValidator(999), ] ) Actually, I can set 0.00 and 999.99 to MinValueValidator() and MaxValueValidator() respectively in models.DecimalField() without any errors as shown below: # "models.py" from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Product(models.Model): name = models.CharField(max_length=50) price = models.DecimalField( # Here max_digits=5, decimal_places=2, default=0, validators=[ # Here # Here MinValueValidator(0.00), MaxValueValidator(999.99) ], ) So, can't I set the number with the decimal part to MinMoneyValidator() … -
TemplateDoesNotExist at/ on Django
I have the project like this: ├── manage.py ├── myProjet │ ├── __init__.py │ ├── settings.py │ ├── templates │ ├── urls.py │ ├── wsgi.py │ └── wsgi.pyc ├── app1 ├── templates When I roun the project, I am always getting this error: TemplateDoesNotExist at/ I have tried everythin, but I can't fix it. My 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': ['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', ], }, }, ] I have tried in a lot of ways, but I am always ge3tting the error. The error is rased on the singUp function. The function is this: 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') -
How to add 2 values in 1 hx-target Django
I have a form to select counterparty, object and section When im choosing counterparty which have object and this objects has section all`s good But when i change counterparty which have object and doesnt have sections i still has sections from previous object I want to clear with hx-target 2 fields: object and sections, but its working only with one How am i suppose to do that? counter.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-target='#id_contractor_object' %} </div> <div class="mt-3"> {{ form.contractor_object.label_tag }} {% render_field form.contractor_object class='form-select mt-2' autocomplete='off' hx-get='/sections/' hx-target='#id_contractor_section' %} </div> <div class="mt-3"> {{ form.contractor_section.label_tag }} {% render_field form.contractor_section class='form-select mt-2' autocomplete='off' %} </div> -
Python 3.11.1. Getting error Failed to establish a new connection: [Errno -5] No address associated with hostname
I am using zeep 4.2.1 library to consume web services(RFC) from SAP. The API's are working in local server and getting the necessary response. However the API is not working in development environment(docker container). Getting error message as HTTPConnectionPool(host=' ', port=): Max retries exceeded with url. (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ffa989589b0>: Failed to establish a new connection: [Errno -5] No address associated with hostname',))" After doing telnet from development environment response received It gets connected but after sometime(1 min approx) 408 "Request Time Out" Application Server Error - Traffic control Violation is raised and connection is closed. Note-('Have removed hostname from error message but hostname and port are correct `HTTPConnectionPool(host=' ', port=) Kindly help me does any additional setting required for SAP RFC in docker container -
can I use .h5 file in Django project?
I'm making AI web page using Django and tensor flow. and I wonder how I add .h5 file in Django project. writing whole code in views.py file but I want to use pre-trained model not online learning in webpage.