Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to save an instance after all processes are completed (including Stripe checkout session)?
#views @transaction.atomic def booking_form(request, id): franchise_id = id form = BookingForm(franchise_id=franchise_id) if request.method == 'POST': form = BookingForm(request.POST, franchise_id=franchise_id) if 'paynow-btn' in request.POST: if form.is_valid(): instance = form.save(commit=False) instance.payment_status = 'due' instance.booking_status = 'unconfirmed' instance.franchise_id = franchise_id #other code #stripe connect [standard account] direct charges connected_account_id = create_or_get_connected_account(franchise_id) success_urlpattern = reverse('booking:booking_successful', kwargs={'id': franchise_id}) success_urlpath = request.build_absolute_uri(success_urlpattern) # Create a Stripe checkout session print("Before checkout session creation") checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ "price_data": { "currency": "gbp", "unit_amount": int(instance.total_amount * 100), "product_data": { "name": f'Booking for {instance.full_name}', }, }, "quantity": 1, }], payment_intent_data={ 'metadata': { 'booking_id': instance.id, }, 'application_fee_amount': int(instance.total_amount * (franchise.payout_percentage / 100) * 100), }, mode='payment', # Create a Stripe checkout session success_url=success_urlpath, cancel_url=settings.PAYMENT_CANCEL_URL, stripe_account=connected_account_id, ) print("After checkout session creation") print(checkout_session) # Check if the checkout session was successfully created if checkout_session and checkout_session.status == 'completed': # Save the instance only if the checkout session is completed instance.save() return redirect(checkout_session.url) else: # Handle the case where the checkout session creation failed messages.error(request, 'Failed to create the checkout session. Please try again.') return redirect(reverse('booking:booking_form', kwargs={'id': franchise_id})) Hi, I'm trying to save the booking object instance after all the processes are completed! It doesn't work and leaves me with Failed to create … -
How can RetrieveUpdateDestroyAPIView supports POST?
I successfully implement Rest API to store IP address and Mac address mapping. The GET/PATCH/DELETE methods are supported, for example: curl -X GET -H 'Content-Type: application/json' -d '{"ip_address": "192.168.1.1"}' http://127.0.0.1:8000/api/ipmac/ curl -X PATCH -H 'Content-Type: application/json' -d '{"ip_address": "192.168.1.1", "mac_address": "aa:bb:cc:dd:ee:ff"}' http://127.0.0.1:8000/api/ipmac/ However, POST is not supported in RetrieveUpdateDestroyAPIView. I don't wanna create another endpoint for POST method. How to have only one endpoint and support all the methods? Here is my code: models.py from django.db import models class IPMacMapping(models.Model): ip_address = models.GenericIPAddressField(unique=True) mac_address = models.CharField(max_length=17, unique=True) created_at = models.DateTimeField(auto_now_add=True) serializers.py from rest_framework import serializers from .models import IPMacMapping class IPMacMappingSerializer(serializers.ModelSerializer): class Meta: model = IPMacMapping fields = '__all__' urls.py from django.urls import path from .views import IPMacMappingRetrieveUpdateDestroy urlpatterns = [ path('ipmac/', IPMacMappingRetrieveUpdateDestroy.as_view(), name='ipmac-list-create') ] views: from rest_framework import generics from .models import IPMacMapping from .serializers import IPMacMappingSerializer from django.shortcuts import get_object_or_404 class IPMacMappingRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): queryset = IPMacMapping.objects.all() serializer_class = IPMacMappingSerializer lookup_url_kwarg = "ip_address" def get_object(self): result = get_object_or_404(IPMacMapping, ip_address=self.request.data["ip_address"]) return result -
How to set up periodic tasks automatically
I have a celery task in one of my django apps. My django, celery and django-celery-beat services are ran in their own docker containers. Since this is a legacy project, I now assume they interact smoothly already with the current config. What I want is that when the app gets deployed/started it finds my perioidc tasks automatically and registers them in the django celery beat database tables. My task: # project.an_app.tasks.generate_statements from config import celery_app @celery_app.task(...) def generate_statements(): print("Statment generation runs. Current date and time:", datetime.now()) # my task logic This is one solution I've found. But this only gets triggered when I try to access the Periodic tasks tables via admin site (probably would be triggered other ways which interact with these tables, but I don't want to "wait" for anything like that). def schedule_task(): interval, _ = IntervalSchedule.objects.get_or_create( every=30, period=IntervalSchedule.SECONDS, ) PeriodicTask.objects.get_or_create( interval=interval, name="generate-statements", task=project.an_app.tasks.generate_statements, ) schedule_task() Looking at our legacy code I've found this, this one looks from project.an_app.tasks import generate_statements @celery_app.on_after_finalize.connect def register_periodic_tasks(sender, **kwargs): """ Callback for Celery to register periodic tasks. """ sender.add_periodic_task( 30.0, task=generate_statements, name="generate-statements", ) The task of the copied code is indeed already django_celery_beat_periodictask table. So I would say this works. However … -
Reusing the types from the DjangoObjectType in the graphene
I have created the PreferencesNode from the DjangoObjectType which contains the gateway provider as TextChoices. class GatewayProvider(models.TextChoices): STRIPE = "stripe", "Stripe" RAZORPAY = "razorpay", "Razorpay" class PreferencesNode(DjangoObjectType): class Meta: model = Preferences exclude_fields = ("user_id",) Now I want to use AccountPreferencesGatewayProviderChoices enum (created via PreferencesNode). How can I do this? Currently I am creating another enum inheriting graphene.Enum. class GatewayProviderEnum(graphene.Enum): STRIPE = GatewayProvider.STRIPE.value RAZORPAY = GatewayProvider.RAZORPAY.value But this is creating redundant enum type. -
Polling a Celery Task with Ajax
I have a Celery task that populates a PostgreSQL database over the course of a few minutes. I want to retrieve the current data from the database in a Django view and send it to a template where it will be constantly re-displayed according to the progress of the task. So, I want to update the template in real-time. Currently, I have a view that calls the Celery task and gets the result of the task. It then renders the template and sends it the result of the task in the form of a string, as well as the id of the task. I am not very familiar with AJAX, but from what I've read I will need another view that AJAX will call to retrieve the most up-to-date result of the task. Here is the code so far: View that renders the template: def dashboard(request): result = prepare_database.delay() result_str = result.get() return render(request, 'appname/template.html', {'task_id': result.task_id(), 'str': result_str}) View that gets the current data def current_data(request): task_id = request.GET.get('task_id') if task_id: async_result = AsyncResult(task_id) return JsonResponse({'data': async_result.get()}) Ajax to poll the task (again, very new to AJAX): $.ajax({ url: '/current_data/', method: 'GET', data: { data: 'data' }, success: function(response) … -
How to get 'value' attribute of tag <input> in Django?
I have this view function to delete task from ToDo application: def delete_task(request): if request.method == 'POST': task = Task.objects.get(pk=request.POST['delete']) task.delete() return HttpResponseRedirect(reverse('todoapp:index')) else: tasks = Task.objects.all() return render(request, 'index.html', {'tasks': tasks}) I get 'value' of tag Here is my html: <form action="{% url 'todoapp:delete_task' %}" method="post"> {% csrf_token %} <input type="submit" name="delete" value="{{ task.id }}" class="btn btn-primary"> </form> And my button shows id of task instead of word 'Delete' any ideas how I can get data of tag <input> in another way? Thank you advance!! -
How do i apply multiple filters on my website
THIS IS MY HTML CODE <div class="container"> <button id="buttonH" class="buttonhindi" onclick="toggleFilterLanguage('H')">Hindi</button> <button id="buttonE"class="buttonhindi" onclick="toggleFilterLanguage('E')">English</button> <button id="buttonP" class="buttonhindi" onclick="toggleFilterLanguage('P')">Punjabi</button> </div> <div class="container"> <button id="buttonA" class="buttonhindi" onclick="toggleFilter('A')">18+ / A </button> <button id="buttonUA" class="buttonhindi" onclick="toggleFilter('UA')">UA</button> </div> <div class="row" id="movieList"> </div> <div class="end"> <p class="pp"> Copy right @2024 screen and fun limited.<br><br> The content and images used on this site are copyright and protected and copyright vest with the respective owner. the usage of content and images<br> on this website is intented to promote the works and no endosments of the artist shall be implied.</p> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // Function to toggle dropdown menu function toggleDropdown() { var dropdownMenu = document.querySelector('.dropdown-menu'); dropdownMenu.style.display = (dropdownMenu.style.display === 'block') ? 'none' : 'block'; } // Function to select city and fetch movies function selectCity(city) { document.getElementById('buttonA').classList.remove('buttonhindiClicked'); document.getElementById('buttonUA').classList.remove('buttonhindiClicked'); document.getElementById('selectedCity').innerText = city; document.getElementById('selectedCity2').innerText = city; toggleDropdown(); fetchMovies(city); } // Function to fetch movies for the selected city async function fetchMovies(city) { try { const response = await fetch(`/get_movies/${city}`); // Replace with your endpoint URL const data = await response.json(); displayMovies(data); } catch (error) { console.error('Error fetching movies:', error); } } // Function to display movies function displayMovies(movies) { const movieList = document.getElementById('movieList'); movieList.innerHTML = ''; movies.forEach(movie => { … -
Strange issue using CryptoJS, encrypts fine but decrypts just shows a blank file
I'm creating a browser based Django app that allows a user to upload some files to encrypt and then to decrypt using a password. I have managed to get the encryption part working but when decrypting the files all return blank. I've read through the CryptoJS docs and searched around but can't find a solution that works. I'm sure this is just a minor mistake on my behalf but would really appreciate the help. Please ignore the public/private key encryption stuff, one problem at a time :') // Event listener for encrypt button click document.getElementById('encryptBtn').addEventListener('click', function() { // Retrieve encryption mode, encryption type, and password from input fields var mode = document.getElementById('modeSelect').value; var encryptionType = document.getElementById('encryptionType').value; var password = document.getElementById('password').value; // Retrieve selected files var files = document.getElementById('fileInput').files; // Create a new JSZip instance var zip = new JSZip(); // Total number of files to process var totalFiles = files.length; // Counter to track processed files var filesProcessed = 0; // Initialize SweetAlert2 progress popup Swal.fire({ title: mode === 'encrypt' ? 'Encrypting Files' : 'Decrypting Files', html: 'Processing: 0 / ' + totalFiles, allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } }); // Loop through each file for (var i … -
"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" in post method
(https://i.stack.imgur.com/4OABY.png) views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from .models import note from .serializers import noteSerializer @api_view(['GET']) def getroute(request): routes = [ { 'Endpoint':'/note/', 'method':'GET', 'body':None, 'description':'Returns an array of notes'}, { 'Endpoint':'/note/id', 'method':'GET', 'body':None, 'description':'Returns an single note object'}, { 'Endpoint':'/note/create/', 'method':'POST', 'body':{'body':""}, 'description':'creates a single note object'}, { 'Endpoint':'/note/id/update', 'method':'PUT', 'body':{'body':""}, 'description':'updates a single note object'}, { 'Endpoint':'/note/id/delete', 'method':'DELETE', 'body':None, 'description':'deletes a single note object'} ] return Response(routes) @api_view(['POST']) def createnote(request): print("request.data") data = JSONParser().parse(request) serializer = noteSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @api_view(['GET']) def getNotes(request): notes = note.objects.all().order_by('-updated') serializer = noteSerializer(notes,many=True) return Response(serializer.data) @api_view(['GET']) def getNote(request,pk): notes = note.objects.get(id=pk) serializer = noteSerializer(notes,many=False) return Response(serializer.data) @api_view(['PUT']) def updatenote(request,pk): data =request.data notes =note.objects.get(id=pk) serializer = noteSerializer(instance=notes,data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @api_view(['Delete']) def deletenote(request,pk): notes = note.objects.get(id=pk) notes.delete() return Response("Note deleted") models.py from django.db import models class note(models.Model): body = models.TextField(null=True,blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) serializers.py from rest_framework.serializers import ModelSerializer from .models import note class noteSerializer(ModelSerializer): class Meta: model = note fields = '__all__' atfirst I used the api/todo/create url and it showed me "detail": "Method "GET" not allowed." and I added get method in the apiview … -
How can I associate existing child to parent in Django
I trying to build an IPAM by Django. I will create the Subnet model and create the IPAddress by the post_save signal. class Subnet(models.Model): usage = models.CharField('Usage', max_length=40) vlan = models.PositiveSmallIntegerField('vlan') cidr = models.CharField('CIDR', max_length=18) gateway = models.GenericIPAddressField('Gateway') def __str__(self): return str(self.vlan) + ' ' + self.usage class IPAddress(models.Model): subnet = models.ForeignKey(Subnet, on_delete=models.CASCADE, verbose_name="Subnet") ip = models.GenericIPAddressField('IP Address', unique=True) mac = models.CharField('Mac Address', max_length=17, blank=True, null=True) vm = models.ForeignKey(VM, on_delete=models.SET_NULL, blank=True, null=True) class Meta: indexes = [ models.Index(fields=['ip','mac']), models.Index(fields=['ip'], name='vm_ip_idx'), ] verbose_name = 'IP Address' verbose_name_plural = 'IP Addresses' def __str__(self): return str(self.ip) @receiver(post_save, sender=Subnet) def create_ip(sender, instance, created, **kwargs): if created: except_ip = ["0","255"] for ip in ipaddress.IPv4Network(instance.cidr): if (str(ip) != str(instance.gateway)) and (str(ip).split('.')[-1] not in [i for i in except_ip]): IPAddress(subnet=instance, ip=str(ip)).save() class VM(models.Model): vm_name = models.CharField('VM Name', max_length=60) def __str__(self): return str(self.vm_name) What I want to do: I created a Subnet with CIDR 172.0.0.0/24 and will automatically create total 255 IPAddress (172.0.0.1-172.0.0.254). And now I want to attach one of the IPAddress to a VM and update the MAC address in admin page. I tried to edit in admin.py class VMIPAdminForm(forms.ModelForm): ip = forms.ModelChoiceField(queryset=IPAddress.objects.all(), empty_label="IP Address") mac = forms.CharField(max_length=17, required=False, label="MAC Address") class Meta: model = IPAddress … -
Django Daphne – Database connections max out + "took too long to shut down"
I'm implementing a messaging system, but experiencing the following two errors on the dev server: "Application instance <...> took too long to shut down and was killed." The database connections get increased on every new EventSource that is created, despite it being closed on the frontend. Here is my code: Backend: @transaction.non_atomic_requests async def stream_chat_messages(request: HttpRequest) -> StreamingHttpResponse: async def event_stream(): SLEEP_INTERVAL = 0.3 """ We use this function to send a continuous stream of data to the connected clients. """ async for message in get_existing_messages(): yield message last_id = await get_last_message_id() # Continuously check for new messages while True: new_messages = _get_messages().filter(id__gt=last_id) async for message in new_messages: yield f"data: {json.dumps(message)}\n\n" last_id = message["id"] await asyncio.sleep(SLEEP_INTERVAL) return StreamingHttpResponse(event_stream(), content_type="text/event-stream") Frontend (React): const [currentChatroom, setCurrentChatroom] = useState<ChatroomProps | null>( null, ); useEffect(() => { setMessages([]); if (!currentChatroom) return; let sse = new EventSource( `.../stream-chat-messages/?chatroom=${currentChatroom.id}`, ); sse.onmessage = (event) => { // ... }; sse.onerror = () => { sse.close(); }; return () => { sse.close(); }; }, [currentChatroom?.id]); What am I doing wrong here? Every time the page is loaded, a new database connection is created, but it keeps persisting. Thanks! -
unknown redirect problem while using django view functions
"My URL configuration code: path("get_attendance/", staff_views.get_attendance, name="get_attendance") I placed the get_attendance method in the staff_views.py file. When a user accesses the page with a staff role and makes a POST request to /get_attendance/, it returns a status code of 200, which is normal. However, when a user accesses the page with an admin role and makes a POST request to /get_attendance/, it returns a status code of 302 for a redirection response, and then the user is redirected to the /admin/home/ page." I tried placing the method in two different routes to simulate requests, but the result is still the same. When the user is staff, it returns normally, but when the user is admin, it still redirects without any response But when I moved the get_attendance method into the views.py file, both staff and admin users can now receive a response without redirection. -
Django taggit view leading to FieldError: Related Field got invalid lookup: name
Tag view leads to this error message. The FieldError: Related Field got invalid lookup: name indicates a mismatch between what the Django ORM expects for a query on the tags relation and the actual query being executed. [...] File "/workspace/Coach-Matrix/main_forum/views/filters.py", line 18, in get_queryset return Question.objects.filter(tags__name=tag.name) File "/workspace/.pip-modules/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/workspace/.pip-modules/lib/python3.9/site-packages/django/db/models/query.py", line 1420, in filter return self._filter_or_exclude(False, args, kwargs) File "/workspace/.pip-modules/lib/python3.9/site-packages/django/db/models/query.py", line 1438, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/workspace/.pip-modules/lib/python3.9/site-packages/django/db/models/query.py", line 1445, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/workspace/.pip-modules/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1532, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/workspace/.pip-modules/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1562, in _add_q child_clause, needed_inner = self.build_filter( File "/workspace/.pip-modules/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1478, in build_filter condition = self.build_lookup(lookups, col, value) File "/workspace/.pip-modules/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1292, in build_lookup raise FieldError( Exception Type: FieldError at /questions/tag/tag4/ Exception Value: Related Field got invalid lookup: name I had tried Fetching the Tag instance using its slug and Using the name of the fetched Tag instance to filter Question objects. from django.views.generic.list import ListView from ..models import Question from django.shortcuts import get_object_or_404 from taggit.models import Tag class FilterByTagView(ListView): model = Question template_name = 'filtered_questions.html' context_object_name = 'questions' def get_queryset(self): tag_slug = self.kwargs.get('tag_slug') # Retrieve the Tag object by slug tag = … -
Saving a search history on django project?
I'm working on Django project, and I have created search option. Now I'm interested to see if I can save what users are searching and I can used that to create new content. Also, I'd like to see that on admin side. First, this is my current setup, I have views, forms and html parts. views.py def search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] search_vector = SearchVector('title', weight='A') + SearchVector('body', weight='B') search_query = SearchQuery(query) results = Lesson.published.annotate(search=search_vector,rank=SearchRank(search_vector, search_query)).filter(rank__gte=0.3).order_by('-rank') context = {'page_title':page_title, 'form': form, 'query': query, 'results': results} return render(request, 'pages/search.html', context) forms.py class SearchForm(forms.Form): query = forms.CharField() In order to save, I have tried to do following. I created models and updated views, but it hasn't worked as I hopped. models.py class MySearchQuery(models.Model): query = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.query updated views.py def search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] search_vector = SearchVector('title', weight='A') + SearchVector('body', weight='B') search_query = SearchQuery(query) search_query.save() results = Lesson.published.annotate(search=search_vector,rank=SearchRank(search_vector, search_query)).filter(rank__gte=0.3).order_by('-rank') context = {'page_title':page_title, 'form': form, 'query': query, 'results': results} return render(request, 'pages/search.html', … -
What should I do to fix this error that occurs when running a test web server on django
I needed to reinstall the ide, and after I opened my last django project and tried python manage.py runserver gave me the following error: ModuleNotFoundError: No module named 'djangoProject78' and a number of other errors after this command. djangoProject78 is the name of my project, I do not know why this error appeared and how to fix it. I've already tried to reinstall django. i tried reinstall django or change settings.py -
Django application to manage a small Inventory
I have created a very small Django application to manage a very small Inventory. My models.py code is: class Inventory(models.Model): account = models.ForeignKey( "accounts.Account", on_delete=models.DO_NOTHING, null=False, blank=False ) class InventoryProduct(models.Model): inventory = models.ForeignKey("Inventory", on_delete=models.CASCADE) sku = models.ForeignKey( "products.SKU", on_delete=models.DO_NOTHING, null=False, blank=False ) quantity = models.PositiveIntegerField( default=0 ) class Transaction(models.Model): IN = 1 OUT = 0 TYPE_CHOICES = ( (IN, "Incoming"), # Carico / Entrata (OUT, "Outgoing"), # Scarico / Uscita ) inventory = models.ForeignKey("Inventory", on_delete=models.CASCADE) transferred_to = models.ForeignKey( "Inventory", on_delete=models.CASCADE, blank=True, null=True ) code = models.UUIDField(default=uuid.uuid4) transaction_type = models.PositiveSmallIntegerField( choices=TYPE_CHOICES, default=IN ) transaction_date = models.DateTimeField(auto_now_add=True) notes = models.TextField(null=True, blank=True) class TransactionItem(models.Model): transaction = models.ForeignKey("Transaction", on_delete=models.CASCADE) item = models.ForeignKey("InventoryProduct", on_delete=models.CASCADE) quantity = models.IntegerField() def save(self, *args, **kwargs): super().save(*args, **kwargs) self.item.quantity += self.quantity self.item.save() The code is quite explanatory, I basically have an Inventory per account and the Inventory has products that I add in the related model InventoryItem. Each product in InventoryItem has a quantity that will be updated during a Transaction. A Transaction has a type IN/OUT to understand if i have to add or remove Items from the Inventory. Lastly, as you can surelly understand the TransactionItem has all the Items with the quantity (to add or remove) inside … -
Getting 'QuerySet' object has no attribute 'append' when making a function that automatically add a certain value from a ManyToManyField in Django
I am making a dictionary, and one of the features is to detect any input that is similar in the Censorships model. The reason for that is to give a tag for vulgar words. This is my Word model the tag is also in the same file, model.py. `class Word(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # Attributes of the model word = models.CharField(max_length=120) # Tags for searching and label tags = models.ManyToManyField('Tag', blank=True, related_name="word_tag") class Tag(models.Model): name = models.CharField(max_length=50)` My forms.py looks like this, it contains forms for both word and tag model. `class RawWordForm(forms.Form): word = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Enter a word"})) tags = forms.ModelMultipleChoiceField( queryset=Tag.objects.all(), widget=forms.CheckboxSelectMultiple ) user = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.HiddenInput) class RawTagForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Enter a tag"}))` Now the censorship occurs in the views.py where the word will be inputted. I made sure the word is saved first and then have the tags be set because the ModelMultipleChoiceField doesn't allow tags to be retrieved through cleaned_data. `from .forms import RawWordForm, RawTagForm from .models import Word, Tag from database.models import Censorship def word_create(request): form = RawWordForm() if request.method == "POST": form_data = { 'word': request.POST.get('word'), 'tags': request.POST.getlist('tags'), 'user': request.user, } form = RawWordForm(form_data) if form.is_valid(): # Word save w = … -
How to limit the number of visible pages shown in pagination with JavaScript
The pagination limit is not defined. I want to show the pagination in this format of 1/4, and the next and previous buttons will work accordingly. Also, on the first and last pages, clicks should be disabled. You can see it at the bottom of the table. Please help me in order to accomplish this. I tried but couldn't do it. That's why I am looking for expert help. const paginationNumbers = document.getElementById("pagination-numbers"); const paginatedList = document.getElementById("paginated-list"); const listItems = paginatedList.querySelectorAll("tbody tr"); const nextButton = document.getElementById("next-button"); const prevButton = document.getElementById("prev-button"); const pageSize = 2; const paginationLimit = 2; const pageCount = Math.ceil(listItems.length / paginationLimit); let currentPage = 1; const disableButton = (button) => { button.classList.add("disabled"); button.setAttribute("disabled", true); }; const enableButton = (button) => { button.classList.remove("disabled"); button.removeAttribute("disabled"); }; const handlePageButtonsStatus = () => { if (currentPage === 1) { disableButton(prevButton); } else { enableButton(prevButton); } if (pageCount === currentPage) { disableButton(nextButton); } else { enableButton(nextButton); } }; const handleActivePageNumber = () => { document.querySelectorAll(".pagination-number").forEach((button) => { button.classList.remove("active"); const pageIndex = Number(button.getAttribute("page-index")); if (pageIndex == currentPage) { button.classList.add("active"); } }); }; const appendPageNumber = (index) => { const pageNumber = document.createElement("button"); pageNumber.className = "pagination-number"; pageNumber.innerHTML = index; pageNumber.setAttribute("page-index", index); pageNumber.setAttribute("aria-label", "Page " … -
Is it possible to connect to the different network between two devices in Django Python?
I have the project that needs the same network in django python. I try to search whether there is the way to connect to different network on YouTube. I don't see. I thought different network connection was possible. I tried different network, but it said took too long or refused to connect even the right IP address. -
Neovim unable to detect Django packages: Getting 'Unable to import 'django.*' error
I've recently configured Neovim for my development workflow, but I'm encountering an issue with Django packages not being detected properly. Whenever I try to import any Django package or use Django functions within Neovim, I receive an error message like this: Unable to import 'django.conf' I've ensured that Django is properly installed and working outside of Neovim, but within Neovim, it seems to have trouble locating the Django packages. I've checked my Neovim configuration and paths, but I'm not sure where the problem lies. Has anyone encountered a similar issue with Neovim and Django packages? How can I troubleshoot and resolve this problem to get Neovim to properly detect Django packages? Any help or suggestions would be greatly appreciated. Thank you! -
How to log in an user coming from an external link into django application
I have a Django application using the out-of-the-box Django authentication system. I need to make an integration with another web app. The users in the other web app will click a button that should take them to my web application and give them access. The other web app will send me the user's email and other data. I should create the user if it doesn't exist without asking for any credentials. I'm not sure what approach I should take. I want something simple but not too insecure. Is SSO or OAuth the way to go? I think this is generally used to sign in with Google or Facebook, etc, but in this case, we don't want to depend on Google/Facebook accounts, the users use business emails. I'm thinking of having the third-party app use a secret key to encrypt an API Token, when the user clicks the button on their app, they will send a redirect to my app with the user data and the encrypted token. I will use the secret key to validate the Token and give the user access. I want guidance on what approach is more convenient, the responsibilities of each app, and how to implement … -
React + Docker: Failed to resolve import
I've been beating my head against a wall here trying to solve this, but I keep getting the following error that I can't resolve whenever I try to yarn add something and then use it: PM [vite] Internal server error: Failed to resolve import "@mui/x-data-grid" from "src/components/formSubmit.tsx". Does the file exist? Could I be somehow screwing up my node_modules? I think my docker script is correct, and I've checked that it exists in node_modules on the image, but I still seem to be getting this issue. My folder structure is: --Myapp |--frontend -node_modules -package.json -index.html - public - src - App.tsx - index.tsx - components - formsubmit.tsx - tsconfig.json - vite.config.js - vite-env.d.ts |--compose |--local |--react |--django |--djangobackend Docker-compose: version: '3' volumes: myapp_local_postgres_data: {} myapp_local_postgres_data_backups: {} services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: myapp_local_django container_name: myapp_local_django depends_on: - postgres volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - '28000:8000' command: /start react: build: context: . dockerfile: ./compose/local/react/Dockerfile image: myapp_react container_name: myapp_react depends_on: - postgres - django volumes: - ./frontend:/app - /app/node_modules/ ports: - 28001:3000 environment: - NODE_ENV=development command: yarn start Frontend dockerfile: ARG BUILD_ENVIRONMENT=local FROM node:lts-bookworm-slim WORKDIR /app COPY ./frontend/package.json . #COPY ./frontend/yarn.lock . COPY ./frontend/src . COPY … -
Reducing docker image size: multistage build or other suggestions
I am trying to deploy my Django app with docker. This is my original docker file FROM python:3.10.5-slim ENV DockerHOME = /app WORKDIR $DockerHOME COPY requirements.txt . RUN pip install --upgrade pip COPY . $DockerHOME RUN pip install --nocache-dir -r requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver"] After it build however, the image size was 300MB which was too big. I then tried doing a multi stage build as follow (which according to google can help reduce the image size significantly): FROM python:3.10.5-slim as base ENV DockerHOME = /app WORKDIR $DockerHOME COPY requirements.txt . RUN pip install --upgrade pip RUN pip install --nocache-dir -r requirements.txt FROM python:3.10.5-slim COPY --from=base $DockerHOME $DockerHOME COPY . $DockerHOME WORKDIR $DockerHOME EXPOSE 8000 CMD ["python", "manage.py", "runserver"] But this also resulted in an image that was 300MB. Could someone help me with this? I have 2 questions: Is the multistage Dockerfile logical? I feel that there is something wrong which would explain why there was no significant reduction in the image size. Are there any other ways to reduce the image size? I was originally using 'FROM python:3.10.5' instead of 'FROM python:3.10.5-slim' and that gave me 600MB image size. I changed to slim and it … -
Django, form/widgets/input.html problems
I'm tryning to change the django input dault,in teory i just need to copy the path from the github django project, but form some reason is not using mine, is just using the default input Django path my path. i really don't know whats the matter, i already try with another browser, and deleting the browser cache -
CSV file not coming through on submission of html form via POST method (in the context of using Django)
I am building a very simple application which includes one page where a user submits a list of zip codes and then is returned a file with zip codes in a certain radius of the original list. My problem is that my function for processing the file that is contained in the views.py file is not able to retrieve the '.csv' file after the post form. The FILES metadata on the request is missing and I cannot figure out why. More details below: Error I am seeing: Internal Server Error: /zip_app/ Traceback (most recent call last): File "/home/louis/.cache/pypoetry/virtualenvs/zip-radius-app-1xSGHScf-py3.10/lib/python3.10/site-packages/django/utils/datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'csvFile' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/louis/.cache/pypoetry/virtualenvs/zip-radius-app-1xSGHScf-py3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/louis/.cache/pypoetry/virtualenvs/zip-radius-app-1xSGHScf-py3.10/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/louis/.cache/pypoetry/virtualenvs/zip-radius-app-1xSGHScf-py3.10/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) File "/home/louis/Documents/github/zip_radius_tool/zip_radius_app/zip_app/views.py", line 30, in index f = request.FILES['csvFile'] File "/home/louis/.cache/pypoetry/virtualenvs/zip-radius-app-1xSGHScf-py3.10/lib/python3.10/site-packages/django/utils/datastructures.py", line 86, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'csvFile' HTML for the index page where the user submits the .csv file: <!DOCTYPE html> <html lang="en"> <head> <title>W3.CSS Template</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" …