Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Load balancer : upstream timed out (110: Connection timed out) while reading response header from upstream
I am new for AWS codepipeline and docker for deploy my django app with load balancer. My app normally work fine. But when i send 10 request in parallel it works. But when i send more than 10 request in parallel than it return 504 gateway timeout error. When i checked in log it return me this error. *257 upstream timed out (110: Connection timed out) while reading response header from upstream, client: xxx.xx.xx.xxx, server: , request: "GET path HTTP/1.1", upstream: "requested url", host: "example.com" I do not know why i got this error error. I try ngnix timeout increase and connection idle timeout also. But did not get any success. I think problem is ==> when my ec2 instance is overload and it create new ec2 instance with load balancer than i got this error. Please help me how can i fix this error. Thank you in advance -
I've a django app connected with my local postgresdb,I've built a docker image of that project using dockerfile but, when I run i'm getting this error
This is my docker file FROM python:3.8.10 # Install required packages # RUN apk add --update --no-cache \ # build-base \ # postgresql-dev \ # linux-headers \ # pcre-dev \ # py-pip \ # curl \ # bash \ # openssl \ # nginx \ # libressl-dev \ # musl-dev \ # libffi-dev \ # rsyslog # Install all python dependency libs RUN mkdir -p /ds_process_apis COPY requirements.txt /ds_process_apis RUN pip install -r /ds_process_apis/requirements.txt # Copy all source files to the container's working directory COPY ./ /ds_process_apis/ WORKDIR /ds_process_apis EXPOSE 8020 CMD ./manage.py migrate --noinput && ./manage.py initadmin && ./manage.py collectstatic --noinput && gunicorn ds_process_apis.wsgi --bind 0.0.0.0:8020 --workers 2 --worker-class sync --threads 6 I'm getting this error I'm new to docker psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? -
student teacher management system
There are two type of users teacher and student: Teacher attributes: First name, last name, teaching since, instrument, email Student attributes: First name, last name ,skill, instrument, student since, email, birthday For every teacher there are one or more students for every student there is only one teacher Teacher roles: Administrator ,assistant and regular teacher Adminstrator: -Can create ,read ,update and delete teacher and student in his school Assistant teacher: -Can read only teacher and student Regular teacher -Can create ,read ,update and delete student -
Cannot change value on form field on Django from template
I am trying to change the value dynamically on a django template via javascript but it is not working, which other ways do I have? Thank you. I have to set a property from Model as a value $('#id_myvariable').change(function() { var name_object = $('#id_myvariable'); var current_name = name_object.val(); var new_name = "new_name" name_object.attr('value',new_name); }); -
How to upload multiple files in Django
I've been trying to find a solution to add multiple files using a drag and drop form. I'm using Django's Rest API and React. This is what i have been trying so far but it seems like this will only do for one file at a time: class FileCollection(models.Model): Name = models.CharField(max_length=150, null=True, blank=True) Files = models.FileField(upload_to='videos_uploaded', null=True, blank=True, validators=[ FileExtensionValidator(allowed_extensions=['mp4', 'm4v', 'mov', 'mpg', 'mpg2', 'mpeg'])]) How can i make it so i can upload multiple files at once with the rest api? I only found some answers on here regarding images. -
cant activate virtual Enviroment
I have tried many ways to enable it, even changing the interpreter, but I still get this error -- ERROR: File C:\Users\Me\Desktop\code.py\learning_log\env\Scripts\Activate.ps1 cannot be loaded because the exe cution of scripts is disabled on this system. Please see "get-help about_signing" for more details. At line:1 char:2 & <<<< c:/Users/Me/Desktop/code.py/learning_log/env/Scripts/Activate.ps1 CategoryInfo : NotSpecified: (:) [], PSSecurityException FullyQualifiedErrorId : RuntimeException -
how to get a particular field from django model
I want a command for getting a query set from the model. The SQL command will be like - SELECT teamName FROM TABLE WHERE userName=userName; -
how can I generate an unique id for a string. in python
how can I generate an unique ID for a string, which means only that string has a that id and if we try to put another string in that function it does not match. -
Django - Displaying model data based on primary key
I have a model of multiple images and I want to display each of them in their own separate Owl carousel when an image is clicked by using the primary key as a reference. I have everything set up but for some reason my images are not being loaded into the carousel. I have no bad responses so If anyone can help me I'd be grateful. urls.py: urlpatterns = [ # homepage path('', views.index, name='index'), # get the primary key when an image is clicked path('<int:pk>', views.index, name='index_with_pk'), # use that primary key to fetch that image's data path('carousel/', views.carouselData, name="carousel_data") ] ajax call in index.html when image is clicked: $.ajax({ type: "GET", url: '{% url "carousel_data"%}', data: { "prime_key": prime_key }, success: function(data) { console.clear(); console.log("Image object primary key: " + prime_key); $(".owl-carousel").owlCarousel({ items:1, loop:true, nav:true, dots: false, autoplay: false, autoplayTimeout: 5000, smartSpeed: 500, autoplayHoverPause: false, margin: 20, touchDrag: true, mouseDrag: false, navText : ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"] }); }, error: function(data){ console.log('something went wrong'); } }) views.py: def carouselData(request): if request.method == "GET": # get the primary key from ajax my_key = request.GET.get('prime_key') carouselObjects = Portrait.objects.filter(pk=my_key).values( 'painting_left', 'painting_right', 'painting_top', 'painting_bottom', 'painting_back' )[0] carouselContext = { 'carouselObjects': carouselObjects … -
In Django Query set using filter with custom arguments
I am using the filter in Django queryset, as it takes arguments like: Model.objects.filter(name="Amit") here is name and it's value, I am getting from the request of API: def get(self, request): column = request.query_params.get('column') val = request.query_params.get('value') query = Data.objects.filter(column=val).values() serializer = DataSerializer(query, many=True).data return Response(serializer) but here column [inside filter] is not getting recognized as the request parameter, it is taken as the column name of the table which is not available. The error I got: django.core.exceptions.FieldError: Cannot resolve keyword 'column' into field. Hope this information is suitable for understanding the problem, if something is missing please let me know and kindly help me out with this. -
corrupted files uploading csv and zip files via postman toward django rest api
Hi, I'm using django 4.0.6 (python 3.8) with djangorestframework 3.13.1 on windows. I'm testing on localhost my app with postman and postman agent up to date. The authorization JWT is working fine. If I upload an image or a txt the files are ok. If I upload csv or zip files they result in corrupted files. Only short csv files are correctly uploaded, long csv files result in corrupted lines on the lower part of the text with this sort of characters: Û™eÞqHÂÔpŠl°‹<û yjϪ›kÃx›Ûr-¥x¡S¼à2SÕkÛår'mÒÕµd5ÿ¶Vê0@1 ̦Záë1§ŠIÇaÎ “’ÏÛ€t»vRoT"·‡Qf„¾´é-Oa)]ЧK‹5C¤sWB0),3 Zž—2¸Ñóo«jŸH“ I can't figure out how to fix it, reading other posts I couldn't find a solution that fit with this situation. Thank You for any suggestion! Here my model: class FileUploader(models.Model): id_file = models.AutoField('id_file', primary_key=True) Campaign_Name = models.CharField('Campaign_Name', max_length=255) ViewpointSurvey = models.FileField('ViewpointSurvey',upload_to=path_and_rename_base,max_length=255,blank=False,null=False,db_column='ViewpointSurvey', name='ViewpointSurvey') ProjectSurvey = models.FileField('ProjectSurvey', upload_to=path_and_rename_base, max_length=255, blank=False, null=False, db_column='ProjectSurvey', name='ProjectSurvey') Trajectories = models.FileField('Trajectories', upload_to=path_and_rename_base, max_length=255, blank=False, null=False, db_column='Trajectories', name='Trajectories') screenshots = models.FileField('screenshots', upload_to=path_and_rename_base, max_length=255, blank=False, null=False, db_column='screenshots', name='screenshots') timestamp=models.DateTimeField('timestamp',auto_now_add=True,db_column='timestamp', name='timestamp') id_project=models.CharField('id_project', max_length=255) class Meta: db_table = "file_uploader" verbose_name_plural = 'file_uploader' verbose_name = "file_uploader" Here the view: class CSVUploadAPI(GenericAPIView): parser_classes = [MultiPartParser] serializer_class = UploadSerializer def put(self, request): data_collect = request.data serializer = UploadSerializer(data=data_collect) if serializer.is_valid(): serializer.save() Here the serializer: class UploadSerializer(serializers.ModelSerializer): … -
The joined path (/static/logo/my_project_logo.jpg) is located outside of the base path component (/home/softsuave/project/my_project_api/static)
I got this error while using this command. The joined path (/static/logo/my_project_logo.jpg) is located outside of the base path component (/home/softsuave/project/my_project_api/static) Traceback (most recent call last): File "", line 1, in File "/home/softsuave/project/my_project_api/venv/lib/python3.10/site-packages/django/contrib/staticfiles/finders.py", line 276, in find result = finder.find(path, all=all) File "/home/softsuave/project/my_project_api/venv/lib/python3.10/site-packages/django/contrib/staticfiles/finders.py", line 110, in find matched_path = self.find_location(root, path, prefix) File "/home/softsuave/project/my_project_api/venv/lib/python3.10/site-packages/django/contrib/staticfiles/finders.py", line 127, in find_location path = safe_join(root, path) File "/home/softsuave/project/my_project_api/venv/lib/python3.10/site-packages/django/utils/_os.py", line 29, in safe_join raise SuspiciousFileOperation( django.core.exceptions.SuspiciousFileOperation: The joined path (/static/logo/my_project_logo.jpg) is located outside of the base path component (/home/softsuave/project/my_project_api/static) result = finders.find(uri) from django.contrib.staticfiles import finders settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'site/assets/') STATICFILES_DIRS = [ BASE_DIR / "static/", BASE_DIR, ] MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/qr_code') file structure: my_project my_app static logo my_project_logo.jpg template my_app my_template.html my_tempate.html {% load static %} <!DOCTYPE html> <html> <head> <title> QR Code </title> <style> #goable{ width: 300px; height: auto; margin: 40%; border: 1px solid black; } #img1{ height:100px ; margin:10px 100px 0px 100px; }#img2{ height: 200px; margin:10px 50px 0px 50px; } h1,p{ text-align: center; } </style> </head> <body> <div id="goable"> <img id='img1' src="{% static 'logo/my_project_logo.jpg' %}" alt="My image"> <h1>SCAN ME!!!</h1> <p> TO Notify Drivers that their car is about to get a parking … -
How to get soap request body with spyne
@rpc(Request91Type, _returns=AnyDict, _out_variable_name="Response91") def Request91(ctx, Request91Type): try: logging.info( f'Initialized objects {str(Request91Type).encode("utf-8")}') return { "GUID": 'aaa', "SendDateTime": "2022-04-11T19:50:11", "Certificate": CertificateMinimumType.generate(), "Status": "Выдан", "StatusCode": "1601", "Inspector": None } except Exception as e: logging.info(f'Exception occurred: {str(e)}') I tried to access Request91type.guid but it did not work:) This is my soap request example:https://pastebin.com/QyJWL2jJ And this one is for complex models : https://pastebin.com/gdZGkmqN I also tried to print(ctx.in_string) but returned <generator object WsgiApplication.__wsgi_input_to_iterable at 0x7faf41451e70> like this message -
The view mainsite.views.winner_detail didn't return an HttpResponse object. It returned None instead
Guys I'm losing my freaking mind. I Keep getting this error after updating a model form. I've made many of these forms before in previous projects and before and never had this issue. I've looked at every single question here with the same issue and got nowhere. this is the view def winner_edit_form(request, pk): winner = PrizeWinner.objects.get(id=pk) if request.method == 'POST': form = WinnerForm(request.POST, instance=winner) if form.is_valid(): form.save() return HttpResponseRedirect('winner-details.html', winner.id) else: form = WinnerForm(instance=winner) return render(request,'edit-winner-form.html',{'form': form}) I've tried several versions of this, including: def winner_edit_form(request, pk): if request.method == 'POST': winner = PrizeWinner.objects.get(id=pk) form = WinnerForm(request.POST or None, instance=winner) if form.is_valid() and request.POST['winner'] != '': form.save() return HttpResponseRedirect('winner-detail') else: form = WinnerForm(instance=winner) context = {'winner': winner, 'form': form} return render(request, 'partials/edit-winner-form.html', context) I literally copied and pasted from previous and more complex projects and from other examples and I keep getting this error. These are my urls from django.urls import path from mainsite import views urlpatterns = [ path('',views.HomePage.as_view(), name='home'), path("winner-detail/<int:pk>", views.winner_detail, name='winner-detail'), path("winner-detail/<int:pk>/edit/", views.winner_edit_form, name='winner_edit_form'), ] models.py class PrizeWinner(models.Model): name = models.CharField(max_length=200, blank= False) prizecode = models.CharField(max_length=120, blank=True) prizestatus = models.CharField(max_length=200, null=True, blank=True, choices=STATUS_CHOICES, default='Unclaimed') prizechoices = models.CharField(max_length=200, null= True, blank= True, choices =PRIZE_CHOICES, default='£10 Bar Tab') … -
Don't want to change value of specific variable when function run with threading
want to store that value of variable and don't want to change it until condition meets in function which run in threading in python...I don't want to change value of that variable -
How would I be able to use the Emmet tag "!" in Djang-html?
I know that to fix the emmet abbreviations for most tags for Django-html is by going to preferences ---> settings ---> Emmet. After getting there I proceeded to add (Django-html, html) into the item and value area. After doing so I am able to use normal emmet abbreviations but I want to use the "!" tag. is there a reason why I cannot use it or is there a fix needed. Thank y'all in advance. -
Django filters date range filter is not working
I really don't understand how to connect these two fields or should I just create one. On my front, I have a starting date and end date I can not connect to the backend properly using django-filters Please see the below code My filters.py class VideoFolderFilter(FilterSet): name = CharFilter(field_name='name', lookup_expr='icontains', widget=forms.TextInput(attrs={'class': "form-control"})) subscription_plan = ModelChoiceFilter( label='subscription_plan', queryset=Plans.objects.all()) start_date_range = DateFromToRangeFilter(field_name='start_date_range', widget=forms.TextInput(attrs={'class': "form-control"})) end_date_range = DateFromToRangeFilter(field_name='end_date_range', widget=forms.TextInput(attrs={'class': "form-control"})) def get_date_range(self, start_date_range, end_date_range): return Sample.objects.filter(sampledate__gte=start_date_range, sampledate__lte=end_date_range) class Meta: model = VideoFolder fields = '__all__' widgets = {'start_date_range': DateInput(),} exclude = [ 'thumbnail_link', 'link', 'name'] My views.py @login_required def search_videos(request): if Subscriber.objects.filter(user=request.user).exists(): subscription = Subscriber.objects.get(user=request.user) else: message = "Seams like you don't have subscription with us please select one of the plans" return redirect(reverse('main')) video_filter = VideoFolderFilter(request.GET, queryset=VideoFolder.objects.filter(type='video').order_by('-created_date')) videos = video_filter.qs return render(request, 'search-videos.html', locals()) Should I change the views.py to query if yes how to date range and other fields will be included And my search-videos.html <div class="search-video-form-section mb-3"> <p>Use one or more filters to search below</p> <form method="GET"> <div class="form-group mb-px-20 filter-form"> <label class="text-base">Name Contains</label> <!-- <input type="text" class="form-control" placeholder="Keyword" /> --> {{ video_filter.form.name }} </div> <div class="d-flex flex-wrap date-box"> <div class="form-group input-field"> <label class="text-base">Start Date</label> <div class="input-group input-daterange"> {{ video_filter.form.start_date_range … -
How to return Boolean from jQuery plugin to html?
I am currently working on a password strength meter that provides real-time update to the user via onkeyfocus event. I have decided to use https://github.com/elationbase/jquery.passwordRequirements for this purpose. Currently I am trying to return a Boolean from the jQuery plugin to my html so that I could check if the user input password has met the requirement completely. If it does not, to prevent them from further continuing in whatever they are doing. Below is what I have came up with so far. My question is how can I pass the var is_passed back to the html? jQuery Plugin (function($){ $.fn.extend({ passwordRequirements: function(options) { // options for plugin var defaults {...}; options = $.extend(defaults, options); var is_passed = false; // the variable that I wish to return return this.each(function() { ... //skipping all the checks $(this).on("keyup focus", function(){ var thisVal = $(this).val(); if (thisVal !== '') { checkCompleted(); if (is_passed === true) { console.log('is_passed', is_passed); return is_passed; } } )}; HTML <script> $(document).ready(function () { $('.pr-password').passwordRequirements({}); var is_passed = $('.pr-password').passwordRequirements({}); //not working as it returns an Obj }); </script> -
edit post always going to the same pk in url django
im making a social media app in django im setting up the edit post option at the home page but im getting a problem that in the for loop each post's edit option points to a same posts pk for example if the edit option of post 2 or post 3 is clicked, it still goes to the edit page of post 1. views.py class EditPostView(UpdateView): model = Post form_class = EditPostForm template_name = "edit_post.html" home page {% for post in object_list %} <div class="flex flex-wrap -m-4"> <div class="p-4 md:w-2/5"> <div class="h-full border-2 border-gray-200 border-opacity-60 shadow-lg rounded-md overflow-hidden"> <img class="w-full object-cover object-center " src="{{post.image.url}}" alt="blog"> <div class="p-6"> <h2 class="tracking-widest text-xs title-font font-medium text-gray-400 mb-1">{{post.hashtag}} </h2> <h1 class="title-font text-lg font-medium text-gray-900 mb-3">@{{post.user.username}} </h1> <p class="leading-relaxed mb-3"><span class="font-medium font-bold mr-2">{{post.user.username}}</span> {{post.caption}} </p> <div class="flex items-center flex-wrap "> <div class="inline-flex items-center md:mb-2 lg:mb-0"> <span class="mr-3 inline-flex items-center lg:ml-auto md:ml-0 ml-auto leading-none text-sm pr-3 py-1"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-suit-heart-fill w-4 h-4 mr-1" viewBox="0 0 16 16"> <path d="M4 1c2.21 0 4 1.755 4 3.92C8 2.755 9.79 1 12 1s4 1.755 4 3.92c0 3.263-3.234 4.414-7.608 9.608a.513.513 0 0 1-.784 0C3.234 9.334 0 8.183 0 4.92 0 2.755 1.79 1 4 1z" /> … -
Image not getting updated/replaced in CRUD
I am doing CRUD operation which also has image, I am unable to replace the image in the update operation with another image, the previous image remains, please help below is my update function def update(request,id): if request.method == 'GET': print('GET',id) editclothes = Products.objects.filter(id=id).first() s= POLLSerializer(editclothes) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) sub_category_dict = SUBCategories.objects.filter(isactive=True) sub_category = SUBCategoriesSerializer(sub_category_dict,many=True) color_dict = Colors.objects.filter(isactive=True) color = ColorsSerializer(color_dict,many=True) size_dict = Size.objects.filter(isactive=True) size = SizeSerializer(size_dict,many=True) hm = {"context": category.data,"sub_context":sub_category.data,"color_context":color.data,"size_context":size.data,"Products":s.data} return render(request, "polls/product_edit.html", hm) else: print('POST',id) editclothes = {} d = Products.objects.filter(id=id).first() if d: editclothes['categories']=request.POST.get('categories') # print('categories is equal to:',editclothes['categories']) editclothes['sub_categories']=request.POST.get('sub_categories') editclothes['color']=request.POST.get('color') editclothes['size']=request.POST.get('size') editclothes['title']=request.POST.get('title') editclothes['price']=request.POST.get('price') editclothes['sku_number']=request.POST.get('sku_number') editclothes['gender']=request.POST.get('gender') editclothes['product_details']=request.POST.get('product_details') editclothes['quantity']=request.POST.get('quantity') if len(request.FILES)!=0: if len(d.image)>0: os.remove(d.image.path) editclothes['image']=request.FILES['image'] form = POLLSerializer(d,data=editclothes) if form.is_valid(): form.save() print("data of form",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('polls:show') else: print(form.errors) print("not valid") return redirect('polls:show') below is my product_edit html <form method="POST" > {% csrf_token %} <table> <thead> <tr> <td>Categories</td> <td> <select name="categories" id=""> {% for c in context %} {% if c.id == Products.categories %} <option value="{{c.id}}" selected></option> {% endif %} <option value="{{c.id}}">{{c.category_name}}</option> {% endfor %} </select> </td> </tr> <tr> <td>Sub-Categories</td> <td> <select name="sub_categories" id=""> {% for c in sub_context %} {% if c.id == Products.sub_categories %} <option value="{{c.id}}" selected></option> {% endif %} <option … -
imshow() got an unexpected keyword argument 'hover_data'
def staff_activity_view(request, pk): staff = get_object_or_404(User, pk=pk) staff_activity = StaffActivity.objects.filter(user_id=staff.id) now = timezone.now() start = now - timezone.timedelta(days=364) daterange = date_range(start, now) counts = [[] for i in range(7)] dates = [[] for i in range(7)] day_names = list(calendar.day_name) first_day = daterange[0].weekday() days = day_names[first_day:] + day_names[:first_day] for dt in daterange: count = staff_activity.filter(timestamp__date=dt).count() day_number = dt.weekday() counts[day_number].append(count) dates[day_number].append(dt) fig = px.imshow( counts, color_continuous_scale='Blues', x=dates[0], y=days, # hover_data=['count', 'date', 'day'], height=300, width=900, title='Staff Activity', ) fig.update_layout( plot_bgcolor='white', paper_bgcolor='white', # xaxis_title='Date', yaxis_title='Activity', ) fig.update_traces( xgap=5, ygap=5, ) chart = fig.to_html() return render(request, 'gym_admin/chart.html', {'chart': chart}) What I wanted to change is the label color on hover, if I add hover_data directly, getting the above error. Tried the following solution but still the labels are same hover_text = [f'{day} {date.strftime("%d %b %Y")} {color}' for day, date in zip(days, dates[0]) for color in counts[0]] fig.update_traces(text=hover_text) Labels currently I am getting are x, y and color, looking for a solution, thank you -
Linkify Foreign Keys with Django Tables2 and Slugs
I am trying to build summary tables with clickable links that drill down to lower levels. The hierarchy in descending order is Division -> Region -> Branch -> Profit Center where each profit center can have multiple "receivables." I want the division summary view to show all of the regions (e.g. California, Central Texas, Ohio, etc) and a sum of the 'total_amount' for the regions. I want to be to click a region and it drills down to the branches where I can see a summary for each branch. So on and so forth I've spent far longer than I would like to admit on this and the lines commented out on tables.py is just a fraction of what I have tried. What am I missing? class Division(models.Model): name = models.CharField(max_length=128, unique=True) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('division-detail', args=[str(self.slug)]) class Region(models.Model): name = models.CharField(max_length=128, unique=True) division = models.ForeignKey('Division', to_field='name', on_delete=models.CASCADE) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('region-summary', args=[str(self.slug)]) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs) class Branch(models.Model): name = models.CharField(max_length=128) number = models.CharField(max_length=4, unique=True) region = models.ForeignKey('Region', to_field='name', on_delete=models.CASCADE) slug = models.SlugField(unique=True, null=True) def … -
Payfort Error code 00013 invalid currency
I was trying to make a request to Payfort API using python: url = "https://sbcheckout.payfort.com/FortAPI/paymentPage" sign = "766l8ccloPvjBEb1dzhPj6?]access_code=0zXXVcMMK04wNqwk9EgBamount=10000command=AUTHORIZATIONcurrency=AEDcustomer_email=test@payfort.comlanguage=enmerchant_identifier=2dccbd67merchant_reference=XYZ9239-yu89813434432order_description=iPhone 6-S766l8ccloPvjBEb1dzhPj6?]" requestParams = { 'command' : 'AUTHORIZATION', 'access_code' : '*****************', 'merchant_identifier' : '********', 'merchant_reference' : 'XYZ9239-yu8981343443254', 'amount' : '10000', 'currency' : 'USD', 'language' : 'en', 'customer_email' : 'test@payfort.com', 'signature' : 'a9cca1a93b2c9326748c8b884229e2b8da345a2dd3fea34ba3491a7f2902d402', 'order_description' : 'iPhone 6-S', } res = requests.post(url, requestParams) print(res.text) and got this response {"response_code":"00013","response_message":"Invalid Currency","fort_id":null,"token":"52190Zl41PbSHvmr9OqmVKx6G817501458703215891441727366723522234"}; I need help to know what causes Invalid currency error? -
how to dynamically show form input fields base on user selection from dropdown options
I have this form that is used to enter student grades per subject now on this form I have 3 dropdown boxes that are dependent on each other, what I want to accomplish is that after the user selects the classroom that the students are in, I want the input fields for each subject to appear on the same form that is only in that class that the user selected so that the user can enter the grades of the students per subject but I am having a hard time figuring out how to implement such behavior. in short,i want to show input fields for subjects base on the classroom the user selected form.py <div class="container-fluid"> <form id="result-form" method="post"> {% csrf_token %} <!-- Modal --> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel"> {% block modal-title%} Add Result {% endblock%}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="row"> <div class="col-md-12" id="msg8" style="font-size: 2rem; color:rgb(255, 144, 47)"></div> <div class="col-md-12 form-group p-2"> <label class="form-label">Class Name</label> {% render_field form.room class+="form-control" %} </div> <div class="col-md-12 form-group p-2"> <label class="form-label">Exam Name</label> {% render_field form.exam class+="form-control" %} </div> <div class="col-md-12 form-group p-2"> <label class="form-label">Student</label> {% render_field form.student class+="form-control select2" %} </div> <div class="hidden" id="subject-fields"></div> <div class="form-group mb-3 … -
Code run in setUpTestData for django testing is not captured in test time
When I run tests using setUpTestData() the time spent in setUpTestData() is not captured. I can see this when running it in pycharm (it shows only the test run time) as well as when the tests run in CircleCi. Is there something special that needs to be done so that setUpTestData() time will be captured (at least on the TestSuite xml)