Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble Deleting Items from Cart Using AJAX In Django
I am new in Stack overflow and I am getting problem during deleting product from cart In my cart.html: <button class="btn btn-sm btn-remove delete-item" data-item="{{product_id}}"><i class="fas fa-trash-alt" ></i></button> This is the delete button I created. Now also I created js for this button so in my cart.js: console.log("Hi"); $(document).on("click", '.delete-item' ,function(){ let this_val=$(this) var _pID=$(this).attr('data-item'); console.log(_pID); $.ajax({ url: '/delete-from-cart', data: { 'id': _pID, }, dataType: 'json', beforeSend: function(){ this_val.hide() }, success: function(response){ this_val.show() $(".cart-items-count").text(response.totalcartitems) $("#cart-list").html(response.data) } }) }) for the js file when i am clicking on the delete button I am getting product ids as output I also created a views for it. So, In my views.py: def delete_item_from_cart(request): product_id=str(request.GET['id']) if 'cart_data_obj' in request.session: if product_id in request.session['cart_data_obj']: cart_data=request.session['cart_data_obj'] del request.session['cart_data_obj'][product_id] request.session['cart_data_obj'] = cart_data cart_total_ammount=0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_ammount += int(item['qty']) * float(item['price']) context= render_to_string("core/async/cart_list.html", {"products":products}, {"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) return JsonResponse({"data": context, 'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) and then In urls.py: path("delete-from-cart/", delete_item_from_cart,name="delete-from-cart"), this is my url Note: At last I would say that I made a cart page where all the products are displaying which are sellected. and I connected cart-lsit.html with cart.html by main tag with id you can see this in the … -
Django project with a RESTful API for user registration and login using Google or Apple OAuth
which backend parameter to add Internal Server Error: /accounts/google/login/callback/ Traceback (most recent call last): File "/home/zaibe/Desktop/project2/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/zaibe/Desktop/project2/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: api_google_oauth2_callback() missing 1 required positional argument: 'backend' [17/Mar/2024 06:39:23] "GET /accounts/google/login/callback/?code=4%2F0AeaYSHADSCseU_Nkg2BMLc5P8UpfRRqCJUNRIAyHrcW_tX4uQDpPADdj5rTJRS8v6siZHw&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=consent HTTP/1.1" 500 65562 from django.http import JsonResponse from django.contrib.auth import authenticate, login from django.views.decorators.csrf import csrf_exempt from .forms import UserRegistrationForm from .models import Profile from django.shortcuts import redirect from social_django.utils import psa import json from social_django.views import auth from django.views.generic import RedirectView from django.shortcuts import render def default_callback(request): return render(request, 'default_callback.html') @psa() def api_google_oauth2_login(request): backend = 'social_core.backends.google.GoogleOAuth2' return redirect('social:begin', backend=backend) @psa() def api_google_oauth2_callback(request): backend = 'social_core.backends.google.GoogleOAuth2' return auth(request, backend=backend) @csrf_exempt def api_user_login(request): if request.method == 'POST': # Retrieve raw JSON data from the request body data = json.loads(request.body) # Extract username and password from the JSON data username = data.get('username') password = data.get('password') if username is None or password is None: return JsonResponse({'error': 'Missing credentials'}, status=400) user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return JsonResponse({'message': 'Authenticated successfully'}, status=200) else: return JsonResponse({'error': 'Invalid login'}, status=401) else: return JsonResponse({'error': 'Invalid request method'}, status=405) @csrf_exempt def api_user_register(request): if request.method == 'POST': form … -
How to set BinaryField to primary key in django?
In this code i have: IDChuyenBien = models.BinaryField(primary_key=True, max_length=8) But when i makemigrations and migrate have an error: _mysql.connection.query(self, query) django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'IDChuyenBien' used in key specification without a key length") Although I used max_length as above, I am using Django 4.2.9 connect to Mysql I followed the docs as follows: https://docs.djangoproject.com/en/4.2/ref/models/fields/ I have also tried to think of a few other ways but still do not have a solution, because it is required that the data transmitted is binary and will be saved directly to the database, and before that when I did not use the primary key, in mysql when migrating it was also LONGBLOB. Meanwhile t only needs BINARY type with 8 bytes or 10 bytes -
ERROR : metadata-generation-failed while installing uwsgi
using the command pip install uwsgi it gave the error : metadata-generation-failed i was tring to install a WSGI web server for flask, pip install uwsgi and install web server, i needed, And to get thorough the installing functonal webserver for my flask app -
Recursion Error when Modifying ManyToManyField during Django Model Save
I have an issue with removing users from the friends field during save in Django. Here's a description of my idea: Each Profile has a type, which corresponds to a certain rank. For instance, a Profile with type X can have 10 friends, whereas a Profile with type Y can have 20 friends. Here's how I've implemented it: POWER_OF_PROFILE_TYPE = {"X": 0, "Y": 1} class ProfileType(models.TextChoices): X = "X", "x" Y = "Y", "y" class Profile(models.Model): type = models.TextField(choices=ProfileType.choices, default=ProfileType.BASIC, max_length=1) friends = models.ManyToManyField(User, blank=True, related_name="friends") __currently_type = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__currently_type = self.type_of_profile def save(self, *args, **kwargs) -> None: if self.type_of_profile != self.__currently_type: if POWER_OF_PROFILE_TYPE[self.type_of_profile] < POWER_OF_PROFILE_TYPE[self.__currently_type]: users = self.friends.all()[10:] self.friends.remove(*users) self.save() # This is causing recursion error super().save(*args, **kwargs) self.__currently_type = self.type_of_profile Unfortunately, this piece of code results in a recursion error RecursionError ...maximum recursion depth exceeded Could someone help me figure out what I should do? -
Django Serializers, how to show data in nested bridge model serializer
I'm using Django REST Framework. I have 3 different models, 2 are standalone models while the 3rd one is a bridge model that connects the first 2 models # First standalone model class Build(TimeStampedModel): name = models.CharField(max_length=64, null=False, blank=False) type = models.CharField(max_length=64, null=False, blank=False) play_as = models.CharField(max_length=64, null=False, blank=False) link = models.CharField(max_length=255, null=False, blank=False) class Meta: ordering = ['-created_at'] def __str__(self): return f'{self.play_as} - {self.name}' # Second standalone model class Run(TimeStampedModel): name = models.CharField(max_length=64, null=False, blank=False) difficulty = models.CharField(max_length=64, null=False, blank=False) origin = models.CharField(max_length=64, null=False, blank=False) alignment = models.CharField(max_length=64, null=False, blank=False) class Meta: ordering = ['-created_at'] def __str__(self): return f'{self.name} - {self.difficulty}' # Bridge model class RunBuild(TimeStampedModel): run = models.ForeignKey( Run, related_name='runBuild_run', on_delete=models.CASCADE, null=False, blank=False ) build = models.ForeignKey( Build, related_name='runBuild_builds', on_delete=models.CASCADE, null=False, blank=False ) class Meta: ordering = ['-run'] def __str__(self): return f'{self.run.name} - {self.build.name}' The Build serializer is fine, the problem stands in RunBuild and Run serializer. # Model Serializer for Build model class BuildSerializer(serializers.ModelSerializer): created_at = serializers.SerializerMethodField() class Meta: model = Build exclude = ['updated_at'] def get_created_at(self, instance): return instance.created_at.strftime('%B %d, %Y') # Model Serializer for RunBuild model class RunBuildSerializer(serializers.ModelSerializer): # This doesn't work runBuild_builds = BuildSerializer(many=True, read_only=True) created_at = serializers.SerializerMethodField() class Meta: model = RunBuild fields … -
why i showing this error now. because its actually worked still now
why I getting this error this is my code this is my error and I tried. it worked ones. but now its showing this error. I completely undo all works but still its showing this error. can anyone help me? anyone have same problem? -
Django makemigrations returns no changes detected
When I want to run makemigrations, I get no changes detected. I have this class in my models. class car (models.Model): name=models.CharField(max_length=50) def __str__(self): return self.name I have also added myapp in installed apps How can I fix this? -
How can I get a queryset with data for 2 tables?
I am quite new to Django. I'm writing and app using Vue3 in the frontend and Django5 in the backend. I've implemented login already, but I want the user returning to contain the role, that happens to be in another table, and I just get the id. My Django models: class Role(models.Model): id_role = models.AutoField(primary_key=True) name = models.TextField(max_length=100) permissions = models.ManyToManyField(Permission) def __str__(self): return self.name class User(models.Model): id_user = models.AutoField(primary_key=True) email = models.TextField(max_length=100) password = models.CharField(max_length=255) role_id = models.ForeignKey(Role, on_delete=models.PROTECT) locale = models.TextField(max_length=5) def __str__(self): return self.email Serializers: class RoleSerializer(ModelSerializer): class Meta: model = Role fields = ( 'id_role', 'name', 'permissions' ) class UserSerializer(ModelSerializer): class Meta: model = User fields = ( 'id_user', 'email', 'password', 'role_id', 'locale' ) This is my viewset, where I have the login method, and I want it to return the role name instead of the role_id: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() @action(detail=False, methods=['post']) def login(self, request, pk=None): user = serializers.serialize('json', self.queryset.filter(email=request.data["email"], password=request.data["password"])) if (user and user != "[]"): return Response(user) else: return Response({"error": "The user does not exist"}, status=status.HTTP_400_BAD_REQUEST) I've already looked at SO questions (How to make an Inner Join in django?) and tried using this code: @action(detail=False, methods=['post']) def login(self, … -
I'm always getting false for is_authenticate() in Django
I'm a beginner in Django, I'm trying to do email authentication for the users who successfully logged in and redirect them to the respective homepages based on their role. The login is working, I'm getting the otp in mail and otp authentication is also working fine and the user is redirected to the correct homepage. But I realized that I can able to directly access the homepage from the url in browser, even if I'm not logged in. I tried @login_required decorator before the homepages view, but for some reasons it was not working and redirects me to login page even if the user already logged in, so I tried the below way, but now the is_authenticated is always giving me false. def reader_home(request): if request.user.is_authenticated: return render(request, 'reader_home.html', {'username': request.session.get('username')}) else: messages.info(request, 'User is not yet authenticated!') return redirect('homepage') def writer_home(request): print(f'request.user:{request.user}') if request.user.is_authenticated: return render(request, 'writer_home.html', {'username':request.session.get('username')}) else: messages.info(request, 'User is not yet authenticated!') return redirect('homepage') The below is the login_view and otp-verification view: login_view: def login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') role = request.POST.get('role') try: user = UserCredentials.objects.get(username=username, role=role) except UserCredentials.DoesNotExist: user = None if user: if user.check_password(password): login(request, user) otp_secret = … -
djangocms - data not showing in published page, available in edit mode?
I am trying to setup a djangocms plugin to handle FAQ's. When I am in edit mode, everything works. I can see the FAQ's. When I switch to published page, the FAQ's are not showing. Looking at the queryset in edit mode, I have the FAQ's but in published mode the FAQ's queryset is empty. I tried to debug as best as I could with a lot of answers from stackoverflow but just can't find the error. models.py from django.db import models from cms.models.pluginmodel import CMSPlugin class FAQPluginModel(CMSPlugin): title = models.CharField(max_length=255, default="FAQs") def __str__(self): return self.title class FAQItem(models.Model): plugin = models.ForeignKey(FAQPluginModel, related_name="faq_items", on_delete=models.CASCADE) question = models.CharField(max_length=255) answer = models.TextField() def __str__(self): return self.question plugins.py from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import gettext_lazy as _ from .models import FAQPluginModel from .admin import FAQPluginModelAdmin, FAQItemInline class FAQPluginPublisher(CMSPluginBase): model = FAQPluginModel module = _("FAQs") name = _("FAQ Plugin") render_template = "faq_plugin.html" # render_template = "faq_collapsible.html" admin_preview = False inlines = [FAQItemInline, ] def render(self, context, instance, placeholder): context.update({ 'instance': instance, 'faq_items': instance.faq_items.all(), }) print("faq_items:", context.get('faq_items')) return context plugin_pool.register_plugin(FAQPluginPublisher) I have tried a lot of the posted solutions: def copy_relations(self, oldinstance): self.faq_items = oldinstance.faq_items.all() This is the one which seemed … -
drf-social-oauth2 JWT token and documentation
I am trying to use drf-social-oauth2 for authentication and authorization. I set it up using the documentation linked above. But the documentation is lacking. I could not find find how to change certain settings in the documentation. When I send request to /auth/token/, this is the response I get: { "access_token": "KQP6l5nHezWlFO3Ixwz4IIFNUjkvEp", "expires_in": 36000, "token_type": "Bearer", "scope": "read write", "refresh_token": "rmyOZJPQE6Z1eqbpihr2Ux6YMDN1LU" } But I want to use JWT with custom claims and I cannot find how to do it in the documentation linked above. My question for now is that how can I use JWT instead of Bearer. And how can I include custom claims in the JWT tokens using drf-social-oauth2 ? If you can, please point me towards a documentation with more details about drf-social-oauth2. The only thing I found to customize the token is this in this documentation. -
Error: subprocess-exited-with-error when pip install mysqlclient
I am trying to install MySQLClinet on Ubuntu and when I pip install mysqlclient I get this error: Defaulting to user installation because normal site-packages is not writeable Collecting mysqlclient Using cached mysqlclient-2.2.4.tar.gz (90 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [27 lines of output] /bin/sh: 1: pkg-config: not found /bin/sh: 1: pkg-config: not found /bin/sh: 1: pkg-config: not found Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 127. Trying pkg-config --exists libmariadb Command 'pkg-config --exists libmariadb' returned non-zero exit status 127. Traceback (most recent call last): File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module> main() File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/home/ubuntu/.local/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-8kpxdgiv/overlay/local/lib/python3.10/dist-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "/tmp/pip-build-env-8kpxdgiv/overlay/local/lib/python3.10/dist-packages/setuptools/build_meta.py", line 295, in _get_build_requires self.run_setup() File "/tmp/pip-build-env-8kpxdgiv/overlay/local/lib/python3.10/dist-packages/setuptools/build_meta.py", line 311, in run_setup exec(code, locals()) File "<string>", line 155, in <module> File "<string>", line 49, in get_config_posix File "<string>", line 28, in find_package_name Exception: Can not find valid pkg-config name. … -
AttributeError: 'bytes' object has no attribute 'is_valid_format'
I want to validate an email by abstractapi. After running api_url and key , the data given below is gotten. { "email": "email@domain.com", "autocorrect": "", "deliverability": "DELIVERABLE", "quality_score": "0.80", "is_valid_format": { "value": true, "text": "TRUE" }, "is_free_email": { "value": false, "text": "FALSE" }, "is_disposable_email": { "value": false, "text": "FALSE" }, "is_role_email": { "value": false, "text": "FALSE" }, "is_catchall_email": { "value": true, "text": "TRUE" }, "is_mx_found": { "value": true, "text": "TRUE" }, "is_smtp_valid": { "value": true, "text": "TRUE" } } when i want to acces the data by this code given below , i found attribute error. AttributeError: 'bytes' object has no attribute 'is_valid_format'. api_key = '0191f6bdc0eb401a951bfa95f1564210' api_url = 'https://emailvalidation.abstractapi.com/v1/?api_key=' + api_key def validate_email(email): response = requests.get(api_url + "&email=email") data = response.content if data.is_valid_format.value and data.is_mx_found.value and data.is_smtp_valid.value: if not data.is_catchall_email.value and not data.is_role_email.value and not data.is_free_email.value: return True return False the error is: AttributeError at /send_email 'bytes' object has no attribute 'is_valid_format' Request Method: GET Request URL: http://127.0.0.1:8000/send_email Django Version: 4.1.5 Exception Type: AttributeError Exception Value: 'bytes' object has no attribute 'is_valid_format' Exception Location: H:\Python\send_email\app\utils.py, line 16, in validate_email Raised during: app.views.send_email Python Executable: C:\Users\anupa\anaconda3\envs\Python\python.exe Python Version: 3.9.12 Python Path: ['H:\\Python\\send_email', 'C:\\Users\\anupa\\anaconda3\\envs\\Python\\python39.zip', 'C:\\Users\\anupa\\anaconda3\\envs\\Python\\DLLs', 'C:\\Users\\anupa\\anaconda3\\envs\\Python\\lib', 'C:\\Users\\anupa\\anaconda3\\envs\\Python', 'C:\\Users\\anupa\\anaconda3\\envs\\Python\\lib\\site-packages'] Server time: Sat, 16 … -
Nginx Problem with Django-ckeditor package
I have deployed django application on ubuntu 20 and it gives me an error when trying to make messages File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'ckeditor' Everything is set up. On my local machine there is no such problem. -
How to save more than one objects from one view to one model in Django?
I have a template where I have as many input field as many goals the user have. I like to save all the input values to the same model but as different objects. So I like to do a bulk save function but the method I using now just save the last input value. models.py class IndividualGoal(models.Model): def __str__(self): return str(self.user) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_goal") leader = models.ForeignKey(User, on_delete=models.CASCADE, related_name="leader_added_individual_goal") datetime = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True, null=True) goal = models.CharField(max_length=500, null=True, blank=True) deadline = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) updated_at = models.DateTimeField(auto_now_add=False, auto_now=True, blank=True, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) period = models.ForeignKey('Period', on_delete=models.CASCADE, blank=True, null=True) class IndividualEvaluation(models.Model): def __str__(self): return str(self.user) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_evaluation") leader = models.ForeignKey(User, on_delete=models.CASCADE, related_name="leader_added_individual_evaluation") datetime = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True, null=True) goal = models.ForeignKey(IndividualGoal, on_delete=models.CASCADE, blank=True, null=True) evaluation = models.CharField(max_length=500, null=True, blank=True) updated_at = models.DateTimeField(auto_now_add=False, auto_now=True, blank=True, null=True) period = models.ForeignKey('Period', on_delete=models.CASCADE, blank=True, null=True) views.py def individual_evaluation(request, company_uuid, user_id, period_id): individual_goals = Profile.objects.raw("SELECT *, target_individualgoal.id AS goal_id FROM stressz_profile LEFT JOIN stressz_company ON stressz_profile.company_id = stressz_company.id LEFT JOIN target_individualgoal ON target_individualgoal.user_id = stressz_profile.user_id WHERE stressz_company.company_uuid = %s AND stressz_profile.user_id = %s AND target_individualgoal.period_id = %s GROUP BY target_individualgoal.id", [company_uuid, user_id, period_id]) form = … -
nginx x-accel redirect to gcloud storage is returning empty HTML page
Stack: I am running django app (DRF) behind nginx proxy server. Media files are stored in Google Cloud Storage's private bucket. Django app along with nginx is hosted in cloud run and has all the necessary permissions to access the bucket. (It can upload files with no problem) Storage backend is django-storages library. Problem: Server is returning empty html. PS: I am not using signed urls, since my django app has the necessary permissions & credentials to access the bucket. But I am not sure if this is enough to stream the files to client and whether this is the problem. My Code: (django storage) settings.py # STORAGES # -------------------------------------------------------------- DOMAIN_NAME = env.str("DOMAIN_NAME") SECRET_PATH = env.str("G_STORAGE_SECRET_PATH") GS_CREDENTIALS = service_account.Credentials.from_service_account_file(SECRET_PATH) GS_BUCKET_NAME = env("GS_BUCKET_NAME") GS_PROJECT_ID = env.str("GS_PROJECT_ID") GS_EXPIRATION = env.int("GS_EXPIRATION", 28800) # 8 hours GS_IS_GZIPPED = env.bool("GS_IS_GZIPPED", True) GS_CUSTOM_ENDPOINT = "https://" + DOMAIN_NAME GS_QUERYSTRING_AUTH = False MEDIA_LOCATION = "my_project/media" STORAGES = { "default": { "BACKEND": "storages.backends.gcloud.GoogleCloudStorage", "OPTIONS": { "location": MEDIA_LOCATION, "file_overwrite": True, }, }, } MEDIA_URL = f"https://{DOMAIN_NAME}/{GS_BUCKET_NAME}/{MEDIA_LOCATION}/" urls.py re_path( r"^my_project/media/app/users/(?P<user_id>[^/]+)/files/(?P<filename>[^/]+)/$", gcloud_storage.gcloud_redirect, name="gcloud_storage_redirect", ), view.py def gcloud_redirect(request, user_id, filename): file_id = filename.split(".")[0] user_file = get_object_or_404(UserFile, id=file_id) file_URI = user_file.file bucket_name = settings.GS_BUCKET_NAME media_prefix = settings.MEDIA_LOCATION # Create a response with the X-Accel-Redirect … -
AttributeError: 'RefreshToken' object has no attribute 'blacklist_after'
I am working on a django project. I am using a custom user model (not using django's Abstract User or anything) during Verify OTP i am using if not user.refresh_token or RefreshToken(user.refresh_token).blacklist_after: refresh = RefreshToken.for_user(user) user.refresh_token = str(refresh) user.save() else: refresh = RefreshToken(user.refresh_token) access_token = str(refresh.access_token) and I am getting the error: AttributeError: 'RefreshToken' object has no attribute 'blacklist_after' My Question is that is there anyway that if the RefreshToken is expired in the database, make a new one and store it in the User Object by using user.save() ?? i tried the following code if not user.refresh_token or RefreshToken(user.refresh_token).blacklist_after: refresh = RefreshToken.for_user(user) user.refresh_token = str(refresh) user.save() else: refresh = RefreshToken(user.refresh_token) access_token = str(refresh.access_token) i was expecting that if the refresh token is valid, it will make an access token and if invalid or expired it will create a new refresh token and save it in db. but i got attribute error.d -
How to add Chosen Groups or Chosen user permissions in Django Admin Panel
I'm fairly new to the Django Framework so this might be very easy I'm trying to replicate the result picture below enter image description here using this code i was able to add the Available Groups to the panel ('Permissions', { 'fields': ('is_active', 'is_staff','is_superuser','groups','user_permissions',) }), however i wasn't able to find the name of the attribute for either chosen groups or chosen user permissions. I would appreciate it if you could point out the name and a link to the django documentation regarding this below is the picture of the panel i have made so far enter image description here I read the documentation regarding the django admin panel but wasn't able to find the correct name of the attributes. -
Trouble Deleting Items from Cart Using AJAX In Django
I am new in Stack overflow and I am getting problem during deleting product from cart In my cart.html: <button class="btn btn-sm btn-remove delete-item" data-item="{{product_id}}"><i class="fas fa-trash-alt" ></i></button> This is the delete button I created. Now also I created js for this button so in my cart.js: console.log("Hi"); $(document).on("click", '.delete-item' ,function(){ let this_val=$(this) var _pID=$(this).attr('data-item'); console.log(_pID); $.ajax({ url: '/delete-from-cart', data: { 'id': _pID, }, dataType: 'json', beforeSend: function(){ this_val.hide() }, success: function(response){ this_val.show() $(".cart-items-count").text(response.totalcartitems) $("#cart-list").html(response.data) } }) }) for the js file when i am clicking on the delete button I am getting product ids as output I also created a views for it. So, In my views.py: def delete_item_from_cart(request): product_id=str(request.GET['id']) if 'cart_data_obj' in request.session: if product_id in request.session['cart_data_obj']: cart_data=request.session['cart_data_obj'] del request.session['cart_data_obj'][product_id] request.session['cart_data_obj'] = cart_data cart_total_ammount=0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_ammount += int(item['qty']) * float(item['price']) context= render_to_string("core/async/cart_list.html", {"products":products}, {"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) return JsonResponse({"data": context, 'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) and then In urls.py: path("delete-from-cart/", delete_item_from_cart,name="delete-from-cart"), this is my url Note: At last I would say that I made a cart page where all the products are displaying which are sellected. and I connected cart-lsit.html with cart.html by main tag with id you can see this in the … -
GeoDjango: How can I calculate the distance between two points on a linestring?
I have two points with srid 4326 and linestring with srid 4326. I want to calculate the distance between two points on a line string with django geo -
Adding index.FilterField for Page object in Wagtail?
I need to implement a language-specific search in Wagtail, so I modified the default search/views.py like this: def search(request): search_query = request.GET.get("query", None) page = request.GET.get("page", 1) language = request.LANGUAGE_CODE if search_query: search_results = Page.objects.live().filter(locale__language_code=language).search(search_query) The result is an error message: Please add index.FilterField('language_code') to Page.search_fields Adding index.FilterField('language_code') to my classes derived from Page does not work – so how can I add that filter field index to wagtailcore.Page? -
Django translation doesnt work in python code
I have an application with the default language set to RU. My 2nd second language on the page is en. Everything in my HTML templates seem to be working except this part of code If I set the translation to the code below. I will get only english translation, it means even if my page is in russian, i will get english translation of the text below anyway. from django.utils.translation import gettext_lazy as _ def get_country_info(country): country_info = { "Germany": _("Германия - это страна с богатой историей и культурой, расположенная в центре Европы. Она является домом для таких всемирно известных городов, как Берлин, Мюнхен, Гамбург и Кёльн. Германия славится своей архитектурой, музеями, пивом и колбасой."), "USA": _("США - это крупнейшая страна мира по площади и населению. Она расположена в Северной Америке и является ведущим мировым экономическим и культурным центром. США известны своими небоскрёбами, Голливудом, Диснейлендом и Ниагарским водопадом."), "UK": _("Соединённое Королевство - это островное государство, расположенное в Северной Атлантике. Оно включает в себя Англию, Шотландию, Уэльс и Северную Ирландию. Великобритания является родиной английского языка, парламента, Биг-Бена и королевы Елизаветы II."), "Turkey": _("Турция - это страна, расположенная на стыке Европы и Азии. Она известна своими пляжами, древними руинами, мечетями и базарами. … -
MySQLdb installation issue on Mac. Required for MySQL connectivity with Django
I am creating a Django project on Mac. I want to use MySQL for database. I am trying to install MySQLdb which gives the following error: (djangodev) $ pip3 install MySQL-python Collecting MySQL-python Using cached MySQL-python-1.2.5.zip (108 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [8 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/private/var/folders/9z/lf5bsw2929j34m5g6g9qcfqm0000gn/T/pip-install-5qv449ur/mysql-python_191252dd91f14deab09b6860c8c503d9/setup.py", line 13, in <module> from setup_posix import get_config File "/private/var/folders/9z/lf5bsw2929j34m5g6g9qcfqm0000gn/T/pip-install-5qv449ur/mysql-python_191252dd91f14deab09b6860c8c503d9/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. -
Redirect URI mismatch error with LinkedIn OAuth in Django Allauth on localhost
I am developing a LinkedIn sign-in feature for my Django application using Django Allauth. Everything seems to be configured correctly, and authentication works fine up until the point where LinkedIn attempts to redirect back to my application. I'm working on localhost and I'm receiving an error stating "The redirect_uri does not match the registered value" after attempting to authenticate with LinkedIn. I'm using http://127.0.0.1:8000/accounts/linkedin/login/callback/ as my redirect URI during tests in my local environment. Question: Could anyone provide some guidance or help on this matter? Does LinkedIn allow redirect URIs to localhost for development testing, or is there something else I'm missing here? Ensuring the redirect URI in my LinkedIn application matches exactly with what I'm using in my local environment. Checking for any typos or mismatches in the URL scheme, port, path, or query parameters between my Django application configuration and the LinkedIn application. Attempting to use both localhost and 127.0.0.1 to make sure the issue isn’t with the hostname resolution. What I expected: I expected LinkedIn to successfully redirect to my local Django app and complete the authentication process.