Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError ... not JSON serializable in Django with no reference to my code in the traceback
Notice that my code is not listed. It is all libraries. Traceback (most recent call last): File "/root/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/root/env/lib/python3.9/site-packages/django/utils/deprecation.py", line 138, in __call__ response = self.process_response(request, response) File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/middleware.py", line 59, in process_response request.session.save() File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/backends/db.py", line 82, in save obj = self.create_model_instance(data) File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/backends/db.py", line 69, in create_model_instance session_data=self.encode(data), File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/backends/base.py", line 94, in encode return signing.dumps( File "/root/env/lib/python3.9/site-packages/django/core/signing.py", line 150, in dumps return TimestampSigner(key, salt=salt).sign_object( File "/root/env/lib/python3.9/site-packages/django/core/signing.py", line 228, in sign_object data = serializer().dumps(obj) File "/root/env/lib/python3.9/site-packages/django/core/signing.py", line 125, in dumps return json.dumps(obj, separators=(",", ":")).encode("latin-1") File "/usr/lib/python3.9/json/__init__.py", line 234, in dumps return cls( File "/usr/lib/python3.9/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.9/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/usr/lib/python3.9/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' Exception Type: TypeError at /financialreconciliation/ Exception Value: Object of type AllCompany is not JSON serializable I knew the offending view via the URL. I did a binary search in the view to try and find the line where it occurred using print statements but I did not find it. I got all the way to the return with print statements and they all showed. Then I did … -
How to I make this If statement work on my Django project?
The if statement looks correct to me but when i save and execute the server, the printed out information is incorrect. Its almost like the information is not being picked up. Am i missing something in my model or view? Or is there anything else that i have to add to the if statement to allow it to see the data i'm trying to have it post? Can someone point out what i'm missing here?? HTML code: {% if leads.lead_status == "Active Deal" %} {% for lead in leads %} <tr> <td data-href="{% url 'leads:lead-detail' lead.pk %}"><i class="far fa-paper-plane"></i> {{ lead.id }}</td> <td>{{ lead.first_name|title }} {{ lead.last_name|title }}</td> <td>{{ lead.city|title }}</td> <td>{{ lead.state|upper }}</td> <td data-href="tel:{{ lead.phone }}">{{ lead.phone }} <i class="fas fa-phone-square"></i> </td> <td>$34,567.89</td> <td> {% if lead.contract_out == "" %} --/--/---- {% else %} {{ lead.contract_out }} {% endif %} </td> <td> {% if lead.contract_back == "" %} --/--/---- {% else %} {{ lead.contract_back }} {% endif %} </td> <td> {% if lead.hearing_date == "" %} --/--/---- {% else %} {{ lead.hearing_date }} {% endif %} </td> </tr> {% endfor %} {% endif %} views.py class DashboardPageView(LoginRequiredMixin, ListView): template_name = 'dashboard.html' context_object_name = "leads" def get_queryset(self): user = … -
Set up DRF Browsable API Root with all api urls
In my urls.py I have many rest framework urls: path( "api/", include([ path("users/", api_views.users, name="users"), path("proposals/", api_views.Proposals.as_view(), name="proposals"), path("requests/", api_views.Requests.as_view(), name="requests"), #... ]) ) I can visit the individual endpoints in the browser and access the browsable API, but I want to set up a browsable API Root where I can see all the available endpoints. The DRF tutorial has an example in which they list the urls they want in the root, but I have a lot of urls and I want all of them to show up. Is there a way to include all the urls in my "api/" path? -
django cloud run custom domain redirecting to login
During development I an able to login and logout just fine. I have deployed the Django app to Google cloud run. I am also able to login with the Service URL which has the syntax https://example-service-xxxxxxx-ey.a.run.app. Furthermore, I have also connected a custom domain via Firebase to the cloud run service and everything works well apart when I signin in which case I am redirected back to the login page. -
Websocket connection to ws://localhost:8000/ws/jobs/<job_id> failed
I am trying to connect to the websocket using django and I'm still getting same connection error. I've checked the documents and using the same code from the tutorial. const jobSocket = new WebSocket( "ws{% if request.get_host != 'localhost:8000' %}s{% endif %}://" + window.location.host + "/ws/jobs/{{ job.id }}/" ); // Execute this function whenever this page receives an event from Job Consumer via WebSocket jobSocket.onmessage = function (e) { var data = JSON.parse(e.data); var job = data.job; console.log(job); l've tried using routing.py and asgi.py to access the path but the error is still the same "raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/jobs/c5d1cc51-c2ad-458e-9cc7-f62520009112/'." I've tried different url patterns, different regrex esspresion and no luck. I tried this create a wair function to see if the websocket would open but it never does. function waitForSocketConnection(socket, callback){ setTimeout( function () { if (socket.readyState === 1) { console.log("Connection is made") if (callback != null){ callback(); } } else { console.log("wait for connection...") waitForSocketConnection(socket, callback); } }, 10); // wait 5 milisecond for the connection... } function updateCourierPosition(map) { let url = `ws://${window.location.host}/ws/jobs/{{ job.id }}/` const jobSocket = new WebSocket(url) waitForSocketConnection(jobSocket,function() { jobSocket.onopen = function(event){ jobSocket.send("connect") … -
Introspecting Django queryset field lookups
I'm building a querybuilder in Django for something similar to an issues dashboard, which allows users to query and save dashboards for custom subsets of the issues in our database (e.g., all issues assigned to team A, created by client X, and created or updated in the current quarter). The frontend would allow the user to interact with the issues API to generate the list of issues they're looking for, and to save the filter criteria so they can visit the page and see an updated list of issues that match the filter criteria. I'm thinking of saving the filter criteria as a dictionary in a JSONField, which I'd pass to the Model.objects.filter and the Q APIs. I'd like to provide the Frontend a list of all eligible Field lookups (e.g., exact, iexact, contains, icontains, in, gt, etc.). Is there a class I can introspect to programmatically get a list of these lookups? I read through the Field Lookup Docs tried looking through the Django source code, but couldn't find something similar to Model._meta.get_fields() for introspecting the fields on a model, as listed in the Model _meta API docs. -
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'
Hello I had to rewrite my user model for add some filed, I used AbstractUser My models: It's on blog app: class Article(models.Model): author = models.ForeignKey(User , null=True, on_delete=models.SET_NULL , related_name='articles' , verbose_name='نویسنده')... it's on account app: `from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_authour = models.BooleanField(default=False, verbose_name="وضعیت نویسندگی") special_user = models.DateTimeField(default=timezone.now, verbose_name="کاربر ویژه تا") def is_special_user(self): if self.special_user > timezone.now(): return True else: return False is_special_user.boolean = True is_special_user.short_description = "وضغیت کاربر ویژه"` I imported my User view in this way: from account.models import User And I added this to my setting: AUTH_USER_MODEL = 'account.User' I seatched my error but I can't find my solution -
How can I create "profile" urls without explicit passing arguments in django?
I am kinda new at django. For example let's say I'd like to create a BrAnD nEw social network as a pet project. I want my urls to look something like example.com/my-profile but not as example.com/profile/slug_or_pk. I have a user and profile models in different apps for now. Is it actually possible somehow to hide the slug? Models.py class Profile(models.Model): user = models.OneToOneField(User, verbose_name='User', on_delete=models.CASCADE) slug = models.SlugField(null=True) about = models.TextField('About', null=True, blank=True) avatar = models.ImageField("Avatar", upload_to=f"profile/", blank=True, null=True) cover = models.ImageField("Cover", upload_to="profile/", blank=True, null=True) def __str__(self): return self.user def get_absolute_url(self): return reverse('profile_detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.user.username) return super().save(*args, **kwargs) class Meta: verbose_name = "Profile" verbose_name_plural = "Profiles" views.py class ProfileDetail(DetailView): model = Profile context_object_name = 'profile' template_name = 'user_detail.html' urls.py urlpatterns = [ path('<slug:slug>/', ProfileDetail.as_view(), name='profile_detail'), ] And the root URLconf: urlpatterns = [ path('', IndexView.as_view(), name='index'), path('register/', RegisterUserView.as_view(), name='register'), path('login/', LoginUserView.as_view(), name='login'), path('logout/', LogoutUserView.as_view(), name='logout'), path('users/', include('users.urls')), path('profile/', include('profiles.urls')), path('posts/', include('posts.urls')), ] I've looked over tutorials, articles and etc.but I didn't manage to find something really useful. Maybe I am wrong somewhere at the fundamentals. Please help! -
AttributeError: module 'django.db.models.signals' has no attribute 'post_syncdb'
I created two models in my Django db. Now, I want to make migrations, but it shows error like this: AttributeError: module 'django.db.models.signals' has no attribute 'post_syncdb' . I tried to google the answer and found that this signal was deprecated in new Django version. It is not my project and I can't change the current version, so my colleagues recommended me to find the solution. What am I supposed to do if I can't change the version of Django and working on dev branch in project? How do I make migrations? What packages I can update? -
Docker redis sync fell into error loop on remote server
I am running Django dev server in docker with celery and redis on my remote host machine. Everything works fine like 30 mins, and then redis starts falling into infinite loop while MASTER <-> REPLICA sync started Here's the console output: redis_1 | 1:S 16 Feb 2023 17:42:37.119 * Non blocking connect for SYNC fired the event. redis_1 | 1:S 16 Feb 2023 17:42:37.805 # Failed to read response from the server: No error information redis_1 | 1:S 16 Feb 2023 17:42:37.805 # Master did not respond to command during SYNC handshake redis_1 | 1:S 16 Feb 2023 17:42:38.057 * Connecting to MASTER 194.40.243.205:8886 redis_1 | 1:S 16 Feb 2023 17:42:38.058 * MASTER <-> REPLICA sync started redis_1 | 1:S 16 Feb 2023 17:42:38.111 * Non blocking connect for SYNC fired the event. redis_1 | 1:S 16 Feb 2023 17:42:39.194 * Master replied to PING, replication can continue... redis_1 | 1:S 16 Feb 2023 17:42:39.367 * Partial resynchronization not possible (no cached master) redis_1 | 1:S 16 Feb 2023 17:42:39.449 * Full resync from master: ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ:1 redis_1 | 1:S 16 Feb 2023 17:42:39.449 * MASTER <-> REPLICA sync: receiving 54992 bytes from master to disk redis_1 | 1:S 16 Feb … -
How to return a standard Django Rest Framework JSON from an enum?
I'm not very familiar with DRF and I haven't found a solution on google for this problem (most answers are about a model with a field as enum, my problem is different) You see, we have an Enum in a Django application. Let's call it SomeValuesEnum. class SomeValuesEnum(Enum): ONE_VALUE = "One value" ANOTHER_VALUE = "Another value" What I need to do is to create a GET endpoint that returns the following { "count": 2, "page_count": 1, "next": null, "previous": null, "results": [ { "value": "One value", "name": "ONE_VALUE" }, { "value": "Another value", "name": "ANOTHER_VALUE" } ] } I know I need to create a serializer, but I haven't been able to create one and "feed it". For example, I started with something like this: class SomeValueSerializer(serializers.Serializer): Meta: model = SomeValuesEnum, fields = '__all__' and on the view: class SomeValueListView(APIView): serializer_class = SomeValueSerializer def get(self, request): choices = [{"value": target.value, "name": target.value.capitalize()} for target in SomeValuesEnum] serializer = SomeValueSerializer(data=choices) return Response(status=status.HTTP_200_OK, data=serializer.data) I also tried this class IncidentSerializer(serializers.Serializer): name = serializers.CharField(required=False, allow_blank=True, max_length=100) value = serializers.CharField(required=False, allow_blank=True, max_length=100) I'm not sure if I'm failing on the creation of the serializer, or in how I invoke him on the view (or … -
Protect views from anonymus users in simpleJWT
so I'm getting this weird issue. I have my simpleJWT auth working on the server but for some reason, I can't get permission_classes=[permissions.IsAuthenticated] to block the view from an anonymous user. There are many similar posts but I can't figure out where the issue is. from rest_framework import permissions class UsersListView(ListView): http_method_names = ['get'] permission_classes=[permissions.IsAuthenticated] def get_queryset(self): return UserModel.objects.all().exclude(id=self.request.user.id) def render_to_response(self, context, **response_kwargs): users: List[AbstractBaseUser] = context['object_list'] data = [{ "username": user.user_name, "pk": str(user.pk) } for user in users] return JsonResponse(data, safe=False, **response_kwargs) I've tried the dumbest approach first and removed allow any from here but no luck REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } Can you spot the issue? -
Django Rest: User validation: Is it safe to access self.request in ViewSet for validation in methods like perform_destroy
I want to validate that the user owns the model (is specified in the special field in the model referenced by this model) when user tries to update or destroy a model. In perform_update and perform_create I can access request to get user (with serializer.context["request"]) and referenced model instance with (serializer.validated_data["another_model"]) But in perform_destroy request is not passed. Is it safe to access self.request (will it always return the same request as request passed to destroy)? Even if django rest becomes async once? Or should I validate user in some other way? -
(Django) Why would my code not execute in an .html template?
this is my first post. I'll try get things right first time. I am having a play around with django and slowly creating a dummy store website. I'm following along a Corey Schafer YouTube tutorial and I didn't have this issue on my first run, so scratching my head now! My problem is that my .html template is not displaying the listing item when I run the page. I still see the <h1>DaftPrices Store Homepage</h1>, but not the listings. This is my template (store_home.html): <!DOCTYPE html> <html lang="en"> <head> <title>DaftPrices - Home</title> </head> <body> <h1>DaftPrices Store Homepage</h1> {% for listing in listings %} <p>{{ listing.item }}</p> {% endfor %} </body> </html> This is saved in a store dir, inside a templates dir, inside the store app. Image of directories This is my app views.py: from django.shortcuts import render listings = [ { 'seller': 'Chazsharpe', 'title': 'Something to sell', 'date_posted': '28th August 3030' } ] def store_home(request): context = {'listing': listings} return render(request, 'store/store_home.html', context) def store_about(request): return render(request, 'store/store_about.html') To clarify, the page pulls the template, but the "code" isn't working I have tried re-writing the dummy listings and changing the variables. I wasn't expecting this to do anything (and … -
Django serializer data
I need to get value of basket in 'title' not in 'id'. How can I do this? How can I get a value of 'title' from 'Position' model in another 'Client' model using ManyToManyField. It automatically transmits ID and the 'title' is required I have tried many ways but... It must be easy, but i search info 2 days class Position(models.Model): title = models.CharField(max_length=150, verbose_name='Title') slug = models.SlugField(max_length=100, unique=True, db_index=True, verbose_name='URL') description = models.CharField(max_length=500, verbose_name='Describe') photo = models.ImageField(upload_to="photos/%Y/%m/", verbose_name='Photo', null=True) price = models.DecimalField(decimal_places=2, max_digits=10, verbose_name='Price') date_create = models.DateTimeField(auto_now_add=True, verbose_name='Date create') date_update = models.DateTimeField(auto_now=True, verbose_name='Date update') is_published = models.BooleanField(default=True, verbose_name='Is published') in_stock = models.BooleanField(default=True, verbose_name='In stock') class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) basket = models.ManyToManyField('Position', default=None, blank=True, related_name='basket') def __str__(self): return f'{self.user.username}, id-{self.user.id}' class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" class ClientViewSet(viewsets.ModelViewSet): serializer_class = ClientSerializer permission_classes = (IsOwnerOrReadOnly,) def get_queryset(self): pk = self.kwargs.get('pk') # need a list of objects, not an one return Client.objects.filter(pk=pk) result: { "id": 1, "user": 1, "basket": [ 1 ] } need something like this - "basket":['monitor','keyboard'] -
Why would js function not trigger on button click?
I'm trying to follow this guide and I'm having a bit of an issue I can't figure out how to fix. Basically in PassKeys.html you have these 2 following bits of code: <button class="btn btn-success" onclick='start()'>Add Key</button> function start(){ $("#modal-title").html("Enter a token name") $("#modal-body").html(`<p>Please enter a name for your new token</p> <input type="text" placeholder="e.g Laptop, PC" id="key_name" class="form-control"/><br/> <div id="res"></div> `) $("#actionBtn").remove(); $("#modal-footer").prepend(`<button id='actionBtn' class='btn btn-success' onclick="begin_reg()">Start</button>`) $("#popUpModal").modal('show') } Now I'm no JavaScript expert but I would wager that when I click that button (which I can see in my webpage) a function should run that activates a modal. In the example provided by the guide things do work exactly that way, but in my application it doesn't seem to, and the code itself is exactly the same. What could be the cause of that? -
Correct use of pytest fixtures of ojects with Django
I am relatively new to pytest, so I understand the simple use of fixtures that looks like that: @pytest.fixture def example_data(): return "abc" and then using it in a way like this: def test_data(self, example_data): assert example_data == "abc" I am working on a django app and where it gets confusing is when I try to use fixtures to create django objects that will be used for the tests. The closest solution that I've found online looks like that: @pytest.fixture def test_data(self): users = get_user_model() client = users.objects.get_or_create(username="test_user", password="password") and then I am expecting to be able to access this user object in a test function: @pytest.mark.django_db @pytest.mark.usefixtures("test_data") async def test_get_users(self): # the user object should be included in this queryset all_users = await sync_to_async(User.objects.all)() .... (doing assertions) ... The issue is that when I try to list all the users I can't find the one that was created as part of the test_data fixture and therefore can't use it for testing. I noticed that if I create the objects inside the function then there is no problem, but this approach won't work for me because I need to parametrize the function and depending on the input add different groups … -
simpleJWT confirm password field
I'm creating a small app that uses simpleJWT. I want the user to retype their password when registering. Currently, I'm sending data like this { "email":"test", "user_name":"test3", "password":"b12@wsqp" } But what I want to validate is { "email":"test", "user_name":"test3", "password":"b12@wsqp", "password2":"b12@wsqp" } What i have now is class CustomUserCreate(APIView): permission_classes = (AllowAny,) def post(self, request): reg_serializer = RegisterUserSerializer(data=request.data) if reg_serializer.is_valid(): new_user = reg_serializer.save() if new_user: return Response(status=status.HTTP_201_CREATED) return Response(reg_serializer.errors, status=status.HTTP_400_BAD_REQUEST) class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'user_name', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance So my guess is to do class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'user_name', 'password1', 'password2') extra_kwargs = {'password': {'write_only': True}, 'password2':{'write_only': True}} def create(self, validated_data): password1 = validated_data.pop('password1', None) password2 = validated_data.pop('password2', None) instance = self.Meta.model(**validated_data) if password1 is not None and password2 is not None: if password1 == password2: instance.set_password(password) else: #return some error instance.save() return instance How can I validate if the password are matching? -
Chrome Extension Requesting django server
I am creating a chrome extension that requires a back end server for processing. I would like it to send data to the server, the server will process this data and send some other data back to the user. Preferably this back end server should be in python as there are libraries I would like to use. Any idea how to go about this? I was thinking to use a django server with rest API but I'm not sure what would be best. If anyone could provide a tutorial link or briefly explain the code behind this idea it would be brilliant. -
permission for show media folder in django, python
I want set permission for show media folder images. for example, I want show my images to users who are staff. When user in not staff, show 404 Error Thanks -
Django filter objects and do not select objects if there are objects that were created before them with same field value
I'm trying to do a get_queryset for ModelList view, but I only want to select those records that don't have other records with the same event_id in front of them. For example, we have two records. The second record is a child of the first one, and therefore, I don't want to select this second record from the database because it will already be in the children field of the first record. The children field is generated in the serializer, and does not exist in the database. Dataset [ { "event_id": "63395", "operation_id": "25180328", "time_created": "2023-01-12T09:16:11.873700+01:00", "children": [ { "event_id": "63395", "time_created": "2023-01-12T09:16:41.285390+01:00", "operation_id": "25180329", "children": [] } ] }, { "event_id": "63395", "time_created": "2023-01-12T09:16:41.285390+01:00", "operation_id": "25180329", "children": [] } ] View class ModelList(generics.ListAPIView): permission_classes = [permissions.IsAuthenticated] queryset = Model.objects.all() serializer_class = ModelSerializer def get_queryset(self): return Model.objects.filter( ~Q( Q(event_id=F('event_id')) & Q(operation_id__gt=F('operation_id')) ) ) -
How can I update specific field after retrieved in django rest framework
How can I update specific field after retrieved in django rest framework # Models.py class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() view = models.IntegerField(default=0) def __str__(self): return self.title I want to update view after read a specific data. # Views.py class ArticleDetail(generics.RetrieveUpdateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer # Update view + 1 # serializers.py class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = "__all__" Please help me -
How to display not id but another value in ForeignKey
This is my code for the hotel website models.py class Rooms(models.Model): room = models.BigIntegerField(verbose_name='Комната', unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория', related_name='wer') room_bool = models.BooleanField(verbose_name='Статус', default=True) price = models.BigIntegerField(verbose_name='Цена', null=True,blank=True) class Registrations(models.Model): room_num = models.ForeignKey(Rooms, on_delete=models.CASCADE, verbose_name='Номер', related_name='ertgdb', limit_choices_to={'room_bool': True}) first_name = models.CharField(max_length=250, verbose_name='Имя') last_name = models.CharField(max_length=250, verbose_name='Фамилия') tel_num = models.BigIntegerField(verbose_name='Номер телефона') img = models.FileField(verbose_name='Паспорт', null=True, blank=True) visit_date = models.DateField(default=now, verbose_name='Дата прибытия') leave_date = models.DateField(blank=True, null=True, help_text='Дата отбытия') guest_count = models.IntegerField(default=1, verbose_name='Кол-во людей') room_relevant = models.BooleanField(default=False, verbose_name='Статус') price = models.BigIntegerField(verbose_name='Цена', default=100) serializers.py class RegistrationSer(serializers.ModelSerializer): class Meta: model = Registrations fields = ('id', 'room_num', 'first_name', 'last_name', 'tel_num', 'img', 'visit_date', 'guest_count', 'room_relevant') I need the room_num field (in the picture) to have not Id but room_num as in the Input form SlugRelatedField doesn't work because I can't make POST PUT requests later -
Django - ValueError: could not convert string to float: ''
Learning Django with tutorial and have error. File "F:\Python\COTSW\teashop\main\views.py", line 98, in cart_list total_amt+=int(item['qty'])*float(item['price']) ValueError: could not convert string to float: '' Views.py def cart_list(request): total_amt = 0 for p_id, item in request.session['cartdata'].items(): total_amt+=int(item['qty'])*float(item['price']) return render(request, 'cart.html', {'cart_data': request.session['cartdata'], 'totalitems': len(request.session['cartdata']), 'total_amt': total_amt}) Custom.js $(document).on('click', ".add-to-cart", function(){ var _vm=$(this); var _index=_vm.attr('data-index'); var _qty = $(".product-qty-"+_index).val(); var _productId = $(".product-id-"+_index).val(); var _productTitle = $(".product-title-"+_index).val(); var _productImage = $(".product-image-"+_index).val(); var _productPrice = $(".product-price-"+_index).text(); var _productSlug = $(".product-slug-"+_index).val(); console.log(_productPrice) // Ajax $.ajax({ url:'/add-to-cart', data:{ 'qty':_qty, 'id':_productId, 'title':_productTitle, 'image':_productImage, 'price':_productPrice, 'slug':_productSlug, }, dataType:'json', beforeSend:function(){ _vm.attr('disabled', true); }, success:function(res){ $(".cart-list").text(res.totalitems); _vm.attr('disabled',false); } }); Before changes var _productPrice = $(".product-price").text(); was var _productPrice = $(".product-price").text(); and worked. Console.log showing correct price 500.00, but total_amt+=int(item['qty'])*float(item['price']) taking an empty string. Everything works correctly in the tutorial and I don't understand what could be wrong. -
Django: how to filter the inbox messages that belong to a user?
I am trying to get the messages that belongs to a user, something that look like this I am finding it difficult to write the filter query, according to this Answer, i wrote a query that looks like this class MyInbox(generics.ListCreateAPIView): serializer_class = MessageSerializer def get_queryset(self): user_id = self.kwargs['user_id'] messages = ChatMessage.objects.filter(Q(sender__in=user_id) | Q(reciever__in=user_id)).order_by("-date") return messages This is my response what i am trying to do is this, get the latest message that i had with sam, also the latest message that i had with moz and not all the messages. I am trying to get this messages because i want to loop through the message just like in the screenshot above. This is my model class ChatMessage(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="user") sender = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="sender") reciever = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="reciever") message = models.CharField(max_length=10000000000) is_read = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) mid = ShortUUIDField(length=10, max_length=25, alphabet="abcdefghijklmnopqrstuvxyz") Please how do i go about this?