Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failed to load resource: net::ERR_INSUFFICIENT_RESOURCES when creating Infinite Scroll
In my front page, I made it for the webpage to load more results when the user scrolls to the bottom of the page. It's paginated so that it loads 15 results at a time. When I'm testing, I have almost 400 in total, and it shows Failed to load resource: net::ERR_INSUFFICIENT_RESOURCES at about 9th page and the page kind of freezes. Why does this happen even though I'm only loading 15 at a time? Do you think I have to use multiple webpage pagination (the "ordinary" pagination where you get redirected to next page)? By the way, I use pure javascript for front-end, and django rest framework in the back-end. I'm kind of a beginner, so my explanation might not be clear, so please be patient with me. -
How to update field and not refresh the template
I am making the polls app in the first Django tutorial. I see each time you vote, the page refresh and goes to the top of the page, I want it to just stay where it is and only update the paragraph tag. detail.html: <html dir="rtl"> <h1>{{ article.title }}</h1> <h2>{{ article.author }}</h2> <h1>{{ article.text }}</h1> <p>I have {{article.votes}}</p> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'main:vote' article.id %}" method="post"> {% csrf_token %} <input type="submit" value="Vote"> </form> </html> vote function in views.py: def vote(request, article_id): article = get_object_or_404(Article, pk=article_id) article.votes += 1 article.save() # TODO: Change it so it doesnt return new refreshed html return render(request, 'main/detail.html', {'article': article}) -
Inconsistent MEDIA URLs in Django 3.0 vs 3.1 in tests
I have a Django project whose models have a thumbnail image, and I have some tests to check the generated paths of the images. # myapp/models.py from django.db import models def thumbnail_upload_path(instance, filename): # There's more happening in this method, but to simplify: return f"books/{filename}" class Book(models.Model): thumbnail = models.ImageField( upload_to=thumbnail_upload_path, null=False, blank=True, default="" ) # tests/myapp/test_models.py from django.test import TestCase from myapp.factories import BookFactory # using factoryboy class BookTestCase(TestCase): def test_thumbnail_url(self): book = BookFactory(thumbnail__filename="tester.jpg") self.assertTrue(book.thumbnail.url.startswith("books/tester")) That test passes in Django 2.2 and 3.0. But when running it in Django 3.1 the thumbnail URL starts with a slash: "/books/tester..." I'm guessing it's this change in 3.1... The STATIC_URL and MEDIA_URL settings set to relative paths are now prefixed by the server-provided value of SCRIPT_NAME (or / if not set). This change should not affect settings set to valid URLs or absolute paths. I'm not sure how to make the test behaviour consistent in all Django versions. When running the tests I set MEDIA_ROOT to tempfile.mkdtemp(). I've tried appending a "/" to the end of that. I've tried setting FORCE_SCRIPT_NAME to "/". On the actual website - not in the tests - I have MEDIA_ROOT = "/" and the image paths … -
Showing Anonymous user error and also not able to check whether user is authenticated only on one page.Working fine on all others in django
My views.py was working fine for every function except the below one(handlerequest).It is showing me error that Anonymous user has no object customer on website even when there is (working correctly on other pages). This is my views.py: @csrf_exempt def handlerequest(request): customer=request.customer.user order, created=Order.objects.get_or_create(customer=customer, complete=False) form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': print('order successful') else: print('order was not successful because' + response_dict['RESPMSG']) return render(request, 'paymentstatus.html', {'response': response_dict,'types':Category.objects.all()}) Also in my html which I have given below even after writing the if else conditions it is not showing whether the user is logged in or not and it is working correctly for all other pages but not the html page under this view.Below is my html which is working fine for all html files except paymentstatus.html(from the view above) {% if user.is_authenticated %} <li class="d-none d-xl-block"> <div class="alert alert-success" role="alert"> Hello , {{user.first_name}} </div> </li> <li class="d-none d-xl-block"> <a href="/logout/" class="btn header-btn">Logout</a> </li> {% else %} <li class="d-none d-xl-block"> <a href="/signup/" class="btn header-btn">Sign Up</a> </li> <li class="d-none d-xl-block"> <a href="/login/" class="btn header-btn">Login</a> </li> {% endif %} Please … -
I tried using makemigrations to connect the website to the server but got the "password authentication failed for user 'postgres'"error message
I think the problem might be where I saved my local_settings.py but not too sure about that. Does anyone have any idea on what I could do here? Picture of Error Message -
Django: No route found for path 'messages/'
So I have a django project that includes websockets, it works perfect, then I decided to add to another html file script the websockets code to have in two pages the same websockets, the problem is that the websockets of the second page is giving me this error No route found for path 'messages/'. What I think the problem is that I did not add the other url page "messages" to my routing. does anyone know what is going on? -
when i try to acess by using http://127.0.0.1:8000/models/1 throwing unbound local error
i checked everything multiple times but i dont understand where is the problem My url.py file urlpatterns=[ path('models/<int:name_id>',views.name,name='name'), path('models/',views.index,name='models') ] my views.py file def index(request): return render(request,'index.html',{ 'Persons': Person.objects.all() }) def name(request,name_id): Person=Person.objects.get(pk=name_id) return render(request,'name.html',{ 'Person':Person }) my models.py file class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name it is throwing an error -
Response 400 while using Requests package in Django
I want to scrap Myntra using Django Framework but when I put my code in Django project I get 400 error. The same code runs without error when I run it on the same file even in Django. Means calling the MyntraScraperClass in MyntraScraper.py file. Here is my project directory BackendController -MyntraScraper.py myDjangoApp -views.py Inside views.py, there is a function where I am calling my MyntraScraperClass def tst(request): ------------ The same code that is MyntraScraperClass runs error free when I call it on BackendController -MyntraScraper.py Here is my code: import requests, json from bs4 import BeautifulSoup import os, ssl import certifi import urllib3 class MyntraScraperClass: def __init__(self,url): self.url=url def myntra(self): mt={} http = urllib3.PoolManager( cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)): ssl._create_default_https_context = ssl._create_unverified_context proxy = {'http': '-------'} headers = {'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'} for x in range(0,5): print(x) try: s = requests.Session() res = s.get(self.url, headers=headers, verify=True, proxies=proxy) print(res) soup = BeautifulSoup(res.text, "lxml") print(soup) if "Access Denied" in soup.title: continue break except requests.exceptions.ProxyError: continue except Exception as e: print(e) mt['error']=e script = None for s in soup.find_all("script"): if 'pdpData' in s.text: script = s.get_text(strip=True) break … -
Django KeyError on handling of JS cookies
I am doing some simple web-shop project in django and keep having this issue after cleaning cookies generated and running project. KeyError at / 'device' I've already understood that code generating the problem is from one of views files (the line of most importance here is device = request.COOKIES['device'] ): def cartData(request): if request.user.is_authenticated: customer = request.user.customer else: device = request.COOKIES['device'] customer, created = Customer.objects.get_or_create(device=device, name = None) order, created = Order.objects.get_or_create(customer=customer, complete=False,) items = order.orderitem_set.all() cartItems = order.get_cart_items return {'cartItems':cartItems ,'order':order, 'items':items} I need a system that creates a device code that allows me to track people without authentication. To do this I use JS cookies. Here is the code I am using: function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? … -
Django: Why does a POST to UpdateView silently fail?
I've had a couple of occasions where I have introduced a very annoying bug into my Django site. I'm using Class Based Views (CBV), and I caused CreateView and UpdateView to silently fail. The repro steps for, say, the CreateView problem are: Enter a URL into the browser to display the CreateView-related form Enter the form data Click the submit button The completed form re-appears but no object is created - Django doesn't go to the URL in the model's get_absolute_url(...) function # views.py snippet class ListingUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Listing fields = ['orig', 'dest', 'container_type_code', 'container_bic_owner', 'container_max_kg', 'ship_imo', 'ship_owner_imo', 'ship_embarkation', 'ship_sailing', 'ship_docking', 'ship_unloaded', 'reserve_price', 'buy_now_price', 'currency', 'stage'] # listing_form.html snippet <div class="col-4" style="padding-left: 0; display: inline; float: left;"> {{ form.orig|as_crispy_field }} </div> <div class="col-4" style=" display: inline; float: left;"> {{ form.dest|as_crispy_field }} </div> <div class="col-4" style=" display: inline; float: left;"> {{ form.container_type_code|as_crispy_field }} </div> As you can see, I render individual fields rather than render the whole form with one tag. -
Django "OR" like statement in Queryset?
Just have a simple syntax question onto Django, imagining the following queryset: queryset = Requests.objects.get_queryset().filter(status='Pending', up_rank__gte=config.REQ_RANK - 10, down_rank__gte=config.REQ_RANK - 10) Is there any way that I can setup my query like that: up_vote__gte=config.REQ_RANK - 10 OR down_vote__gte=config.REQ_RANK - 10 ?! (See pseudo OR) As I want to filter onto both, up_rank and down_rank __gte. The only way I know would be a query chain but to me that seems not to be efficient, Is there any other way than a query chain statement or do I just talk nonsense and chain is fine? Thanks in advance -
How do I only get values from Django queryset?
So I have a filtered QuerySet with a specific field, that looks like this: [{'category':'book'}, {'category':'food'}, {'category':'movie'}, {'category':'book'}, {'category':'style'}, ...]. I now want to make a list that only contains the values(book, food, movie, style), with no duplicates. How do I make it possible? Thanks. :) -
Django REST POST null value in column "user_id" violates not-null constraint
I have error after send post request for creating new item in user field - it return null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (61, My Company, {2,3}, 2020-08-08 10:41:54.355926+00, My desc, 2, 2, null). . My data for send in JSON { "name": "My Company", "members":[2, 3] , "user": 2, "description": "My desc", "status": 2, "theme": 2 } serializers.py class AccountSerializer(serializers.ModelSerializer): user=serializers.StringRelatedField(read_only=False) class Meta: model=Account fields='__all__' class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class CompanySerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) try: if self.context['request'].method in ['GET']: self.fields['members'] = serializers.SerializerMethodField() except KeyError: pass class Meta: model = Company fields = '__all__' def get_members(self, obj): accounts = Account.objects.filter(id__in=obj.members) return AccountSerializer(accounts, many=True).data class CompanyListSerializer(serializers.ModelSerializer): class Meta: model = Company fields = '__all__' -
User registration using UserCreationForm failing to save to database
I've been learning Django and I'm trying to understand how to extend some of the built-in functionality. To do that I've referenced Customizing Authentication in Django and tried to implement the instructions I've found there in a standard django-admin project. The problem is that when I try to save the form to the database (sqlite3 included db), nothing is recorded. The form passes the is_valid check, but when I check the database however, nothing has been added to either my user or patients tables. Hoping someone can point out where this is going wrong, thank you. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): isPatient = models.BooleanField(default=False) class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) age = models.PositiveIntegerField() forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.db import transaction from .models import * class RegisterPatient(UserCreationForm): age = forms.IntegerField() class Meta: model = User fields = UserCreationForm.Meta.fields + ("age") @transaction.atomic def save(self, commit=True): user = super(RegisterPatient, self).save(commit=False) user.isPatient = True user.save() patient = Patient.objects.create(user=user) patient.firstName.add(*self.cleaned_data.get('age')) patient.save() views.py def register(response): form = RegisterPatient(response.POST) if form.is_valid(): print("is Valid") # < Code reaches here form.save return redirect("/") settings.py AUTH_USER_MODEL = 'main.User' admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin … -
rollback saved objects whenever email send failed
Hi I've been wondering how to rollback a saved object on a following method when one method failed. forms.py # somewhere class forms def handle(self, view, request, *args, **kwargs): # assuming i get an object successfully. application = models.Application.objects.first() # do something in its attrs and save application.name = 'test' application.save() # application is fix and send via django.core.mail EmailMessage self.send_mail(application) return True now when I had a good connection everything will work fine. But when it does not it will save the application but will not send the email. Resend is not an option since its a one time send supposedly. Now my idea to rollback the application and throw exception something like "Action Failed. Maybe poor connection. Please try again". try: application.save() self.send_mail(application) except ConnectionError?: # rollback ? raise Exception(msg) ? Any help and better way to handle it? Thanks for the help and sorry for the trouble. -
telethon - message to some channels does not forwarded
I have created a Django app that it will forward messages from specific channels to some channels. I call them broker. My problem is that for two of my channels forwarded messages are not sent to telegram server. In fact I get not any error and I see this on console msg forw to dest channel .... but it does not show on channel. This problem will show after some hours working and just for two of my channels (other channels work correctly).Now for solving the problem i restart Django app. It's interesting when I restart app, all sent messages that were didn't show in channel will come to channel. How can I debug or solve this problem? @client.on(events.NewMessage) async def my_event_handler(event): chat = await event.get_chat() sender = await event.get_sender() brokers = Broker.objects.all() for broker in brokers: for source in broker.source_channels.all(): if source.username == sender.username: for dest in broker.destination_channels.all(): if source.username == dest.username: continue try: print('msg forw to dest cahnnel: {} at time: {}'.format(dest.username, timezone.now())) await event.forward_to(dest.username) except: print('error, dest channel is: {}'.format(dest.username)) pass client.start() client.run_until_disconnected() -
Django BooleanField - Checkbox not showing in form on website
I have the following: forms.py class StoreSettingsForm(ModelForm): enable_repricer = forms.BooleanField(required=True) enable_ignore_min_price = forms.BooleanField(required=True) class Meta: model = Store fields = '__all__' exclude = ['user'] models.py class Store(models.Model): user = models.ForeignKey(User, models.SET_NULL, blank=True, null=True) store_name = models.CharField(max_length=100, blank=False) ... enable_repricer = models.BooleanField(default=False) enable_ignore_min_price = models.BooleanField(default=False) template.html <form method="post"> {% csrf_token %} <h4>Repricer Settings</h4> <div class="row"> {{ form.non_field_errors }} <div class="fieldWrapper col s4"> {{ form.enable_repricer.errors }} <label for="{{ form.enable_repricer.id_for_label }}">Enable Repricer:</label> {{ form.enable_repricer }} </div> <div class="fieldWrapper col s4"> {{ form.enable_ignore_min_price.errors }} <label for="{{ form.enable_ignore_min_price.id_for_label }}">Allow Repricer to ignore min_price:</label> {{ form.enable_ignore_min_price }} </div> <div class="fieldWrapper col s4"> {{ form.repricer_factor.errors }} <label for="{{ form.repricer_factor.id_for_label }}">Repricer aggressiveness factor (1-100):</label> {{ form.repricer_factor }} </div> </div> <input class="btn" type="submit" value="Submit"> </form> </div> view.py class StoreSettingsView(View): template_name = 'store_settings.html' def get(self, *args, **kwargs): store = Store.objects.get(id=kwargs['id']) data = { 'store_name': store.store_name, 'store_email': store.store_email, ... 'enable_ignore_min_price': store.enable_ignore_min_price, 'enable_repricer': store.enable_repricer, 'repricer_factor': store.repricer_factor, } form = StoreSettingsForm(initial=data) return render(self.request, self.template_name, { "store": store, "form": form, }) It does not show up in the form. All field are showing on the page but not the 2 boolean fields. The labels are showing and in the HTML. I have excluded many fields from the code blocks to make it more easy … -
Incorrect data of user for create and update for field
I can not send POST and PUT method requests with JSON data, as { "name": "My Company", "members":[2, 3] , "user": 2, "description": "My desc", "status": 2, "theme": 2 } Incorrect data of user for create and update for field and get error Invalid data. Expected a dictionary, but got int . How i can solve it? serializers.py class AccountSerializer(serializers.ModelSerializer): user=serializers.StringRelatedField(read_only=False) class Meta: model=Account fields='__all__' class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class CompanySerializer(serializers.ModelSerializer): user = UserSerializer() #(read_only=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) try: if self.context['request'].method in ['GET']: self.fields['members'] = serializers.SerializerMethodField() except KeyError: pass class Meta: model = Company fields = '__all__' #('id', 'name', 'description', 'date_created', 'user', 'status', 'theme', 'members') def get_members(self, obj): accounts = Account.objects.filter(id__in=obj.members) return AccountSerializer(accounts, many=True).data class CompanyListSerializer(serializers.ModelSerializer): # memb = serializers.ReadOnlyField(source='members.user') class Meta: model = Company fields = '__all__' -
Django require Ajax test
I am working on quite old project (django version 1.7.4, python 2.7). Some tests that were functional are now crashing. I want to override test, that is controlling if request is or is not ajax. I have similar problem also on other tests. i defined my own decorator: def require_ajax(view): @wraps(view, assigned=available_attrs(view)) def wrapped_view(request, *args, **kwargs): if not request.is_ajax(): raise SuspiciousOperation() return view(request, *args, **kwargs) return wrapped_view test_with_ajax is working fine, but when i ommit HTTP_X_REQUESTED_WITH=u'XMLHttpRequest' in test_without_ajax i got NoReverseMatch: Reverse for 'homepage' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] instead as expected HttpResponseBadRequest class RequireAjaxTest(TestCase): @require_ajax def require_ajax_view(request): return HttpResponse() urls = tuple(patterns(u'', url(r'^require-ajax/$', require_ajax_view), )) def test_with_ajax(self): response = self.client.get(u'/require-ajax/', HTTP_X_REQUESTED_WITH=u'XMLHttpRequest') self.assertIs(type(response), HttpResponse) self.assertEqual(response.status_code, 200) # FIXME def test_without_ajax(self): response = self.client.get(u'/require-ajax/') self.assertIs(type(response), HttpResponseBadRequest) self.assertEqual(response.status_code, 400) Whole error message: ====================================================================== ERROR: test_without_ajax (...test_views.RequireAjaxTest) ---------------------------------------------------------------------- Traceback (most recent call last): File ".../test_views.py", line 39, in test_without_ajax response = self.client.get(u'/require-ajax/') File ".../env/lib/python2.7/site-packages/django/test/client.py", line 470, in get **extra) File ".../env/lib/python2.7/site-packages/django/test/client.py", line 286, in get return self.generic('GET', path, secure=secure, **r) File ".../env/lib/python2.7/site-packages/django/test/client.py", line 358, in generic return self.request(**r) File ".../env/lib/python2.7/site-packages/django/test/client.py", line 422, in request response = self.handler(environ) File ".../env/lib/python2.7/site-packages/django/test/client.py", line 110, in __call__ response = … -
Displaying a submission for a specific post. Django
So i want to display submission for a post, but it seems that Django cant link it to the post. (error when accessing the page: Submission matching query does not exist.) Also trying to create a view, which has both details of a post and also can display submissions for that post How can you link the submission in this case? To be more specific, how do i need to change the views.py function in order to do that? (made a migration and also created a submission for a post in admin view) models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=40) author = models.ForeignKey(User, on_delete=models.CASCADE) post_creation_time = models.DateTimeField(auto_now_add=True) genre = models.CharField(max_length=30, blank=True, null=True, choices= genre_choices) stage = models.CharField(max_length=30, blank=True, null=True, choices= stage_choice) optional_notes = models.CharField(max_length=80, default= 'dummy-text') def get_absolute_url(self): return reverse('home_view') def __str__(self): return self.title + ' | ' + str(self.author) class Submission(models.Model): post = models.ForeignKey(Post, related_name='submissions', on_delete=models.CASCADE) submission_author = models.ForeignKey(User, on_delete=models.CASCADE) submission_title = models.CharField(max_length=40) submission_creation_time = models.DateTimeField(auto_now_add=True) submission_body = models.TextField() def __str__(self): return self.submission_title + ' | ' + self.submission_body views.py def ViewPostMain(request, pk): post = Post.objects.get(id=pk) submissions = post.submissions.get(id = pk) context = {'post' : post, 'submissions' : … -
iam getting foloowing error when i am trying to save my project to github
i tried saving my django project to github but am getting an error after running the commands ,after running final commaad i am getting the following error,please some one help me wit this error and please give me a tutorial form where i can learn how to save my work to github as well as the changes i made to my project ! [rejected] master -> master (non-fast-forward) error: failed to push some refs to 'https://github.com/kp1311/Careerboost' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. -
AttributeError: 'function' object has no attribute 'as_view'. What's wrong?
Good afternoon! I am trying to solve this problem, but all my attempts to solve it myself have only resulted in changing def to class, and this does not help. Can you tell me what the problem is? views.py from django.core.mail import send_mail, BadHeaderError from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .models import Form def FormListView(request): if request.method == 'GET': form = FormListView() else: form = FormListView(request.POST) if form.is_valid(): name = form.cleaned_data['name'] surname = form.cleaned_data['surname'] email = form.cleaned_data['email'] try: send_mail(name, surname, email, ['kirill_popov_000@mail.ru']) except BadHeaderError: return HttpResponse('Invalid') return redirect('success') return render(request, "index.html", {'form': form}) def Success(request): return HttpResponse('Success!') urls.py from django.urls import path from .views import FormListView urlpatterns = [ path('', FormListView.as_view(), name = 'home'), path('success/', Success.as_view(), name = 'success') ] -
TypeError at /payment/ argument of type 'method' is not iterable .Not able to figure out the reason of this error
This is a checksum.py file provided by paytm for their payment gateway integration. When I am using it I am getting argument of type 'method' is not iterable . I am not able to figure out the reason of this error. IV = "@@@@&&&&####$$$$" BLOCK_SIZE = 16 def generate_checksum(param_dict, merchant_key, salt=None): params_string = __get_param_string__(param_dict) salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def generate_refund_checksum(param_dict, merchant_key, salt=None): for i in param_dict: if("|" in param_dict[i]): param_dict = {} exit() params_string = __get_param_string__(param_dict) salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def generate_checksum_by_str(param_str, merchant_key, salt=None): params_string = param_str salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def verify_checksum(param_dict, merchant_key, checksum): # Remove checksum if 'CHECKSUMHASH' in param_dict: param_dict.pop('CHECKSUMHASH') # Get salt paytm_hash = __decode__(checksum, IV, merchant_key) salt = paytm_hash[-4:] calculated_checksum = generate_checksum(param_dict, merchant_key, salt=salt) return calculated_checksum == checksum def verify_checksum_by_str(param_str, merchant_key, checksum): # Remove checksum #if 'CHECKSUMHASH' in param_dict: … -
Custom error messages in Django form are not shown
I have a form in Django with custom error messages: from django import forms class OnlineOrderForm(forms.Form): # order info order_count = forms.FloatField(label="count", max_value=10000.0, error_messages={ "invalid": "لطفا یک عدد صحیح یا اعشاری معتبر وارد کنید", "required": "وارد کردن تعداد درخواستی اجباری است", "max_value": "حداکثر تعداد درخواستی، دههزار عدد میباشد", }) And the template is: <li class="padding-16"> <span class="margin-right">تعداد درخواستی</span> <span class="margin-left left">{{ form.order_count }}</span> </li> But I still get default error messages on the field. Is there anything that I've done wrong? I also tried this approach: class Meta: fields = '__all__' error_messages = { 'order_count': { 'required': "وارد کردن تعداد درخواستی اجباری است", }, } Got the same result. -
Froala Editor in Django project (ImageManager)
Im using froala Editor in my Django Project, its working fine, but not the image manager, the upload of images working fine but the ImageManager loading images from froala server and not my server. In the SDK documentation I should use this as view.py for listing files: # Django from django.http import HttpResponse import json from froala_editor import Image def load_images(request): try: response = Image.list('/public/') except Exception: response = {'error': str(sys.exc_info()[1])} return HttpResponse(json.dumps(response), content_type="application/json") But Im using the django framework not SDK so I have to write an own SDK because Image is not included in the framwork so I cant import it. ¨The output of the files should looks like: [ { "url":"https://myserver.com/assets/photo1.jpg", "thumb":"https://myserver.com/assets/thumbs/photo1.jpg", }, ... ] Original list methode from Froala SDK @staticmethod def list(folderPath, thumbPath = None): """ List images from disk. Parameters: folderPath: string thumbPath: string Return: list: list of images dicts. example: [{url: 'url', thumb: 'thumb', name: 'name'}, ...] """ if thumbPath == None: thumbPath = folderPath # Array of image objects to return. response = [] absoluteFolderPath = Utils.getServerPath() + folderPath # Image types. imageTypes = Image.defaultUploadOptions['validation']['allowedMimeTypes'] # Filenames in the uploads folder. fnames = [f for f in listdir(absoluteFolderPath) if isfile(join(absoluteFolderPath, f))] for …