Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add a string before product name
In the following code, I would like to add a string called "ABC" before appending the product name table_po= set() for tr in orders: table_po.add(str(tr.product)) table_data.append(table_po) After execution, it could be like ABC = Cat where Cat is the {tr.product} value -
content security policy blocking inline execution
I am working on a project in Django, where I am using a javascript from an external payment provider. Upon calling their script, they will insert a payment form embedded in my page. The documentation on how to integrate with their service is found here. Specifically I am following step 3 and 4. A snippet of my html is as below. Upon calling my javascript the payment form from checkout.js will be rendered as an iframe in the checkout-container-div element <div id="checkout-container-div"> </div> <script src="https://test.checkout.dibspayment.eu/v1/checkout.js?v=1"></script> In my javascript, I first call my backend to get the paymentId. Then using the obtained paymentId, I am calling the external checkout.js with const checkout = new Dibs.Checkout(checkoutOptions); in order to render the payment form document.getElementById("paymentButton").addEventListener("click", function() { //Collect all the fields value and send it to the server console.log("pay button clicked") $.ajax({ url : "localDeliveryPayment", type : "get", success: function(response) { if (response['paymentIdCreation'] == true) { console.log(response); const checkoutOptions = { checkoutKey: response['checkoutKey'], // Replace! paymentId: response['paymentId'], containerId: "checkout-container-div", }; const checkout = new Dibs.Checkout(checkoutOptions); checkout.on('payment-completed', function (response) { window.location = 'completed.html'; }); } } }) }) From Google Chrome's console I get the following error related to test.checkout.dibspayment.eu/:1 Refused to execute inline … -
What is the user of sentinel method in Django?
I have seen sentinel methods being used while setting foreign relationship to users, what exactly is the use of these methods? -
Django load huge data to drop down list (select) quicker?
I’m new to django, I have a application with search + drop down field where data load from database which contains 5000+ records, to load data it is taking 30-40 sec, this is not I expected. Is there a better way to load data faster? Any idea/thoughts/example appreciated. -
Is there a way to use Next.js API Routes to Authenticate Django Rest Framework backend?
I'm using DRF as a backend to Next.js frontend. I followed this very fine tutorial to set up authentication, but I read I should use Next.js API Routes as proxy to the DRF API Routes and I can do that on any route other than the authentication one because I must send the X-CSRFToken and credentials: "include" in the request headers. Currently I'm getting the CSRF Token on page load with useEffect: useEffect(()=> { fetch("http://localhost:8000/api-auth/csrf",{ credentials: "include" }) .then( res => setCsrf(res.headers.get("X-CSRFToken"))) .catch( err => console.error(err)) },[]) Im using a direct route to DRF API "http://localhost:8000/api-auth/csrf" instead of a Next.js API like "/api-auth/csrf". The same happens with the handleLogin function: const handleLogin = async (event) => { event.preventDefault(); fetch("http://localhost:8000/api-auth/login/", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": csrf }, credentials: "include", body: JSON.stringify(formValues), }) .then(() => Router.push("/profile")) }; It is working like this, but I can't set credentials using Next.js API Routes. Even using the same pattern it doesn't work. I think I'm missing some fundamental concept here and I looked it up but couldn't find. If anyone can help I'd appreciate :) -
How to re-upload/Update data with django-import-export
I have uploaded data into the system. I however went ahead and edited soe of the data in the excel, meaning there are changes in that excel. When I want to re-upload so that the changes made can reflect, it doesn't accept. I can't tell why. It says like such data already exists in the system. I have skip_unchanged = True but that isn't helping. Is my model setup having a hand in this? unique_together = ("school", "student_id",)? class ImportStudentsResource(resources.ModelResource): def __init__(self, school_id,klass,*args, **kwargs): super().__init__() self.school_id = school_id self.klass = klass self.fields["id"] = fields.Field(widget=ForeignKeyWidget(Student,'id')) self.fields["stream"] = fields.Field(attribute="stream",column_name="stream",widget=StreamForeignKeyWidget(klass,),) def before_save_instance(self, instance, using_transactions, dry_run): instance.school_id = self.school_id instance.klass_id = self.klass#2 def before_import_row(self, row, **kwargs): row['stream'] = row['stream'].lower() class Meta: model = Student import_id_fields = ('id',) fields = ('student_id','name','year','stream') import_order = ('student_id','name','year','stream') skip_unchanged = True The view . class uploadF1Students(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadStudentsForm() self.context['form'] = form return render(request,'libman/upload_student.html',self.context) def post(self, request): klass = get_object_or_404(Klass,school_id=request.user.school.id,name=1).id school_id = request.user.school.id form = UploadStudentsForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) resource = ImportStudentsResource(school_id,klass) try: result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) except Exception … -
using curly double brackets inside another curly double brackets in django template
I started studying Django few days back, while doing a project I came across a situation. In the views.py, I'm passing def chat_rooms(request): context = dict() context['title'] = 'Chat' rooms = Chat_rooms.objects.filter(Q(user1 = request.user.id) | Q(user2 = request.user.id) ) context['rooms'] = rooms for room in rooms: rmssg = Chats.objects.filter(room_id = room.id) lmssg = Chats.objects.latest('id') context[str(room.id)] = lmssg return render(request,'previlageGroup/chat_rooms.html',context) In the Django template,chat_room.html {% for room in rooms %} <div class="card" style="width: 100%;"> <a href="{% url 'pgroup:chat.screen' room.id %}"> <div class="card-body"> <p class="card-text"> {{ {{room.id}}.message}} </p> </div> </a> </div> {% endfor %} In models.py class Chat_rooms(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user1') user2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user2') created_on = models.DateTimeField(auto_now_add=True) class Chats(models.Model): date = models.DateTimeField(auto_now_add=True) has_viewed = models.BooleanField(default= False) message = models.CharField(max_length = 200) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') room = models.ForeignKey(Chat_rooms, on_delete=models.CASCADE) Django is giving me a error, that {{ {{room.id}}.message }} is not possible. How can I do this? Is there any other way? Thanks in advance -
Error when deploying django web application with daphne: Requested setting INSTALLED_APPS, but settings are not configured
I have been battling with an error that I encountered when trying to deploy a django application that uses channels. Error in heroku logs Starting process with command `daphne friendship.asgi:application --port 52589 --bind 0.0.0.0 -v2` 2021-06-02T19:51:57.338171+00:00 heroku[web.1]: Process exited with status 1 2021-06-02T19:51:57.105387+00:00 app[web.1]: Traceback (most recent call last): 2021-06-02T19:51:57.105477+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2021-06-02T19:51:57.105796+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2021-06-02T19:51:57.105861+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 170, in entrypoint 2021-06-02T19:51:57.106200+00:00 app[web.1]: cls().run(sys.argv[1:]) 2021-06-02T19:51:57.106259+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 232, in run 2021-06-02T19:51:57.106713+00:00 app[web.1]: application = import_by_path(args.application) 2021-06-02T19:51:57.106774+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/utils.py", line 12, in import_by_path 2021-06-02T19:51:57.107059+00:00 app[web.1]: target = importlib.import_module(module_path) 2021-06-02T19:51:57.107118+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-06-02T19:51:57.107436+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-06-02T19:51:57.107491+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-06-02T19:51:57.107783+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-06-02T19:51:57.107986+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-06-02T19:51:57.108196+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-06-02T19:51:57.108533+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 790, in exec_module 2021-06-02T19:51:57.108768+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-06-02T19:51:57.108967+00:00 app[web.1]: File "./friendship/asgi.py", line 5, in <module> 2021-06-02T19:51:57.109233+00:00 app[web.1]: import errands.routing 2021-06-02T19:51:57.109290+00:00 app[web.1]: File "./errands/routing.py", line 2, in <module> 2021-06-02T19:51:57.110045+00:00 app[web.1]: from . import consumers 2021-06-02T19:51:57.110094+00:00 app[web.1]: File "./errands/consumers.py", line 3, in <module> 2021-06-02T19:51:57.110331+00:00 … -
How do I get stripe's application fee to reflect the adjustable quantity during checkout?
I added the adjustable quantity for Stripe's check out session call. I understand that the fee object is created after the payment. I'm looking at the application fee object in stripe's documentation and it says it is capped at the final charge amount. How do I retrieve the charge amount or better, quantity during the checkout session? checkout_session = stripe.checkout.Session.create( success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], customer=customer.id, payment_intent_data={ 'application_fee_amount': int(stripe_price * fee_percentage), 'transfer_data': { 'destination': seller.stripe_user_id, }, }, line_items=[ { 'price_data': { 'currency': currency, 'unit_amount': price, 'product_data': { 'name': title }, }, 'adjustable_quantity': { 'enabled': True, 'minimum': 0, 'maximum': available_quantity, }, 'quantity': 1, }, ], metadata={ "product_id": product.id, "client_reference_id": user.id, }, mode='payment', ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) -
Django Class Based Views Flow
My app is data driven with a postgres db. When a user first sees my “customers” page I would like all existing db entries to be displayed. This part I am using ListView in my class based view. I would also like for these fields to be update-able, removable, as well as have the ability to create new entries. What is the proper way to implement this? -
Django display foreign key on admin dashboard when inheriting from AbstractUser not working?
I'm having a model like a restaurants model from django.db import models class Restaurants(models.Model): name = models.CharField(max_length=200) description = models.TextField(max_length=250) location = models.CharField(max_length=200) rating = models.DecimalField(null=True,decimal_places=2,max_digits=5) def __str__(self): return self.name class Meta: db_table = "Restaurants" verbose_name_plural = "Restaurants" And three different User models: from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from restaurants.models import Restaurants class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) … -
Add a field in the database using the Django function
this is my model class : class complete_taxi_driver_account(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) STATUS_CHOICES = (('woman', 'Woman'), ('man', 'Man'),) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) phone_number = models.CharField(max_length=11) life_place = models.CharField(max_length=120) birth_date = models.DateTimeField(null=False, blank=False) gender = models.CharField(max_length=25, choices=STATUS_CHOICES, default='man') number_plates = models.CharField(max_length=8) national_code = models.CharField(max_length=10) car_number = models.CharField(max_length=50) name_and_type_of_car = models.CharField(max_length=50) # Check if this car is taxi , this field will change to True else False confirmation = models.BooleanField(default=False) # If the taxi app starts, this section will change True, meaning the taxi is ready to pick up passengers online = models.BooleanField(default=False) #I do not know what to do here to add these two fields to the database when this function is called def location(self): # Location of the taxi lat = models.DecimalField(max_digits=20, decimal_places=10) lng = models.DecimalField(max_digits=20, decimal_places=10) I want to have a function in the model class that, when called, creates two fields in the database and fills them in, and from now on be updated by calling it. How can I do this? -
DRF, in perform_authentication() the test for request.user is set to an empty string only when multiple tests are run
When I run a test by itself the test always passes, but when run even with one other test in the same test class it fails. I've tracked down the cause to the perform_authentication() method not having the AnonymousUser set instead, it is set to an empty string. This is not happening on all tests but maybe 20% of the 415 tests I've written. The change I made to the code was to use the Authorization header and removed the code that put credentials in the body of the login request. This should not have affected most of the tests that are now failing. If I override the perform_authentication() by catching the exception and just exiting the method the test works fine, but this is not what I want to do obviously. I would show code, but am not sure what to show. The tests have many layers since the same tests need to be done on many endpoints. Does anybody have a better idea as to how this authorization works? -
ReactJS How can I edit user with functional component useSelector
With the code I have, I am getting the user in input but the input won't change when I type here is the input <div className="pInput"> <label>last Name</label> <input type="text" className="ppInput" value={user.last_name} onChange={(e) => HandleEditDesc(e)} placeholder={user.last_name} /> </div> Here is my on change function e.preventDefault() user.last_name = useSelector((state) => e.target.value); state.auth.user.last_name = user.last_name } Here is how I am getting the user import React from "react"; import { useSelector } from "react-redux"; import { Link } from "react-router-dom"; import Axios from "axios"; const Profile = () => { const user = useSelector((state) => state.auth.user); const subscriptionStatus = useSelector( (state) => state.auth.subscriptionStatus ); I am using Django as my backend -
Filtering three related models in django-filter
I have three models in my models.py file: models.py ################################## Application models ################################## class attack(models.Model): attack_name = models.CharField(max_length=200) defense_mechanism = models.CharField(max_length=200) def __str__(self): return self.attack_name ACTIONS = ( ('malware', 'Malware'), ('hacking', 'Hacking'), ('social', 'Social'), ('misuse', 'Misuse'), ('physical', 'Physical'), ('error', 'Error'), ('environmental', 'Environmental') ) class action(models.Model): action = models.CharField(max_length=15, choices=ACTIONS) attacks = models.ManyToManyField(attack) def __str__(self): return self.action ATTRIBUTES = ( ('confidentiality', 'Confidentiality'), ('integrity', 'Integrity'), ('availability', 'Availability') ) ACTORS = ( ('external', 'External'), ('internal', 'Internal'), ('partner', 'Partner') ) class security_incident(models.Model): asset = models.CharField(max_length=200) #one asset actor = models.CharField(max_length=15, choices=ACTORS) #one actor action = models.ForeignKey(action, on_delete=models.CASCADE) # one security incident can have several actiobns attributes = models.CharField(max_length=15, choices=ATTRIBUTES) #as many attributes as wished, should be two for hierarchial tree def __str__(self): return self.asset I am trying to filter these models in a django-filter filterset: class SecIncFilter(django_filters.FilterSet): asset = django_filters.CharFilter(lookup_expr='icontains', distinct=True, label='Search for security incidents, related attacks and defense mechanisms to an asset') attributes = django_filters.MultipleChoiceFilter(widget=forms.CheckboxSelectMultiple(), choices=ATTRIBUTES, label='Choose categories') action = django_filters.MultipleChoiceFilter(name='action') class Meta: model = security_incident fields = ['asset','attributes'] def __init__(self, *args, **kwargs): super(SecIncFilter, self).__init__(*args, **kwargs) # at sturtup user doen't push Submit button, and QueryDict (in data) is empty if self.data == {}: self.queryset = self.queryset.none() And then rendering results into this … -
display different elements based on even and odd in Django html template
I am a noob at django. And I faced this problem: dest over here is a list which is coming from views.py. I want to use this(code below) for even occurrences : <div class="row no-gutters"> <div class="col-lg-6 order-lg-2 text-white showcase-img" style="background-image:url( {{baseUrl}}/{{dest.img}} );"><span></span></div> <div class="col-lg-6 my-auto order-lg-1 showcase-text"> <h2> {{dest.name}} </h2> <p class="lead mb-0">{{dest.desc}}</p> The Price : <p class="lead mb-0" style="font-weight:bold">Rs. {{dest.price}}</p> </div> </div> and this(code below) for odd positions : <div class="row no-gutters"> <div class="col-lg-6 text-white showcase-img" style="background-image:url(&quot;{% static 'img/bg-showcase-2.jpg' %}&quot;);"><span></span></div> <div class="col-lg-6 my-auto order-lg-1 showcase-text"> <h2>Updated For Bootstrap 4</h2> <p class="lead mb-0">Newly improved, and full of great utility classes, Bootstrap 4 is leading the way in mobile responsive web development! All of the themes are now using Bootstrap 4!</p> </div> </div> how to achieve this ? -
Refresh <div> element in a Django html template
How can I refresh an element within a Django HTML template Example <div class="container" id="myForm"> <form action="/cgi-bin/hello_get.cgi" method="get"> Fill the Detail: <br/> <textarea rows="5" cols="50" name="description">{{ bar_codes }} </textarea> <input type="submit" value="submit"/> </form> </div> I have JavaScript code that tries to refresh the div element with id myform. <script> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: {% url 'detect_barcodes' %}, // URL to your view that serves new info data: {'append_increment': append_increment} }) .done(function(response) { $('#myForm').append(response); append_increment += 10; }); }, 10000) </script> the variable bar_codes data gets being updated contantly. The data is not from an api but from a barcode scanner. This is the view def detect(request): stream = CameraStream() success, frame = stream.camera.read() if success: status = True else: status = False bar_codes = stream.used_codes print(bar_codes) return render(request, 'detect_barcodes/detect.html', context={'bar_codes': bar_codes, 'cam_status': status}) This is the url.py file urlpatterns = [ path('', views.detect, name='detect_barcodes'), path('camera_feed', views.camera_feed, name='camera_feed'), ] -
How to sort and search a time field in 12 format? DRF
I have two fields of type time in postgresql, which saves these values in 24 format (03:30 PM would save 15:30:00). How can I run a search with a time in format 12 and match it with its equivalent in format 24? How can I order these fields in 12 format? the fields are 'ho_inicio' and 'ho_fin'. My Viewset (I override the list method to search regardless of accents): class HorasEscolaresViewSet(ListModelPagination, viewsets.ModelViewSet): queryset = TbledcHora.objects.all() serializer_class = HorasEscolaresSerializer filter_backends = [DjangoFilterBackend, AliasedOrderingFilter] filterset_class = HorasEscolaresFilter search_fields = ['id_nivel_academico__nb_nivel_academico', 'nu_hora'] filterset_fields = ['id_nivel_academico', 'in_status'] ordering_fields=('id_nivel_academico', 'nu_hora', 'ho_inicio', 'ho_fin') ordering= 'id_nivel_academico' renderer_classes = (EmberJSONRenderer, ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if "search" in request.GET: if request.GET['search'] != '': q_list = [] q_list.append(Q(id_nivel_academico__nb_nivel_academico__unaccent__icontains=request.GET['search'])) queryset = queryset.filter(reduce(operator.or_, q_list)) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many = True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) My serializer: class HorasEscolaresSerializer(serializers.ModelSerializer): valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] ho_inicio = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats) ho_fin = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats) class Meta: model = TbledcHora fields = '__all__' depth = 1 -
Why my user model is not saving even after the code is running successfully
I want to create a social media web app. I am currently working on the signup functionality Please help me find why my user model is not saving My models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser import string import random # Create your models here. def generate_unique_code(): length = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=length)) if ProfileUser.objects.filter(user_name=code).count() == 0: break return code class ProfileUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name = models.SlugField( unique=True, max_length=30, default=generate_unique_code) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] My SignUp View class signUpView(APIView): def get(self, request, format=None): try: user_name = request.GET.get("name") password = request.GET.get("password") email = request.GET.get("email") first_name = request.GET.get("first_name") last_name = request.GET.get("last_name") except Exception as e: print(e) return Response({"Invalid Data": "Not Enough Data"}, status=status.HTTP_206_PARTIAL_CONTENT) user = ProfileUser(email=email, user_name=user_name, first_name=first_name, last_name=last_name, password=password) user.save() return Response({"User Created": { "name": user_name, "email": email, "password": password }}, status=status.HTTP_201_CREATED) I am a beginner in Django -
Django DRF / JS - React Notifications API
I am working on a browser extension with a Django DRF backend and currently JS frontend ( working to convert it to React ). What I am trying to achieve is when a user clicks a buttons to trigger the Notification API for a set of users. Reading about this I have found some solutions: Websockets - currently the API is WSGI, seen that in order to add ASGI I need to change pretty much the entire foundation of my app or can I just hook up a different module that can talk to WSGI side? Sorry not very confident that I understand how this actually some clarification would be awesome. Also if for example you have 100 users with their channels open to the server how would that impact performace? The Super Hacky way - have an ajax/axios request that runs every 2 min or so and checks for DB changes, if true create the notification object. Again if you have 100 users pining the server constantly I assume performance will take a big hit Cron Job - would something like this work? Could also have a signal, post_save do something but I am not sure how I can … -
How to convert x-www-form-urlencoded to json with Python (Django)
From api i recive x-www-form-urlencoded data. data = 'leads%5Bstatus%5D%5B0%5D%5Bid%5D=29078079' when i try to convert it with urllib.parse.parse_qs or urllib.parse.unquote i got a dict like { "leads[status][0][id]": [ "29078079" ] } how can i convert it to normal json or dict ? like this { "leads": [ "id": "29078079" ] } -
Django Rest Framework Error: Unsupported Media Type: 415
Clicking on the like buttons is throwing the following error: Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) The code is supposed to submit the like action, retrieve the like counts and return the new serialized data. After doing some debugging on chrome, it looks like there is something wrong in the request header as when I inserted a print statement as the first line to the view function, it was never printed on the console, which indicates the error happens before the code makes it to the backend. But, I have set all the required headers, to the best of my knowledge. Searching online did not help either. So, here I am. Here is the Vanilla JavaScript code: function handleLikeButtons(){ let likeButtonsEls = document.querySelectorAll("[id^='likeBtn-']") likeButtonsEls.forEach( (likeBtn) => { likeBtn.addEventListener( 'click', event => { event.preventDefault(); // Submit the like const method = "POST" const url = likeBtn.getAttribute("data-like-endpoint") const headerOptions = "json" const commentId = likeBtn.getAttribute("data-comment-id") const data = JSON.stringify({"id": commentId, "action": "like"}) // createXHRRequest(method, url, data, updateLikeCount, commentId, headerOptions) createXHRRequest(method, url, data, null, commentId, headerOptions) }) }) } function createXHRRequest(method, url, data=null, callbackFn, extraData = null, headerOptions = null){ const xhr = new … -
Incorrect dispatching of url
When I use the configuration below of urls.py, I can see all the API response correctly. path('blog-tags/', include([ path('', BlogTagAPIView.as_view(), name='blogtags'), path('<slug:slug_tag>/', BlogTagDetailsAPIView.as_view(), name='details-blogtag'), ])), path('blog/', include([ path('', BlogCategoryAPIView.as_view(), name="categories"), path('<slug:slug_category>/', BlogCategoryDetailsAPIView.as_view(), name="details-blogcategory"), path('<slug:slug_category>/<slug:slug_post>/', BlogPostDetailsAPIView.as_view(), name="details-blogpost"), ])), But if I use this configuration: path('blog/', include([ path('', BlogCategoryAPIView.as_view(), name="categories"), path('<slug:slug_category>/', BlogCategoryDetailsAPIView.as_view(), name="details-blogcategory"), path('<slug:slug_category>/<slug:slug_post>/', BlogPostDetailsAPIView.as_view(), name="details-blogpost"), path('tags/', include([ path('', BlogTagAPIView.as_view(), name='blogtags'), path('<slug:slug_tag>/', BlogTagDetailsAPIView.as_view(), name='details-blogtag'), ])), ])), I can't see the response from BlogTagAPIView and BlogTagDetailsAPIView and instead I see this message: HTTP 404 Not Found Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Why happen this? -
Why response is None testing view using RequestFactory()?
I am trying to test my view using RequestFactory(). However, calling this view in the test responded as None: View def add_to_basket(request): cart = Cart(request) if request.POST.get('action') == 'post': # GETS game DATA FROM AJAX REQUEST game_id = request.POST.get('gameId') game_qty = int(request.POST.get('gameQty')) # check if game exists try: game = Game.objects.get(pk=game_id) except Game.DoesNotExist: return JsonResponse({'message': 'Game not found'}) Test setUp def setUp(self) -> None: # request factory self.factory = RequestFactory() self.middleware = SessionMiddleware() Test itself def test_add_to_basket(self): # set sessions middleware request = self.factory.get(reverse('order:add-to-cart')) self.middleware.process_request(request) request.session.save() # request.user = self.test_user response = add_to_basket(request) print(response.status_code) print(response.content) Printing response outputs None - though apart test, view is working as expected. What could cause this? -
How to download a archive using django response?
I want to download the archive after i created. The code is bellow: def downloadArchive(room, catalog): test = RoomTest.objects.get(idRoom=room) zip_name = room.name + "_" + token_urlsafe(5) + '.zip' zip_path = 'media/zipFiles/' + zip_name if test.OLD_Archive != '' and os.path.exists(test.OLD_Archive): # remove old file. os.remove(test.OLD_Archive) with ZipFile(zip_path, 'w') as zipObj: for student in catalog: zipObj.write('media/' + str(student.file), student.studentFullName() + os.path.splitext('media/' + str(student.file))[1]) test.OLD_Archive = zip_path test.save() response = HttpResponse(zipObj) response['Content-Type'] = 'application/x-zip-compressed' response['Content-Disposition'] = 'attachment; filename=' + zip_name return response Every time i try to download, got error "The archive is either in unknown format or damaged". I think the route is broken. Any ideas how can i check the response route? Btw: if i download the archive manually (after archive), it's working fine.