Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Detecting non-translation wrapped strings in Django?
I have a Django project being maintained by multiple developers. It needs to support i18n, so all model field names, help text, labels in custom templates, etc need to get wrapped by gettext_lazy. Occasionally, however, a developer will forget to wrap a new string, which leads to regressions where text does not get translated in the UI. Is there an existing tool I can run to scan Django's templates and models and report non-translation wrapped strings so I can add a check to my build to catch these regressions? I guess it would be the inverse of django-admin makemessages, which finds all strings wrapped by gettext_lazy, but I can't find anything like this in Django's docs. -
How to prevent Pycharm from opening the source file of a function or a class when trying to edit a particular line,or a function/class name?
My current Pycharm version is 2023.2.5(Ubuntu linux) Whenever I try to edit a name of a function or click on a classname it takes me to it's source file which is annoying.How to disable this feature? from .views import test """when I click on the above line to add test2,it takes me to the views.py Expected behavior:-Should be able to edit a line(add to the end of it) without Pycharm taking me to the source file of that function or class...""" urlpatterns = [path('home', test, name='test'), path('about', test2, name='test2')] -
Django 5: custom AdminSite got " 'generator' object is not subscriptable "
I'm trying to do default admin site just like this here is settings.INSTALLED_APPS INSTALLED_APPS = [ #'django.contrib.admin', 'core.apps.AppAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'routefilterfeeder.apps.RoutefilterfeederConfig', ] here is my core.apps from django.contrib.admin.apps import AdminConfig class AppAdminConfig(AdminConfig): default_site = 'core.admin.AppAdminSite' and here is my core.admin from django.contrib.admin import AdminSite #from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from django.apps import apps from django.contrib.admin.sites import site from operator import itemgetter # ref: https://unfoldadmin.com/blog/custom-django-admin-site/ class AppAdminSite(AdminSite): def index(self, request, extra_context=None): # Update extra_context with new variables return super().index(request, extra_context) def get_app_list(self, request, app_label=None): """ Return a sorted list of all the installed apps that have been registered in this site. """ app_dict = self._build_app_dict(request, app_label) # First, sort the models of each app, based on 'admin_priority' # Ref: https://forum.djangoproject.com/t/reordering-list-of-models-in-django-admin/5300 for app_name in app_dict.keys(): app = app_dict[app_name] model_priority = { model['object_name']: getattr( site._registry[apps.get_model(app_name, model['object_name'])], 'admin_site_priority', 9999 ) for model in app['models'] } app['models'].sort(key=lambda x: model_priority[x['object_name']]) yield app # Sort the apps alphabetically. all_app = sorted(app_dict.values(), key=lambda x: x["name"].lower()) app_list = [] prio_list = [] # Sort the models alphabetically within each app. for app in all_app: this_config = apps.get_app_config(app["app_label"]) try : this_prio = this_config.admin_site_priority prio_list.append([this_prio,app['app_label']]) except Exception as e: app_list.append(app) prio_list = sorted(prio_list, … -
how I can catch when pressed cancel_url on stripe?
I have a question about Stripe payments... I figured out how to do some code when payment was succesful, but what and where I can check that user even didn't enter anything in checkout form, and just pressed Back cancel_url? my checkout code: domain = 'http://127.0.0.1:8000/profiles/'+username+'/balance/' stripe.api_key = settings.STRIPE_SECRET_KEY try: # Create new Checkout Session for the order # Other optional params include: # [billing_address_collection] - to display billing address details on the page # [customer] - if you have an existing Stripe Customer ID # [payment_intent_data] - capture the payment later # [customer_email] - prefill the email input in the form # For full details see https://stripe.com/docs/api/checkout/sessions/create # ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.username if request.user.is_authenticated else None, success_url=domain + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain + 'cancelled', payment_method_types=['card'], mode='payment', line_items=[ { 'price_data': { 'currency': 'eur', 'unit_amount': grata_points_amount, #6900, 'product_data': { 'name': pack.name, #'69 GP', # 'description': 'package with 6900 Grata Points', # 'images': [''], }, }, 'quantity': pack_cnt, #1, } ], metadata={ 'transactionID': transaction.id } ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) sucess payment (all needed fields was filled up): def stripe_webhook(request): stripe.api_key = settings.STRIPE_SECRET_KEY endpoint_secret … -
Token Expiry based on user inactivity
So I am using django rest framework, and i am using simple jwt for token authentication, and i want to implement this (if the user hasn't been active on the website for 30 min then the token should expire and the user should be redirected to login page). How should i do this, for your information i know about session authentication, however, i don't want to use it. Note: If you have any other security methods/approaches i am open to hearing them since this is the only one that i know and i don't know how to implement it :-) i have tried adding some fields in the payload, so i can use it to determine if the user is active or not, however idk how to make the server check it, since the only way that i check on the token is when the clinet make an api call -
Why does my filter __exact not working in my django, postgresql?
Before are my codes in my django app frame, everything is working well. There is no error but my filter __exact does not print out the results in my html. Please help. def list(request, type): genes = Gene.objects.filter(entity__exact=type) return render(request, 'genedata/list.html', {'genes': gene, 'type': type}) def poslist(request): genes = Gene.objects.filter(entity__exact='Chromosome').filter(sense__startswith='+') return render(request, 'genedata/list.html', {'genes': gene, 'type': 'Poslist'}) path('list/\<str:type\>', views.list, name='list'), path('poslist/', views.poslist, name='poslist') class Gene(models.Model): gene_id = models.CharField(max_length=256, null=False, blank=False, db_index=True) entity = models.CharField(max_length=256, null=False, blank=False) start = models.IntegerField(null=False, blank=True) stop = models.IntegerField(null=False, blank=True) sense = models.CharField(max_length=1) start_codon = models.CharField(max_length=1, default="M") sequencing = models.ForeignKey(Sequencing, on_delete=models.DO_NOTHING) ec = models.ForeignKey(EC, on_delete=models.DO_NOTHING) def __str__(self): return self.gene_id index.html <h1>D.Bucheria Genes List</h1> Gene ID {% for gene in genes %} <a href="/gene/{{ gene.pk }}"> {{ gene }}</a> {% endfor %} <h2>Select Gene Location</h2> <a href="/list/Chromosome">Chromosome</a> OR <a href="/list/Plasmid">Plasmid</a> <h2>Show Positive Chromosome Genes</h2> <a href="/poslisti">Chromosome</a>Show Positive List</a> list.html: <h1>Filtered List: {{ type }} </h1> Gene ID {% for gene in genes %} <a href="/gene/{{ gene.pk }}"> {{ gene }}</a> {% endfor %} -
get TaskResult object when testing the Celery task in Django
I have a very simple celery task inside my Django application: @app.task(name='test', bind=True) def my_celery_task(self, schema=None, ref_id=None, user_id=None): print('Start Task 1') with schema_context(schema): print(self.get_task_result()) print(self.get_task_result().pk) print('Start Task 2') return {'status': 'Task finished successfully'} I also have the base class for Celery tasks class MyTaskBase(Task): def delay(self, *args, **kwargs): print('Delaying task: {}'.format(self.name)) argsrepr = [arg for arg in args] kwargsrepr = {key: value for key, value in kwargs.items()} new_task = super().s(*args, **kwargs) return new_task.apply_async( argsrepr=json.dumps(argsrepr), kwargsrepr=json.dumps(kwargsrepr) ) def get_task_result(self): from django_celery_results.models import TaskResult task_result = TaskResult.objects.get_task(self.request.id) return task_result I also have the trigger for a TaskResult on_save: @receiver(post_save, sender=TaskResult) def create_task_entry(sender, instance=None, created=None, **kwargs): print("INSIDE THE POST_SAVE") ... TaskEntry.objects.create(...) I want to test this configuration: SO... : I wrote this little test: @override_settings(CELERY_TASK_ALWAYS_EAGER=True) def test_test(self): my_celery_task.delay(schema=self.get_test_schema_name()) print(TaskResult.objects.all()) print(TaskEntry.objects.all()) The prints are: Delaying task: my_celery_task Start Task 1 <Task: 7a0e8063-2be9-44b1-b438-1c0d37e33456 (PENDING)> None Start Task 2 <QuerySet []> <QuerySet []> From this, I conclude: the task was run The TaskResult was created but never saved to the DB If I omit the CELERY_TASK_ALWAYS_EAGER and run this def test_test(self): my_celery_task.delay(schema=self.get_test_schema_name()) print(TaskResult.objects.all()) print(TaskEntry.objects.all()) Then the prints are on the worker: Delaying task: my_celery_task Start Task 1 <Task: 7a0e8063-2be9-44b1-b438-1c0d37e33456 (PENDING)> None Start Task 2 INSIDE THE … -
fetching Django API with pagination in react
so I have this code in my react import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { Bar } from 'react-chartjs-2'; import moment from 'moment'; import 'chartjs-adapter-moment'; import { MultiSelect } from "react-multi-select-component"; const AllFilters = () => { const [startDate, setStartDate] = useState(null); const [endDate, setEndDate] = useState(null); const [operatorId, setOperatorId] = useState(null); // const [statuses, setStatuses] = useState([]); const [operatorsList, setOperatorsList] = useState([]); const [orderStatuses, setOrderStatuses] = useState([]); const [orders, setOrders] = useState([]); const [selectedStatuses, setSelectedStatuses] = useState([]); const [viewBy, setViewBy] = useState('month'); const filterOrdersByDay = (day) => { const formattedDay = moment(day).format('YYYY-MM-DD'); const filteredOrders = orders.filter(order => moment(order.created_at).isSame(formattedDay, 'day', 'minute')); console.log(`Filtered orders for day ${formattedDay}:`, filteredOrders); return filteredOrders; }; const getStatusCountByDay = (status, day) => { const formattedDay = moment(day).format('YYYY-MM-DD'); return filterOrdersByDay(formattedDay).filter(order => order.status === status).length; }; useEffect(() => { const fetchData = async () => { try { const loginToken = localStorage.getItem('loginToken'); const operatorsListResponse = await axios.get('http://localhost:8000/accounts/profile/operators/', { headers: { Authorization: `Token ${loginToken}`, }, }); const orderStatusesResponse = await axios.get('http://localhost:8000/dashboard/OrderStatus/', { headers: { Authorization: `Token ${loginToken}`, }, }); setOperatorsList(operatorsListResponse.data); setOrderStatuses(orderStatusesResponse.data); let pageOrders = []; const response = await axios.get('http://localhost:8000/dashboard/AllFilters/', { headers: { Authorization: `Token ${loginToken}`, }, params: { start_date: startDate ? … -
no idea about how to store a token or another credentials of another Django app that acts as a gateway in my another Django app
I have a Django app named something like d1 app that acts as my gateway service in my micro service architecture and another Django app as a client of d1 named as something like d2. I'm confused about how can I get a token or some credentials like phone number and password from the frontend and pass it to d1 to verifying user and logging it in my d2 Auth system. big part of my problem is confusing about how to store the temporary token or credentials of my frontend in d2 app. one of my own ideas was using REDIS or some caching server like that; but as I'm new to backend I don't have a great confidence about it and I'll be thank of any advices of anybody who can guide me. thanks -
performing case insensitive validation in django
I'm new to the backend world and learning how to make an API with django rest framework. I went through some concepts already but I ran into some issues. Context: There are 4 resources. Store, Author, Book, Address. 1 CRUD endpoint for each of them except address. A store must have an address and a name. if the address exists, link it on creation, else create the address and create the store. Problem: I cannot seem to figure out this part "if the address exists, link it on creation, else create the address and create the store." Here is the relevant info to the problem in hand views.py class StoreViewSet(viewsets.ViewSet): def list(self, request): stores = Store.objects.prefetch_related('address') serializer = StoreSerializer(stores, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def retrieve(self, request, pk=None): pass def create(self, request): serializer = StoreSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class Address(models.Model): country = CountryField(null=False) city = models.CharField(max_length=255, null=False) street = models.CharField(max_length=255, null=False) street_number = models.IntegerField(null=False) addition = models.CharField(max_length=255, blank=True, default='') class Meta: unique_together = ['country', 'city', 'street', 'street_number', 'addition'] constraints = [models.CheckConstraint(check=models.Q(street_number__lt=100000), name="street_number_lt_100000")] class Store(models.Model): name = models.CharField(max_length=255, null=False) address = models.OneToOneField(Address, null=False, on_delete=models.CASCADE) books = models.ManyToManyField(Book, blank=True) serializers.py class AddressSerializer(CountryFieldMixin, serializers.ModelSerializer): class Meta: model … -
django rest framework, how to prefetch_related with a single object
for some reason,I pass a instance(not queryset) to ModelSerializer. but I want to do prefetch_related with this instance. # instance is a Workout object instance = queryset.order_by('?').first() # I want to do something like: instance.prefetch_related('exercises') to avoid N+1 problem workout = WorkoutModelSerializer(instance) return Response(workout.data, status=status.HTTP_200_OK) -
What does the new `Field.db_default` of django 5 imply ? Should we use it by default or stick with `Field.default`?
If I understand correctly, Field.default do not set a value in the DB, but the value is used when a model instance is created. On the other hand, Field.db_default set the value in the DB. I am not sure to fully understand the implications that this new option is giving us. So my question is, which one should be used by default (no pun intended) and why? -
Find which IP address was used by manage.py while the Django dev server was started
In Django dev environment, we start our Django server in various way, like:- python3 manage.py runserver which auto starts development server at http://127.0.0.1:8000/ OR python3 manage.py runserver 192.168.1.1:8005 which auto starts development server at http://192.168.1.1:8005/ How or in what ways, can I find the IP address that the development server was started using which IP address and which port number? I want to write a python script within this Django project (in an app), which could tell me that the dev server is accessible on <this_specific_ip_address> (ex: 127.0.0.1 or 192.168.1.1) and then on <this_specific_port_number> (ex: 8000 or 8005). Is there a way this can be achieved? -
making downloaded file not transferable in django
I am developing a bookstore app, I want to make downloaded files not shareable to other devices. which means users can not share files that are downloaded from the site. I tried searching different sites to know how I can make the file downloaded not shareable but I didn't get any solution. please help me with what can I do to solve this problem. -
How to create a separate column for each related field while exporting data via django-import-export
I have a PaymentRecord model which stores user payments for event tickets. I have a TicketPurchase model which records which tickets were purchased by which PaymentRecord. So my models look something like this - class Event(models.Model): name = models.CharField(max_length=128) class PaymentRecord(models.Model): event = models.ForeignKey(Event, on_delete=models.SET_NULL, null=True, related_name='payments') payment_time = models.DateTimeField(auto_add_now=True) # various payment details and user identifiers class TicketPurchase(models.Model): payment_record = models.ForeignKey(PaymentRecord, on_delete=models.CASCADE, related_name='tickets') tier_name = models.CharField(max_length=32) ticket_count = models.IntegerField() Each event that I am selling tickets for has a few "tiers", like Silver, Gold, Platinum (Each event has different names for tiers). When I export all the PaymentRecord objects for a particular event, I want to have a separate column for each tier showing how many tickets for that tier were purchased by a payment. So I want my output to be something like this - Event Name Payment Time Silver Tickets Gold Tickets Platinum Tickets Event 1 # time 1 3 0 0 Event 1 # time 2 1 1 1 How can I achieve this using django-import-export? Right now I am using a ModelResource to export a summary of the different tiers purchased in a single column, as so - class PaymentRecordsResource(resources.ModelResource): class Meta: model = PaymentRecord … -
How to fix "IntegrityError Foreign Key constraint failed" error in django rest framework?
I have Client (AbstractUser) and Team models in my django app class Team(models.Model): name = models.CharField(max_length=255) class Client(AbstractUser): team = models.ForeignKey(Team, blank=True, null=True, related_name='client', on_delete=models.SET_NULL, db_index=True) name = models.CharField(max_length=255) code = models.CharField(max_length=255, unique=True) pass So, when I logged in using Client (not superuser, with permission to add-change Client) I can't change Client. I want to be one administrator for each team to manage own team, can add or change Client. So Client with permission is_staff can manage own team. But it gives an error IntegrityError. Django admin.py -
Django Nextjs webscoket connecting can't established and getting 404 error
I am trying to build an real time chat app so using django channel but I can't build web socket connect with my django and nextjs app. my folder and file structure backend ->backend ->settings.py ->wsgi.py ->routing.py ->consumers.py my code: settings.py ASGI_APPLICATION = "backendfb.routing.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from backendfb.consumers import TextRoomConsumer application = ProtocolTypeRouter({ 'websocket': URLRouter( [ path('ws/<room_name>/', TextRoomConsumer.as_asgi()) ] ), }) consumers.py # backendfb/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class TextRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f"chat_{self.room_name}" # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat.message', 'message': message } ) async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) wsgi.py import os from backendfb.routing import application from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backendfb.settings') application = application app = get_wsgi_application() my fontend code const client = new WebSocket(`ws://localhost:8000/ws/${Room}/`); -
how to remove the first slash in django?
The tutorial is written like this urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include("polls.urls") but i prefer urlpatterns = [ path('/admin', admin.site.urls), path('/polls', include("polls.urls") So the url would be '127.0.0.1:8000//polls' Is there any way to remove the first slash that is automatically added? I try to set APPEND_SLASH = FALSE but it makes nothing -
How do I always add a value from my data to serializer.errors (DRF)?
I'd like to pass an integer field called Id into a serializer, and always add it to serializer.errors (if there are any. For example: class ItemSerializer(serializers.ModelSerializer): # magical way to take Id in and add it to errors class Meta: model = Item fields = "__all__" Then, if there are any errors, they should look like: {"error": "error message", "Id": 1} I can't just add the field to serializer.errors after serializer.is_valid() runs, because I also want to use many=True on my serializer. Also, it turns out that you can't add a dictionary as an error message, for example: validators = [ UniqueTogetherValidator( queryset=Item.objects.all(), fields=["org", "item_name"], message={"cool":"dictionary"}, #this doesn't work :( ) ] And no, I can't store the Id in the model itself. Due to the way my frontend is using this API, the Id will change on most API calls. -
Error in the configuration of django parameter files in VSC
Good evening, I am following a python course on the web, dictated by the Universidad Pontificia de Chile, according to the video and documentation provided by them, using django. At the moment I am configuring the parameters for the Views of django. The first web page works perfectly, but when reconfiguring the views.py and urls.py files, to take information provided by the user through the API gives the following message: Request Method: GET Request URL: http://127.0.0.1:8000/music/ Beatles Using the URLconf defined in AyudantiaMP1.urls, Django tried these URL patterns, in this order: music/ artists/<artist_id>/ [name='artist_detail'] music/ [name='index'] admin/ The current path, music/Beatles, didn’t match any of these. I do not find it wrong. Greetings and thank you in advance Below are the related .py files: view.py from django.http import HttpResponse def index(request): return HttpResponse('Bienvenidos a la app de música!') def artist_detail(request, artist_id): return HttpResponse('Estás viendo al artista %s.' % artist_id) urls.py (app) from django.urls import path from . import views urlpatterns = [ path('artists/<artist_id>/',views.artist_detail,name='artist_detail'), path(' ' , views.index,name='index'),] urls.py (environment) from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('music/',include('music.urls')), path('admin/', admin.site.urls),] According to the course, by configuring the parameters shown, the web page will … -
Django 404 image for profile picture
I have added a new attribute to my django model that includes a imagefield attribute for profile pictures: Models.py: class AvailableDrinks(models.Model): drink_name = models.CharField(max_length=200) store_name = models.ForeignKey('Stores', on_delete=models.CASCADE,) description = models.CharField(max_length=1200) drinksSlug = models.SlugField(unique=True, null=True) photo = models.ImageField(upload_to="static/media/images/drinkPhotos", blank=True) def __str__(self): return self.drink_name Views.py: class DrinksView(generic.DetailView): template_name = "drinks.html" context_object_name = "drinks" model = AvailableDrinks slug_url_kwarg = 'drinksSlug' def get_object(self): return get_object_or_404(AvailableDrinks, drinksSlug=self.kwargs['drinksSlug']) def get_queryset(self): return AvailableDrinks.objects.all() class StoreView(generic.DetailView): template_name = "caffeine-stores.html" model = Stores context_object_name = 'stores' slug_url_kwarg = 'slug' Url.py: urlpatterns = [ path("", HomeView.as_view(), name="home"), path('<slug:slug>/', StoreView.as_view(), name="stores"), path("<slug:slug>/<slug:drinksSlug>/", DrinksView.as_view(), name="drinks"), path("<int:account_id>/select_drinks/", views.select_drink, name="select") ] print(settings.DEBUG) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings.py: STATIC_URL = 'static/' MEDIA_URL = '' MEDIA_ROOT = BASE_DIR I have printed out my directories to make sure that they are properly pointing to the image files. I have also insured that they are uploading correctly from the admin page yet I still get an error: ""GET /static/media/images/drinkPhotos/icepop_drink.jpeg HTTP/1.1" 404 1888". Am I just missing something simple? I originally was getting a file attribute error saying that there was no file associated with the imagefield but I got around that with some fiddling. Now the website displays but the images revert to their alt … -
cant create django superuser when User model extends Abstract User
I am trying to create a custom user model by inheriting from AbstractUser.Only issue is that I am not able to create a SuperUser in my terminal. It prompts me to enter my username and then throws this error after that django.db.utils.OperationalError: no such column: api_user.name this is what my user model looks like: class User(AbstractUser): name = models.CharField(max_length=200) email = models.EmailField(unique=True) password = models.CharField(max_length=200, default="") dob = models.DateField("Date Of Birth",blank=True, default=None) profileImg = models.ImageField(upload_to='frontend/src/assets/profileImgs/',blank=True) createdAt = models.DateTimeField(auto_now_add=True) REQUIRED_FIELDS = [] USERNAME_FIELD = "username" def __str__(self): return self.username def was_published_recently(self): return self.createdAt >= timezone.now() - datetime.timedelta(days=1) def to_dict(self): return{ "id": self.id, "name": self.name, "email": self.email, "password": self.password, "dob": self.dob, "profileImg": os.path.basename(self.profileImg.name), "createdAt": self.createdAt, } I am really new to django so I am not sure what am I doing wrong here -
Several Django Projects
I want to create several django projects that use the same package; can I create them in the same virtual environment won't this create conflict? the idea is that each of them can use a separate database. or would it be better to list each in its own directory? I put them all in the same directory and therefore the same virtual environment -
Django & HTMX - make forms render_field a target of HTMX
I've created a django form where user can input partial name of a client. HTMX displays all matching clients and when button is pressed next to clients name, I'd like it to fill multiple form fields. Let's consider simplified Django manual form example: invoices/templates/invoice_add.html {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <form method='POST' autocomplete='off'> {% csrf_token %} <label>{{ form.number.label_tag }}</label> {{ form.number.errors }} {% render_field form.number class="form-control" %} <br> <label>{{ form.buyer_name.label_tag }}</label> {{ form.buyer_name.errors }} {% render_field form.buyer_name class="form-control" hx-post="/invoices/check_client/" hx-trigger="keyup" hx-target="#buyer_names_list" %} <div id="buyer_names_list"></div> <br> <label>{{ form.buyer_tax_no.label_tag }}</label> {{ form.buyer_tax_no.errors }} {% render_field form.buyer_tax_no class="form-control" %} <br><div id="tax_no_test"></div> <input type='submit' value='save'/> </form> {% endblock %} As mentioned above, when populating buyer_name I'm getting a list of client names with a button next to their name inside buyer_names_list. This button calls below function to pull the tax number: invoices/views.py def particular_client_invoice(request): client_obj = Client.objects.all().filter(name=request.POST.get('clientname')) context = {'client_tax_no': client_obj.values_list('tax_no', flat=True)[0]} return render(request, 'partials/specific-invoice.html', context) My issue: While it properly returns desired tax number, I can only return the values from HTMX inside a div (id="tax_no_test" in this case). I'd like field form.buyer_tax_no to be the target field of the tax number. Is that possible? Alternatively (worse … -
How do I change the URL a user copies in Django?
Building a DJANGO app. All the links on one of my pages when you click 'copy link' don't return the links URL but the GET command that I'm firing off in a custom function, for context clicking a link increments a vote counter in the app and then it redirects to the actual link, however this is preventing users from getting the URL of that link if they use right-click -> copy link in a browser. How do I intercept a 'Copy Link' request and pass the actual URL to the user? I've not been able to find any resources on the web to help me, granted I'm not sure what I'm searching has been the right keywords.