Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am getting MultiValueDictKeyError when I am clicking on add to cart button
I created an add-to-cart function for my website so in my product-detail.html: {% for p in products %} <div class="product-price"> <span id="current-product-price">Our Price:{{p.price}}</span> <del>M.R.P: {{p.old_price}}</del> </div> <div class="button"> <input type="hidden" value="{{p.id}}" class="product-id" name=""> <input type="hidden" value="{{p.title}}" class="product-title" name=""> <a href="#" class="btn" id="add-to-cart-btn">Add to cart</a> <a href="#" class="btn">Buy Now</a> </div> {% endfor %} 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 product_image = $(".product-image").val() //#1 let product_pid=$(".product-pid").val() //#2 let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("PId:", product_pid); console.log("Image:", product_image); 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, 'pid': product_pid, 'image':product_image, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(res){ this_val.html("Go to Cart") console.log("Added products to cart"); $(".cart-items-count").text(response.totalcartitems) } }) }) In the above js program is anything is wrong for the value error in product_pid(#2) & product_image(#1) and in 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'], 'image': request.GET['image'], #1 'pid': request.GET['pid'], #2 } 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']}) I think the error … -
Django+Graphene Error on Unknown argument while writing mutation
I am getting this as an error import graphene from .types import ApplicationType from api.graphql.helpers.save_application_helper import save_application_helper class ApplicationMutation(graphene.Mutation): class Arguments: firstname = graphene.String() lastname = graphene.String() gender = graphene.String() district = graphene.String() pin_code = graphene.String() connection_type =graphene.String() category =graphene.String() govt_id_type =graphene.String() govt_id_number = graphene.String() load_applied = graphene.Int() application = graphene.Field(ApplicationType) @classmethod def mutate(self, info, requested_data): application = save_application_helper(requested_data) return ApplicationMutation( application = application ) my mutations.py code looks like this I tried looking at the code but I cannot find any leads on why is it behaving like this. -
Django upgrade to 4.2 admin static files issue
I am currently using django 3.2 and would like to upgrade to 4.2 soon. Doing so on a local environment and using python manage.py collectstatic works. However the problem comes when I try to deploy this to a development environment. The new admin static files are not loading which causes the django admin page to look dysfunctional. Particularly, django 4.2 introduces a dark_theme.css static file which returns a 404 error when looking at the browser network tab. On my local environment, the file returns a 200 ok. This is the most similar thread to my issue I could find on the official django forum, however there is not a clear fix for the problem (perhaps because there are a lot of reasons why the issue could be happening) I am using nginx for the server. We have a CI process that runs collectstatic then copies the output to a docker container and I have this nginx configuration to get the static files: location /static/ { autoindex on; alias /usr/share/nginx/html/static/; } In django settings, I have this configuration: STATIC_ROOT = BASE_DIR / "ui/build/static" STATIC_URL = "/static/" Such that the static files are generated at STATIC_ROOT then the docker container copies them … -
How to tie this to a specific model
I am getting this bellow error: null value in column "two_week_period_id" of relation "timesheets_usertimesheet" violates not-null constraint Which I understand because the very last null value is not being passed through. Here are my models: models.py 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) The above created a two_week_period as an id for every two weeks entered. For example, 03/10/2024-03/14/2024 is two_week of id 1, next two week will add an id of 2 and so on. I am trying to pass the two_week_period from CreateNewTimesheet over to: simplied verion of UserTimesheet class UserTimesheet(models.Model): employee = models.ForeignKey(Employee, models.SET_NULL, blank=True, null=True) start_date = models.DateField(_("Start Date")) end_date = models.DateField(_("End Date")) two_week_period = models.ForeignKey(TwoWeekPeriod, on_delete=models.CASCADE) It seems without the two_week_period in the Usertimesheet model, I do not get this error. But I want to display the two_week_period, so that I can tie the two weeks to … -
Django e-commerce Wishlists menu list in dropdown menu on product page of currently logged in user to choose from to add the product to not working
What I'm trying to achieve is give the currently logged in user the ability to add a product to a specific wishlist that the user has made earlier. To do this I want there to be a dropdown menu button with a list of all the current wishlists the user has with a checkbox. I tried to do queryset on the form field but it wont let me filter the currently logged in user it give me the "requests not defined" error. Its not working because I believe you can't use filter to filter the user with ModelForm. What's another way of doing this? -
Django authentication user login
`I'm encountering an issue with user authentication in my Django project. I have a custom user model for doctors Doctor which inherits from AbstractUser. Despite entering the correct email and password during login, the system returns an "Invalid password" error. base/models.py from django.db import models from django.contrib.auth.models import AbstractUser, Group, Permission class Doctor(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=50) name = models.CharField(max_length=50) profession = models.CharField(max_length=50, default='Doctor') email = models.EmailField(max_length=254, unique=True) emp_code = models.CharField(max_length=50) password = models.TextField(max_length=150) USERNAME_FIELD = 'email' groups = models.ManyToManyField( Group, blank=True, related_name='doctor_group' ) user_permissions = models.ManyToManyField( Permission, blank=True, related_name='doctor_user_permission' ) def __str__(self): return self.username base/views.py def docter_login(request): if request.method == 'POST': email = request.POST.get('email').lower() password = request.POST.get('password') print(email,password) # Authenticate the user using the email and password provided in the form if not Doctor.objects.filter(email__iexact=email).exists(): messages.error(request, 'User with that email Does not exists.') return render(request, 'base/error.html') user = authenticate(request, email=email, password=password) if user is not None and user.is_doctor: login(request, user) return redirect('home') else: messages.error(request,'Invalid password.') return render(request, 'base/error.html') return render(request, 'base/doctor_login.html') the user exists and passing the correct credentials to authenticate, it's still returning "Invalid password". What could be causing this issue? ` -
How to add ManyToMany field in geojson serializer
After loading geospatial data into postgresql + postgis database, the goal is to return it in a view as geojson format. models.py class Group(models.Model): name = models.CharField(max_length=60) class Country(models.Model): name = models.CharField(max_length=60) groups = models.ManyToManyField(Group, related_name='groups') views.py def countries(request): queryset = Country.objects.annotate(json=AsGeoJSON('mpoly')) data = serializers.serialize( 'geojson', queryset, geometry_field='mpoly', fields=('name', 'groups') ) return HttpResponse(data) The output geojson does not include nested groups for each country. How to add them into the features / properties field? -
Pip dependeny issue while tring to host with AWS beanstalk
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. awscli 1.32.58 requires botocore==1.34.58, but you have botocore 1.31.85 which is incompatible. s3transfer 0.10.0 requires botocore<2.0a.0,>=1.33.2, but you have botocore 1.31.85 which is incompatible. I keep getting this error whisst using thw awscli. I can't manage to find a version that is compatible allaround. Tryied donwgrading and upgrading the dependencies but still not working. Anyone knows a way to workaround this issue? I keep getting this error whisst using thw awscli. I can't manage to find a version that is compatible allaround. Tryied donwgrading and upgrading the dependencies but still not working. Anyone knows a way to workaround this issue? -
How to make input boxes' width same with each other in django-crispy-forms?
I'm rewriting my website with Django, and I would like to utilize Django forms since it's really easier than writing every form by hand in HTML. I looked at crispy-forms documentation and found out there is something called Layout. I don't know if I'm using as intended or if I'm repeating myself over and over, but here is what I got: from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, Submit, HTML, Div from django import forms from .models import Member class EnrollForm(forms.ModelForm): message = forms.CharField(widget=forms.Textarea) def __init__(self): super().__init__() self.helper = FormHelper() self.helper.form_show_labels = False self.helper.layout = Layout( Fieldset( '', input_with_icon('bi bi-person', 'first_name'), input_with_icon('bi bi-person', 'last_name'), input_with_icon('bi bi-123', 'student_id'), input_with_icon('bi bi-building', 'department'), input_with_icon('bi bi-list-ol', 'degree'), input_with_icon('bi bi-envelope', 'email'), input_with_icon('bi bi-telephone', 'mobile_number'), input_with_icon('bi bi-chat-left-text', 'group_chat_platform'), input_with_icon('bi bi-send', 'message'), ), Submit('submit', 'Üye Ol', css_id='signup-btn') ) class Meta: model = Member fields = ['first_name', 'last_name', 'student_id', 'department', 'degree', 'email', 'mobile_number', 'group_chat_platform'] def input_with_icon(icon_class, field_name): return Div( Div( HTML( f"""<span class="m-3"> <i class="{icon_class} fs-2" style="color: #ff4100;"></i> </span>""" ), css_class='input-group-prepend' ), field_name, css_class='input-group mb-3' ) {% extends "base/boilerplate.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container-sm align-items-center"> <div class="py-2 mt-4 align-items-center"> <div class="ml-5 pt-3 align-items-center form-container"> <h1 class="text-center mb-5">Topluluğumuza Katılın</h1> <form method="POST" … -
how do i do a image display form
I want an image found referring to the person that was searched for (in the people table) to be presented in the html, but at the same time I want it so that if the user wants to change the photo, he just needs to click on it of the image already presented and then the file explorer is opened so that a new image can be chosen. Once the new image has been chosen, the new image must be displayed in the html in place of the old one temporarily. the program is opening the file explorer, i choose the new image but the old image isn't change and the new image isn't displayed in any place of the html too my code: <script> // Quando a imagem da pessoa for clicada document.getElementById("imagem-pessoa").addEventListener('click', function() { // Abrir o explorador de arquivos ao clicar no campo de arquivo oculto document.getElementById("input-imagem").click(); }); // Quando uma nova imagem for selecionada document.getElementById("input-imagem").addEventListener('change', function(event) { // Capturar a nova imagem selecionada const novaImagem = event.target.files[0]; // Atualizar temporariamente a imagem no HTML const urlNovaImagem = URL.createObjectURL(novaImagem); document.getElementById("imagem-pessoa").src = urlNovaImagem; }); </script> and the html <img class="rectangle" id="imagem-pessoa" src="{{ pessoa.imagem.url }}" alt="Imagem da Pessoa">> <input … -
Pytest --no-migrations throws "relation already exists"
I have a fairly large django app that I usually test using pytest --no-migrations (as the migrations take ages), but since I added a ManyToMany relationship this way: class Object(models.Model): # ... collections = models.ManyToManyField(Collection, through=Collection.products.through, blank=True) class Collection(models.Model): # ... products = models.ManyToManyField("objects.Object", blank=True) Running pytest works fine, but running pytest --nomigrations throws this error on every test: self = <django.db.backends.utils.CursorWrapper object at 0xffff91150820> sql = 'CREATE TABLE "brand_collections_collection_products" ("id" bigserial NOT NULL PRIMARY KEY, "collection_id" bigint NOT NULL, "object_id" bigint NOT NULL)', params = None ignored_wrapper_args = (False, {'connection': <django.db.backends.postgresql.base.DatabaseWrapper object at 0xffff94ed1330>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0xffff91150820>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. > return self.cursor.execute(sql) E django.db.utils.ProgrammingError: relation "brand_collections_collection_products" already exists /usr/local/lib/python3.10/site-packages/django/db/backends/utils.py:82: ProgrammingError I have no idea what this error means in this context, or why it suddenly triggers, and I could not find an easy answer online... -
What is the most optimize way to use annotate with Count function with many filter in django query
For example in school, there is many data to store example "Class", "Student", "Book", etc. Also, the model used softdelete(softdelete refers to action when delete just change the is_deleted to True in the model). In each model, there are create_time, update_time, is_delete, etc. In my code now I use the method below, it spent at least 30s to run sql. So what is the most optimised way to query Count with the filter that contains many conditions? Also sometimes we need to count the same model but using the different filter Here is an example of code in Django (Check count data for each school). # In this code, each model already implements softdelete manager query. School.objects.annotate( number_of_class=Count( "class", filter=Q(class__is_deleted=False, class__create_time__lte=datetime, ...more filter), distinct=True ), number_of_student=Count( "student", filter=Q(student__is_deleted=False, student__create_time__lte=datetime, ...more filter), distinct=True ), number_of_public_book=Count( "book", filter=Q(book__is_deleted=False, book__create_time__lte=datetime, book__create_time__gte=datetime, book__type=1, ...more filter), distinct=True ), number_of_private_book=Count( "book", filter=Q(book__is_deleted=False, book__create_time__lte=datetime, book__create_time__gte=datetime, book__type__in=[2,3], ...more filter), distinct=True ) more_count... ) Please help give all code queries that you know and what you think can be optimised for counting with many counts and filters. -
Seeking advice on the architecture of a Django project
I'm currently developing a project in Django split into 4 applications for managing stock, creating a quote, managing production and a Djangorestframework API for generating quotes. All for a printing company. The production management interface must include all the production information as well as the quote information. The quote information contains the stock information as well as some additional information. To explain in more technical terms, the production management models inherit from the quotes models, which inherit from the stock models. How can I design my models to avoid redundancies in the database and make design simpler? I'm looking for good practice in application design. I looked at how to do inheritance between applications and how this is interpreted in the database. -
Unable to view my django and react website on ec2
So I have been trying to host my react and django application on AWS EC2. The approach I was following is that to deploy both the servers and be able to access them by http://ec2publicip:3000 for react and http://ec2publicip:8000 for django. I want to be able to test my website on the ec2 website before I purchase a domain and have both my servers as subdomains. I launched the ec2 instance and then git cloned my repo, which contains both the react and django applications. I successfully installed all the requirements and when I run my django server, on the terminal it shows that its been activated, but when I go to http://ec2publicip:8000 I just get that it took to long to respond on my web browser I have followed the following guide [https://www.programink.com/django-tutorial/django-deployment.html] but I have had no success Attaching my git hub repo link just in case since I don't think there is a problem with the code as I have been running the same on my local machine, and its working fine Any help or pointers would be appreciated -
how to setup stripe webhook in django
I am working on a project where buyer will make the payment and the payment will be transferred to multiple users is this the right way to do the split payment how can i run my webhook here is my code class AuctionPayment(View): def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('/') else: user = request.user customer_id = user.stripe_customer_id if customer_id == "": customer_id = stripe.Customer.create(email=user.email)["id"] user.stripe_customer_id = customer_id user.save() user = request.user mode = request.GET.get('mode', 'auction') auction_id = self.kwargs["auction_id"] courier_id = self.kwargs["courier_id"] if mode == 'auction': auction = Auction.objects.get(pk=auction_id) seller_id = auction.user seller_account_id = seller_id.stripe_connect_id referrals = Referral.objects.filter(referred_user=seller_id).first() # referred_by = referrals.referred_by courier = CourierService.objects.get(auction=auction, courier_id=courier_id) if auction.current_bid is not None: price = int(round(float(auction.current_bid) * 100.0)) if auction.auction_status == "Ongoing": price = int(round(float(auction.product.nail_buy_now_price) * 100.0)) buyer_address = auction.buyer_address else: event = SpecialEvent.objects.get(pk=auction_id) courier = CourierService.objects.get(event=event, courier_id=courier_id) seller = event.selected_seller seller_request = SellerRequest.objects.get(event=event, user=seller) price = int(round(float(seller_request.price) * 100.0)) buyer_address = event.buyer_address taxes = 0 if buyer_address.state.lower() == 'alabama' or buyer_address.state.lower() == 'al': taxes = int(round(float(price * 0.08))) shipping_charges = courier.price total_charges = price + taxes # if referrals: admin_amount = int((total_charges) * 0.2) seller_amount = total_charges - admin_amount referral_amount = int(admin_amount * 0.02) stripe.api_key = "sk_test_EI5Kddsg2MCELde0vbX2cDGw" charge_id = … -
Django Filter Consolidate data using Aggregate
I want to populate dynamic data using Django Filter Date Range, I have achieved this. In this there is a consolidated data which I am collecting of a single column, which is also working using aggregate. Now I want the consolidated to change as per the records which gets selected when date range is applied in Django filter form. I am able to consolidate data in the column and get a total out of it in “manual_total” [when I pre-define the date field]. But when I filter using the Django Filter Date range field using Form and filters, I am not getting total as per the columns being fetched. How do I achieve it? When I filter as per date in the form, the total should be as per the records showing post filter. For example, I have 2 records from March 1st to March 31st and 1 record for April 1st. If I filter March 1st to 31st, it shows only total of 2 records, but total it shows including the 3rd record. Below are my code and pls guide me to join the queryset and aggregate together to retrieve data as per the date range filter I select. … -
Sometimes I can't send a file
I am using django-channels with daphne and I know that there are strong restrictions on the size of the file or message I can send. But as it turned out, with a message limit of 1 MB, I can send a 2.5 MB image in the message and at the same time there are situations when images with a much smaller size do not want to load, as a result of which I do not get any error, and my client-side method, which should receive a new message from the socket for all users, shows nothing. This is my method that sends messages from the client side. The file is loaded into the input.: document.querySelector('#chat-message-submit').onclick = function (e) { e.preventDefault(); const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value; const fileInput = document.querySelector('#chat-file'); const file = fileInput.files[0]; if (file) { const reader = new FileReader(); reader.onload = function (event) { const fileData = event.target.result.split(',')[1]; const fileExtension = file.name.split('.').pop(); const fileObject = { name: file.name, type: file.type, extension: fileExtension, data: fileData }; chatSocket.send(JSON.stringify({ 'message': message, 'username': userName, 'slug': slug_info, 'media_file': fileObject, })); }; reader.readAsDataURL(file); } else { chatSocket.send(JSON.stringify({ 'message': message, 'username': userName, 'slug': slug_info, })); } messageInputDom.value = ''; fileInput.value = ''; … -
Can transaction.on_commit() be used to
I have a function that delete an object from a group of objects bound together and that are ordered by a "order" value they have like this: `{id:23, name:name1, order:1} {id:12, name:name2, order:2} {id:46, name:name3, order:3}` After deleting other objects order should change to represent the deletion, like if i delete the object with id 12 the object with id 46 should become "order:2" This i can make easy with a function that get the others objects and lowers every object with more than order 2 by one but if i update those objects sometimes happens that they are reordered in the database before the delete has ended. So, can i use transaction.on_commit() so the reorder function does not execute after the delete has ended? Or there is something i am missing? Trying it does not appear to be a problem, but i don´t now if i am not doing anything to resolve my problem or i am misreading something of the correct usage of this function -
Django throws the duplicate key value violates unique constraint error
I study the Django framework and there is that exercise that asks you to create a simple blog web application. This app has simple models and forms to handle the data a theoretical user would save in the project's db. Here are the models: from django.db import models class Blog(models.Model): text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Post(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text Here are the forms: from django import forms from . models import Blog, Post class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ['text'] labels = {'text': ''} class PostForm(forms.ModelForm): class Meta: model = Post fields = ['text'] labels = {'text': ''} So, let's say I add a Blog instance via the db. This is how I do it: INSERT INTO learning_logs_topic (id, text, date_added) VALUES (1, 'A blog #1', now()::timestamptz); This data appears on the Django admin site and on the html template. It happens almost instantly, which means that Django actually is aware of the new date has been added to the db. But when I'm trying to add a Blog instance via the admin site or by the saving the html … -
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