Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Paypal server side integration in python
I am unable to follow this.I want to use it in my django application. Can you please show me how to use these things or where to place those code. Or if you have any other ways to integrate the paypal payment gateway(server side) in python, Please help me!! thank you -
Django Query to get count of all distinct values for column of mongodb ArrayField
What is the best way to count all distinct values in mongodb ArrayField? Here is my model: class tweet(models.Model): topic = models.JSONField() 3 sample documents: 1. ["investment", "economy"] 2. ["investment"] 3. ["economy", "politics"] Desire result: [{"investment":2},{"economy":2},{"politics":1}] Maybe something like this: tweet.objects.annotate(t=Func(F('topic'), function='$unwind')).values_list('t').annotate(c=Count('_id')) any help would be appreciated -
Custom text for exceptions and informations in external python libraries
How can I translate (customize) some strings and arguments in an external library without changing it directly (without modifying the library)? For example this is line 103 of file oauth2_grants.py in rest_framework_social_oauth2 library: if not user: raise errors.InvalidGrantError('Invalid credentials given.', request=request) And I want receive something like this when it return to my program: if not user: raise errors.InvalidGrantError('اطلاعات شناسایی نا معتبر', request=request) Is there any way to translate/change library texts without modifying directly? -
ajax call not firing up success function on status 200
I'm trying to implement a simple login system using Django. The page takes credentials and submits them to server using ajax call. If information submitted is correct,it logs in user. Otherwise, it returns a json response which should give an alert. Below is view which returns json response on invalid information submitted. def login(request): email=request.POST['email'] password=request.POST['password'] username=get_object_or_404(users,email=email) user=authenticate(username=username,password=password) if user is not None and user.active_status: request.session['id']=user.pk return render(request,'home.html') else: return JsonResponse({"status":"1"}) and javascript part handling ajax using jquery <script> $("#submit").click( function(){ var email= $("email").val(); var password=$("password").val() $.ajax({ url: $(".login-form").attr('action'), method:"POST", data:{ 'email':email, 'password':password, 'csrfmiddlewaretoken' : '{{ csrf_token }}' }, dataType: 'json', success: function(){ alert("wrong") } From debug section of browser, it gives status 200 on wrong credentials but doesn't execute alert. Instead it changes entire page to blank html with only text '{"status":"1"}' which was json response by server. I've tried changing or omitting 'dataType' in ajax call but that doesn't seem to work. Please help with it -
How to convert a array of dictionaries in form of string into an array javascript?
Read the full question before you say duplicate, I have imported an array from python, the array is in form of string for example - "["{"key1":"value1","key2":"value2"}","{"key1":"value1","key2":"value2"}"]" I want to parse this into an actual array in javascript, so basically I want it like - [{"key1":"value1","key2":"value2"}, {"key1":"value1","key2":"value2"}] I have tried a way though it didn't produce the results I wanted temp = JSON.parse(testVal); //testVal is that array On debugging temp I got it value as ["{'key1': 'value1', 'key2': 'value2'}", "{'key1': 'value1', 'key2': 'value2'}"] It converted it into array but the dictionary remained in string format. So I thought I should not convert each dictionary into string so changed array to - "[{'key1': 'value1', 'key2': 'value2'}, {'key1': 'value1', 'key2': 'value2'}]" But this gave me error on parsing - Uncaught SyntaxError: Unexpected token ' in JSON at position 2 Is there any possible way to do this? Any help is appreciated -
how to create multiple image upload widget like this
hey i am trying to implement this type of image upload feature in my project but cant find any good resources can someone tell me how to make this type of multiple image upload: I am using Django for the backend and plain HTML,CSS and JS for the frontend. this widget also has a drag and drop feature and it shows the uploaded image as you can see but i dont know how to do that in django. -
How to convert a array of dictionaries into an array javascript?
I have imported an array from python, the array is in form of string for example - "["{"key1":"value1","key2":"value2"}","{"key1":"value1","key2":"value2"}"]" I want to parse this into an actual array in javascript, so basically I want it like - [{"key1":"value1","key2":"value2"}, {"key1":"value1","key2":"value2"}] Is there any possible way to do this? Any help is appreciated -
Subprocess cannot access pipenv
I'm trying to write a Django starter so I wouldn't have to keep typing separate long commands. I could not access my path using /home/stevek/.local/share/virtualenvs/startdjango-iuzIP2Ap . I tried sudo /home/stevek/.local/share/virtualenvs/startdjango-iuzIP2Ap and it would not work. I found this path by using `pipenv --venv. I want to use subprocess to run my startprojects and startapp since they'll only work while inside pipenv because it has the installed django packages. I couldn't access pipenv shell so I couldn't do any django stuff. Anyone know how to fix this? #!/usr/bin/env python3 import subprocess import time import sys import os ################################################################ # arg0 is main.py # arg1 is pipenv django version # arg2 is project name # arg3 is app name # arg4 is for debug ################################################################ venv_python = '/home/stevek/.local/share/virtualenvs/startdjango-iuzIP2Ap' project_arg = [venv_python, 'django-admin', 'startproject', sys.argv[2]] app_arg = [venv_python, 'python3', 'manage.py', 'startapp', sys.argv[3]] """ Create in main environment """ subprocess.run(["pipenv", "install", f"django~={sys.argv[1]}"]) subprocess.run(["pipenv", "shell"]) """ Needs pipenv compatible""" subprocess.run(project_arg) subprocess.run(debug_arg) subprocess.run(app_arg) if sys.argv[4].startswith("debug"): debug_arg = [venv_python, 'debug', sys.argv[4]] subprocess.run(debug_arg) seconds = debug_arg[2][-2:] # Waits for the amount of seconds before nuke time.sleep(seconds) # deletes virtual environment subprocess.run([venv_python, "pipenv --rm"]) subprocess.run([venv_python, "rm Pipfile*"]) # leave virtual environment subprocess.run([venv_python, "exit"]) # delete pipenv files and the … -
1 unapplied migration even though I have performed migration operation
I was creating AbstractUser model in django. I have performed migrations but while running the server there occurs the error that 1 unappllied migrationenter image description here this was the model I created. from django.db import models from django.contrib.auth.models import AbstractUser Create your models here. class LoginTable(AbstractUser): phone = models.BigIntegerField(default=0,null=True) user_type = models.CharField(max_length=30,default='admin',null=True) -
Getting Error => ModuleNotFoundError: No module named 'django' When I attempt to deploy my django app to heroku
When I attempt to deploy my django app to heroku, the deployment will fail with the following error message Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Here is my requirements.txt asgiref==3.3.4 dj-database-url==0.5.0 Django==3.2.3 django-cors-headers==3.7.0 django-on-heroku==1.1.2 djangorestframework==3.12.4 gunicorn==20.1.0 psycopg2-binary==2.8.6 python-dotenv==0.17.1 pytz==2021.1 sqlparse==0.4.1 whitenoise==5.2.0 My Procfile release: python3 manage.py migrate web: gunicorn app_name.wsgi --log-file - And the buildpacks (using nodejs for the frontend) 1. heroku/nodejs 2. heroku/python I have tried to deploy the app from both the CLI and a github repository. Both result in the same error. I am happy to provide any additional information from the project if needed. How can I fix this error so my app will deploy successfully? -
django-oscar 3.0 with paypal payment
I am fairly new with Django as well as Djnago-oscar, so far I have django-oscar store setup and I am trying to integrate with paypal but because I am running django.oscar 3.x 'django-oscar-paypal' doesn't work for me and there is not enough documentation on how to implement payments. My checkout process: Adding items to cart User enter details including shipping etc Select payment method, review redirect to Paypal to complement payment Redirect back to website and confirm the order On paymentMethodeView I have created a form to get the payment method, and on paymentDetailsView I have handle_payment def handle_payment(self, order_number, order_total, **kwargs): method = self.checkout_session.payment_method() if method == 'pt': #payment terms admin manually invoice return self.handle_pt_payment(order_number, order_total, **kwargs) elif method == 'paypal_payment': return self.handle_paypal_payment(order_number, order_total, **kwargs) else: raise PaymentError(_('Bad payment method in handle_payment!')) And at handle_paypal_payment function I am not sure how to proceed. Any help would be much appreciated -
How to show paginated items in their respective pages
I tried paginating models items but all of the items are showing on the same page... What could it be that I'm not doing well??? def view_books(request): books = Books.objects.filter(school = request.user.school) page = request.GET.get('page', 1) paginator = Paginator(books, 10) try: userd = paginator.page(page) except PageNotAnInteger: userd = paginator.page(1) except EmptyPage: userd = paginator.page(paginator.num_pages) return render(request, 'libman/view_book.html',{'userd':userd}) The rendering template {% if userd.has_other_pages %} <ul class="pagination container text-center"> {% if userd.has_previous %} <li><a href="?page={{ userd.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in userd.paginator.page_range %} {% if userd.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if userd.has_next %} <li><a href="?page={{ userd.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} -
name field is not defined
On the existing API in django I am trying to add a text area field. I have tried adding a create with serializer but experience following error; NameError at /api/v1/notes/images/ name 'dateImg' is not defined My model has: class ImageAttachment(models.Model): note = models.ForeignKey(Note, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_file_path, storage=NoteS3Boto3Storage(bucket=settings.AWS_STORAGE_BUCKET_NAME)) dateImg=models.TextField() My serializer has: class ImageListSerializer(serializers.Serializer): note = PrimaryKeyRelatedField(queryset=Note.objects.all()) image = serializers.ListField( child=serializers.ImageField(max_length=None, allow_empty_file=False)) dateImg=serializers.CharField(style={'base_template': 'textarea.html'}) def create(self, validated_data): note = validated_data.pop('note') images = validated_data.pop('image') dateImg=validated_data.pop('dateImg') self.dateImg = dateImg image_obj = [] for image in images: image_obj.append(ImageAttachment.objects.create(note=note, image=image,dateImg=dateImg)) return image_obj -
How to link input in html form to its form actions in django?
Is it possible to get value from HTML form input and use it in form action? <form action="/wiki/ /" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> Here,I want the form action to be "/wiki/input_in_q/".How do you do that? -
Hello, I need help to update a field when the other is filled on Django
Here is the fields in my model : PAID = 'PG' UNPAID = 'UN' OVERDUE = 'OV' status_CHOICE = [ (PAID, 'Pago'), (UNPAID, 'Aberto'), (OVERDUE, 'Vencido') ] status = models.CharField(max_length=10, blank=True, null=True, choices=status_CHOICE) subtotal = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) I need the 'status' field filled with status_CHOICE when change the subtotal field is equal to zero, and equal to date OVERDUE -
Migration error(django.db.utils.OperationalError)
I'm trying to migrate my custom user model and I run makemigrations command to make migrations for new models. But when I run migrate command it throws this error : conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError Trace back: (venv_ruling) C:\Users\enosh\venv_ruling\ruling>python manage.py migrate Traceback (most recent call last): File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\enosh\venv_ruling\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\enosh\venv_ruling\ruling\manage.py", line 22, in <module> main() File "C:\Users\enosh\venv_ruling\ruling\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) … -
How to let Django drf backend UpdateAPIView only update required fields rather than all?
In my Django Rest Framework backend, those are my code: serializers.py: class DomainUpdateSerializer(serializers.ModelSerializer): class Meta: model = Domain fields = "__all__" my model: class Domain(models.Model): domain_name = models.CharField(max_length=512, help_text='domain. eg.example.com') cname = models.ForeignKey( to=CNAMEModel, on_delete=models.DO_NOTHING, related_name="domains") ssl_key = models.TextField(max_length=40960, help_text="SSL. key") ssl_cert = models.TextField(max_length=40960, help_text="SSL. cert ") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.domain_name def __unicode__(self): return self.domain_name class Meta: verbose_name = "domain" verbose_name_plural = "domain" ordering = ['ctime'] In my frontend when I use the API to update domain. I must fill up all fields, but in my thinking, if I want to update domain_name there should just use id and domain_name, the ssl_key and ssl_cert should be optional. Is is possible to implements my thinking in backend? -
Django Nested Serializer Issue: Field name is not valid for model
I'm trying to setup the following output: { season: 1, player_profile: { name: John Doe, } } The models are setup as such: class PlayerProfile(models.Model): name = models.CharField(max_length=120, null=True) class TeamAffinityReward(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, #db_constraint=False null=True) season = models.IntegerField(null=True, blank=True) The serializers are setup like this: class PlayerProfileForNestingSerializer(serializers.ModelSerializer): class Meta: model = PlayerProfile fields = ( 'name', ) class TeamAffinityRewardSerializer(serializers.ModelSerializer): class Meta: model = TeamAffinityReward playerprofile = PlayerProfileForNestingSerializer() fields = ( 'playerprofile', 'season', ) However, I get the following error: Field name `playerprofile` is not valid for model `TeamAffinityReward`. If I change playerprofile to player_profile, the error goes away but it displays the player_profile_ID instead of the PlayerProfileForNestingSerializer. -
Input value based on previous one
I have a Post method for an Rest API of django rest framework, it's all working so far but I would like to know if it's possible to have an input value automatically filled based on a previous one. Longitude='3.0' Latitude ='3.0' And now I would like for example to have Intensity ='low' because of the latitude value, all of this is in json. -
how to makemigrations in django without a recursion error?
I'm getting the following error when I try the command in windows: python manage.py makemigrations It's an error in some sort of recursion function and I understand that python stops after 999 recursion calls. This is a snippet of the repeating error that finally ends with a RecursionError... File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 414, in check messages.extend(self._check_custom_error_handlers()) File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 431, in _check_custom_error_handlers signature = inspect.signature(handler) File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 3130, in signature return Signature.from_callable(obj, follow_wrapped=follow_wrapped) File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2879, in from_callable return _signature_from_callable(obj, sigcls=cls, File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2330, in _signature_from_callable return _signature_from_function(sigcls, obj, File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2194, in _signature_from_function parameters.append(Parameter(name, annotation=annotation, File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 2517, in __init__ self._kind = _ParameterKind(kind) File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\enum.py", line 360, in __call__ return cls.__new__(cls, value) RecursionError: maximum recursion depth exceeded while calling a Python object I have created a models.py: from django.db import models # Create your models here. class fligjt(models.Model): origin = models.CharField(max_length=64) destination = models.CharField(max_length = 64) duration = models.IntegerField() I'm quite new to Django and I'm not sure how to understand this error. -
Different serializers for different objects in a single queryset
For a ForeignKey relationship, how can I change the serializer used based off some criteria? # models.py class Relationship(models.Model): ... class Item(models.Model): relationships = ForeignKey(Relationship) class OddPKSerializer(serializers.Serializer): ... class EvenPKSerializer(serializers.Serializer): ... class ItemSerializer(serializer.Serializer): # relationships = OddPKSerializer and/or EvenPKSerializer(many=True) # depending on some criteria class Meta: model = Item fields = ["relationships"] # Where for example, OddPKSerializer is used if # the specific relationship object has an odd pk # and EvenPKSerializer is used for even pks In my actual use case, I'm looking to serialize differently based on the ForeignKey object's class. (I'm using proxy models so a single ForeignKey field can point to different classes.) I've tried using SerializerMethodField but that only seems to act on the "Item" object and not the "Relationship" objects that I'm looking to serialize. -
Foreignkey Searchbox and Django Crispy Forms
I am using the Django Crispy forms and a Foreignkey field. When creating a new form, is there a way to add a search box in the forms in order to search for the right foreignkey value? Many thanks -
Django social share links to show as buttons
I have installed change social share package and would like to have buttons instead of links. {% post_to_facebook <object_or_url> <link_text> <link_class> %} {% post_to_gplus <object_or_url> <link_text> <link_class> %} {% post_to_twitter <text_to_post> <object_or_url> <link_text> <link_class> %} {% post_to_linkedin <object_or_url> <link_class> %} {% send_email <subject> <text_to_post> <object_or_url> <link_text> <link_class> %} {% post_to_reddit <text_to_post> <object_or_url> <link_text> <link_class> %} {% post_to_telegram <text_to_post> <object_or_url> <link_text> <link_class> %} {% post_to_whatsapp <object_or_url> <link_text> <link_class> %} {% save_to_pinterest <object_or_url> <link_class> %} {% add_pinterest_script %} How can I do it? -
Django "No 'Access-Control-Allow-Origin' header is present on the requested" just to patch request
I am running a backend server made with django and I am trying to send requests to it from my React app. The "No 'Access-Control-Allow-Origin' header is present on the requested" error happened to me earlier when I was trying to send a get request, but I solved it doing what is shown here https://dzone.com/articles/how-to-fix-django-cors-error. What I can't understand is why this problem is happening again when I try to send patch requests if it worked just fine with post and get requests. Here you can see the error in my browser the first get request returned what it should, but then the patch request gets this error. Parts of my settings.py that I made changes: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL=True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', My patch django view: class UpdateUser(generics.ListAPIView): serializer_class = UserSerializer queryset = '' def patch(self, request, format=None): try: data = request.data user = User.objects.get(username=data['username']) user.level = data['level'] user.xp = data['xp'] user.completed_challenges = data['completed_challenges'] user.save(update_fields=['level', 'xp', 'completed_challenges']) return Response(model_to_dict(user), status=status.HTTP_200_OK) except: return Response({'Error': 'Invalid data'}, status=status.HTTP_400_BAD_REQUEST) My patch request made in my React frontend: fetch(`https://pedro-moveit-backend.herokuapp.com/update-user`, { method: 'patch', headers: … -
“unresolved import” error in Visual Studio Code pylint
I am using the following, Windows , Python 3.9.5 , Visual Studio Code 1.56 , Pylint 2.8.2 , Django 3.2.3 , If I use Every import has states "unresolved import". Even on default Django imports (i.e. from django.db import models). How can I fix this ?