Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgresql not working with django on Macos: El Capitan
I installed Postgresql from the official site (version 4.0), I created a database with "pgAdmin 4", and tried to connect my django project to it. But an error prevented me from the running the django server, the error says: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 25, in <module> import psycopg2 as Database File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 2): Symbol not found: ____chkstk_darwin Referenced from: /Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/psycopg2/.dylibs/libcrypto.1.1.dylib Expected in: /usr/lib/libSystem.B.dylib in /Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/psycopg2/.dylibs/libcrypto.1.1.dylib During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/yyy/.local/share/virtualenvs/mysite-G0YpajmP/lib/python3.9/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen … -
How to Deploy Django project in Cpanel that shows neither setup python app nor terminal?
I have finished creating a Django app and i want to deploy it in webserver Cpanel, it is my first time, but it seems my client has a cheap hosting plan that has Cpanel without setup python app nor terminal so i have found no way to install python and python app. Is there a way i can get these things in the Cpanel software section or install python and Deploy Django app. I have been searching for some days but there seem to be no relevant answer according to the problem i face. The Cpanel shows a softaculous as a way to install softwares in the server. -
How out from nested JSON in JSON, get this date and do serialization for API in Django RestFramework
Hi I'm new in DRF and need a help . I write API.Then user ,for example, put in url http://api.result/82467/pulse , then he get information for result whith number 82467 and measurement of pulse (must to get only this data): { "code": "1120", "norm": null, "value": "1", }, { "code": "1121", "norm": null, "value": "2", } and if http://api.result/82467/termom then he get information for result whith number 82467 and measurement of termom (must to get only this data): { "code": "1118", "norm": "35.9 - 37.0", "value": "36.5", } I get this data from db and give information for user, that`s why I must serialize this data. field "type" is dynamic.Field "exams" is JSONField() in model Result and "code","value" and "norm" - BaseData objects .My problem is in point, when I must get fields from "review"("code","value" and "norm") in views.py for serialization , because it is json and I don't know how I must work with it , how get this data and how do serialization . Maybe json.dump() but then I got str and can't convert in dict . Maybe someone give me some advice, please. { "id": 56, "number": "82467", "date": "2021-08-19", "exams": [ { "type": "termom", "stamp": "2021-08-19R17:00:17", … -
Django/React/Postgres One-to-Many wont update hero_id column to user_id
I am trying to store the UsersHeroes to the UserAccount database by doing a one-to-many relational database. It seems to work fine when I manually set the UserHero from the Admin site to relate to a user but when it comes to trying to submit it on the front end, it just defaults it to 1 since I set it up that way in the model. If I am logged in as user id = 2 and create a hero with that user logged in, it will only save it to user id = 1. This is how my models is set up: class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): #allows you to create user if not email: raise ValueError("Adventurers must have an email address or you shall not pass.") email = self.normalize_email(email) #normalize is a built in function to normalize email user = self.model(email = email, name = name) #normalizes capital to lowercase user.set_password(password) #hashes password for security and sets database # if hacker hacks database you see it user.save() #saves the user return user def create_superuser(self, email, name, password=None ): u = self.create_user(email, name, password) u.is_staff = True u.is_active = True u.is_superuser = True u.save(using=self._db) return u class … -
iterating with django customized filters
SO i'm trying to use symbols on my textarea to edit the users input when it's been displayed on the website, but my problem is after getting all the text within the symbols i.e ( __ myText __ ), The output isn't what it's meant to be, this is the output 👆👆 and this is the input 👆👆👆, python isn't iterating through the article completely as the code above tells it to but instead it just stops at the first text in-between the double-underscore(_). I would appreciate as you help me out :) -
Can't show progress bar in PyTube
I'm wrote a video downloader in Python Django and I'm using PyTube. There is an extra function from PyTube which allows you to show an progress bar. I wrote some lines from the bar but this erorr appears: TypeError: progress_function() missing 1 required positional argument: 'bytes_remaining' I'm sure my code isn't complete yet but I cant figure out what to change that everything works. This is my code: views.py def converter(request): download_begins = True if request.method == 'POST': link = request.POST['link'] video = YouTube(link) format = request.POST['format'] uuid = shortuuid.ShortUUID().random(length=4) if format == "3": with OpenKey(HKEY_CURRENT_USER, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders') as key: downloads = QueryValueEx(key, '{374DE290-123F-4565-9164-39C4925E467B}')[0] yt = YouTube(link, on_progress_callback=progress_function) audio_file = yt.streams.filter(only_audio=True).first().download(downloads) base, ext = os.path.splitext(audio_file) new_file = base + uuid + '.mp3' os.rename(audio_file, new_file) elif format == "4": with OpenKey(HKEY_CURRENT_USER, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders') as key: downloads = QueryValueEx(key, '{374DE290-123F-4565-9164-39C4925E467B}')[0] yt = YouTube(link, on_progress_callback=progress_function) ys = yt.streams.filter(res="1080p").first().download(downloads) base, ext = os.path.splitext(ys) new_file = base + uuid + '.mp4' os.rename(ys, new_file) context = {'format': format, 'begins': download_begins} return render(request, 'home/videoconverter.html', context) return render(request, 'home/videoconverter.html') def percent(tem, total): perc = (float(tem) / float(total)) * float(100) return perc def progress_function(stream, chunk, file_handle, bytes_remaining): size = stream.filesize p = 0 while p <= 100: progress = … -
django select_for_update acquires relation lock
I have this code sample that should take row (tuple) lock in postgres, however it seems to take table (relation) lock instead: with transaction.Atomic(savepoint=True, durable=False): record = MyModel.objects.select_for_update().filter(pk='1234') record.delete() time.sleep(5) raise Exception By looking at the pg_locks during the time of the transaction I can see: select locktype, database, relation::regclass, pid, mode, granted from pg_locks where pid <> pg_backend_pid(); For my knowledge, I should have seen "tuple" in the locktype since I'm only locking specific row/s and not the entire table -
Filter by fields from foreignKey relationships
I got a bunch of models and some of them are connected (by foreign-key relationships) and I wrote a serializer which allows me to print out all of the connected fields that I want, and leave out what I do not want to see. Great. Now I also have a basic filter, which uses the model (PmP) which contains all the foreignkeys, but now I want to add another filter for a field (field name e from PmPr Model) from a different Model, one that is read in via foreignkey connection (pr in Model PmP). But I dont know how to do that and as far as I can see, I cant set two filter_classes inside my view (PmPLListView)?! And I dont know how to access the field via the foreignkey relation. So how do I go about this? If I can access the e field from PmPr Model via my existing filter - than that is also fine with me, I dont necessary want two filter classes (if even possible). It was just me first thought. (btw. sorry about the strange names, but unfortunately I'm not allowed to write the real names) these are my models (at least the … -
Unable to fetch data from mysql using django
I am not getting the data into the table. I assure you that I didn't get any errors while running python manage.py runserver and my database connection with Django is working perfectly. I also assure you that the table in my database has adequate data and there is no issue in the database. From views.py: from django.shortcuts import render, HttpResponse from anapp.models import Tblchkone # Create your views here. def main(request): return render(request, 'main.html') def getTblchkone(request): allcategories = Tblchkone.objects.all() context = {'allcategories' : allcategories} return render(request, 'main.html', context) From models.py: from django.db import models from django.db.models.base import Model # Create your models here. class Tblchkone(models.Model): categoryId = models.BigAutoField(primary_key=True, editable=False) categoryName = models.CharField(max_length=14, unique=True) From main.html: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>MAIN</title> </head> <body> <table class="table"> <thead> <tr> <th scope="col">Category_Id</th> <th scope="col">Catefory_Name</th> </tr> </thead> <tbody> {% for x in getTblchkone %} <tr> <td>{{x.categoryId}}</td> <td>{{x.categoryName}}</td> </tr> {% endfor %} </tbody> </table> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> -
Is settings CORS_ALLOW_ALL_ORIGINS in production ever okay?
I have a project where many different domains will be making requests to my django API, these domains will frequently change and I will not know what these domains will be, so have no way of whitelisting them. Is it okay to set CORS_ALLOW_ALL_ORIGIN to True, and if not, what security risks do I face, and is there an alternative method I can approach this with if so? -
Extract JSON content in Metabase SQL query
Using: Django==2.2.24, Python=3.6, PostgreSQL is underlying DB Working with Django ORM, I can easily make all sort of queries, but I started using Metabase, and my SQL might be a bit rusty. The problem: I am trying to get a count of the items in a list, under a key in a dictionary, stored as a JSONField: from django.db import models from jsonfield import JSONField class MyTable(models.Model): data_field = JSONField(blank=True, default=dict) Example of the dictionary stored in data_field: {..., "my_list": [{}, {}, ...], ...} Under "my_list" key, the value stored is a list, which contains a number of other dictionaries. In Metabase, I am trying to get a count for the number of dictionaries in the list, but even more basic things, none of which work. Some stuff I tried: Attempt: SELECT COUNT(elem->'my_list') as my_list_count FROM my_table, json_object_keys(data_field:json) AS elem Error: ERROR: syntax error at or near ":" Position: 226 Attempt: SELECT ARRAY_LENGTH(elem->'my_list') as my_list_count FROM my_table, JSON_OBJECT_KEYS(data_field:json) AS elem Error: ERROR: syntax error at or near ":" Position: 233 Attempt: SELECT JSON_ARRAY_LENGTH(data_field->'my_list'::json) FROM my_table Error: ERROR: invalid input syntax for type json Detail: Token "my_list" is invalid. Position: 162 Where: JSON data, line 1: my_list Attempt: SELECT ARRAY_LENGTH(JSON_QUERY_ARRAY(data_field, '$.my_list')) … -
How to implement custom django filter for aggregated data from related model
models.py ... class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Hike(models.Model): hiker = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='hikes') hike_date = models.DateField(max_length=100, blank=False) distance_mi = models.FloatField(blank=False) views.py ... class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer serializers.py class PersonSerializer(serializers.ModelSerializer): hikes = serializers.PrimaryKeyRelatedField(many=True, read_only=True) all_hikes = Hike.objects.all() def total_mi(self, obj): result = self.all_hikes.filter(hiker__id=obj.id).aggregate(Sum('distance_mi')) try: return round(result['distance_mi__sum'], 2) ... total_miles = serializers.SerializerMethodField('total_mi') ... class Meta: model = Person fields = ('id','first_name','last_name','total_miles') filters.py class HikerFilter(django_filters.FilterSet): hiker = django_filters.ModelChoiceFilter(field_name="hiker", queryset=Person.objects.all()) class Meta: model = Hike fields = { 'hiker': ['exact'], 'hike_date': ['gte', 'lte', 'exact', 'gt', 'lt'], 'distance_mi': ['gte', 'lte', 'exact', 'gt', 'lt'], } *simplified data +---------+------------+-------------+ | hike_id | hike_date | distance_mi | +---------+------------+-------------+ | 2 | 2020-11-02 | 4.5 mi | | 3 | 2021-03-16 | 3.3 mi | | 5 | 2021-08-11 | 5.3 mi | | 7 | 2021-10-29 | 4.3 mi | +---------+------------+-------------+ The Person view includes "total_miles" stat added via the Serializer (total_mi). Person endpoint http://localhost:8000/persons/2/ { "id": 2, "first_name": "Miles", "last_name": "Marmot", "hikes": [ 2, 3, 5, 7 ], "total_miles": 17.4, }, Currently, the "total_miles" is for all years. My QUESTION: how can I filter "total_miles" in the Person view by a specific year? e.g. http://localhost:8000/persons/2/?year=2020 > "total_miles": 4.5, e.g. … -
How to redirect back two pages Django?
I have a book page. On this page is the button "In favorite". If the user clicks on the button and is authenticated, it will use addBookmark view to add a new object into the database(and just reload the book page). However, if the user isn't authenticated, it'll redirect to the login page firstly. @login_required def addBookmark(request, slug): book = Book.objects.get(slug=slug) if BookMark.objects.filter(user=request.user, book=book).exists(): bookMark = BookMark.objects.get(user=request.user, book=book) bookMark.delete() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) newBookMark = BookMark.objects.create(user=request.user, book=book) newBookMark.save() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) The problem: When a user is redirected to the login page, the next URL will just add a new object in db and reload the page, but this is the login page. How can I redirect users back to the book page if the user isn't authenticated firstly? -
How can I use the value of a model atributte inside a <img> src?
I am trying to create a project in which a model attribute is used as part of an image name. I have tried many methods and I think I am close to the solution, but I have a problem. This is my code: <img src="{% static 'media/{{model.atributte}}.jpg' %}" alt="{% static 'media/{{model.atributte}}.jpg' %}"></img> For example: if the value of the attribute is "img" this should result in = static/media/img.jpg My intention was to use that to set the src path but this is the result I get in the HTML. /static/media/%7B%7Bmodel.atributte%7D%7D.jpg I appreciate any kind of help or recommendation, as an extra comment, I want to clarify that if I write the value of the attribute in the src it does locate the image, but would always do it for the same model and I have several models. Thanks in advance. -
I am confused while rendering my views.py "Django"
My vews.py: if you want me to share another piece of information feel free to ask! def viewList(request, id): # check for the watchlist listing = Post.objects.get(id=id) user = User.objects.get(username=request.user) if listing.watchers.filter(id=request.user.id).exists(): is_watched = True else: is_watched = False if not listing.activate: if request.POST.get('button') == "Close": listing.activate = True listing.save() else: price = request.POST.get('bid', 0) bids = listing.bids.all() if user.username != listing.creator.username: if price <= listing.price: return render(request, 'auctions/item.html', { "listing": listing, 'form': BidForm(), "message": "Error! Your bid must be largest than the current bid!", 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'is_watched': is_watched, }) form = BidForm(request.POST) if form.is_valid(): bid = form.save(commit=False) bid.user = user bid.save() listing.bids.add(bid) listing.bid = price listing.save() else: return render(request, 'acutions/item.html', {'form'}) context = { 'listing': listing, 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'is_watched': is_watched, 'form': BidForm() } return render(request, 'auctions/item.html', context) inside this view, I added a punch of my project requirement (comments/watchlist(bookmark)/and the last thing(that what I have a lot of problem with it) is the system of Bid) that lets users add bids on such posts and let the creator of that post the ability to close it.... please help I am sticking in this zone, I tried many times to understand! Note I am new at … -
403 error with Apache 2 running on Linode Ubuntu 21.10 in Django
I am following along with the "Python Django Tutorial: Deploying Your Application (Option #1) - Deploy to a Linux Server" by Coref Shafer. After I've activated my Apache 2 server and tried to access my Django app, the page returns a 403 error. After checking my error log, I find the following: Current thread 0x00007f57a341f780 (most recent call first): <no Python frame> [Sat Nov 06 18:29:53.698451 2021] [wsgi:warn] [pid 24290:tid 140014377891712] (13)Permission denied: mod_wsgi (pid=24290): Unable to stat Python home /home/vavao/website/venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/vavao/website/venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/vavao/website/venv' sys.base_exec_prefix = '/home/vavao/website/venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/vavao/website/venv' sys.exec_prefix = '/home/vavao/website/venv' sys.path = [ '/home/vavao/website/venv/lib/python39.zip', '/home/vavao/website/venv/lib/python3.9', '/home/vavao/website/venv/lib/python3.9/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f57a341f780 (most recent call first): <no Python frame> And here is my website.conf file <VirtualHost … -
Use both Django REST framework and web sockets
I have an application built on Django. Initially, I constructed a few APIs using the Django REST API framework, which worked fine. Later, I implemented web sockets to listen to a server. I started the application server on port 5010 and the socket on which this application listens to the server is 8010. However, after implementing web sockets, my API calls started to fail(screenshot below). Please explain if using both REST API framework and web sockets would be possible in Django. -
No module named _tkinter on heroku
I have a Django app that uses PIL import PIL.Image from PIL import ImageTk as itk But when I deploy this app on Heroku, it gives me a traceback error or No module named "_tkinter" is found I'm not using Tkinter but still, this is happening. -
is there any way in django rest framework to list all devices a user logged in?
I'm trying to mimic goggle account's feature of listing all devices and terminate session from devices is there any approach with to create this feature using django rest framework. Thanks -
Trying to iterate through a nested dictionary in django template
I am trying to use for loop though a dictionary in django template and inside the for loop, I am trying to nest another for loop to loop through say quantity for displaying those many images of product - the template is like this - {% for product_id, item in b_data.items %} {% for i in item.numItems %} <div class="col-md-4 mb-4"> <div class="card" style="width: 18rem;"> <img src="/media/{{item.image}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.title}}</h5> <p class="card-text">{{product_id}} {{item.qty}}</p> <div class="card-footer"> <a href="#" class="btn btn-primary"><i class="bi bi-cart2"></i></a> </div> </div> </div> </div> {% endfor %} {% endfor %} The views.py looks like below - def make_your_box(request): box_p = {} box_p[str(request.GET['id'])]={ 'image':request.GET['image'], 'title':request.GET['title'], 'qty':request.GET['qty'], 'price':request.GET['price'], 'numItems': list(range(1, int(request.GET['qty'])+1)), } print(box_p) if 'boxdata' in request.session: if str(request.GET['id']) in request.session['boxdata']: box_data=request.session['boxdata'] box_data[str(request.GET['id'])]['qty']=int(box_data[str(request.GET['id'])]['qty'])+1 box_data[str(request.GET['id'])]['numItems']=list(range(1,int(box_data[str(request.GET['id'])]['qty'])+1)), box_data.update(box_data) request.session['boxdata']=box_data else: box_data=request.session['boxdata'] box_data.update(box_p) request.session['boxdata']=box_data else: request.session['boxdata']=box_p print(request.session['boxdata']) print(len(request.session['boxdata'])) x = 0 for prodid, item in request.session['boxdata'].items(): x = x + int(item['qty']) print(x) t_box=render_to_string('ajax/TestSelect1_1.html',{'b_data':request.session['boxdata']}) return JsonResponse({'b_data':t_box}) even in the print stmts outputs correct outpput in the command prompt as shown below - [06/Nov/2021 23:05:30] "GET /TestSelect1 HTTP/1.1" 200 13945 [06/Nov/2021 23:05:30] "GET /media/product_imgs/IMG_0910.JPG HTTP/1.1" 200 3462312 {'5': {'image': 'product_imgs/RedCookies.jpg', 'title': 'Strawberry Cookies', 'qty': '1', 'price': '10', 'numItems': [1]}} {'5': {'image': 'product_imgs/RedCookies.jpg', 'title': 'Strawberry … -
Payment gateway in Pakistan for ecommerce project
I am making an ecommerce store in Django, I want to integrate payment so I can accept payments through Credit/Debit card from my customers. Requirements: I should be able to accept local as well as international credit cards. I have searched a lot, What I have searched through is Following: Popular services for payments are Stripe and Paypal but unfortunately both are not supporting Pakistan. Another Popular service I came up with is 2checkout but their terms and conditions are crazy, its hard to get account on their site. As For local banks, just to give you an idea, HBL bank also provides gateway but its setup fee is 1 hundred thousand and annual fee is also 1 hundred thousand and 3% per transaction. As For other banks some are 40 thousand + 3% per transaction so thats why I can't go with that. For example stripe is 3% per transaction and thats it no annual fee no setup fee. I also looked at skrill but problem is that my customer should also have skrill account for paying me through skrill which is not practical. Please Guide me what I do now, Also If I go with local services such … -
should django password validation not working
I am trying to build a vanilla user registration system with django using a custom registration_form. I would like to check that the password is correct without reloading the page. I am struggling both to require the passwords to comply with the standard set of django password requirements, as well as check that the two passwords match. What I want to achieve is to have the password fields behave like the email field. In the email field, if the @ symbol is missing, a popup appears telling me it needs to change. However, if the passwords don't match or are very few characters, I am still able to submit the form. Is this the expected behavior or is something going wrong? I know that I can check if the form is valid without reloading (e.g. using ajax to do an is_valid() check on the form) after it has been submitted but I am trying to figure out if this is necessary? here is my form class registration_form(UserCreationForm): username = forms.Field(widget=forms.TextInput(attrs={'class': "form-field w-input", 'placeholder': 'Username'})) email = forms.Field(widget=forms.EmailInput(attrs={'class': "form-field w-input", 'placeholder': 'Email address'})) password1 = forms.Field(widget=forms.PasswordInput(attrs={ 'class': "form-field w-input", 'placeholder': 'Password'})) password2 = forms.Field(widget=forms.PasswordInput(attrs={ 'class': "form-field w-input", 'placeholder': 'Repeat Password'})) class … -
Django Select 2 Widget not working , Field rendered but styles not applied
I have been trying to use multiple select using django-select2 widget for a while Step-1: I installed django-select2 using pip install django-select2 Step-2: Added it the installed app INSTALLED_APPS = [ ... django_select2 ... ] Step-3: I added the below to settings.py SELECT2_JS = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/select2.min.js" SELECT2_CSS = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/css/select2.min.css" SELECT2_I18N_PATH = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/i18n" Step 4: I tried it using the widgets from django_select2.forms import Select2MultipleWidget class ClientForm(AppModelForm): class Meta: model = Client fields = "__all__" exclude = ['client_website'] widgets = { 'point_of_contact': Select2MultipleWidget } Step 5: Just render the form without any loop of any sort {{ client_form }} The result is No style is applied to the select. I also tried including the styles and scripts in the head tag (Didn't help). I belive the widget is working, because when i switch from Select2MultipleWidget to Select2Widget , It changes to a single select <select name="point_of_contact" lang="None" data-minimum-input-length="0" data-theme="default" data-allow-clear="true" data-placeholder="" id="id_point_of_contact" class="django-select2" multiple=""> <option value="2">Test</option> <option value="1">Tester</option> </select> The above is the html rendered for the multi select widget by django Kindly help in getting the functionality of django-select2 -
Best way to search with a ManyToMany field Django
I have 2 models, and I wanted to search with a Many to Many field according to my structuring, below is my models : class User(django_models.AbstractBaseUser, TimeStampedModel, django_models.PermissionsMixin): """ User model for the user creation """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) account_types = models.ManyToManyField(AccountTypes, related_name='account_types') Then another model AccountTypes : class AccountTypes(TimeStampedModel, models.Model): """ Account types for the users. e.g Mentors, Mentees, Parents etc. """ uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) name = models.CharField(_('Account Name'), max_length=30, blank=False, null=False) How can I search a user uuid with the certain AccountType ? My try was like this : User.objects.get(uuid=uuid, account_types__in=['Mentor']) But I got this error : ValueError: Field 'id' expected a number but got 'Mentor'. -
fields.E304 Reverse accessor clashes in Django for multiple custom user model
ERRORS: core.User.groups: (fields.E304) Reverse accessor for 'core.User.groups' clashes with reverse accessor for 'seller.User.groups'. HINT: Add or change a related_name argument to the definition for 'core.User.groups' or 'seller.User.groups'. core.User.user_permissions: (fields.E304) Reverse accessor for 'core.User.user_permissions' clashes with reverse accessor for 'seller.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'core.User.user_permissions' or 'seller.User.user_permissions'. seller.User.groups: (fields.E304) Reverse accessor for 'seller.User.groups' clashes with reverse accessor for 'core.User.groups'. HINT: Add or change a related_name argument to the definition for 'seller.User.groups' or 'core.User.groups'. seller.User.user_permissions: (fields.E304) Reverse accessor for 'seller.User.user_permissions' clashes with reverse accessor for 'core.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'seller.User.user_permissions' or 'core.User.user_permissions'. This is the error I get when I try to migrate two identical custom User Models. I copy pasted the code of the custom user model from my user app models.py to the seller app models.py. # seller/models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('Users must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=False) is_staff = …