Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError at /approve/1
def approve_qoute(request, application_id): approve = get_object_or_404(Application, pk=application_id, created_by=request.user) if request.method == 'POST': form = EditStatusForm(request.POST, instance=approve) if form.is_valid(): approve = form.save(commit=False) approve.status = request.POST.get('status') approve.save() return redirect('dashboard') else: form = EditStatusForm(instance=approve) return render(request, 'job/approve_qoute.html',{'form':form, 'approve':approve}) -
KeyError: 'id' in django rest framework when trying to use update_or_create() method
I am trying to update the OrderItem model using update_or_create() method. OrderItem model is related to the Order model with many to one relationship ie with a Foreignkey. I am trying to query the orderitem object using id and update the related fields using default as you can see, but got this error. My models: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) #billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') My view: class UpdateOrderView(UpdateAPIView): permission_classes = [AllowAny] queryset = Order.objects.all() serializer_class = OrderUpdateSerializer My serializers: class OrderUpdateSerializer(serializers.ModelSerializer): order_items = OrderItemUpdateSerializer(many=True) billing_details = BillingDetailsSerializer() class Meta: model = Order fields = ['id','ordered','order_status','order_items','billing_details'] def update(self, instance, validated_data): instance.order_status = validated_data.get('order_status') instance.ordered = validated_data.get('ordered') #billing_details_logic billing_details_data = validated_data.pop('billing_details',None) if billing_details_data is not None: instance.billing_details.address = billing_details_data['address'] instance.billing_details.save() #order_items_logic instance.save() order_items_data = validated_data.pop('order_items') # print(order_items_data) #instance.order_items.clear() for order_items_data in order_items_data: oi, created = OrderItem.objects.update_or_create( id= order_items_data['id'], defaults={ 'quantity' : order_items_data['quantity'], 'order_item_status': … -
How add variable to django request from my front-end?
I am developing web app, with djangorestframework on the back and Vue.js on the front. Interface was translated to a few language. On the site footer user can see icons of language represented country flag. After hit the need icon, app translate all text to required language. All actions for translate do in front and my backend know nothing about what is language was chosen. Now I want to tell my back-end about chosen language, how can I do it? I think to add a variable language to my django request object, but I can find nothing about it. Any ideas? -
django error check in function reaching Ajax call
The scenario is adding an item to a cart and also choosing a fabric with it. Two errors I want to show with an alert pop up: a) when either when no color is selected / e.g. general error b) Only 1 item with the same fabric allowed per cart Putting out the (a) general error message works. But I'm unsure how to trigger the error alert of my ajax from the if statement in my view from django. My Ajax form: var productForm = $(".form-product-ajax") productForm.submit(function(event){ event.preventDefault(); var thisForm = $(this) var actionEndpoint = thisForm.attr("data-endpoint"); var httpMethod = thisForm.attr("method"); var formData = thisForm.serialize(); $.ajax({ url: actionEndpoint, method: httpMethod, data: formData, success: function(data){ var submitSpan = thisForm.find(".submit-span") if (data.added){ $.alert({ title: "Success", content: "Product added", theme: "modern", }) submitSpan.html("<button type='submit' class='btn btn-success'>Add to cart</button>") } }, error: function(errorData){ $.alert({ title: "Oops!", content: data.message, theme: "modern" }) } }) }) Django carts.view simplified def cart_update(request): added = False error_messages = "Please check your selections." if str(product_obj.type).lower() == "fabric": cart_obj, new_obj = Cart.objects.new_or_get(request) fabric_obj = str(Fabric.objects.filter(name__contains=fabric_select).first()) for item in cart_obj.choices.all(): if fabric_obj == item.fabric_note: error_messages = "You've reached the maximum order amount for this fabric." # how to trigger ajax error: function() … -
How to frequently update some perticular field in database?
This is my model to store bus details. Here I have kept a field named bookedSeat to store which seat is booked ( input a-z or A-Z ).Every-time user book a seat a single character (inputted from user) should be added to bookedSeat field in database. class busDetails(models.Model): busID = models.AutoField(primary_key=True) arrival = models.CharField(max_length=50) destination = models.CharField(max_length=50) rent = models.IntegerField() distance = models.IntegerField() bookedSeat = models.CharField(max_length=100) def __str__(self): return self.arrival+' --> '+self.destination I am getting stuck at how to frequently update(add into existing) that particular database field(bookedSeat)? ( without adding any new row ) How to solve this problem? Thank You :) -
How do I attach a PaymentMethod to a stripe Customer in DjStripe?
I have the following Django class: class PurchaseSubscriptionView(APIView): def post(self, request, user_id): price_name = request.data.get("price_name") payment_method = request.data.get("payment_method") user = User.objects.get(id=user_id) customer, created = djstripe.models.Customer.get_or_create(subscriber=user) payment_method_json = json.dumps(payment_method) customer.add_payment_method(payment_method_json) price = djstripe.models.Price.objects.get(nickname=price_name) customer.subscribe(price=price) Everything works until customer.add_payment_method(payment_method_json) At which point I get: stripe.error.InvalidRequestError: Request req_8KcCUrPg7z8Aok: No such PaymentMethod: '{\"id\": \"pm_1IaFMyJs57u3g5HDGoe83cGx\", \"object\": \"payment_method\", \"billing_details\": {\"address\": {\"city\": null, \"country\": null, \"line1\": null, \"line2\": null, \"postal_code\": null, \"state\": null}, \"email\": null, \"name\": null, \"phone\": null}, \"card\": {\"brand\": \"visa\", \"checks\": {\"address_line1_check\": null, \"address_postal_code_check\": null, \"cvc_check\": null}, \"country\": \"US\", \"exp_month\": 2, \"exp_year\": 2022, \"funding\": \"credit\", \"generated_from\": null, \"last4\": \"4242\", \"networks\": {\"available\": [\"visa\"], \"preferred\": null}, \"three_d_secure_usage\": {\"supported\": true}, \"wallet\": null}, \"created\": 1617002320, \"customer\": null, \"livemode\": false, \"type\": \"card\"}' What exactly is going on? I passed the PaymentMethod from my client after generating it - this should work, correct? Am I missing any steps? -
Djangocms: cannot do anything in the page tree
I encountered an error when I open the page tree of my djangocms project. enter image description here It appeared abnormal so that I counld not add or delete any page in fact. aldryn-apphooks-config 0.6.0 asgiref 3.3.1 dj-database-url 0.5.0 Django 3.1.7 django-admin-ip-restrictor 2.2.0 django-appdata 0.3.2 django-classy-tags 2.0.0 django-cms 3.8.0 django-filer 2.0.2 django-formtools 2.2 django-ipware 3.0.2 django-js-asset 1.2.2 django-meta 2.0.0 django-mptt 0.11.0 django-parler 2.2 django-polymorphic 3.0.0 django-sekizai 2.0.0 django-sortedm2m 3.0.2 django-taggit 1.3.0 django-taggit-autosuggest 0.3.8 django-taggit-templatetags 0.2.5 django-templatetag-sugar 1.0 django-treebeard 4.4 djangocms-admin-style 2.0.2 djangocms-apphook-setup 0.4.1 djangocms-attributes-field 2.0.0 djangocms-blog 1.2.3 djangocms-bootstrap4 2.0.0 djangocms-file 3.0.0 djangocms-googlemap 2.0.0 djangocms-icon 2.0.0 djangocms-installer 2.0.0 djangocms-link 3.0.0 djangocms-picture 3.0.0 djangocms-snippet 3.0.0 djangocms-style 3.0.0 djangocms-text-ckeditor 4.0.0 djangocms-video 3.0.0 easy-thumbnails 2.7.1 html5lib 1.1 lxml 4.6.2 Pillow 8.1.0 pip 21.0.1 pkg-resources 0.0.0 pytz 2021.1 setuptools 44.0.0 six 1.15.0 sqlparse 0.4.1 tzlocal 2.1 Unidecode 1.1.2 webencodings 0.5.1 I I had updated django from 3.1.6 to 3.1.7 and django-mptt from 0.11.0 to 0.12.0, but it did not work. -
Fix transparent box CSS
While doing a site with html and css I've faced problem with transparent box. Every element in this box is transparent too, but I want it without opacity. How can I fix this? My html: <!-- Search form --> <div class="container py-6 py-lg-7 text-white overlay-content text-center"> <div class="parent"> <div class="transbox"> <div class="search-form" id="id_forms"> <div class="col-lg-4"> {{ search_form.category }} </div> <div class="col-lg-4"> {{ search_form.city }} </div> <button class="btn btn-primary custom-btn" type="submit"><i class="fas fa-search"></i>Szukaj</button> </div> </div> </div> </div> and my css: .parent { display: inline-block; position:relative; width: 100%; border: 2px solid rgb(255, 255, 255); } .transbox { height: 350px; width: 100%; background-color: #ffffff; opacity: 0.4; display: flex; justify-content: center; } .parent .transbox .search-form { display: flex; justify-content: center; align-items: center; } -
Django channels: Coroutine object is not callale
I'm making a custom token authentication backend for my django channels app. I'm trying to setup the self.scope['user'] as follows. This is my middleware.py file class TokenAuthMiddleware: """ Token authorization middleware for Django Channels 2 """ def __init__(self, inner): self.inner = inner async def __call__(self, scope): User = get_user_model() query = str(scope['query_string'].decode()) user_slug = query[-8:] print(user_slug) user = await database_sync_to_async(User.objects.get)(slug=user_slug) scope['user'] = await user print('__________') print(scope['user']) print('__________') return self.inner(scope) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) And the following is my error log: [Failure instance: Traceback: <class 'TypeError'>: 'coroutine' object is not callable How to solve this? Thanks in advance -
How to convert MoneyField currency?
I created a management system for my Django app. In this app, the user has several customers and every customer has a credit_limit field. I am using MoneyField from django-money for this field so, users can select any currency. But I want to make some operations in this field like addition. For this I need each customer's credit_limit field to be converted to the same currency (dollar). But I couldn't find how to do this. I need help. Here are my codes. models.py from djmoney.models.fields import MoneyField ... class Customer(models.Model): ... credit_limit = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', default=0) ... forms.py class NewCustomerForm(forms.ModelForm): class Meta: model = Customer fields = ('customer_name', 'country', 'address', 'VATnumber', 'telephone', 'email', 'contact_person', 'credit_limit', 'risk_rating') views.py def customer(request): form_class = NewCustomerForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': form = NewCustomerForm(request.POST) if form.is_valid(): newCustomer = form.save() newCustomer.company = company newCustomer.save() return redirect('user:customer_list') else: form = form_class() return render(request, 'customer.html', {'form': form}) -
Values not getting reflected in UI . --> DJANGO
I am doing a Django program with a single UI containing two table, But the data is reflected only in one table of UI and not the other . In Network --> Response it prints both data so here is my code : Views.py def secondtableonDashboard(request): Server_list = "" NewList = "" afterConcat = "" conn = pyodbc.connect('Driver={SQL Server};' 'Server=IN2-1027310LTT\SQLEXPRESS;' 'Database=WebstartUI;' 'Trusted_Connection=yes;') cursor = conn.cursor() cursor.execute("select * from CustomerServer") result = cursor.fetchall() if request.method=='POST': user_list = request.POST.getlist('checked_list') Server_list = listToString(user_list) +"," else: print("No Values") for listValue in Server_list.split(","): NewList = "'"+listValue+"'," afterConcat = afterConcat + NewList Server_list = afterConcat[:-5] Server_list = Server_list[1:] ServiceList = conn.cursor() cmd = "Select * from dbo.ServiceRunningStatus where ServerName IN ('"+Server_list+"')" ServiceList.execute(cmd) resultOfServiceList = ServiceList.fetchall() print(resultOfServiceList) return render(request,'side-menu-light-tabulator.html',{'customerserver':result,'ServerList':resultOfServiceList}) So here it prints the value of "resultOfServiceList" on my terminal side-menu-light-tabulator.html <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th></th> <th>ServerName</th> <th>Customer Name</th> <th>node Labels</th> </tr> </thead> <tbody> {% for datas in customerserver %} <tr> <td> <div class="form-check form-switch"> <form method="post">{% csrf_token %} <input class="form-check-input" name="Servers[]" value="{{datas.ServerName}}" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault"> </form> </div> </td> <td>{{datas.ServerName}}</td> <td>{{datas.CustomerName}}</td> <td>{{datas.NodeLabels}}</td> </tr> {% endfor %} </tbody> </table> <!-- </div> --> </div> <div class="source-code hidden"> <div class="alert alert-danger-soft show flex items-center … -
Tailwind-Django SIte - Extending base.html causing strange table behaviour with For Loops
I have been making a website with Django and Tailwind which has a For loop in my HTML file that looks like: <div> Top companies currently hiring: <table class="table-fixed"> <tbody> <tr> {% for companies in top_companies %} <td>{{companies.0}}</td> <td>{{companies.1}}</td> </tr> {% endfor %} </tbody> </table> </div> Previously this would print a list as follows: Table when not extending base.html However when I extend from the base.html and use block content it does not add new rows and looks like this: <section class="bg-white border-b py-20"> <div class="flex justify-center content-center"> <div> {% block content %} {% endblock %} </div> </div> </section> Table when extending base.html I have tried moving the location of the block content within base.html but it doesn't make any difference. Is it possible something in the head is causing this behaviour? <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title> Test </title> <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="author" content="" /> <link rel="stylesheet" href="https://unpkg.com/tailwindcss/dist/tailwind.min.css" /> <!--Replace with your tailwind.css once created--> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700" rel="stylesheet" /> <!-- Define your gradient here - use online tools to find a gradient matching your branding--> <style> .gradient { background: linear-gradient(90deg, #d53369 0%, #daae51 … -
I want to create a script that takes a list of values as input and outputs a python file (django)
I'm doing a lot of work that is comparable to data entry -- essentially copying functions from one script to use for something that only differs in the names of the attributes. Like: Script 1: Business.objects.create( field_cat=something["cat"], field_doggo=something["doggo"], field_birb=something["birb], ) Script 2 OtherBusiness.objects.create( field_catto=something["catto"], field_dog=something["dog"], field_bird=something["bird"], ) This is a very simplified version of what I'm talking about. These scripts range from 60-90 lines long each. I'm getting tired of this monotonous work of replacing attribute names for dozens of files. There has got to be another way. Can anyone lend some insight? -
Django Razorpay integration working on test server but fails during live session
I am using razorpay integration with Django, I have tested the integration on localhost and it worked, also the checkout process and the payment collection works fine but when it comes to verifying the payment it seems to break on the live server. The order amount and details sent to razorpay seem to be working fine but response capture is maybe breaking. Below is my copy of views.py class CheckOutW2(View): def get(self, request, customer_phone): dtt = dt.datetime.now() phone = request.session.get('customer') customer_object = Customer.objects.filter(phone=phone, date__hour= str(dtt.hour)) customer_object = customer_object.reverse()[0] address = Addresses.objects.filter(customer=customer_object, date__hour= str(dtt.hour)) address = address.reverse()[0] cart = request.session.get('cart') products = Product.get_products_by_id(list(cart.keys())) ot = 0 for p in products: summed = p.price * cart.get(str(p.id)) ot = ot+summed ot_rz = ot *100 context = {'userD':customer_object, 'address':address, 'ot':ot_rz } return render(request, 'checkoutW2.html', context) def post(self, request, customer_phone): dtt = dt.datetime.now() cart = request.session.get('cart') products = Product.get_products_by_id(list(cart.keys())) ot = 0 for p in products: summed = p.price * cart.get(str(p.id)) ot = ot+summed order_amount = ot order_currency = 'INR' order_reciept = ('{}_{}_{}_{}'.format(dtt.day,dtt.month,dtt.year,customer_phone)) # response = client.order.create(amount=order_amount, currency=order_currency, reciept=order_reciept ) # order_id = response['id'] order_status = 'created' if order_status == 'created': return render(request,'checkoutW2.html', {'rzp_oid':order_id}) @csrf_exempt def payment_status(request ): response = request.POST phone = request.session.get('customer') cart … -
Django use LEFT JOIN instead of INNER JOIN
I have two models: Comments and CommentFlags class Comments(models.Model): content_type = models.ForeignKey(ContentType, verbose_name=_('content type'), related_name="content_type_set_for_%(class)s", on_delete=models.CASCADE) object_pk = models.CharField(_('object ID'), db_index=True, max_length=64) content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk") submit_date = models.DateTimeField(_('date/time submitted'), default=None, db_index=True) ... ... class CommentFlags(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comment_flags", on_delete=models.CASCADE) comment = models.ForeignKey(Comment, related_name="flags", on_delete=models.CASCADE) flag = models.CharField(max_length=30, db_index=True) ... ... CommentFlags flag can have values: like, dislike etc. Problem Statement: I want to get all Comments sorted by number of likes in DESC manner. Raw Query for above problem statement: SELECT cmnts.*, coalesce(cmnt_flgs.num_like, 0) as num_like FROM comments cmnts LEFT JOIN ( SELECT comment_id, Count(comment_id) AS num_like FROM comment_flags WHERE flag='like' GROUP BY comment_id ) cmnt_flgs ON cmnt_flgs.comment_id = cmnts.id ORDER BY num_like DESC I have not been able to convert the above query in Django ORM Queryset. What I have tried so far... >>> qs = (Comment.objects.filter(flags__flag='like').values('flags__comment_id') .annotate(num_likes=Count('flags__comment_id'))) which generates different query. >>> print(qs.query) >>> SELECT "comment_flags"."comment_id", COUNT("comment_flags"."comment_id") AS "num_likes" FROM "comments" INNER JOIN "comment_flags" ON ("comments"."id" = "comment_flags"."comment_id") WHERE "comment_flags"."flag" = 'like' GROUP BY "comment_flags"."comment_id", "comments"."submit_date" ORDER BY "comments"."submit_date" ASC LIMIT 21 Problem with above ORM queryset is, it uses InnerJoin and also I don't know how it adds submit_date in groupby clause. Can you please … -
Is making a different models for different categories is good, Django?
I'm making a website that provides services Shall I create different model for different type of service available -
Django How to use Javascript file from my local Django project in an external app
Let's say I have an application, myapp, and in that application I have installed another application via pip install wiki to add a wiki into my project. The wiki app is installed in the following directory: /Users/{my_username}/.virtualenvs/{my_virtualenv_name}/lib/python3.9/site-packages/wiki/ So to make modifications I have to overwrite the templates. In myapp I have been able to modify without problems the styles and others of the wiki app by overriding the templates, but the problem comes when I want to load javascript libraries external to wiki and that are in my local project (myapp) I would like to add the following js, but for some reason it doesn't work: <script type="text/javascript" src="/static/myapp/bootstrap/js/bootstrap-typeahead.js"> </script> <script type="text/javascript" src="/static/myapp/scripts/jquery.autocomplete.min.js"> </script> <script type="text/javascript" src="/static/myapp/scripts/myapp.js"></script> <script type="text/javascript" src="{% static 'project/search.js' %}"></script> <script type="text/javascript" src="{% static 'myapp/scripts/underscore-1.8.3.min.js' %}"> Probably if i add those js files in site-packages it will work but I don't think its good practice. Any ideas or suggestions on how to import such js files correctly? -
TypeError: Password must be a string or bytes, got BoundField
I am creating a login page. There I want to receive json format at backend, with fields username and password in string format. But when I try to authenticate username and password (in views.py). I get the following error: TypeError: Password must be a string or bytes, got BoundField. views.py from .serializers import event_serializer, student_serializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError @api_view(['POST', 'GET']) def login_view(request): if request.method == "POST": serializer = student_login_serializer(data=request.data) if serializer.is_valid(): print("serializer is valid") username_pwd = serializer username = username_pwd["username"] password = username_pwd["password"] student = authenticate(request, username=username, password=password) if student is not None: login(request, student) events = Event.objects.all() serializer = event_serializer(events, many=True) return Response(serializer.data, status=status.HTTP_202_ACCEPTED) else: return Response(serializer.data, status=status.HTTP_401_UNAUTHORIZED) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) elif request.method == "GET": users = Student.objects.all() serializer = student_serializer(users, many=True) return Response(serializer.data) serializers.py from rest_framework import serializers from .models import Student, Club, member_request, Event, Comment from django import forms class student_login_serializer(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'})) password = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Password'})) fields = ['username', 'password'] models.py from django.contrib.auth.models import AbstractUser from django.db import models class Student(AbstractUser): pass Please feel free to ask me for more details regarding this problem and … -
FAIL: test_category_model_entry (store.test.test_model.TestCategoriesModel)
I am trying to do unit test using coverage.py. From my understnadng I supposed to passed the test with no error as object name is 'django'. However, the output is irritates me when it mentioned Category Object (1) instead of 'django' and due to that my test will be forever error. Kindly somebody please help. from django.test import TestCase from store.models import Category, Product class TestCategoriesModel(TestCase): def setUp(self): self.data1 = Category.objects.create(name="django", slug="django") def test_category_model_entry(self): # Test category model data insertion/types/field attributes data = self.data1 self.assertTrue(isinstance(data, Category)) self.assertEqual(str(data), "django") The output displays as follows: in test_category_model_entry self.assertEqual(str(data), "django") AssertionError: 'Category object (1)' != 'django' Category object (1) django -
How can I let users authenticate into my django-react website with github?
I can't find ANYTHING on google or stackoverfliow about this. I'm using django and react and I want one of those "Log in with Github" buttons on my login page. I doubt anyone has time to write the whole process but maybe a link to a good source? Thanks! -
How to refresh quantity of cart in the span or the div after add product to cart AJAX / Django?
The product is successfully added to the cart but the div containing the cart value is not up to date. You will have to refresh the page so that the div is up to date. I tried the load() and html() methods. How to refresh cart container when I add the product to the cart ? I need a help please. Views Django def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({}) Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Form Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> HTML Span <ul class="navbar-nav ml-auto d-block d-md-none"> <li class="nav-item"> <a class="btn btn-link" href="#"><i class="bx bxs-cart icon-single"></i> <span class="badge badge-danger" id="cartval">{{ cart | length }}</span></a> </li> </ul> JS Code $(".form-order").on('submit', function(e){ e.preventDefault(); var product_id = $(this).attr('data-id') var quantity = $(this).find("#id_quantite").val() console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id+'/' $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, type: 'POST', dataType: 'json', data: data, success: function(data){ $("cartval").load(); … -
Django Stripe library is having trouble with Payment Method
I am using Stripe JS on my front end, and sending it to my backend, which is based on Django. All of generating a subscription is working, except for the payment method. Here's the code: class PurchaseSubscriptionView(APIView): def post(self, request, user_id): price_name = request.data.get("price_name") payment_method = request.data.get("payment_method") user = User.objects.get(id=user_id) customer, created = djstripe.models.Customer.get_or_create(subscriber=user) customer.add_payment_method(payment_method) price = djstripe.models.Price.objects.get(nickname=price_name) customer.subscribe(price=price) return Response({"success": "eventual subscription data"}) My payment_method looks like this (all of this is fake card data): { "id":"pm_1Ia7gGJs57u3g5HDEpaI5Pv2", "object":"payment_method", "billing_details":{ "address":{ "city":"None", "country":"None", "line1":"None", "line2":"None", "postal_code":"None", "state":"None" }, "email":"None", "name":"None", "phone":"None" }, "card":{ "brand":"visa", "checks":{ "address_line1_check":"None", "address_postal_code_check":"None", "cvc_check":"None" }, "country":"US", "exp_month":2, "exp_year":2022, "funding":"credit", "generated_from":"None", "last4":"4242", "networks":{ "available":[ "visa" ], "preferred":"None" }, "three_d_secure_usage":{ "supported":true }, "wallet":"None" }, "created":1616972764, "customer":"None", "livemode":false, "type":"card" } However upon this line: customer.add_payment_method(payment_method) I get the following error: TypeError: quote_from_bytes() expected bytes What exactly am I missing here? Is this not how I am supposed to use a payment method? This is using the Djstripe library -
Django Reverse function not working in this example
I'm not able to access the url named "forum" using the reverse function. It gives me this error: django.urls.exceptions.NoReverseMatch: Reverse for 'forum' not found. 'forum' is not a valid view function or pattern name. I'm able to access all my other namespaces URLs within the other apps. But I just can't access anything by name from my root URLs.py file. Here is my root URLs.py file from django.contrib import admin from django.urls import path, include from machina import urls as machina_urls from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('forum/',include(machina_urls), name='forum'), path('admin/', admin.site.urls), path('symposium/', include('symposium.urls')), path('elearning/', include('elearning.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Efficient Django query filter first n records
I'm trying to filter for the first (or last) n Message objects which match a certain filter. Right now I need to filter for all matches then slice. def get(self, request, chat_id, n): last_n_messages = Message.objects.filter(chat=chat_id).order_by('-id')[:n] last_n_sorted = reversed(last_n_messages) serializer = MessageSerializer(last_n_sorted, many=True) return Response(serializer.data, status=status.HTTP_200_OK) This is clearly not efficient. Is there a way to get the first (or last) n items without exhaustively loading every match? -
Using python manage.py runserver is giving me "file or directory does not exist"
So I keep getting that message and I am in the right folder when doing the command. I pip install django'd, I ran the command django-admin startapp firstproject, but this problem persists. I even tried updating django and python and reinstalled everything once. The photo I've attatched are the contents of my projects directory. Has anyone else had this problem before?