Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker Celery configuration - For Django/React/Redis/Celery project. No Celery logo and background task log appearing
I have created a project github repository that has Docker, Django, React, Redis, Celery: https://github.com/axilaris/dockerize-django-react-celery-redis. My goal is to get celery working correctly with the logo appearing and background task log prints. This is based from this Docker - React and Django example tutorial code: https://github.com/dotja/authentication_app_react_django_rest And trying to use Docker - Celery & Redis from this tutorial code: https://github.com/veryacademy/docker-mastery-with-django/tree/main/Part-4%20Django%20Postgres%20Redis%20and%20Celery <-- Part 4 tutorial for Celery & Redis Here is the docker-compose.yaml for the redis & celery part: # Redis redis: image: redis:alpine container_name: redis ports: - "6379:6379" # celery celery: restart: always build: context: ./backend command: celery -A backend worker -l DEBUG volumes: - .:/django container_name: celery depends_on: - redis - backend my project should work if you need to check: docker-compose build docker-compose up However, there is no celery logo (1) and I dont see the logs print on the background process (2). I think it is executing as result.ready returns. But I want these 2 for completeness. (eventhough result.ready maybe be working with celery executing background task) It did not print this celery logo. celery | -------------- celery@b755a7cdba8d v5.3.6 (emerald-rush) celery | --- ***** ----- celery | -- ******* ---- Linux-6.6.12-linuxkit-aarch64-with 2024-03-02 20:48:06 celery | - *** … -
Seeking Feedback on Map Optimization in Django App
I'm currently working on a Django app involving maps and would appreciate some guidance on my approach. Here's what I'm doing in simpler terms: Receiving Trip Details: When a user makes a post call, I receive details about their trip. Fetching Coordinates: Depending on whether it's a pickup or drop trip: For pickups: We have multiple pickup locations and one common drop-off point. For drops: We have multiple drop-off points and one pickup location. Optimizing Trip Order: Using the TomTom API, I optimize the order of these coordinates to find the most efficient route. For example: If the trip type is "Pickup" and we have coordinates [0,1,2,3], and the optimized order is [0,2,1,3], we'll calculate the route geometry for pairs like 0,2 then 2,1 then 1,3. Calling TomTom APIs: With the optimized order, we call the TomTom Route API, passing consecutive pairs of optimized coordinates to get a complete optimized route geometry. Adding Route Layer to Map: Finally, using these optimized geometries, we add a route layer to the map for visualization. I'm wondering if this approach makes sense and if there are any potential improvements or better ways to achieve this. Any insights or suggestions would be greatly appreciated! -
django framework 404 error page not found
i don't understand were i was doing wrong i'm getting this again and again i'm getting error like this Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in sitaram.urls, Django tried these URL patterns, in this order: members/ [name='members'] admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. wanted to know were i'm i doing wrong -
In my webpage add to cart button (from homepage) is not working
I created a add-to-cart button for my website so, In Index.html: <button class="btn-action add-to-cart-btn" data-index="{{p.id}}" id="add-to-cart-btn"> <input type="hidden" value="1" id="product-quantity" class="product-quantity-{{p.id}}"> <input type="hidden" class="product-pid-{{p.pid}}" value="{{p.pid}}" name=""> <input type="hidden" class="product-image-{{p.id}}" value="{{p.image}}" name=""> <input type="hidden" class="product-id-{{p.id}}" value="{{p.id}}" name=""> <input type="hidden" class="product-title-{{p.id}}" value="{{p.title}}" name=""> <ion-icon name="bag-add-outline"></ion-icon> </button> This is the add-to-cart button and in function.js: $(".add-to-cart-btn").on("click",function(){ let this_val=$(this) let index= this_val.attr("data-index") let quantity=$("#product-quantity-" + index).val() let product_title=$(".product-title-" + index).val() let product_id=$(".product-id-" + index).val() let product_price = $("#current-product-price-" + index).text() let product_pid = $(".product-pid-" + index).text() let product_image=$(".product-image-" + index) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Pid:", product_pid); console.log("Image:", product_image); console.log("Index:", index); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); The problem is that: When I am clicking on the add-to-cart button, in the console no values are displaying Note: The javascript is taking value from home page(index) and from an another page........... and if you need my views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], } if 'cart_data_obj' in request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data request.session['total_cart_items'] = len(cart_data) else: request.session['cart_data_obj']=cart_product request.session['total_cart_items'] = len(cart_product) return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items']}) But views.py is working perfectly well -
Output to Django template from EAV model
I can’t figure out how to display the value of the characteristics into a template from the model, where the characteristics are compared with the values. I got the value from the Product table, but how do I get it from the ProductProperty table? class Product(models.Model): name = models.CharField(verbose_name='Наименование', max_length=128) name_eng = models.CharField(verbose_name='Наименование (англ.)', max_length=128) slug = models.SlugField(verbose_name='Слаг', max_length=128, unique=True, db_index=True, editable=False) category = models.ForeignKey(verbose_name='Категория', to=Category, on_delete=models.CASCADE) class Property(models.Model): name = models.CharField(verbose_name='Наименование', max_length=128) class ProductProperty(models.Model): product = models.ForeignKey(verbose_name='Продукт', to=Product, on_delete=models.CASCADE) property = models.ForeignKey(verbose_name='Характеристика', to=Property, on_delete=models.CASCADE) value_string = models.CharField(verbose_name='Текстовое значение характеристики', max_length=250, null=True, blank=True) value_integer = models.IntegerField(verbose_name='Числовое значение характеристики', null=True, blank=True) value_genres = models.ManyToManyField(verbose_name='Жанры', to=Genre, null=True, blank=True) I tried to implement this through a for loop, but it didn't work -
Need Authorization Header in test DRF
I try to test some views by the url but seems I'm blocked with the credentials, I see other post with the same problem and try to follow them but I'm still as the sane point test_web_share_file_folder_view_set.py class WebShareFileFolderViewSetTestCase(TestCase): def setUp(self): self.factory = APIRequestFactory() self.user = User.objects.create_user(username='my_user', password='my_password') headers = web_backend_api_access_headers() self.token = headers['Authorization'] self.client = APIClient() def test_list_with_search(self): WebShareFileFactoryBoy(name="file_with_search", path="path_with_search") url = reverse('web-share-file-folders-list') request = self.factory.get(url, {'search': 'file_with_search'}) request.user = self.user self.client.credentials(HTTP_AUTHORIZATION='Bearer' + self.token) response = self.client.get(url, headers={'Authorization': 'Bearer ' + self.token}) print(response.data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue('file_with_search' in response.data['results'][0]['name']) here the error when I start the test FAIL: test_list_with_search (tests.test_web_share_file_folder_view_set.WebShareFileFolderViewSetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "-\tests\test_web_share_file_folder_view_set.py", line 32, in test_list_with_search self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 401 != 200 and here the print of response.data {'detail': ErrorDetail(string='Need Authorization Header', code='authentication_failed')} If anyone has an idea :? thank you I try to access to the view to make a test -
How to setup two Google Storage Buckets for a Django application, one for MEDIA files and the other for STATIC files?
Here is the error I am getting at the home page of my app. Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information. #settings.py from google.oauth2 import service_account from google.cloud import storage try: # Load service account info from environment variables service_account_info = { "type": env("TYPE"), "project_id": env("PROJECT_ID"), "private_key_id": env("PRIVATE_KEY_ID"), "private_key": env("PRIVATE_KEY"), "client_email": env("CLIENT_EMAIL"), "client_id": env("CLIENT_ID"), "auth_uri": env("AUTH_URI"), "token_uri": env("TOKEN_URI"), "auth_provider_x509_cert_url": env("AUTH_PROVIDER_X509_CERT_URL"), "client_x509_cert_url": env("CLIENT_X509_CERT_URL") } # Create credentials from the service account info credentials = service_account.Credentials.from_service_account_info(info=service_account_info) # Initialize the Google Cloud Storage client with your credentials client = storage.Client(credentials=credentials, project=env("PROJECT_ID")) # List all buckets -> this works buckets = list(client.list_buckets()) print("Buckets in {}:".format(client.project)) print(buckets) except Exception as e: print("Error initializing Google Cloud credentials: ", e) #also settings.py DEFAULT_FILE_STORAGE = 'fly_io_test.gcloud.GoogleCloudMediaFileStorage' STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_STATIC_BUCKET_NAME = env("DEV_STATIC_FILES_BUCKET_NAME") GS_MEDIA_BUCKET_NAME = env("DEV_MEDIA_FILES_BUCKET_NAME") STATIC_URL = f"https://storage.googleapis.com/{GS_STATIC_BUCKET_NAME}/admin/" MEDIA_URL = f"https://storage.googleapis.com/{GS_MEDIA_BUCKET_NAME}/" I have have run gcloud auth login , gcloud config set project <project_id>. and then gcloud auth application-default-login in the container seemingly successfully. I'm getting the ADC error I don't know if this will write media files to the MEDIA bucket and STATIC files to the static bucket. -
Django Python Email Subject end of text white space not showing
I have this email to send out with email subject + current date. msg = MIMEMultipart('alternative') msg['Subject'] = Header("Email Subject for " + str(today.strftime("%d/%m/%y"))) msg['From'] = me msg['To'] = you When receive the email, the email subject shows Email Subject forDD/mm/yy. Tried add space after "for" as above but it wont show at Gmail. Is there any way to add a space between for and DD/mm/yyyy? -
Debugging in Django REST Framework
How to correctly catch breakpoints in Django REST Framework debugging session after an HTTP request? When debugging a DRF project breakpoints trigger upon initiating the debug process rather than after sending an HTTP request. i set "justMyCode": false rather than to true When I begin the debugging process, all steps are debugged up to the point where the WSGI server starts, as indicated by the following output: sql Copy code ... System check identified no issues (0 silenced). March 13, 2024 - 02:36:24 Django version 5.0.3, using settings 'tuto.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However, after sending an HTTP request, I immediately receive the response, with no breakpoints being hit during the process. -
autofill html form w/ multiple different fields, including: Checkbox and Dropdown selections
Part of the html form I want to autofill: <div h2 class="display-6 text-uppercase mb-3"> Service</h2> <span class="question">Select Service(s):</span><br> <input type="checkbox" id="car_wash" name="car_wash" value="car_wash"/> <label for="car_wash"> Car Wash</label><br> <input type="checkbox" id="window_cleaning" name="window_cleaning" value="Window Cleaning" autocomplete="name"> <label for="window_cleaning"> Window Cleaning</label><br> <input type="checkbox" id="power_wash" name="power_wash" value="Power Wash" autocomplete="name" <label for="power_wash"> Powerwashing</label><br> <input type="checkbox" id="curb_address" name="curb_address" value="Curb Address Painting" autocomplete="name" <label for="curb_address"> Curb Address Painting</label><br> </div> <div id="dropdownHolder" class="col-lg-12 mb-3"> <select id="carwash_type" name="carwash_type" class="form-select form-control" aria-label="Default select example" value="ON"> <option selected> Car Type</option> <option value="1">Coupe / Sedan / Hatchback</option> <option value="2">Suv / Crossover</option> <option value="3">Mini Van</option> <option value="4">Pickup Truck</option> <option value="5">I'm not sure</option> </select> </div> <div id="dropdownHolder" class="col-lg-12 mb-3"> <select id="carwash_type" name="carwash_type" class="form-select form-control" aria-label="Default select example" value="ON"> <option selected> Car Wash Package</option> <option value="1">Express Interior</option> <option value="2">Express Exterior</option> <option value="3">Full Service Wash</option> </select> </div> There are several pages linking to this form, each of which have a service selected and if it's a car wash, the extras as well, including car type and wash package. Here is the html of the car wash selection - before the form page, trying to link to it w/autofilled selections. <div class="services-content text-center border py-3 py-md-5 px-3"> <iconify-icon class="service-icon" icon="fa6-solid:car-on"></iconify-icon> <h4 class="my-3">Auto Detailing</h4> <a href="booking.html" class="icon-link my-3"> … -
Django form submition Problem with Submit button
Im encountering a problem with an html template that i created using bootstrap so my problem is that i have a javascript working dynamically to add rows to a django form with 4 specific fields but whenever i add a row the submit button stops submitting results and instead adds more product fields to fill and they are initialized to None here is the code for my html template {% block createlist %} <form id="form-container" method="POST"> {% csrf_token %} <div class="card"> <div class="form-group" id="form-group"> <div class="row mt-3"> <h4 class="card-title md-2 m-2">List Name</h4> <div class="m-2">{{ listform.name}}</div> </div> <div id="button_row" class="row mt-0 no-gutters"> <!-- Apply .row class here --> <div class="row"> <h2 class="col-md-2 md-2 m-2">Products</h2> <div id="add-form" class="col-md-1 md-2 m-2"><button type="button" class="btn btn-primary">+</button></div> </div> <div class="col-md-2 m-2">Product Name</div> <div class="col-md-2 m-2">Quantity</div> <div class="col-md-2 m-2">Weight</div> <div class="col-md-2 m-2">Price</div> </div> {{ productformset.management_form }} {% for form in productformset %} <div id="form-row" class="row mt-0 no-gutters"> <!-- Apply .row class here --> <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-product_name" value=""></div> <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-quantity" value="{{ form.quantity.value }}"></div> <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-weight" value="{{ form.weight.value }}"></div> <div class="col-md-2 m-2"><input type="text" name="{{ form.prefix }}-price" value="{{ form.price.value }}"></div> </div> {% endfor %} </div> </div> … -
(WAGTAIL) How to add a button, or something similar, items per page to a model listing in the wagtail administrative area?
I'm trying to add an items button per page in the wagtail administrative area, but I didn't find anything in the documentation. Is there any way to customize and create a button to choose the number of items per page? -
Why is the email still not being sent even though all steps have been fulfilles?
I'm trying to send a confirmation email every time a user signs up for my service. I followed tutorials but while the user is getting signed up, the email is not being sent. This is my views.py def signup_view(request): if request.method == "POST": first_name= request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email', 'default user') phone = request.POST.get('phone') password1= request.POST.get('password1') password2= request.POST.get('password2') userHash= email.replace('@','') # userHash =~ s/'@'//g #new =User.objects.filter(username = userHash) if password1 != password2: return render(request, 'signup.html',{'error_message': ' Passwords Different'}) else: user = User.objects.create_user((userHash, password1)) user.save() login(request, user) current_site = get_current_site(request) user = request.user email = request.user.email subject = "Verify Email" message = render_to_string('account/verify_email_message.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) email = EmailMessage( subject, message, to=[email] ) email.send() return HttpResponse("Please Confirm your email address to complete the registration") and render(request,'account/landing.html') else: form = CreateUserForm() context = { 'form': form } return render(request, 'account/signup.html', context) def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return HttpResponse("Thank you for this confirmation") and redirect('account/index.html') else: messages.warning(request, 'The link is invalid.') return render(request, 'account/index.html') def home(request): return render(request, 'account/index.html') This is … -
Create List of Blank Forms on Submit
I am working with Django and have one form for each employee that expires every two weeks. For example, last weeks timesheets are now expired and I need to create a list of new timesheets. How can I create multiple blank forms, based on creation of new time period? Context: class TwoWeekPeriod(models.Model): start_date = models.DateField(_("Start Date")) end_date = models.DateField(_("End Date")) week_number = models.IntegerField(_("Week Number")) class CreateNewTimesheet(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) start_date = models.DateField(_("Start Date")) end_date = models.DateField(_("End Date")) two_week_period = models.ForeignKey(TwoWeekPeriod, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): week_number = (self.start_date - timezone.now().date()).days // 14 + 1 two_week_period, _ = TwoWeekPeriod.objects.get_or_create( start_date=self.start_date, end_date=self.end_date, defaults={'week_number': week_number} ) self.two_week_period = two_week_period super().save(*args, **kwargs) Employee Timesheet example: class Foo(model.Models) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) time_in = ### time_out = ### How can I use CreateNewTimesheet, let’s say 14 (each employee) blank forms using model Foo for each employee in order to input new time, for each employee, for the next two week period, without having to create each individual timesheet manually? -
Why use Pydantic with Django?
I am looking to implement Pydantic into my Django app (for learning and interview purposes), but I'm wondering why would I? Why should I use data validation on things like Django models when the fields themselves already have types declared on them? Are there any other instances in a Django app where it makes sense to use data validation? Please be kind in your responses. I am genuinely curious and asking honestly. I have tried researching reasons to use Pydantic in a Django app, but have not found any strong arguments for its use. -
Integrate model representation with DRF Spectacular and Redoc, similar to the Pet Store Redocly example
I'm new to the developer sphere and the Python environment. As part of my apprenticeship, I'm working on a project to custom document a JS plugin. The project is set up with Django, drf-spectacular and redoc. I already have several views in place to expose the methods, events and properties of the plugin. I am currently having difficulty formatting two User and Addresses models with exactly the same behavior as the Pet and Order models present on the Pet Store API. Depending on the type chosen, the model changes. I've heard about Discriminator and PolymorphicSerializer but I'm a bit lost on what to do. I don't directly use the openapi schema. To generate the documentation, I run a script that will execute the npm command run bundle:standalone which will create the redoc.standalone.js that I then transfer to the Django static folder. Would anyone have a research lead or similar experience with the technologies used ? Thank you very much for your answers. Best regards. -
Styling Django CreateView Form
I want to design the form like option B Which shown in Image but not able to get the result My form looks like A. I am not using any Form or ModelForm just using CreateView. I also don't want to modify my Views or add any FormClass so please let me how can i get the Result. Here is my Model class InfluencerModel(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) instagram_id = models.CharField(max_length=50, null=False, blank=False) message = models.TextField(null=True, blank=True) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email def get_absolute_url(self): return reverse("influencers") Views.py class InfluencersPageView(CreateView): model = InfluencerModel template_name = 'home/influencers.html' fields = ['full_name', 'email', 'contact_number', 'instagram_id', 'message'] def get_context_data(self, *args, **kwargs): context = super(InfluencersPageView, self).get_context_data(*args, **kwargs) return context Here is Template <form action="" role="form" class="php-email-form" method="post"> {% csrf_token %} <div class="row"> <div class="col-md-6 form-group"> {{ form.full_name.errors }} {{form.full_name|as_crispy_field}} </div> <div class="col-md-6 form-group mt-3 mt-md-0"> {{ form.email.errors }} {{form.email|as_crispy_field}} </div> <div class="form-group col-md-6"> {{ form.contact_number.errors }} {{form.contact_number|as_crispy_field}} </div> <div class="form-group col-md-6"> {{ form.instagram_id.errors }} {{form.instagram_id|as_crispy_field}} </div> </div> <div class="form-group mt-3" rows="7"> {{ form.message.errors }} {{form.message|as_crispy_field}} </div> <div class="text-center"> <button type="submit" class="btn btn-outline-secondary" style="background-color:#FF512F; color: white">Send Message</button> </div> </form> -
Browser doesn't find images from HTML when running on local host
I am developing my site and running on the local host now on windows computer. I want to set a background image for the page but when I run the server it throughs a message that the image is not found. The image is located in the same directory where the html is. This is a really simple thing but I am straggling with it from early morning. Looked in all the forums but nothing helped so far. I tried changing the file path as relative/absolute. But no result. No mistake in the file name or path. body { background-image: url("background.jpg") } -
CSRF token from the 'X-Csrftoken' HTTP header incorrect
I'm making a web application (a SPA, to be specific) with a separate frontend (React) and backend (DRF). It uses session authentication, but the CSRF token isn't correct for some reason, and I'm having a hard time figuring out why, specifically on the logout route of my application. Here's how I'm getting and sending the token: fetch(APIURL + "/api/csrf-token/") .then((response) => { return response.json(); }) .then((json_response) => { const XCSRFToken = json_response["X-CSRFToken"]; const logout_response = fetch(APIURL + "/api/logout/", { headers: { "Content-Type": "application/json", "X-CSRFToken": XCSRFToken, }, credentials: "include", method: "POST", }) // then do stuff But this yields the following error: CSRF Failed: CSRF token from the 'X-Csrftoken' HTTP header incorrect. I'm not sure where I'm going wrong here because I'm not sure how the CSRF token can be wrong. Before I give the rest of the code, there's one other thing that I'm confused about. When I log in, an HTTP only cookie called csrftoken is passed to my browser; should I be doing anything with that? Here's my views for getting the CSRF token and logging out. @api_view(["GET"]) def csrf_token(request): response = Response( {"detail": "CSRF cookie set", "X-CSRFToken": get_token(request)} ) return response @api_view(["POST"]) def logout_user(request): logout(request) If there's … -
Django Speed Up Aggregates
I am using Django as Analytics Dashboard where I fetch the Orders data from Takealot Seller API and then store each and every order in SalesModel. In a month, I get around 100000 orders and when I try to aggregate them using following code month = 1 year = 2024 SalesModel.objects.filter(account=user.pk, store=store.pk, order_date__year=year, order_date__month=month).aggregate(Sum("selling_price"))["selling_price__sum"] selling_price is a IntegerField while order_date is DatetimeField. and there are 10 more KPIs similar to it and Product Selling Trends (which are calculated on the go) too. trendData = SalesModel.objects.filter(account=user.pk, store=store.pk, order_date__year=year, order_date__month=month).values("order_date__year","order_date__month","order_date__day").order_by("order_date__year","order_date__month","order_date__day").annotate(total=Sum('selling_price'),total_units=Sum("quantity")) It takes solid 2-3 seconds, how can I speed this up? I am already using the cache which saves the data for 5 minutes. Should I have a separate Model where I add KPIs or what should I do? Want to speed it up. -
In my Website add-to-cart is not(bagicon) not changing its value
I created an add to cart function for my ecommerce website In my index.html: <button class="action-btn"> <ion-icon name="bag-handle-outline"></ion-icon> <span class="count cart-items-count">{{request.session.cart_data_obj|length}}</span> </button> In Image1 you can see that I created a bagicon and when I am clicking add to cart function it is changing Span value (0 to 1) but when I am clicking add-to-cart for another product it is not changing it's value from (1 to 2) In my function.js: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(response){ this_val.html("Item added to cart") console.log("Added products to cart"); $(".cart-items-count").text(response.totalcartitems) } }) }) I also created a view for this So, in views.py def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], } if 'cart_data_obj' is request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data else: request.session['cart_data_obj']=cart_product return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': len(request.session['cart_data_obj'])}) Please help me out with this!!! -
How write Django model query to get product list with product available in wishlist or not?
models.py models.py class Product(models.Model): code = models.CharField(max_length=50, default=None, null=True, blank=True, unique=True) name = models.CharField(max_length=100) category_id = models.ForeignKey(category, on_delete=models.CASCADE) size_id = models.ForeignKey(size, on_delete=models.CASCADE) cost = models.IntegerField() tax_id = models.ForeignKey(Tax, on_delete=models.CASCADE) price = models.IntegerField() class wishlist(models.Model): product_id = models.ForeignKey(Product, on_delete=models.CASCADE, error_messages = {'unique': 'This Product is already in exist',}) user_id = models.ForeignKey(Account, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True) I'm trying to fetch all product like product.objects.all() with check particular product available on cart and wishlist or not -
How do I render snippets that represent ui components in pages on Wagtail CMS?
I am new to wagtail and i'm working on a project to build a cms. The cms will have some ui components like NavBars and cards that i am making throught snippets, so that i can reuse them in diferent pages (or even on the same page). My question is what's the best aproach to render this items? I thought of using templatetags, but i am not complete sure if thats a good idea. What do you think its a nice and clean way of doing this? -
In add to cart Span is not working properly
I Created a add to cart function for my website but in the website span is not working properly . My problem is that: You can see in the marked portion of the image if i clicked on add to cart button it is changing "0-1" but when I am clicking on add to cart button of an another product it is not changing from "1-2" So, In product-detail.html: <button class="action-btn"> <ion-icon name="bag-handle-outline"></ion-icon> <span class="count cart-items-count">{{request.session.cart_data_obj|length}}</span> </button> In js file: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Current Element:", this_val); $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(response){ this_val.html("Item added to cart") console.log("Added products to cart"); $(".cart-items-count").text(response.totalcartitems) } }) }) In Views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], } if 'cart_data_obj' is request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data else: request.session['cart_data_obj']=cart_product return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': len(request.session['cart_data_obj'])}) So please help me out with this problem and I think that the probelm is in views because js file is working properly... In … -
Insert only to specific fields in formModel in django
I have a django model and its corresponding form to insert into and read value from a table with three columns in database. My requirement is I only need to insert in to say two column using form, leaving the third column which is a date field. But I have a requirement to read all three column to display it in html in later time. When I use exclude in the form it works good for the html part but when trying to save the form using form.save(), it tries to insert null in the the third column and raise error. Can anybody please help me to omit the third column completely while saving the form. Class sales(models.Model) product_name = models.CharField(max_length=500) quantity=models.FloatField() sale_date=models.DateField()